Changeset - 697339dbfa61
CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
project(libtransport)
 

	
 
set(CMAKE_MODULE_PATH "cmake_modules")
 

	
 
set(cppunit_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(cppunit)
 

	
 
set(sqlite3_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(sqlite3)
 

	
 
set(mysql_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(mysql)
 

	
 
set(purple_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(purple)
 

	
 
set(glib_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(glib)
 

	
 
if (NOT WIN32)
 
	set(popt_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
	find_package(popt)
 
endif()
 

	
 
set(event_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(event)
 

	
 
set(Swiften_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(Swiften REQUIRED)
 

	
 
set(openssl_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(openssl REQUIRED)
 

	
 
set(Boost_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
if (WIN32)
 
set(Boost_USE_STATIC_LIBS        ON)
 
set(Boost_USE_MULTITHREADED      ON)
 
set(Boost_USE_STATIC_RUNTIME    OFF)
 
endif()
 
find_package(Boost COMPONENTS program_options date_time system filesystem regex thread signals REQUIRED)
 
find_package(Boost COMPONENTS program_options date_time system filesystem regex  signals REQUIRED)
 
message( STATUS "Found Boost: ${Boost_LIBRARIES}, ${Boost_INCLUDE_DIR}")
 

	
 
set(Protobuf_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(Protobuf REQUIRED)
 

	
 
set(Communi_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(Communi)
 

	
 
set(log4cxx_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(log4cxx)
 

	
 
set(event_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(event)
 

	
 
set(pqxx_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(pqxx)
 

	
 
set(dbus_DIR "${CMAKE_SOURCE_DIR}/cmake_modules")
 
find_package(dbus)
 

	
 
find_package(Doxygen)
 

	
 
INCLUDE(FindQt4)
 
FIND_PACKAGE(Qt4 COMPONENTS QtCore QtNetwork)
 

	
 
# ADD_DEFINITIONS(${SWIFTEN_CFLAGS})
 
ADD_DEFINITIONS(-DSUPPORT_LEGACY_CAPS)
 
ADD_DEFINITIONS(-DBOOST_FILESYSTEM_VERSION=2)
 

	
 
message("  Supported features")
 
message("-----------------------")
 

	
 
if (SPECTRUM_VERSION)
 
	ADD_DEFINITIONS(-DSPECTRUM_VERSION="${SPECTRUM_VERSION}")
 
else (SPECTRUM_VERSION)
 
	if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)
 
		execute_process(COMMAND git "--git-dir=${CMAKE_CURRENT_SOURCE_DIR}/.git" rev-parse --short HEAD
 
						OUTPUT_VARIABLE GIT_REVISION
 
						OUTPUT_STRIP_TRAILING_WHITESPACE
 
		)
 
		set(SPECTRUM_VERSION 2.0.0-beta-git-${GIT_REVISION})
 
		ADD_DEFINITIONS(-DSPECTRUM_VERSION="${SPECTRUM_VERSION}")
 
	else (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)
 
		set(SPECTRUM_VERSION 2.0.0-alpha)
 
		ADD_DEFINITIONS(-DSPECTRUM_VERSION="${SPECTRUM_VERSION}")
 
	endif (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)
 
endif (SPECTRUM_VERSION)
 

	
 
message("Version           : " ${SPECTRUM_VERSION})
 

	
 
if (SQLITE3_FOUND)
 
	ADD_DEFINITIONS(-DWITH_SQLITE)
 
	include_directories(${SQLITE3_INCLUDE_DIR})
 
	message("SQLite3           : yes")
 
else (SQLITE3_FOUND)
 
	set(SQLITE3_LIBRARIES "")
 
	message("SQLite3           : no")
 
endif (SQLITE3_FOUND)
 

	
 
if (MYSQL_FOUND)
 
	ADD_DEFINITIONS(-DWITH_MYSQL)
 
	include_directories(${MYSQL_INCLUDE_DIR})
 
	message("MySQL             : yes")
 
else (MYSQL_FOUND)
 
	set(MYSQL_LIBRARIES "")
 
	message("MySQL             : no (install mysql-devel)")
 
endif (MYSQL_FOUND)
 

	
 
if (PQXX_FOUND)
 
	ADD_DEFINITIONS(-DWITH_PQXX)
 
	include_directories(${PQXX_INCLUDE_DIR})
 
	message("PostgreSQL        : yes")
 
else (PQXX_FOUND)
 
	set(PQXX_LIBRARY "")
 
	set(PQ_LIBRARY "")
 
	message("PostgreSQL        : no (install libpqxx-devel)")
 
endif (PQXX_FOUND)
 

	
 
if (PROTOBUF_FOUND)
 
	ADD_DEFINITIONS(-DWITH_PROTOBUF)
 
	include_directories(${PROTOBUF_INCLUDE_DIRS})
 
	message("Network plugins   : yes")
 

	
 
	if(PURPLE_LIBRARY AND PURPLE_INCLUDE_DIR)
 
		message("Libpurple plugin  : yes")
 
		include_directories(${PURPLE_INCLUDE_DIR})
 
		include_directories(${GLIB2_INCLUDE_DIR})
 
	else()
 
		message("Libpurple plugin  : no (install libpurple)")
 
	endif()
 

	
 
	if (HAVE_EVENT)
 
		ADD_DEFINITIONS(-DWITH_LIBEVENT)
 
		include_directories(${EVENT_INCLUDE_DIRS})
 
		message("  libev eventloop : yes")
 
	else()
 
		message("  libev eventloop : no (install libev-devel)")
 
	endif()
 

	
 
	if(IRC_FOUND)
 
		ADD_DEFINITIONS(-DCOMMUNI_SHARED)
 
		message("IRC plugin        : yes")
 
		include_directories(${QT_QTNETWORK_INCLUDE_DIR})
 
		include_directories(${IRC_INCLUDE_DIR})
 
		include(${QT_USE_FILE})
 
	else()
 
		message("IRC plugin        : no (install libCommuni and libprotobuf-dev)")
 
	endif()
 

	
 
	message("Frotz plugin      : yes")
 
	message("SMSTools3 plugin  : yes")
 

	
 
	if(${LIBDBUSGLIB_FOUND})
 
		message("Skype plugin      : yes")
 
		include_directories(${LIBDBUSGLIB_INCLUDE_DIRS})
 
	else()
 
		message("Skype plugin      : no (install dbus-glib-devel)")
 
	endif()
 

	
 
else()
 
	message("Network plugins   : no (install libprotobuf-dev)")
 
	message("Libpurple plugin  : no (install libpurple and libprotobuf-dev)")
 
	message("IRC plugin        : no (install libircclient-qt and libprotobuf-dev)")
 
	message("Frotz plugin      : no (install libprotobuf-dev)")
 
	message("SMSTools3 plugin  : no (install libprotobuf-dev)")
 
endif()
 

	
 
if (LOG4CXX_FOUND)
 
	message("Logging           : yes")
 
	include_directories(${LOG4CXX_INCLUDE_DIR})
 
else()
 
	message(FATAL_ERROR "Logging           : no (install log4cxx-devel)")
 
endif()
 

	
 
if (WIN32)
 
ADD_DEFINITIONS(-D_WIN32_WINNT=0x501)
 
ADD_DEFINITIONS(-DWIN32_LEAN_AND_MEAN)
 
endif()
 

	
 
if(CMAKE_BUILD_TYPE MATCHES Debug)
 
if (CMAKE_COMPILER_IS_GNUCXX)
 
	ADD_DEFINITIONS(-O3)
 
	ADD_DEFINITIONS(-ggdb)
 
	ADD_DEFINITIONS(-Wall)
 
	ADD_DEFINITIONS(-W)
 
	ADD_DEFINITIONS(-Wcast-align)
 
	ADD_DEFINITIONS(-Wextra -Wno-sign-compare -Wno-unused-parameter)
 
	ADD_DEFINITIONS(-Winit-self)
 
	ADD_DEFINITIONS(-Wmissing-declarations)
 
	ADD_DEFINITIONS(-Wpointer-arith)
 
	ADD_DEFINITIONS(-Wreorder)
 
	ADD_DEFINITIONS(-Woverloaded-virtual)
 
	ADD_DEFINITIONS(-Wsign-promo)
 
	ADD_DEFINITIONS(-Wundef -Wunused)
 
endif()
 
	ADD_DEFINITIONS(-DDEBUG)
 
	message("Debug             : yes")
 
else(CMAKE_BUILD_TYPE MATCHES Debug)
 
	message("Debug             : no (run \"cmake . -DCMAKE_BUILD_TYPE=Debug\")")
 
endif(CMAKE_BUILD_TYPE MATCHES Debug)
 

	
 

	
 
SET(TRANSPORT_VERSION 2.0)
 
SET(PROJECT_VERSION 2.0)
 
include_directories(include)
 

	
 

	
 
include_directories(${EVENT_INCLUDE_DIRS})
 
include_directories(${SWIFTEN_INCLUDE_DIR})
 
include_directories(${Boost_INCLUDE_DIRS})
 
include_directories(${OPENSSL_INCLUDE_DIR})
 

	
 
ADD_SUBDIRECTORY(src)
 
ADD_SUBDIRECTORY(plugin)
 
ADD_SUBDIRECTORY(include)
 
ADD_SUBDIRECTORY(spectrum)
 
ADD_SUBDIRECTORY(backends)
 
if (NOT WIN32)
 
	ADD_SUBDIRECTORY(spectrum_manager)
 
endif()
 

	
 
if (CPPUNIT_FOUND)
 
	message("tests             : yes")
 
	include_directories(${CPPUNIT_INCLUDE_DIR})
 
else()
 
	message("tests             : no (install CPPUnit)")
 
endif()
 

	
 
if(DOXYGEN_FOUND)
 
	message("Docs              : yes")
 
	ADD_SUBDIRECTORY(docs)
 
else(DOXYGEN_FOUND)
 
	message("Docs              : no (install doxygen)")
 
endif(DOXYGEN_FOUND)
 

	
 
message("----------------------")
ChangeLog
Show inline comments
 
Version 2.0.0-beta  (X-X-X):
 
	General:
 
	* Added PostreSQL support (thanks to Jadestorm).
 
	* Send presences only "from" bare JID (fixed bug with buddies appearing
 
	  twice in the roster and potential unregistering issues).
 
	* Fixed potential MySQL/SQLite3 deadlocks.
 
	* Fixed disconnecting in server-mode when client does not send unavailable
 
	  presence before disconnection.
 
	* Fixed crash in server-mode when client send its custom jabber:iq:storage
 
	  payload.
 
	* Fixed registration from Pidgin.
 
	* Unsubscribe presence sent to some buddy doesn't disconnect the account.
 
	* Remote Roster requests are not sent to resources, but to bare JID.
 
	* Added automatic reconnection in case of non-fatal error.
 
	* Added more error messages.
 

	
 
	Skype:
 
	* Initial support for Skype added, read more on
 
	  http://spectrum.im/projects/spectrum/wiki/Spectrum_2_Admin_-_Skype_backend
 

	
 
	SMSTools3:
 
	* Initial support for SMSTools3, read more on
 
	http://spectrum.im/projects/spectrum/wiki/Spectrum_2_Admin_-_SMSTools3_backend
 

	
 
version 2.0.0 alpha (2011-12-06):
 
	General:
 
	* First Spectrum 2.0.0 alpha release, check more on
 
	  http://spectrum.im/projects/spectrum/wiki/Spectrum_200_alpha
backends/CMakeLists.txt
Show inline comments
 
if (PROTOBUF_FOUND)
 
	if ( PURPLE_LIBRARY AND PURPLE_INCLUDE_DIR )
 
		ADD_SUBDIRECTORY(libpurple)
 
	endif()
 

	
 
	if (IRC_FOUND)
 
		ADD_SUBDIRECTORY(libcommuni)
 
	endif()
 

	
 
	ADD_SUBDIRECTORY(smstools3)
 

	
 
if (NOT WIN32)
 
	ADD_SUBDIRECTORY(frotz)
 
#	ADD_SUBDIRECTORY(skype)
 
	if (${LIBDBUSGLIB_FOUND})
 
		ADD_SUBDIRECTORY(skype)
 
	endif()
 
endif()
 

	
 
endif()
backends/frotz/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
 
ADD_SUBDIRECTORY(dfrotz)
 
 
FILE(GLOB SRC *.c *.cpp)
 
 
ADD_EXECUTABLE(spectrum2_frotz_backend ${SRC})
 
 
target_link_libraries(spectrum2_frotz_backend transport pthread transport-plugin ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
target_link_libraries(spectrum2_frotz_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
 
INSTALL(TARGETS spectrum2_frotz_backend RUNTIME DESTINATION bin)
 
backends/libcommuni/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp)
 
FILE(GLOB HEADERS *.h)
 
QT4_WRAP_CPP(SRC ${HEADERS})
 
ADD_EXECUTABLE(spectrum2_libcommuni_backend ${SRC})
 
 
target_link_libraries(spectrum2_libcommuni_backend ${IRC_LIBRARY} ${QT_LIBRARIES} transport-plugin transport pthread)
 
target_link_libraries(spectrum2_libcommuni_backend ${IRC_LIBRARY} ${QT_LIBRARIES} transport pthread)
 
 
INSTALL(TARGETS spectrum2_libcommuni_backend RUNTIME DESTINATION bin)
 
backends/skype/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp)
 

	
 
include_directories(/usr/include/dbus-1.0/)
 
include_directories(/usr/lib/dbus-1.0/include/)
 
include_directories(/usr/lib64/dbus-1.0/include/)
 
 
ADD_EXECUTABLE(spectrum2_skype_backend ${SRC})
 
 
target_link_libraries(spectrum2_skype_backend ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport pthread dbus-glib-1 dbus-1 gobject-2.0 transport-plugin)
 
target_link_libraries(spectrum2_skype_backend ${GLIB2_LIBRARIES} ${EVENT_LIBRARIES} transport pthread ${LIBDBUSGLIB_LIBRARIES})
 
 
INSTALL(TARGETS spectrum2_skype_backend RUNTIME DESTINATION bin)
 
backends/skype/geventloop.cpp
Show inline comments
 
deleted file
backends/skype/geventloop.h
Show inline comments
 
deleted file
backends/skype/main.cpp
Show inline comments
 
#include "glib.h"
 
#include <iostream>
 

	
 
#include "transport/config.h"
 
#include "transport/transport.h"
 
#include "transport/usermanager.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 "spectrumeventloop.h"
 
#include <boost/filesystem.hpp>
 
#include "geventloop.h"
 
#include "log4cxx/logger.h"
 
#include "log4cxx/consoleappender.h"
 
#include "log4cxx/patternlayout.h"
 
#include "log4cxx/propertyconfigurator.h"
 
#include "log4cxx/helpers/properties.h"
 
#include "log4cxx/helpers/fileinputstream.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
// #include "valgrind/memcheck.h"
 
#include "malloc.h"
 
#include <dbus-1.0/dbus/dbus-glib-lowlevel.h>
 

	
 

	
 
using namespace log4cxx;
 

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

	
 
using namespace Transport;
 

	
 
class SpectrumNetworkPlugin;
 

	
 

	
 
SpectrumNetworkPlugin *np;
 

	
 
static gboolean nodaemon = FALSE;
 
static gchar *logfile = NULL;
 
static gchar *lock_file = NULL;
 
static gchar *host = NULL;
 
static int port = 10000;
 
static gboolean ver = FALSE;
 
static gboolean list_purple_settings = FALSE;
 

	
 
int m_sock;
 
static int writeInput;
 

	
 
static GOptionEntry options_entries[] = {
 
	{ "nodaemon", 'n', 0, G_OPTION_ARG_NONE, &nodaemon, "Disable background daemon mode", NULL },
 
	{ "logfile", 'l', 0, G_OPTION_ARG_STRING, &logfile, "Set file to log", NULL },
 
	{ "pidfile", 'p', 0, G_OPTION_ARG_STRING, &lock_file, "File where to write transport PID", NULL },
 
	{ "version", 'v', 0, G_OPTION_ARG_NONE, &ver, "Shows Spectrum version", NULL },
 
	{ "list-purple-settings", 's', 0, G_OPTION_ARG_NONE, &list_purple_settings, "Lists purple settings which can be used in config file", NULL },
 
	{ "host", 'h', 0, G_OPTION_ARG_STRING, &host, "Host to connect to", NULL },
 
	{ "port", 'p', 0, G_OPTION_ARG_INT, &port, "Port to connect to", NULL },
 
	{ NULL, 0, 0, G_OPTION_ARG_NONE, NULL, "", NULL }
 
};
 

	
 
DBusHandlerResult skype_notify_handler(DBusConnection *connection, DBusMessage *message, gpointer user_data);
 

	
 
static pbnetwork::StatusType getStatus(const std::string &st) {
 
	pbnetwork::StatusType status = pbnetwork::STATUS_ONLINE;
 
	if (st == "SKYPEOUT" || st == "OFFLINE") {
 
		status = pbnetwork::STATUS_NONE;
 
	}
 
	else if (st == "DND") {
 
		status = pbnetwork::STATUS_DND;
 
	}
 
	else if (st == "NA") {
 
		status = pbnetwork::STATUS_XA;
 
	}
 
	else if (st == "AWAY") {
 
		status = pbnetwork::STATUS_AWAY;
 
	}
 
	return status;
 
}
 

	
 
class Skype {
 
	public:
 
		Skype(const std::string &user, const std::string &username, const std::string &password);
 
		~Skype() { logout(); }
 
		void login();
 
		void logout();
 
		std::string send_command(const std::string &message);
 

	
 
		const std::string &getUser() {
 
			return m_user;
 
		}
 

	
 
		const std::string &getUsername() {
 
			return m_username;
 
		}
 

	
 
		bool createDBusProxy();
 
		bool loadSkypeBuddies();
 

	
 
	private:
 
		std::string m_username;
 
		std::string m_password;
 
		GPid m_pid;
 
		DBusGConnection *m_connection;
 
		DBusGProxy *m_proxy;
 
		std::string m_user;
 
		int m_timer;
 
		int m_counter;
 
		int fd_output;
 
};
 

	
 
class SpectrumNetworkPlugin : public NetworkPlugin {
 
	public:
 
		SpectrumNetworkPlugin(Config *config, const std::string &host, int port) : NetworkPlugin() {
 
			this->config = config;
 
			LOG4CXX_INFO(logger, "Starting the backend.");
 
		}
 

	
 
		~SpectrumNetworkPlugin() {
 
			for (std::map<Skype *, std::string>::iterator it = m_accounts.begin(); it != m_accounts.end(); it++) {
 
				delete (*it).first;
 
			}
 
		}
 

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			std::string name = legacyName;
 
			name = name.substr(name.find(".") + 1);
 
			LOG4CXX_INFO(logger,  "Creating account with name '" << name);
 
			LOG4CXX_INFO(logger,  "Creating account with name '" << name << "'");
 

	
 
			Skype *skype = new Skype(user, name, password);
 
			m_sessions[user] = skype;
 
			m_accounts[skype] = user;
 

	
 
			skype->login();
 
		}
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
			Skype *skype = m_sessions[user];
 
			if (skype) {
 
				skype->logout();
 
				exit(1);
 
			}
 
		}
 

	
 
		void handleStatusChangeRequest(const std::string &user, int status, const std::string &statusMessage) {
 
			Skype *skype = m_sessions[user];
 
			if (!skype)
 
				return;
 

	
 
			std::string st;
 
			switch(status) {
 
				case Swift::StatusShow::Away: {
 
					st = "AWAY";
 
					break;
 
				}
 
				case Swift::StatusShow::DND: {
 
					st = "DND";
 
					break;
 
				}
 
				case Swift::StatusShow::XA: {
 
					st = "NA";
 
					break;
 
				}
 
				case Swift::StatusShow::None: {
 
					break;
 
				}
 
				case pbnetwork::STATUS_INVISIBLE:
 
					st = "INVISIBLE";
 
					break;
 
				default:
 
					st = "ONLINE";
 
					break;
 
			}
 
			skype->send_command("SET USERSTATUS " + st);
 

	
 
			if (!statusMessage.empty()) {
 
				skype->send_command("SET PROFILE MOOD_TEXT " + statusMessage);
 
			}
 
		}
 

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml) {
 
			Skype *skype = m_sessions[user];
 
			if (skype) {
 
				skype->send_command("MESSAGE " + legacyName + " " + message);
 
			}
 
			
 
		}
 

	
 
		void handleVCardRequest(const std::string &user, const std::string &legacyName, unsigned int id) {
 
			Skype *skype = m_sessions[user];
 
			if (skype) {
 
				std::string name = legacyName;
 
				if (name.find("skype.") == 0) {
 
					name = name.substr(6);
 
				}
 
				std::string photo;
 
				gchar *filename = NULL;
 
				gchar *new_filename = NULL;
 
				gchar *image_data = NULL;
 
				gsize image_data_len = 0;
 
				gchar *ret;
 
				int fh;
 
				GError *error;
 
				const gchar *userfiles[] = {"user256", "user1024", "user4096", "user16384", "user32768", "user65536",
 
											"profile256", "profile1024", "profile4096", "profile16384", "profile32768", 
 
											NULL};
 
				char *username = g_strdup_printf("\x03\x10%s", name.c_str());
 
				for (fh = 0; userfiles[fh]; fh++) {
 
					filename = g_strconcat("/tmp/skype/", skype->getUsername().c_str(), "/", skype->getUsername().c_str(), "/", userfiles[fh], ".dbb", NULL);
 
					std::cout << "getting filename:" << filename << "\n";
 
					if (g_file_get_contents(filename, &image_data, &image_data_len, NULL))
 
					{
 
						std::cout << "got\n";
 
						char *start = (char *)memmem(image_data, image_data_len, username, strlen(username)+1);
 
						if (start != NULL)
 
						{
 
							char *next = image_data;
 
							char *last = next;
 
							//find last index of l33l
 
							while ((next = (char *)memmem(next+4, start-next-4, "l33l", 4)))
 
							{
 
								last = next;
 
							}
 
							start = last;
 
							if (start != NULL)
 
							{
 
								char *img_start;
 
								//find end of l33l block
 
								char *end = (char *)memmem(start+4, image_data+image_data_len-start-4, "l33l", 4);
 
								if (!end) end = image_data+image_data_len;
 
								
 
								//look for start of JPEG block
 
								img_start = (char *)memmem(start, end-start, "\xFF\xD8", 2);
 
								if (img_start)
 
								{
 
									//look for end of JPEG block
 
									char *img_end = (char *)memmem(img_start, end-img_start, "\xFF\xD9", 2);
 
									if (img_end)
 
									{
 
										image_data_len = img_end - img_start + 2;
 
										photo = std::string(img_start, image_data_len);
 
									}
 
								}
 
							}
 
						}
 
						g_free(image_data);
 
					}
 
					g_free(filename);
 
				}
 
				g_free(username);
 
				
 
				std::string alias = "";
 
				std::cout << skype->getUsername() << " " << name << "\n";
 
				if (skype->getUsername() == name) {
 
					alias = skype->send_command("GET PROFILE FULLNAME");
 
					alias = alias.substr(17);
 
				}
 
				handleVCard(user, id, legacyName, "", alias, photo);
 
			}
 
		}
 

	
 
		void sendData(const std::string &string) {
 
			write(m_sock, string.c_str(), string.size());
 
// 			if (writeInput == 0)
 
// 				writeInput = purple_input_add(m_sock, PURPLE_INPUT_WRITE, &transportDataReceived, NULL);
 
		}
 

	
 
		void handleVCardUpdatedRequest(const std::string &user, const std::string &p, const std::string &nickname) {
 
		}
 

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

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

	
 
		}
 

	
 
		void handleBuddyBlockToggled(const std::string &user, const std::string &buddyName, bool blocked) {
 

	
 
		}
 

	
 
		void handleTypingRequest(const std::string &user, const std::string &buddyName) {
 

	
 
		}
 

	
 
		void handleTypedRequest(const std::string &user, const std::string &buddyName) {
 

	
 
		}
 

	
 
		void handleStoppedTypingRequest(const std::string &user, const std::string &buddyName) {
 

	
 
		}
 

	
 
		void handleAttentionRequest(const std::string &user, const std::string &buddyName, const std::string &message) {
 

	
 
		}
 

	
 
		std::map<std::string, Skype *> m_sessions;
 
		std::map<Skype *, std::string> m_accounts;
 
		std::map<std::string, unsigned int> m_vcards;
 
		Config *config;
 
		
 
};
 

	
 
		Skype::Skype(const std::string &user, const std::string &username, const std::string &password) {
 
			m_username = username;
 
			m_user = user;
 
			m_password = password;
 
			m_pid = 0;
 
			m_connection = 0;
 
			m_proxy = 0;
 
		}
 

	
 
		void Skype::login() {
 
			boost::filesystem::path	path(std::string("/tmp/skype/") + m_username);
 
			if (!boost::filesystem::exists(path)) {
 
				boost::filesystem::create_directories(path);
 
				boost::filesystem::path	path2(std::string("/tmp/skype/") + m_username + "/" + m_username );
 
				boost::filesystem::create_directories(path2);
 
			}
 

	
 
			std::string shared_xml = "<?xml version=\"1.0\"?>\n"
 
									"<config version=\"1.0\" serial=\"28\" timestamp=\"" + boost::lexical_cast<std::string>(time(NULL)) + ".0\">\n"
 
									"<UI>\n"
 
										"<Installed>2</Installed>\n"
 
										"<Language>en</Language>\n"
 
									"</UI>\n"
 
									"</config>\n";
 
			g_file_set_contents(std::string(std::string("/tmp/skype/") + m_username + "/shared.xml").c_str(), shared_xml.c_str(), -1, NULL);
 

	
 
			std::string config_xml = "<?xml version=\"1.0\"?>\n"
 
									"<config version=\"1.0\" serial=\"7\" timestamp=\"" + boost::lexical_cast<std::string>(time(NULL)) + ".0\">\n"
 
										"<Lib>\n"
 
											"<Account>\n"
 
											"<IdleTimeForAway>30000000</IdleTimeForAway>\n"
 
											"<IdleTimeForNA>300000000</IdleTimeForNA>\n"
 
											"<LastUsed>" + boost::lexical_cast<std::string>(time(NULL)) + "</LastUsed>\n"
 
											"</Account>\n"
 
										"</Lib>\n"
 
										"<UI>\n"
 
											"<API>\n"
 
											"<Authorizations>Spectrum</Authorizations>\n"
 
											"<BlockedPrograms></BlockedPrograms>\n"
 
											"</API>\n"
 
										"</UI>\n"
 
									"</config>\n";
 
			g_file_set_contents(std::string(std::string("/tmp/skype/") + m_username + "/" + m_username +"/config.xml").c_str(), config_xml.c_str(), -1, NULL);
 
			std::string db_path = std::string("/tmp/skype/") + m_username;
 
			char *db = (char *) malloc(db_path.size() + 1);
 
			strcpy(db, db_path.c_str());
 
			LOG4CXX_INFO(logger,  m_username << ": Spawning new Skype instance dbpath=" << db);
 
			gchar* argv[6] = {"skype", "--disable-cleanlooks", "--pipelogin", "--dbpath", db, 0};
 

	
 
			int fd;
 
			int fd_output;
 
			g_spawn_async_with_pipes(NULL,
 
				argv,
 
				NULL /*envp*/,
 
				G_SPAWN_SEARCH_PATH,
 
				NULL /*child_setup*/,
 
				NULL /*user_data*/,
 
				&m_pid /*child_pid*/,
 
				&fd,
 
				NULL,
 
				&fd_output,
 
				NULL /*error*/);
 
			std::string login_data = std::string(m_username + " " + m_password + "\n");
 
			LOG4CXX_INFO(logger,  m_username << ": Login data=" << login_data);
 
			write(fd, login_data.c_str(), login_data.size());
 
			close(fd);
 
			
 
			fcntl (fd_output, F_SETFL, O_NONBLOCK);
 
Skype::Skype(const std::string &user, const std::string &username, const std::string &password) {
 
	m_username = username;
 
	m_user = user;
 
	m_password = password;
 
	m_pid = 0;
 
	m_connection = 0;
 
	m_proxy = 0;
 
	m_timer = -1;
 
	m_counter = 0;
 
}
 

	
 
			free(db);
 

	
 
			sleep(2);
 
static gboolean load_skype_buddies(gpointer data) {
 
	Skype *skype = (Skype *) data;
 
	return skype->loadSkypeBuddies();
 
}
 

	
 
			GError *error = NULL;
 
			DBusObjectPathVTable vtable;
 
bool Skype::createDBusProxy() {
 
	if (m_proxy == NULL) {
 
		LOG4CXX_INFO(logger, "Creating DBus proxy for com.Skype.Api.");
 
		m_counter++;
 

	
 
			//Initialise threading
 
			dbus_threads_init_default();
 
			
 
			if (m_connection == NULL)
 
			{
 
				m_connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error);
 
				if (m_connection == NULL && error != NULL)
 
				{
 
					LOG4CXX_INFO(logger,  m_username << ": DBUS Error: " << error->message);
 
					g_error_free(error);
 
					return;
 
				}
 
			}
 
			
 
			if (m_proxy == NULL)
 
			{
 
				m_proxy = dbus_g_proxy_new_for_name_owner (m_connection,
 
												"com.Skype.API",
 
												"/com/Skype",
 
												"com.Skype.API",
 
												&error);
 
				if (m_proxy == NULL && error != NULL)
 
				{
 
					LOG4CXX_INFO(logger,  m_username << ":" << error->message);
 
					g_error_free(error);
 
				}
 
				
 
				vtable.message_function = &skype_notify_handler;
 
				dbus_connection_register_object_path(dbus_g_connection_get_connection(m_connection), "/com/Skype/Client", &vtable, this);
 
			}
 
		GError *error = NULL;
 
		m_proxy = dbus_g_proxy_new_for_name_owner (m_connection, "com.Skype.API", "/com/Skype", "com.Skype.API", &error);
 
		if (m_proxy == NULL && error != NULL) {
 
			LOG4CXX_INFO(logger,  m_username << ":" << error->message);
 

	
 
			int counter = 0;
 
			std::string re = "CONNSTATUS OFFLINE";
 
			while (re == "CONNSTATUS OFFLINE" || re.empty()) {
 
				sleep(1);
 
				gchar buffer[1024];
 
				int bytes_read;
 
				bytes_read = read (fd_output, buffer, 1023);
 
				if (bytes_read > 0) {
 
					buffer[bytes_read] = 0;
 
					np->handleDisconnected(m_user, 0, buffer);
 
					close(fd_output);
 
					logout();
 
					return;
 
				}
 
				re = send_command("NAME Spectrum");
 
				if (counter++ > 15)
 
					break;
 
			if (m_counter == 15) {
 
				np->handleDisconnected(m_user, 0, error->message);
 
				logout();
 
				g_error_free(error);
 
				return FALSE;
 
			}
 
			g_error_free(error);
 
		}
 

	
 
			close(fd_output);
 
		if (m_proxy) {
 
			LOG4CXX_INFO(logger, "Proxy created.");
 
			DBusObjectPathVTable vtable;
 
			vtable.message_function = &skype_notify_handler;
 
			dbus_connection_register_object_path(dbus_g_connection_get_connection(m_connection), "/com/Skype/Client", &vtable, this);
 

	
 
			if (send_command("PROTOCOL 7") != "PROTOCOL 7") {
 
				np->handleDisconnected(m_user, 0, "Skype is not ready");
 
				logout();
 
				return;
 
			}
 
			
 
			np->handleConnected(m_user);
 

	
 
			std::map<std::string, std::string> group_map;
 
			std::string groups = send_command("SEARCH GROUPS CUSTOM");
 
			groups = groups.substr(groups.find(' ') + 1);
 
			std::vector<std::string> grps;
 
			boost::split(grps, groups, boost::is_any_of(","));
 
			BOOST_FOREACH(std::string grp, grps) {
 
				std::vector<std::string> data;
 
				std::string name = send_command("GET GROUP " + grp + " DISPLAYNAME");
 
				boost::split(data, name, boost::is_any_of(" "));
 
				name = name.substr(name.find("DISPLAYNAME") + 12);
 

	
 
				std::string users = send_command("GET GROUP " + data[1] + " USERS");
 
				users = name.substr(name.find("USERS") + 6);
 
				boost::split(data, users, boost::is_any_of(","));
 
				BOOST_FOREACH(std::string u, data) {
 
					group_map[u] = grp;
 
				}
 
			}
 
			m_counter = 0;
 
			m_timer = g_timeout_add_seconds(1, load_skype_buddies, this);
 
			return FALSE;
 
		}
 
		return TRUE;
 
	}
 
	return FALSE;
 
}
 

	
 
			std::string friends = send_command("GET AUTH_CONTACTS_PROFILES");
 
static gboolean create_dbus_proxy(gpointer data) {
 
	Skype *skype = (Skype *) data;
 
	return skype->createDBusProxy();
 
}
 

	
 
			char **full_friends_list = g_strsplit((strchr(friends.c_str(), ' ')+1), ";", 0);
 
			if (full_friends_list && full_friends_list[0])
 
			{
 
				//in the format of: username;full name;phone;office phone;mobile phone;
 
				//                  online status;friendly name;voicemail;mood
 
				// (comma-seperated lines, usernames can have comma's)
 
void Skype::login() {
 
	boost::filesystem::path	path(std::string("/tmp/skype/") + m_username);
 
	if (!boost::filesystem::exists(path)) {
 
		boost::filesystem::create_directories(path);
 
		boost::filesystem::path	path2(std::string("/tmp/skype/") + m_username + "/" + m_username );
 
		boost::filesystem::create_directories(path2);
 
	}
 

	
 
	std::string shared_xml = "<?xml version=\"1.0\"?>\n"
 
							"<config version=\"1.0\" serial=\"28\" timestamp=\"" + boost::lexical_cast<std::string>(time(NULL)) + ".0\">\n"
 
							"<UI>\n"
 
								"<Installed>2</Installed>\n"
 
								"<Language>en</Language>\n"
 
							"</UI>\n"
 
							"</config>\n";
 
	g_file_set_contents(std::string(std::string("/tmp/skype/") + m_username + "/shared.xml").c_str(), shared_xml.c_str(), -1, NULL);
 

	
 
	std::string config_xml = "<?xml version=\"1.0\"?>\n"
 
							"<config version=\"1.0\" serial=\"7\" timestamp=\"" + boost::lexical_cast<std::string>(time(NULL)) + ".0\">\n"
 
								"<Lib>\n"
 
									"<Account>\n"
 
									"<IdleTimeForAway>30000000</IdleTimeForAway>\n"
 
									"<IdleTimeForNA>300000000</IdleTimeForNA>\n"
 
									"<LastUsed>" + boost::lexical_cast<std::string>(time(NULL)) + "</LastUsed>\n"
 
									"</Account>\n"
 
								"</Lib>\n"
 
								"<UI>\n"
 
									"<API>\n"
 
									"<Authorizations>Spectrum</Authorizations>\n"
 
									"<BlockedPrograms></BlockedPrograms>\n"
 
									"</API>\n"
 
								"</UI>\n"
 
							"</config>\n";
 
	g_file_set_contents(std::string(std::string("/tmp/skype/") + m_username + "/" + m_username +"/config.xml").c_str(), config_xml.c_str(), -1, NULL);
 

	
 
	std::string db_path = std::string("/tmp/skype/") + m_username;
 
	char *db = (char *) malloc(db_path.size() + 1);
 
	strcpy(db, db_path.c_str());
 
	LOG4CXX_INFO(logger,  m_username << ": Spawning new Skype instance dbpath=" << db);
 
	gchar* argv[6] = {"skype", "--disable-cleanlooks", "--pipelogin", "--dbpath", db, 0};
 

	
 
	int fd;
 
	g_spawn_async_with_pipes(NULL,
 
		argv,
 
		NULL /*envp*/,
 
		G_SPAWN_SEARCH_PATH,
 
		NULL /*child_setup*/,
 
		NULL /*user_data*/,
 
		&m_pid /*child_pid*/,
 
		&fd,
 
		NULL,
 
		&fd_output,
 
		NULL /*error*/);
 
	std::string login_data = std::string(m_username + " " + m_password + "\n");
 
	LOG4CXX_INFO(logger,  m_username << ": Login data=" << login_data);
 
	write(fd, login_data.c_str(), login_data.size());
 
	close(fd);
 

	
 
	fcntl (fd_output, F_SETFL, O_NONBLOCK);
 

	
 
	free(db);
 

	
 
	//Initialise threading
 
	dbus_threads_init_default();
 

	
 
	if (m_connection == NULL)
 
	{
 
		LOG4CXX_INFO(logger, "Creating DBus connection.");
 
		GError *error = NULL;
 
		m_connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error);
 
		if (m_connection == NULL && error != NULL)
 
		{
 
			LOG4CXX_INFO(logger,  m_username << ": DBUS Error: " << error->message);
 
			g_error_free(error);
 
			return;
 
		}
 
	}
 

	
 
				for (int i=0; full_friends_list[i] && *full_friends_list[i] != '\0'; i+=8)
 
				{
 
					std::string buddy = full_friends_list[i];
 
	m_timer = g_timeout_add_seconds(1, create_dbus_proxy, this);
 
}
 

	
 
					if (buddy[0] == ',') {
 
						buddy.erase(buddy.begin());
 
					}
 
					std::cout << "BUDDY '" << buddy << "'\n";
 
					std::string st = full_friends_list[i + 5];
 
					
 
					pbnetwork::StatusType status = getStatus(st);
 
bool Skype::loadSkypeBuddies() {
 
//	std::string re = "CONNSTATUS OFFLINE";
 
//	while (re == "CONNSTATUS OFFLINE" || re.empty()) {
 
//		sleep(1);
 

	
 
	gchar buffer[1024];
 
	int bytes_read = read(fd_output, buffer, 1023);
 
	if (bytes_read > 0) {
 
		buffer[bytes_read] = 0;
 
		np->handleDisconnected(m_user, 0, buffer);
 
		close(fd_output);
 
		logout();
 
		return FALSE;
 
	}
 

	
 
					std::string alias = full_friends_list[i + 6];
 
	std::string re = send_command("NAME Spectrum");
 
	if (m_counter++ > 15) {
 
		np->handleDisconnected(m_user, 0, "");
 
		close(fd_output);
 
		logout();
 
		return FALSE;
 
	}
 

	
 
					std::string mood_text = "";
 
					if (full_friends_list[i + 8] && *full_friends_list[i + 8] != '\0' && *full_friends_list[i + 8] != ',') {
 
						mood_text = full_friends_list[i + 8];
 
						i++;
 
					}
 
	if (re.empty() || re == "CONNSTATUS OFFLINE") {
 
		return TRUE;
 
	}
 

	
 
					std::vector<std::string> groups;
 
					groups.push_back(group_map[buddy]);
 
					np->handleBuddyChanged(m_user, buddy, alias, groups, status, mood_text);
 
				}
 
	close(fd_output);
 

	
 
	if (send_command("PROTOCOL 7") != "PROTOCOL 7") {
 
		np->handleDisconnected(m_user, 0, "Skype is not ready");
 
		logout();
 
		return FALSE;
 
	}
 

	
 
	np->handleConnected(m_user);
 

	
 
	std::map<std::string, std::string> group_map;
 
	std::string groups = send_command("SEARCH GROUPS CUSTOM");
 
	groups = groups.substr(groups.find(' ') + 1);
 
	std::vector<std::string> grps;
 
	boost::split(grps, groups, boost::is_any_of(","));
 
	BOOST_FOREACH(std::string grp, grps) {
 
		std::vector<std::string> data;
 
		std::string name = send_command("GET GROUP " + grp + " DISPLAYNAME");
 
		boost::split(data, name, boost::is_any_of(" "));
 
		name = name.substr(name.find("DISPLAYNAME") + 12);
 

	
 
		std::string users = send_command("GET GROUP " + data[1] + " USERS");
 
		users = name.substr(name.find("USERS") + 6);
 
		boost::split(data, users, boost::is_any_of(","));
 
		BOOST_FOREACH(std::string u, data) {
 
			group_map[u] = grp;
 
		}
 
	}
 

	
 
	std::string friends = send_command("GET AUTH_CONTACTS_PROFILES");
 

	
 
	char **full_friends_list = g_strsplit((strchr(friends.c_str(), ' ')+1), ";", 0);
 
	if (full_friends_list && full_friends_list[0])
 
	{
 
		//in the format of: username;full name;phone;office phone;mobile phone;
 
		//                  online status;friendly name;voicemail;mood
 
		// (comma-seperated lines, usernames can have comma's)
 

	
 
		for (int i=0; full_friends_list[i] && *full_friends_list[i] != '\0'; i+=8)
 
		{
 
			std::string buddy = full_friends_list[i];
 

	
 
			if (buddy[0] == ',') {
 
				buddy.erase(buddy.begin());
 
			}
 
			g_strfreev(full_friends_list);
 
			
 
			send_command("SET AUTOAWAY OFF");
 
		}
 

	
 
		void Skype::logout() {
 
			if (m_pid != 0) {
 
				send_command("SET USERSTATUS INVISIBLE");
 
				send_command("SET USERSTATUS OFFLINE");
 
				sleep(2);
 
				g_object_unref(m_proxy);
 
				LOG4CXX_INFO(logger,  m_username << ": Killing Skype instance");
 
				kill((int) m_pid, SIGTERM);
 
				m_pid = 0;
 

	
 
			if (buddy.rfind(",") != std::string::npos) {
 
				buddy = buddy.substr(buddy.rfind(","));
 
			}
 

	
 
			if (buddy[0] == ',') {
 
				buddy.erase(buddy.begin());
 
			}
 

	
 
			LOG4CXX_INFO(logger, "Got buddy " << buddy);
 
			std::string st = full_friends_list[i + 5];
 

	
 
			pbnetwork::StatusType status = getStatus(st);
 

	
 
			std::string alias = full_friends_list[i + 6];
 

	
 
			std::string mood_text = "";
 
			if (full_friends_list[i + 8] && *full_friends_list[i + 8] != '\0' && *full_friends_list[i + 8] != ',') {
 
				mood_text = full_friends_list[i + 8];
 
			}
 

	
 
			std::vector<std::string> groups;
 
			if (group_map.find(buddy) != group_map.end()) {
 
				groups.push_back(group_map[buddy]);
 
			}
 
			np->handleBuddyChanged(m_user, buddy, alias, groups, status, mood_text);
 
		}
 
	}
 
	g_strfreev(full_friends_list);
 

	
 
		std::string Skype::send_command(const std::string &message) {
 
			GError *error = NULL;
 
			gchar *str = NULL;
 
	send_command("SET AUTOAWAY OFF");
 
	send_command("SET USERSTATUS ONLINE");
 
	return FALSE;
 
}
 

	
 
void Skype::logout() {
 
	if (m_pid != 0) {
 
		send_command("SET USERSTATUS INVISIBLE");
 
		send_command("SET USERSTATUS OFFLINE");
 
		sleep(2);
 
		g_object_unref(m_proxy);
 
		LOG4CXX_INFO(logger,  m_username << ": Killing Skype instance");
 
		kill((int) m_pid, SIGTERM);
 
		m_pid = 0;
 
	}
 
}
 

	
 
std::string Skype::send_command(const std::string &message) {
 
	GError *error = NULL;
 
	gchar *str = NULL;
 
// 			int message_num;
 
// 			gchar error_return[30];
 
			
 
			if (!dbus_g_proxy_call (m_proxy, "Invoke", &error, G_TYPE_STRING, message.c_str(), G_TYPE_INVALID,
 
								G_TYPE_STRING, &str, G_TYPE_INVALID))
 
			{
 
					if (error && error->message)
 
					{
 
					LOG4CXX_INFO(logger,  m_username << ": DBUS Error: " << error->message);
 
					g_error_free(error);
 
				} else {
 
					LOG4CXX_INFO(logger,  m_username << ": DBUS no response");
 
				}
 
				
 
			}
 
			if (str != NULL)
 

	
 
	if (!dbus_g_proxy_call (m_proxy, "Invoke", &error, G_TYPE_STRING, message.c_str(), G_TYPE_INVALID,
 
						G_TYPE_STRING, &str, G_TYPE_INVALID))
 
	{
 
			if (error && error->message)
 
			{
 
				LOG4CXX_INFO(logger,  m_username << ": DBUS:" << str);
 
			}
 
			return str ? std::string(str) : std::string();
 
			LOG4CXX_INFO(logger,  m_username << ": DBUS Error: " << error->message);
 
			g_error_free(error);
 
		} else {
 
			LOG4CXX_INFO(logger,  m_username << ": DBUS no response");
 
		}
 

	
 
	}
 
	if (str != NULL)
 
	{
 
		LOG4CXX_INFO(logger,  m_username << ": DBUS:" << str);
 
	}
 
	return str ? std::string(str) : std::string();
 
}
 

	
 
static void handle_skype_message(std::string &message, Skype *sk) {
 
	std::vector<std::string> cmd;
 
	boost::split(cmd, message, boost::is_any_of(" "));
 

	
 
	if (cmd[0] == "USER") {
 
		if (cmd[1] == sk->getUsername()) {
 
			return;
 
		}
 

	
 
		if (cmd[2] == "ONLINESTATUS") {
 
			if (cmd[3] == "SKYPEOUT" || cmd[3] == "UNKNOWN") {
 
				return;
 
			}
 
			else {
 
				pbnetwork::StatusType status = getStatus(cmd[3]);
 
				std::string mood_text = sk->send_command("GET USER " + cmd[1] + " MOOD_TEXT");
 
				mood_text = mood_text.substr(mood_text.find("MOOD_TEXT") + 10);
 

	
 
				std::string alias = sk->send_command("GET USER " + cmd[1] + " FULLNAME");
 
				alias = alias.substr(alias.find("FULLNAME") + 9);
 

	
 
				std::vector<std::string> groups;
 
				np->handleBuddyChanged(sk->getUser(), cmd[1], alias, groups, status, mood_text);
 
			}
 
		}
 
		else if (cmd[2] == "MOOD_TEXT") {
 
			std::string st = sk->send_command("GET USER " + cmd[1] + " ONLINESTATUS");
 
			st = st.substr(st.find("ONLINESTATUS") + 13);
 
			pbnetwork::StatusType status = getStatus(st);
 

	
 
			std::string mood_text = message.substr(message.find("MOOD_TEXT") + 10);
 

	
 
			std::vector<std::string> groups;
 
			np->handleBuddyChanged(sk->getUser(), cmd[1], "", groups, status, mood_text);
 
		}
 
		else if (cmd[2] == "BUDDYSTATUS" && cmd[3] == "3") {
 
			std::string st = sk->send_command("GET USER " + cmd[1] + " ONLINESTATUS");
 
			st = st.substr(st.find("ONLINESTATUS") + 13);
 
			pbnetwork::StatusType status = getStatus(st);
 

	
 
			std::string mood_text = message.substr(message.find("MOOD_TEXT") + 10);
 

	
 
			std::vector<std::string> groups;
 
			np->handleBuddyChanged(sk->getUser(), cmd[1], "", groups, status, mood_text);
 
		}
 
	}
 
	else if (cmd[0] == "CHATMESSAGE") {
 
		if (cmd[3] == "RECEIVED") {
 
			std::string body = sk->send_command("GET CHATMESSAGE " + cmd[1] + " BODY");
 
			body = body.substr(body.find("BODY") + 5);
 

	
 
			std::string chatname = sk->send_command("GET CHATMESSAGE " + cmd[1] + " CHATNAME");
 
			size_t start = chatname.find("$") + 1;
 
			size_t len = chatname.find(";") - start;
 
			std::string from = chatname.substr(start, len);
 

	
 
			std::string from_handle = sk->send_command("GET CHATMESSAGE " + cmd[1] + " FROM_HANDLE");
 
			from_handle = from_handle.substr(from_handle.find("FROM_HANDLE") + 12);
 

	
 
// 			if (from_handle != sk->getUsername()) {
 
				from = from_handle;
 
// 			}
 
			if (from_handle == sk->getUsername())
 
				return;
 

	
 
			np->handleMessage(sk->getUser(), from, body);
 
		}
 
	}
 
}
 

	
 
DBusHandlerResult skype_notify_handler(DBusConnection *connection, DBusMessage *message, gpointer user_data) {
 
	DBusMessageIter iterator;
 
	gchar *message_temp;
 
	DBusMessage *temp_message;
 
	
 
	temp_message = dbus_message_ref(message);
 
	dbus_message_iter_init(temp_message, &iterator);
 
	if (dbus_message_iter_get_arg_type(&iterator) != DBUS_TYPE_STRING)
 
	{
 
		dbus_message_unref(message);
 
		return (DBusHandlerResult) FALSE;
 
	}
 
	
 
	do {
 
		dbus_message_iter_get_basic(&iterator, &message_temp);
 
		std::string m(message_temp);
 
		LOG4CXX_INFO(logger,"DBUS message: " << m);
 
		handle_skype_message(m, (Skype *) user_data);
 
	} while(dbus_message_iter_has_next(&iterator) && dbus_message_iter_next(&iterator));
 
	
 
	dbus_message_unref(message);
 
	
 
	return DBUS_HANDLER_RESULT_HANDLED;
 
}
 

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

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

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

	
 
static int create_socket(char *host, int portno) {
 
	struct sockaddr_in serv_addr;
 
	
 
	int m_sock = socket(AF_INET, SOCK_STREAM, 0);
 
	memset((char *) &serv_addr, 0, sizeof(serv_addr));
 
	serv_addr.sin_family = AF_INET;
 
	serv_addr.sin_port = htons(portno);
 

	
 
	hostent *hos;  // Resolve name
 
	if ((hos = gethostbyname(host)) == NULL) {
 
		// strerror() will not work for gethostbyname() and hstrerror() 
 
		// is supposedly obsolete
 
		exit(1);
 
	}
 
	serv_addr.sin_addr.s_addr = *((unsigned long *) hos->h_addr_list[0]);
 

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

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

	
 

	
 
static gboolean transportDataReceived(GIOChannel *source, GIOCondition condition, gpointer data) {
 
	char buffer[65535];
 
	char *ptr = buffer;
 
	ssize_t n = read(m_sock, ptr, sizeof(buffer));
 
	if (n <= 0) {
 
		LOG4CXX_INFO(logger, "Diconnecting from spectrum2 server");
 
		exit(errno);
 
	}
 
	std::string d = std::string(buffer, n);
 
	np->handleDataRead(d);
 
	return TRUE;
 
}
 

	
 
static void io_destroy(gpointer data) {
 
	exit(1);
 
}
 

	
 
static void log_glib_error(const gchar *string) {
 
	LOG4CXX_ERROR(logger, "GLIB ERROR:" << string);
 
}
 

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

	
 
	if (ver) {
 
// 		std::cout << VERSION << "\n";
 
		std::cout << "verze\n";
 
		g_option_context_free(context);
 
		return 0;
 
	}
 

	
 
	if (argc != 2) {
 
#ifdef WIN32
 
		std::cout << "Usage: spectrum.exe <configuration_file.cfg>\n";
 
#else
 

	
 
#if GLIB_CHECK_VERSION(2,14,0)
 
	std::cout << g_option_context_get_help(context, FALSE, NULL);
 
#else
 
	std::cout << "Usage: spectrum <configuration_file.cfg>\n";
 
	std::cout << "See \"man spectrum\" for more info.\n";
 
#endif
 
		
 
#endif
 
	}
 
	else {
 
#ifndef WIN32
 
		signal(SIGPIPE, SIG_IGN);
 

	
 
		if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
 
			std::cout << "SIGCHLD handler can't be set\n";
 
			g_option_context_free(context);
 
			return -1;
 
		}
 
// 
 
// 		if (signal(SIGINT, spectrum_sigint_handler) == SIG_ERR) {
 
// 			std::cout << "SIGINT handler can't be set\n";
 
// 			g_option_context_free(context);
 
// 			return -1;
 
// 		}
 
// 
 
// 		if (signal(SIGTERM, spectrum_sigterm_handler) == SIG_ERR) {
 
// 			std::cout << "SIGTERM handler can't be set\n";
 
// 			g_option_context_free(context);
 
// 			return -1;
 
// 		}
 
// 
 
// 		struct sigaction sa;
 
// 		memset(&sa, 0, sizeof(sa)); 
 
// 		sa.sa_handler = spectrum_sighup_handler;
 
// 		if (sigaction(SIGHUP, &sa, NULL)) {
 
// 			std::cout << "SIGHUP handler can't be set\n";
 
// 			g_option_context_free(context);
 
// 			return -1;
 
//		}
 
#endif
 
		Config config;
 
		if (!config.load(argv[1])) {
 
			std::cout << "Can't open " << argv[1] << " configuration file.\n";
 
			return 1;
 
		}
 

	
 
		if (CONFIG_STRING(&config, "logging.backend_config").empty()) {
 
			LoggerPtr root = log4cxx::Logger::getRootLogger();
 
			root->addAppender(new ConsoleAppender(new PatternLayout("%d %-5p %c: %m%n")));
 
		}
 
		else {
 
			log4cxx::helpers::Properties p;
 
			log4cxx::helpers::FileInputStream *istream = new log4cxx::helpers::FileInputStream(CONFIG_STRING(&config, "logging.backend_config"));
 

	
 
			p.load(istream);
 
			p.setProperty("pid", boost::lexical_cast<std::string>(getpid()));
 
			log4cxx::PropertyConfigurator::configure(p);
 
		}
 

	
 
// 		initPurple(config);
 

	
 
		g_type_init();
 

	
 
		m_sock = create_socket(host, port);
 

	
 
		g_set_printerr_handler(log_glib_error);
 

	
 
	GIOChannel *channel;
 
	GIOCondition cond = (GIOCondition) READ_COND;
 
	GIOCondition cond = (GIOCondition) G_IO_IN;
 
	channel = g_io_channel_unix_new(m_sock);
 
	g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, cond, transportDataReceived, NULL, io_destroy);
 

	
 
		np = new SpectrumNetworkPlugin(&config, host, port);
 

	
 
		GMainLoop *m_loop;
 
		m_loop = g_main_loop_new(NULL, FALSE);
 

	
 
		if (m_loop) {
 
			g_main_loop_run(m_loop);
 
		}
 
	}
 

	
 
	g_option_context_free(context);
 
}
backends/skype/spectrumeventloop.cpp
Show inline comments
 
deleted file
backends/skype/spectrumeventloop.h
Show inline comments
 
deleted file
backends/smstools3/CMakeLists.txt
Show inline comments
 
new file 100644
 
cmake_minimum_required(VERSION 2.6)
 
 
FILE(GLOB SRC *.c *.cpp)
 
 
ADD_EXECUTABLE(spectrum2_smstools3_backend ${SRC})
 
 
target_link_libraries(spectrum2_smstools3_backend transport pthread ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
 
INSTALL(TARGETS spectrum2_smstools3_backend RUNTIME DESTINATION bin)
 
backends/smstools3/main.cpp
Show inline comments
 
new file 100644
 
/*
 
 * Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
 
 *
 
 * This example is free, and not covered by LGPL license. There is no
 
 * restriction applied to their modification, redistribution, using and so on.
 
 * You can study them, modify them, use them in your own program - either
 
 * completely or partially. By using it you may give me some credits in your
 
 * program, but you don't have to.
 
 */
 

	
 
#include "transport/config.h"
 
#include "transport/networkplugin.h"
 
#include "transport/sqlite3backend.h"
 
#include "transport/mysqlbackend.h"
 
#include "transport/pqxxbackend.h"
 
#include "transport/storagebackend.h"
 
#include "Swiften/Swiften.h"
 
#include <boost/filesystem.hpp>
 
#include "unistd.h"
 
#include "signal.h"
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
#include <fstream>
 
#include <streambuf>
 

	
 
Swift::SimpleEventLoop *loop_;
 

	
 
#include "log4cxx/logger.h"
 
#include "log4cxx/consoleappender.h"
 
#include "log4cxx/patternlayout.h"
 
#include "log4cxx/propertyconfigurator.h"
 
#include "log4cxx/helpers/properties.h"
 
#include "log4cxx/helpers/fileinputstream.h"
 
#include "log4cxx/helpers/transcoder.h"
 
#include <boost/filesystem.hpp>
 
#include <boost/algorithm/string.hpp>
 

	
 
using namespace boost::filesystem;
 

	
 
using namespace boost::program_options;
 
using namespace Transport;
 

	
 
using namespace log4cxx;
 

	
 
static LoggerPtr logger = log4cxx::Logger::getLogger("SMSNetworkPlugin");
 

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

	
 
class SMSNetworkPlugin;
 
SMSNetworkPlugin * np = NULL;
 
StorageBackend *storageBackend;
 

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

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

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

	
 
			m_timer = m_factories->getTimerFactory()->createTimer(5000);
 
			m_timer->onTick.connect(boost::bind(&SMSNetworkPlugin::handleSMSDir, this));
 
			m_timer->start();
 

	
 
			// We're reusing our database model here. Buddies of user with JID INTERNAL_USER are there
 
			// to match received GSM messages from number N with the XMPP users who sent message to number N.
 
			// BuddyName = GSM number
 
			// Alias = XMPP user JID to which the messages from this number is sent to.
 
			// TODO: This should be per Modem!!!
 
			UserInfo info;
 
			info.jid = INTERNAL_USER;
 
			info.password = "";
 
			storageBackend->setUser(info);
 
			storageBackend->getUser(INTERNAL_USER, info);
 
			m_internalUser = info.id;
 
		}
 

	
 

	
 
		void handleSMS(const std::string &sms) {
 
			LOG4CXX_INFO(logger, "Handling SMS " << sms << ".")
 
			std::ifstream t(sms.c_str());
 
			std::string str;
 

	
 
			t.seekg(0, std::ios::end);
 
			str.reserve(t.tellg());
 
			t.seekg(0, std::ios::beg);
 

	
 
			str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
 

	
 
			std::string from = "";
 
			std::string msg = "";
 
			while(str.find("\n") != std::string::npos) {
 
				std::string line = str.substr(0, str.find("\n"));
 
				if (line.find("From: ") == 0) {
 
					from = line.substr(strlen("From: "));
 
				}
 
				else if (line.empty()) {
 
					msg = str.substr(1);
 
					break;
 
				}
 
				str = str.substr(str.find("\n") + 1);
 
			}
 

	
 
			std::list<BuddyInfo> roster;
 
			storageBackend->getBuddies(m_internalUser, roster);
 

	
 
			std::string to;
 
			BOOST_FOREACH(BuddyInfo &b, roster) {
 
				if (b.legacyName == from) {
 
					to = b.alias;
 
				}
 
			}
 

	
 
			if (to.empty()) {
 
				LOG4CXX_WARN(logger, "Received SMS from " << from << ", but this number is not associated with any XMPP user.");
 
			}
 

	
 
			LOG4CXX_INFO(logger, "Forwarding SMS from " << from << " to " << to << ".");
 
			handleMessage(to, from, msg);
 
		}
 

	
 
		void handleSMSDir() {
 
			std::string dir = "/var/spool/sms/incoming/";
 
			if (config->getUnregistered().find("backend.incoming_dir") != config->getUnregistered().end()) {
 
				dir = config->getUnregistered().find("backend.incoming_dir")->second;
 
			}
 
			LOG4CXX_INFO(logger, "Checking directory " << dir << " for incoming SMS.");
 

	
 
			path p(dir);
 
			directory_iterator end_itr;
 
			for (directory_iterator itr(p); itr != end_itr; ++itr) {
 

	
 
				try {
 
					if (is_regular(itr->path())) {
 
						handleSMS(itr->path().string());
 
						remove(itr->path());
 
					}
 
				}
 
				catch (const filesystem_error& ex) {
 
					LOG4CXX_ERROR(logger, "Error when removing the SMS: " << ex.what() << ".");
 
				}
 
			}
 
			m_timer->start();
 
		}
 

	
 
		void sendSMS(const std::string &to, const std::string &msg) {
 
			// TODO: Probably 
 
			std::string data = "To: " + to + "\n";
 
			data += "\n";
 
			data += msg;
 

	
 
			// generate random string here...
 
			std::string bucket = "abcdefghijklmnopqrstuvwxyz";
 
			std::string uuid;
 
			for (int i = 0; i < 10; i++) {
 
				uuid += bucket[rand() % bucket.size()];
 
			}
 
			std::ofstream myfile;
 
			myfile.open (std::string("/var/spool/sms/outgoing/spectrum." + uuid).c_str());
 
			myfile << data;
 
			myfile.close();
 
		}
 

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

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

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			UserInfo info;
 
			if (!storageBackend->getUser(user, info)) {
 
				handleDisconnected(user, 0, "Not registered user.");
 
				return;
 
			}
 
			std::list<BuddyInfo> roster;
 
			storageBackend->getBuddies(info.id, roster);
 

	
 
			// Send available presence to every number in the roster.
 
			BOOST_FOREACH(BuddyInfo &b, roster) {
 
				handleBuddyChanged(user, b.legacyName, b.alias, b.groups, pbnetwork::STATUS_ONLINE);
 
			}
 

	
 
			np->handleConnected(user);
 
		}
 

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

	
 
		void handleMessageSendRequest(const std::string &user, const std::string &legacyName, const std::string &message, const std::string &xhtml = "") {
 
			// Remove trailing +, because smstools doesn't use it in "From: " field for received messages.
 
			std::string n = legacyName;
 
			if (n.find("+") == 0) {
 
				n = n.substr(1);
 
			}
 

	
 
			// Create GSM Number - XMPP user pair to match the potential response and send it to the proper JID.
 
			BuddyInfo info;
 
			info.legacyName = n;
 
			info.alias = user;
 
			info.id = -1;
 
			info.subscription = "both";
 
			info.flags = 0;
 
			storageBackend->addBuddy(m_internalUser, info);
 

	
 
			LOG4CXX_INFO(logger, "Sending SMS from " << user << " to " << n << ".");
 
			sendSMS(n, message);
 
		}
 

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

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

	
 
		void handleBuddyUpdatedRequest(const std::string &user, const std::string &buddyName, const std::string &alias, const std::vector<std::string> &groups) {
 
			LOG4CXX_INFO(logger, user << ": Added buddy " << buddyName << ".");
 
			handleBuddyChanged(user, buddyName, alias, groups, pbnetwork::STATUS_ONLINE);
 
		}
 

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

	
 
		}
 

	
 

	
 
	private:
 
		
 
		Config *config;
 
};
 

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

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

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

	
 

	
 
int main (int argc, char* argv[]) {
 
	std::string host;
 
	int port;
 

	
 
	if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
 
		std::cout << "SIGCHLD handler can't be set\n";
 
		return -1;
 
	}
 

	
 
	boost::program_options::options_description desc("Usage: spectrum [OPTIONS] <config_file.cfg>\nAllowed options");
 
	desc.add_options()
 
		("host,h", value<std::string>(&host), "host")
 
		("port,p", value<int>(&port), "port")
 
		;
 
	try
 
	{
 
		boost::program_options::variables_map vm;
 
		boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
 
		boost::program_options::notify(vm);
 
	}
 
	catch (std::runtime_error& e)
 
	{
 
		std::cout << desc << "\n";
 
		exit(1);
 
	}
 
	catch (...)
 
	{
 
		std::cout << desc << "\n";
 
		exit(1);
 
	}
 

	
 

	
 
	if (argc < 5) {
 
		return 1;
 
	}
 

	
 
// 	QStringList channels;
 
// 	for (int i = 3; i < argc; ++i)
 
// 	{
 
// 		channels.append(argv[i]);
 
// 	}
 
// 
 
// 	MyIrcSession session;
 
// 	session.setNick(argv[2]);
 
// 	session.setAutoJoinChannels(channels);
 
// 	session.connectToServer(argv[1], 6667);
 

	
 
	Config config;
 
	if (!config.load(argv[5])) {
 
		std::cerr << "Can't open " << argv[1] << " configuration file.\n";
 
		return 1;
 
	}
 

	
 
	if (CONFIG_STRING(&config, "logging.backend_config").empty()) {
 
		LoggerPtr root = log4cxx::Logger::getRootLogger();
 
#ifndef _MSC_VER
 
		root->addAppender(new ConsoleAppender(new PatternLayout("%d %-5p %c: %m%n")));
 
#else
 
		root->addAppender(new ConsoleAppender(new PatternLayout(L"%d %-5p %c: %m%n")));
 
#endif
 
	}
 
	else {
 
		log4cxx::helpers::Properties p;
 
		log4cxx::helpers::FileInputStream *istream = new log4cxx::helpers::FileInputStream(CONFIG_STRING(&config, "logging.backend_config"));
 
		p.load(istream);
 
		LogString pid, jid;
 
		log4cxx::helpers::Transcoder::decode(boost::lexical_cast<std::string>(getpid()), pid);
 
		log4cxx::helpers::Transcoder::decode(CONFIG_STRING(&config, "service.jid"), jid);
 
#ifdef _MSC_VER
 
		p.setProperty(L"pid", pid);
 
		p.setProperty(L"jid", jid);
 
#else
 
		p.setProperty("pid", pid);
 
		p.setProperty("jid", jid);
 
#endif
 
		log4cxx::PropertyConfigurator::configure(p);
 
	}
 

	
 
#ifdef WITH_SQLITE
 
	if (CONFIG_STRING(&config, "database.type") == "sqlite3") {
 
		storageBackend = new SQLite3Backend(&config);
 
		if (!storageBackend->connect()) {
 
			std::cerr << "Can't connect to database. Check the log to find out the reason.\n";
 
			return -1;
 
		}
 
	}
 
#else
 
	if (CONFIG_STRING(&config, "database.type") == "sqlite3") {
 
		std::cerr << "Spectrum2 is not compiled with mysql backend.\n";
 
		return -2;
 
	}
 
#endif
 

	
 
#ifdef WITH_MYSQL
 
	if (CONFIG_STRING(&config, "database.type") == "mysql") {
 
		storageBackend = new MySQLBackend(&config);
 
		if (!storageBackend->connect()) {
 
			std::cerr << "Can't connect to database. Check the log to find out the reason.\n";
 
			return -1;
 
		}
 
	}
 
#else
 
	if (CONFIG_STRING(&config, "database.type") == "mysql") {
 
		std::cerr << "Spectrum2 is not compiled with mysql backend.\n";
 
		return -2;
 
	}
 
#endif
 

	
 
#ifdef WITH_PQXX
 
	if (CONFIG_STRING(&config, "database.type") == "pqxx") {
 
		storageBackend = new PQXXBackend(&config);
 
		if (!storageBackend->connect()) {
 
			std::cerr << "Can't connect to database. Check the log to find out the reason.\n";
 
			return -1;
 
		}
 
	}
 
#else
 
	if (CONFIG_STRING(&config, "database.type") == "pqxx") {
 
		std::cerr << "Spectrum2 is not compiled with pqxx backend.\n";
 
		return -2;
 
	}
 
#endif
 

	
 
	if (CONFIG_STRING(&config, "database.type") != "mysql" && CONFIG_STRING(&config, "database.type") != "sqlite3"
 
		&& CONFIG_STRING(&config, "database.type") != "pqxx" && CONFIG_STRING(&config, "database.type") != "none") {
 
		std::cerr << "Unknown storage backend " << CONFIG_STRING(&config, "database.type") << "\n";
 
		return -2;
 
	}
 

	
 
	Swift::SimpleEventLoop eventLoop;
 
	loop_ = &eventLoop;
 
	np = new SMSNetworkPlugin(&config, &eventLoop, host, port);
 
	loop_->run();
 

	
 
	return 0;
 
}
cmake_modules/dbusConfig.cmake
Show inline comments
 
new file 100644
 
# - Try to find LIBDBUS GLIB Bindings
 
# Find LIBDBUSGLIB headers, libraries and the answer to all questions.
 
#
 
#  LIBDBUSGLIB_FOUND               True if libdbus-glib got found
 
#  LIBDBUSGLIB_INCLUDE_DIRS        Location of libdbus-glib headers 
 
#  LIBDBUSGLIB_LIBRARIES           List of libraries to use libdbus-glib 
 
#
 
# Copyright (c) 2008 Bjoern Ricks <bjoern.ricks@googlemail.com>
 
#
 
#  Redistribution and use is allowed according to the terms of the New
 
#  BSD license.
 
#  For details see the accompanying COPYING-CMAKE-SCRIPTS file.
 
#
 

	
 
INCLUDE( FindPkgConfig )
 

	
 
IF ( LibDbusGlib_FIND_REQUIRED )
 
	SET( _pkgconfig_REQUIRED "REQUIRED" )
 
ELSE( LibDbusGlib_FIND_REQUIRED )
 
	SET( _pkgconfig_REQUIRED "" )	
 
ENDIF ( LibDbusGlib_FIND_REQUIRED )
 

	
 
IF ( LIBDBUSGLIB_MIN_VERSION )
 
	PKG_SEARCH_MODULE( LIBDBUSGLIB ${_pkgconfig_REQUIRED} dbus-glib-1>=${LIBDBUSGLIB_MIN_VERSION} )
 
ELSE ( LIBDBUSGLIB_MIN_VERSION )
 
	PKG_SEARCH_MODULE( LIBDBUSGLIB ${_pkgconfig_REQUIRED} dbus-glib-1 )
 
ENDIF ( LIBDBUSGLIB_MIN_VERSION )
 

	
 

	
 
IF( NOT LIBDBUSGLIB_FOUND AND NOT PKG_CONFIG_FOUND )
 
	FIND_PATH( LIBDBUSGLIB_INCLUDE_DIRS dbus/dbus-glib.h PATH_SUFFIXES dbus-1.0 dbus )
 
	FIND_LIBRARY( LIBDBUSGLIB_LIBRARIES dbus-glib dbus-glib-1)
 

	
 
	# Report results
 
	IF ( LIBDBUSGLIB_LIBRARIES AND LIBDBUSGLIB_INCLUDE_DIRS )	
 
		SET( LIBDBUSGLIB_FOUND 1 )
 
		IF ( NOT LIBDBUSGLIB_FIND_QUIETLY )
 
			MESSAGE( STATUS "Found libdbus-glib: ${LIBDBUSGLIB_LIBRARIES} ${LIBDBUSGLIB_INCLUDE_DIRS}" )
 
		ENDIF ( NOT LIBDBUSGLIB_FIND_QUIETLY )
 
	ELSE ( LIBDBUSGLIB_LIBRARIES AND LIBDBUSGLIB_INCLUDE_DIRS )	
 
		IF ( LIBDBUSGLIB_FIND_REQUIRED )
 
			MESSAGE( SEND_ERROR "Could NOT find libdbus-glib" )
 
		ELSE ( LIBDBUSGLIB_FIND_REQUIRED )
 
			IF ( NOT LIBDBUSGLIB_FIND_QUIETLY )
 
				MESSAGE( STATUS "Could NOT find libdbus-glib" )	
 
			ENDIF ( NOT LIBDBUSGLIB_FIND_QUIETLY )
 
		ENDIF ( LIBDBUSGLIB_FIND_REQUIRED )
 
	ENDIF ( LIBDBUSGLIB_LIBRARIES AND LIBDBUSGLIB_INCLUDE_DIRS )
 
else()
 
	MESSAGE( STATUS "Found libdbus-glib: ${LIBDBUSGLIB_LIBRARIES} ${LIBDBUSGLIB_INCLUDE_DIRS}" )
 
ENDIF()
 

	
 
MARK_AS_ADVANCED( LIBDBUSGLIB_LIBRARIES LIBDBUSGLIB_INCLUDE_DIRS )
 
\ No newline at end of file
include/Swiften/TLS/OpenSSL/OpenSSLServerContext.cpp
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 
#include "Swiften/Base/Platform.h"
 

	
 
#ifdef SWIFTEN_PLATFORM_WINDOWS
 
#include <windows.h>
 
#include <wincrypt.h>
 
#endif
 

	
 
#include <vector>
 
#include <openssl/err.h>
 
#include <openssl/pkcs12.h>
 

	
 
#include "log4cxx/logger.h"
 
#include "log4cxx/consoleappender.h"
 
#include "log4cxx/patternlayout.h"
 
#include "log4cxx/propertyconfigurator.h"
 
using namespace log4cxx;
 
static LoggerPtr logger = Logger::getLogger("OpenSSLServerContext");
 

	
 

	
 
#include "Swiften/TLS/OpenSSL/OpenSSLServerContext.h"
 
#include "Swiften/TLS/OpenSSL/OpenSSLCertificate.h"
 
#include "Swiften/TLS/PKCS12Certificate.h"
 
#ifndef _MSC_VER
 
#pragma GCC diagnostic ignored "-Wold-style-cast"
 
#endif
 
namespace Swift {
 

	
 
static const int MAX_FINISHED_SIZE = 4096;
 
static const int SSL_READ_BUFFERSIZE = 8192;
 

	
 
static void freeX509Stack(STACK_OF(X509)* stack) {
 
	sk_X509_free(stack);
 
}
 

	
 
// static int _sx_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
 
// 	return 1;
 
// }
 

	
 
OpenSSLServerContext::OpenSSLServerContext() : state_(Start), context_(0), handle_(0), readBIO_(0), writeBIO_(0) {
 
	ensureLibraryInitialized();
 
	context_ = SSL_CTX_new(SSLv23_server_method());
 
// 	SSL_CTX_set_verify(context_, SSL_VERIFY_PEER, _sx_ssl_verify_callback);
 

	
 
	// Load system certs
 
#if defined(SWIFTEN_PLATFORM_WINDOWS)
 
	X509_STORE* store = SSL_CTX_get_cert_store(context_);
 
	HCERTSTORE systemStore = CertOpenSystemStore(0, "ROOT");
 
	if (systemStore) {
 
		PCCERT_CONTEXT certContext = NULL;
 
		while (true) {
 
			certContext = CertFindCertificateInStore(systemStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, certContext);
 
			if (!certContext) {
 
				break;
 
			}
 
			ByteArray certData(createByteArray(certContext->pbCertEncoded, certContext->cbCertEncoded));
 
			OpenSSLCertificate cert(certData);
 
			if (store && cert.getInternalX509()) {
 
				X509_STORE_add_cert(store, cert.getInternalX509().get());
 
			}
 
		}
 
	}
 
#elif !defined(SWIFTEN_PLATFORM_MACOSX)
 
	SSL_CTX_load_verify_locations(context_, NULL, "/etc/ssl/certs");
 
#endif
 
}
 

	
 
OpenSSLServerContext::~OpenSSLServerContext() {
 
	SSL_free(handle_);
 
	SSL_CTX_free(context_);
 
}
 

	
 
void OpenSSLServerContext::ensureLibraryInitialized() {
 
	static bool isLibraryInitialized = false;
 
	if (!isLibraryInitialized) {
 
		SSL_load_error_strings();
 
		SSL_library_init();
 
		OpenSSL_add_all_algorithms();
 

	
 
		// Disable compression
 
		/*
 
		STACK_OF(SSL_COMP)* compressionMethods = SSL_COMP_get_compression_methods();
 
		sk_SSL_COMP_zero(compressionMethods);*/
 

	
 
		isLibraryInitialized = true;
 
	}
 
}
 

	
 
void OpenSSLServerContext::connect() {
 
	handle_ = SSL_new(context_);
 
	// Ownership of BIOs is ransferred
 
	readBIO_ = BIO_new(BIO_s_mem());
 
	writeBIO_ = BIO_new(BIO_s_mem());
 
	SSL_set_bio(handle_, readBIO_, writeBIO_);
 

	
 
	state_ = Connecting;
 
	doConnect();
 
}
 

	
 
void OpenSSLServerContext::doConnect() {
 
	int connectResult = SSL_accept(handle_);
 
	int error = SSL_get_error(handle_, connectResult);
 
// 	std::cout << "DO CONNECT\n";
 
	switch (error) {
 
		case SSL_ERROR_NONE: {
 
			if (SSL_is_init_finished(handle_)) {
 
// 				std::cout << "FINISHED\n";
 
				state_ = Connected;
 
				//std::cout << x->name << std::endl;
 
				//const char* comp = SSL_get_current_compression(handle_);
 
				//std::cout << "Compression: " << SSL_COMP_get_name(comp) << std::endl;
 
				onConnected();
 
				ERR_print_errors_fp(stdout);
 
				sendPendingDataToNetwork();
 
			}
 
			break;
 
		}
 
		case SSL_ERROR_WANT_READ:
 
			sendPendingDataToNetwork();
 
			break;
 
		default:
 
			state_ = Error;
 
// 			std::cout << "AAAAAAAA 1 " << error << " " << connectResult <<  "\n";
 
			ERR_print_errors_fp(stdout);
 
			onError();
 
	}
 
}
 

	
 
void OpenSSLServerContext::sendPendingDataToNetwork() {
 
	int size = BIO_pending(writeBIO_);
 
	if (size > 0) {
 
		SafeByteArray data;
 
		data.resize(size);
 
		BIO_read(writeBIO_, vecptr(data), size);
 
		onDataForNetwork(data);
 
	}
 
}
 

	
 
void OpenSSLServerContext::handleDataFromNetwork(const SafeByteArray& data) {
 
	BIO_write(readBIO_, vecptr(data), data.size());
 
// 	std::cout << "handleDataFromNetwork\n";
 
	switch (state_) {
 
		case Connecting:
 
			doConnect();
 
			break;
 
		case Connected:
 
			sendPendingDataToApplication();
 
			break;
 
		case Start: assert(false); break;
 
		case Error: /*assert(false);*/ break;
 
	}
 
}
 

	
 
void OpenSSLServerContext::handleDataFromApplication(const SafeByteArray& data) {
 
// 	std::cout << "SSL_WRITE\n";
 
	if (SSL_write(handle_, vecptr(data), data.size()) >= 0) {
 
		sendPendingDataToNetwork();
 
	}
 
	else {
 
		state_ = Error;
 
// 		std::cout << "AAAAAAAA 2\n";
 
		onError();
 
	}
 
}
 

	
 
void OpenSSLServerContext::sendPendingDataToApplication() {
 
	SafeByteArray data;
 
	data.resize(SSL_READ_BUFFERSIZE);
 
	int ret = SSL_read(handle_, vecptr(data), data.size());
 
	while (ret > 0) {
 
		data.resize(ret);
 
		onDataForApplication(data);
 
		data.resize(SSL_READ_BUFFERSIZE);
 
		ret = SSL_read(handle_, vecptr(data), data.size());
 
	}
 
	if (ret < 0 && SSL_get_error(handle_, ret) != SSL_ERROR_WANT_READ) {
 
		state_ = Error;
 
// 		std::cout << "AAAAAAAA 3\n";
 
		onError();
 
	}
 
}
 

	
 
bool OpenSSLServerContext::setServerCertificate(const PKCS12Certificate& certificate) {
 
	if (certificate.isNull()) {
 
// 		std::cout << "error 1\n";
 
		LOG4CXX_ERROR(logger, "TLS WILL NOT WORK: Certificate can't be loaded.");
 
		return false;
 
	}
 

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

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

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

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

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

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

	
 
CertificateVerificationError::Type OpenSSLServerContext::getVerificationErrorTypeForResult(int result) {
 
	assert(result != 0);
 
	switch (result) {
 
		case X509_V_ERR_CERT_NOT_YET_VALID:
 
		case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
 
			return CertificateVerificationError::NotYetValid;
 

	
 
		case X509_V_ERR_CERT_HAS_EXPIRED:
 
		case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
 
			return CertificateVerificationError::Expired;
 

	
 
		case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
 
		case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
 
			return CertificateVerificationError::SelfSigned;
 

	
 
		case X509_V_ERR_CERT_UNTRUSTED:
 
			return CertificateVerificationError::Untrusted;
 

	
 
		case X509_V_ERR_CERT_REJECTED:
 
			return CertificateVerificationError::Rejected;
 

	
 
		case X509_V_ERR_INVALID_PURPOSE:
 
			return CertificateVerificationError::InvalidPurpose;
 

	
 
		case X509_V_ERR_PATH_LENGTH_EXCEEDED:
 
			return CertificateVerificationError::PathLengthExceeded;
 

	
 
		case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
 
		case X509_V_ERR_CERT_SIGNATURE_FAILURE:
 
		case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
 
			return CertificateVerificationError::InvalidSignature;
 

	
 
		case X509_V_ERR_INVALID_CA:
 
		case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
 
		case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
 
		case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
 
			return CertificateVerificationError::InvalidCA;
 

	
 
		case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
 
		case X509_V_ERR_AKID_SKID_MISMATCH:
 
		case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
 
		case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
 
			return CertificateVerificationError::UnknownError;
 

	
 
		// Unused / should not happen
 
		case X509_V_ERR_CERT_REVOKED:
 
		case X509_V_ERR_OUT_OF_MEM:
 
		case X509_V_ERR_UNABLE_TO_GET_CRL:
 
		case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
 
		case X509_V_ERR_CRL_SIGNATURE_FAILURE:
 
		case X509_V_ERR_CRL_NOT_YET_VALID:
 
		case X509_V_ERR_CRL_HAS_EXPIRED:
 
		case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
 
		case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
 
		case X509_V_ERR_CERT_CHAIN_TOO_LONG:
 
		case X509_V_ERR_APPLICATION_VERIFICATION:
 
		default:
 
			return CertificateVerificationError::UnknownError;
 
	}
 
}
 

	
 
}
spectrum/src/sample.cfg
Show inline comments
 
[service]
 
jid = localhost
 
password = secret
 
server = 127.0.0.1
 
port = 5222
 
server_mode = 1
 
backend_host=localhost
 
pidfile=./test.pid
 
# < this option doesn't work yet
 
backend_port=10001
 
admin_username=admin
 
admin_password=test
 
#cert=server.pfx #patch to PKCS#12 certificate
 
#cert_password=test #password to that certificate if any
 
users_per_backend=10
 
backend=/home/hanzz/code/libtransport/backends/libpurple/spectrum2_libpurple_backend
 
#backend=/home/hanzz/code/libtransport/backends/libpurple/spectrum2_libpurple_backend
 
backend=/home/hanzz/code/libtransport/backends/smstools3/spectrum2_smstools3_backend
 
#backend=/usr/bin/mono /home/hanzz/code/networkplugin-csharp/msnp-sharp-backend/bin/Debug/msnp-sharp-backend.exe
 
#backend=/home/hanzz/code/libtransport/backends/frotz/spectrum2_frotz_backend
 
#backend=/home/hanzz/code/libtransport/backends/libircclient-qt/spectrum2_libircclient-qt_backend
 
#protocol=prpl-msn
 
protocol=any
 
#protocol=prpl-icq
 
irc_server=irc.freenode.org
 

	
 
[backend]
 
#default_avatar=catmelonhead.jpg
 
#no_vcard_fetch=true
 
incoming_dir=/var/spool/sms/incoming
 

	
 
[logging]
 
#config=logging.cfg # log4cxx/log4j logging configuration file
 
#backend_config=/home/hanzz/code/libtransport/spectrum/src/backend-logging.cfg # log4cxx/log4j logging configuration file for backends
 

	
 
[database]
 
type = none # or "none" without database backend
 
database = test.sql
 
prefix=icq
 
#type = sqlite3 # or "none" without database backend
 
#database = test.sql
 
#prefix=icq
 
type = mysql # or "none" without database backend.......................................................................................................................
 
database = test
 
prefix=
 
user=root
 
password=yourrootsqlpassword
 
#encryption_key=hanzzik
spectrum/src/sample2.cfg
Show inline comments
 
[service]
 
# 1 if Spectrum should run in server mode.
 
server_mode = 1
 

	
 
# The name of user/group Spectrum runs as.
 
#user=spectrum
 
#group=spectrum
 

	
 
# JID of Spectrum instance.
 
jid = localhost
 

	
 
# Password used to connect the XMPP server in gateway mode.
 
# In server mode, this option is ignored.
 
password = secret
 

	
 
# XMPP server to which Spectrum connects in gateway mode.
 
# In server mode, this option is ignored.
 
server = 127.0.0.1
 

	
 
# XMPP server port.
 
port = 5222
 

	
 
# Interface on which Spectrum listens for backends.
 
backend_host = localhost
 

	
 
# Port on which Spectrum listens for backends.
 
# By default Spectrum chooses random backend port and there's
 
# no need to change it normally
 
#backend_port=10001
 

	
 
# Full path to PKCS#12 cetficiate used for TLS in server mode.
 
#cert=
 

	
 
# Certificate password if any.
 
#cert_password= 
 

	
 
# Number of users per one legacy network backend.
 
users_per_backend=10
 

	
 
# Full path to backend binary.
 
backend=/usr/bin/spectrum2_libpurple_backend
 
#backend=/usr/bin/spectrum2_libircclient-qt_backend
 
# For skype:
 
#backend=/usr/bin/setsid /usr/bin/xvfb-run -n BACKEND_ID -s "-screen 0 10x10x8" -f /tmp/x-skype-gw /usr/bin/spectrum2_skype_backend
 
#backend=/usr/bin/xvfb-run -n BACKEND_ID -s "-screen 0 10x10x8" -f /tmp/x-skype-gw /usr/bin/spectrum2_skype_backend
 

	
 
# Libpurple protocol-id for spectrum_libpurple_backend
 
protocol=prpl-jabber
 
#protocol=prpl-msn
 
#protocol=prpl-icq
 

	
 
# prpl-any means that user sets his protocol in his JID which has to be
 
# in following format: protocol.username@domain.tld
 
# So for example: prpl-jabber.hanzz.k%gmail.com@domain.tld
 
#protocol=prpl-any
 

	
 
[identity]
 
# Name of Spectrum instance in service discovery
 
name=Spectrum Jabber Transport
 

	
 
# Type of transport ("msn", "icq", "xmpp").
 
# Check http://xmpp.org/registrar/disco-categories.html#gateway
 
type=xmpp
 

	
 
# Category of transport, default is "gateway
 
#category=gateway
 

	
 
[logging]
 
# log4cxx/log4j logging configuration file in ini format used for main spectrum2 instance.
 
config = /etc/spectrum2/logging.cfg
 

	
 
# log4cxx/log4j logging configuration file in ini format used for backends.
 
backend_config = /etc/spectrum2/backend-logging.cfg
 

	
 
[database]
 
# Database backend type
 
# "sqlite3", "mysql", "pqxx", or "none" without database backend
 
type = none
 

	
 
# For SQLite3: Full path to database
 
# For MySQL and PostgreSQL: name of database
 
# default database = /var/lib/spectrum2/$jid/database.sql
 
#database = jabber_transport
 

	
 
# Server.
 
#server = localhost
 

	
 
# Port.
 
#port = 0
 

	
 
# User.
 
#user = spectrum
 

	
 
# Paasword.
 
#password = secret
 

	
 
# Prefix used for tables
 
#prefix = jabber_
 

	
 
[registration]
 
# Enable public registrations
 
enable_public_registration=1
 

	
 
# Text to display upon user registration form
 
#username_label=Jabber JID (e.g. user@server.tld):
 
#instructions=Enter your remote jabber JID and password as well as your local username and password
 

	
 
# If True a local jabber account on <local_account_server> is needed 
 
# for transport registration, the idea is to enable public registration
 
# from other servers, but only for users, who have already local accounts
 
#require_local_account=1
 
#local_username_label=Local username (without @server.tld):
 
#local_account_server=localhost
 
#local_account_server_timeout=10000
 

	
src/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp *.h)
 
FILE(GLOB_RECURSE SWIFTEN_SRC ../include/Swiften/*.cpp)
 
FILE(GLOB HEADERS ../include/transport/*.h)
 

	
 
if (CPPUNIT_FOUND)
 
	FILE(GLOB SRC_TEST tests/*.cpp)
 

	
 
	ADD_EXECUTABLE(libtransport_test ${SRC_TEST})
 

	
 
	target_link_libraries(libtransport_test transport ${CPPUNIT_LIBRARIES} ${Boost_LIBRARIES})
 
endif()
 

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

	
 
# SOURCE_GROUP(headers FILES ${HEADERS})
 

	
 

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

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

	
 
if (WIN32)
 
	TARGET_LINK_LIBRARIES(transport ${PQXX_LIBRARY} ${PQ_LIBRARY} ${SQLITE3_LIBRARIES} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES})
 
	TARGET_LINK_LIBRARIES(transport transport-plugin ${PQXX_LIBRARY} ${PQ_LIBRARY} ${SQLITE3_LIBRARIES} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES})
 
else (WIN32)
 
	TARGET_LINK_LIBRARIES(transport ${PQXX_LIBRARY} ${PQ_LIBRARY} ${SQLITE3_LIBRARIES} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES} ${POPT_LIBRARY})
 
	TARGET_LINK_LIBRARIES(transport transport-plugin ${PQXX_LIBRARY} ${PQ_LIBRARY} ${SQLITE3_LIBRARIES} ${MYSQL_LIBRARIES} ${SWIFTEN_LIBRARY} ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES} ${POPT_LIBRARY})
 
endif(WIN32)
 

	
 
SET_TARGET_PROPERTIES(transport PROPERTIES
 
      VERSION ${TRANSPORT_VERSION} SOVERSION ${TRANSPORT_VERSION}
 
)
 

	
 
INSTALL(TARGETS transport LIBRARY DESTINATION lib ARCHIVE DESTINATION lib COMPONENT libraries)
 

	
 
#CONFIGURE_FILE(transport.pc.in "${CMAKE_CURRENT_BINARY_DIR}/transport.pc")
 
#INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/transport.pc" DESTINATION lib/pkgconfig)
src/config.cpp
Show inline comments
 
/**
 
 * libtransport -- C++ library for easy XMPP Transports development
 
 *
 
 * Copyright (C) 2011, Jan Kaluza <hanzz.k@gmail.com>
 
 *
 
 * This program is free software; you can redistribute it and/or modify
 
 * it under the terms of the GNU General Public License as published by
 
 * the Free Software Foundation; either version 2 of the License, or
 
 * (at your option) any later version.
 
 *
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#include "transport/config.h"
 
#include "transport/util.h"
 
#include <fstream>
 
#ifdef _MSC_VER
 
#include <direct.h>
 
#define getcwd _getcwd
 
#include <windows.h>
 
#define PATH_MAX MAX_PATH
 
#endif
 

	
 
using namespace boost::program_options;
 

	
 
namespace Transport {
 

	
 
bool Config::load(const std::string &configfile, boost::program_options::options_description &opts, const std::string &jid) {
 
	std::ifstream ifs(configfile.c_str());
 
	if (!ifs.is_open())
 
		return false;
 

	
 
	m_file = configfile;
 
	bool ret = load(ifs, opts, jid);
 
	ifs.close();
 

	
 
	char path[PATH_MAX] = "";
 
	if (m_file.find_first_of("/") != 0) {
 
		getcwd(path, PATH_MAX);
 
		m_file = std::string(path) + "/" + m_file;
 
	}
 

	
 
	return ret;
 
}
 

	
 
bool Config::load(std::istream &ifs, boost::program_options::options_description &opts, const std::string &_jid) {
 
	m_unregistered.clear();
 
	opts.add_options()
 
		("service.jid", value<std::string>()->default_value(""), "Transport Jabber ID")
 
		("service.server", value<std::string>()->default_value(""), "Server to connect to")
 
		("service.password", value<std::string>()->default_value(""), "Password used to auth the server")
 
		("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.working_dir", value<std::string>()->default_value("/var/lib/spectrum2/$jid"), "Working dir")
 
		("service.allowed_servers", value<std::string>()->default_value(""), "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")
 
		("service.cert", value<std::string>()->default_value(""), "PKCS#12 Certificate.")
 
		("service.cert_password", value<std::string>()->default_value(""), "PKCS#12 Certificate password.")
 
		("service.admin_jid", value<std::string>()->default_value(""), "Administrator jid.")
 
		("service.admin_password", value<std::string>()->default_value(""), "Administrator password.")
 
		("service.reuse_old_backends", value<bool>()->default_value(true), "True if Spectrum should use old backends which were full in the past.")
 
		("service.idle_reconnect_time", value<int>()->default_value(0), "Time in seconds after which idle users are reconnected to let their backend die.")
 
		("service.memory_collector_time", value<int>()->default_value(0), "Time in seconds after which backend with most memory is set to die.")
 
		("service.more_resources", value<bool>()->default_value(false), "Allow more resources to be connected in server mode at the same time.")
 
		("service.enable_privacy_lists", value<bool>()->default_value(true), "")
 
		("vhosts.vhost", value<std::vector<std::string> >()->multitoken(), "")
 
		("identity.name", value<std::string>()->default_value("Spectrum 2 Transport"), "Name showed in service discovery.")
 
		("identity.category", value<std::string>()->default_value("gateway"), "Disco#info identity category. 'gateway' by default.")
 
		("identity.type", value<std::string>()->default_value(""), "Type of transport ('icq','msn','gg','irc', ...)")
 
		("registration.enable_public_registration", value<bool>()->default_value(true), "True if users should be able to register.")
 
		("registration.language", value<std::string>()->default_value("en"), "Default language for registration form")
 
		("registration.instructions", value<std::string>()->default_value("Enter your legacy network username and password."), "Instructions showed to user in registration form")
 
		("registration.username_label", value<std::string>()->default_value("Legacy network username:"), "Label for username field")
 
		("registration.username_mask", value<std::string>()->default_value(""), "Username mask")
 
		("registration.encoding", value<std::string>()->default_value("utf8"), "Default encoding in registration form")
 
		("registration.require_local_account", value<bool>()->default_value(false), "True if users have to have a local account to register to this transport from remote servers.")
 
		("registration.local_username_label", value<std::string>()->default_value("Local username:"), "Label for local usernme field")
 
		("registration.local_account_server", value<std::string>()->default_value("localhost"), "The server on which the local accounts will be checked for validity")
 
		("registration.local_account_server_timeout", value<int>()->default_value(10000), "Timeout when checking local user on local_account_server (msecs)")
 
		("database.type", value<std::string>()->default_value("none"), "Database type.")
 
		("database.database", value<std::string>()->default_value(""), "Database used to store data")
 
		("database.database", value<std::string>()->default_value("/var/lib/spectrum2/$jid/database.sql"), "Database used to store data")
 
		("database.server", value<std::string>()->default_value("localhost"), "Database server.")
 
		("database.user", value<std::string>()->default_value(""), "Database user.")
 
		("database.password", value<std::string>()->default_value(""), "Database Password.")
 
		("database.port", value<int>()->default_value(0), "Database port.")
 
		("database.prefix", value<std::string>()->default_value(""), "Prefix of tables in database")
 
		("database.encryption_key", value<std::string>()->default_value(""), "Encryption key.")
 
		("logging.config", value<std::string>()->default_value(""), "Path to log4cxx config file which is used for Spectrum 2 instance")
 
		("logging.backend_config", value<std::string>()->default_value(""), "Path to log4cxx config file which is used for backends")
 
		("backend.default_avatar", value<std::string>()->default_value(""), "Full path to default avatar")
 
		("backend.avatars_directory", value<std::string>()->default_value(""), "Path to directory with avatars")
 
		("backend.no_vcard_fetch", value<bool>()->default_value(false), "True if VCards for buddies should not be fetched. Only avatars will be forwarded.")
 
	;
 

	
 
	parsed_options parsed = parse_config_file(ifs, opts, true);
 

	
 
	bool found_working = false;
 
	bool found_pidfile = false;
 
	bool found_backend_port = false;
 
	bool found_database = false;
 
	std::string jid = "";
 
	BOOST_FOREACH(option &opt, parsed.options) {
 
		if (opt.string_key == "service.jid") {
 
			if (_jid.empty()) {
 
				jid = opt.value[0];
 
			}
 
			else {
 
				opt.value[0] = _jid;
 
				jid = _jid;
 
			}
 
		}
 
		else if (opt.string_key == "service.backend_port") {
 
			found_backend_port = true;
 
			if (opt.value[0] == "0") {
 
				opt.value[0] = boost::lexical_cast<std::string>(Util::getRandomPort(_jid.empty() ? jid : _jid));
 
			}
 
		}
 
		else if (opt.string_key == "service.working_dir") {
 
			found_working = true;
 
		}
 
		else if (opt.string_key == "service.pidfile") {
 
			found_pidfile = true;
 
		}
 
		else if (opt.string_key == "database.database") {
 
			found_database = true;
 
		}
 
	}
 

	
 
	if (!found_working) {
 
		std::vector<std::string> value;
 
		value.push_back("/var/lib/spectrum2/$jid");
 
		parsed.options.push_back(boost::program_options::basic_option<char>("service.working_dir", value));
 
	}
 
	if (!found_pidfile) {
 
		std::vector<std::string> value;
 
		value.push_back("/var/run/spectrum2/$jid.pid");
 
		parsed.options.push_back(boost::program_options::basic_option<char>("service.pidfile", value));
 
	}
 
	if (!found_backend_port) {
 
		std::vector<std::string> value;
 
		std::string p = boost::lexical_cast<std::string>(Util::getRandomPort(_jid.empty() ? jid : _jid));
 
		value.push_back(p);
 
		parsed.options.push_back(boost::program_options::basic_option<char>("service.backend_port", value));
 
	}
 
	if (!found_database) {
 
		std::vector<std::string> value;
 
		value.push_back("/var/lib/spectrum2/$jid/database.sql");
 
		parsed.options.push_back(boost::program_options::basic_option<char>("database.database", value));
 
	}
 

	
 
	BOOST_FOREACH(option &opt, parsed.options) {
 
		if (opt.unregistered) {
 
			m_unregistered[opt.string_key] = opt.value[0];
 
		}
 
		else if (opt.value[0].find("$jid") != std::string::npos) {
 
			boost::replace_all(opt.value[0], "$jid", jid);
 
		}
 
	}
 

	
 
	store(parsed, m_variables);
 
	notify(m_variables);
 

	
 
	onConfigReloaded();
 

	
 
	return true;
 
}
 

	
 
bool Config::load(std::istream &ifs) {
 
	options_description opts("Transport options");
 
	return load(ifs, opts);
 
}
 

	
 
bool Config::load(const std::string &configfile, const std::string &jid) {
 
	options_description opts("Transport options");
 
	return load(configfile, opts, jid);
 
}
 

	
 
bool Config::reload() {
 
	if (m_file.empty()) {
 
		return false;
 
	}
 

	
 
	return load(m_file);
 
}
 

	
 
}
src/mysqlbackend.cpp
Show inline comments
 
@@ -377,242 +377,246 @@ bool MySQLBackend::createDatabase() {
 
				"`language` varchar(25) collate utf8_bin NOT NULL,"
 
				"`encoding` varchar(50) collate utf8_bin NOT NULL default 'utf8',"
 
				"`last_login` datetime,"
 
				"`vip` tinyint(1) NOT NULL  default '0',"
 
				"`online` tinyint(1) NOT NULL  default '0',"
 
				"PRIMARY KEY (`id`),"
 
				"UNIQUE KEY `jid` (`jid`)"
 
			") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;");
 

	
 
		exec("CREATE TABLE IF NOT EXISTS `" + m_prefix + "users_settings` ("
 
				"`user_id` int(10) unsigned NOT NULL,"
 
				"`var` varchar(50) collate utf8_bin NOT NULL,"
 
				"`type` smallint(4) unsigned NOT NULL,"
 
				"`value` varchar(255) collate utf8_bin NOT NULL,"
 
				"PRIMARY KEY (`user_id`,`var`),"
 
				"KEY `user_id` (`user_id`)"
 
			") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;");
 

	
 
		exec("CREATE TABLE IF NOT EXISTS `" + m_prefix + "db_version` ("
 
				"`ver` int(10) unsigned NOT NULL default '1',"
 
				"UNIQUE KEY `ver` (`ver`)"
 
			") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;");
 

	
 
		exec("INSERT IGNORE INTO db_version (ver) VALUES ('2');");
 
	}
 

	
 
	return true;
 
}
 

	
 
bool MySQLBackend::exec(const std::string &query) {
 
	if (mysql_query(&m_conn, query.c_str())) {
 
		LOG4CXX_ERROR(logger, query << " " << mysql_error(&m_conn));
 
		return false;
 
	}
 
	return true;
 
}
 

	
 
void MySQLBackend::setUser(const UserInfo &user) {
 
	std::string encrypted = user.password;
 
	if (!CONFIG_STRING(m_config, "database.encryption_key").empty()) {
 
		encrypted = Util::encryptPassword(encrypted, CONFIG_STRING(m_config, "database.encryption_key"));
 
	}
 
	*m_setUser << user.jid << user.uin << encrypted << user.language << user.encoding << user.vip << user.uin << encrypted;
 
	EXEC(m_setUser, setUser(user));
 
}
 

	
 
bool MySQLBackend::getUser(const std::string &barejid, UserInfo &user) {
 
	*m_getUser << barejid;
 
	EXEC(m_getUser, getUser(barejid, user));
 
	if (!exec_ok)
 
		return false;
 

	
 
	int ret = false;
 
	while (m_getUser->fetch() == 0) {
 
		ret = true;
 
		*m_getUser >> user.id >> user.jid >> user.uin >> user.password >> user.encoding >> user.language >> user.vip;
 

	
 
		if (!CONFIG_STRING(m_config, "database.encryption_key").empty()) {
 
			user.password = Util::decryptPassword(user.password, CONFIG_STRING(m_config, "database.encryption_key"));
 
		}
 
	}
 

	
 
	return ret;
 
}
 

	
 
void MySQLBackend::setUserOnline(long id, bool online) {
 
	*m_setUserOnline << online << id;
 
	EXEC(m_setUserOnline, setUserOnline(id, online));
 
}
 

	
 
bool MySQLBackend::getOnlineUsers(std::vector<std::string> &users) {
 
	EXEC(m_getOnlineUsers, getOnlineUsers(users));
 
	if (!exec_ok)
 
		return false;
 

	
 
	std::string jid;
 
	while (m_getOnlineUsers->fetch() == 0) {
 
		*m_getOnlineUsers >> jid;
 
		users.push_back(jid);
 
	}
 

	
 
	return true;
 
}
 

	
 
long MySQLBackend::addBuddy(long userId, const BuddyInfo &buddyInfo) {
 
// 	"INSERT INTO " + m_prefix + "buddies (user_id, uin, subscription, groups, nickname, flags) VALUES (?, ?, ?, ?, ?, ?)"
 
	std::string groups = Util::serializeGroups(buddyInfo.groups);
 
	*m_addBuddy << userId << buddyInfo.legacyName << buddyInfo.subscription;
 
	*m_addBuddy << groups;
 
	*m_addBuddy << buddyInfo.alias << buddyInfo.flags;
 

	
 
	EXEC(m_addBuddy, addBuddy(userId, buddyInfo));
 

	
 
	long id = (long) mysql_insert_id(&m_conn);
 

	
 
// 	INSERT OR REPLACE INTO " + m_prefix + "buddies_settings (user_id, buddy_id, var, type, value) VALUES (?, ?, ?, ?, ?)
 
	if (!buddyInfo.settings.find("icon_hash")->second.s.empty()) {
 
	if (buddyInfo.settings.find("icon_hash") != buddyInfo.settings.end() && !buddyInfo.settings.find("icon_hash")->second.s.empty()) {
 
		*m_updateBuddySetting << userId << id << buddyInfo.settings.find("icon_hash")->first << (int) TYPE_STRING << buddyInfo.settings.find("icon_hash")->second.s << buddyInfo.settings.find("icon_hash")->second.s;
 
		EXEC(m_updateBuddySetting, addBuddy(userId, buddyInfo));
 
	}
 

	
 
	return id;
 
}
 

	
 
void MySQLBackend::updateBuddy(long userId, const BuddyInfo &buddyInfo) {
 
// 	"UPDATE " + m_prefix + "buddies SET groups=?, nickname=?, flags=?, subscription=? WHERE user_id=? AND uin=?"
 
	std::string groups = Util::serializeGroups(buddyInfo.groups);
 
	*m_updateBuddy << groups;
 
	*m_updateBuddy << buddyInfo.alias << buddyInfo.flags << buddyInfo.subscription;
 
	*m_updateBuddy << userId << buddyInfo.legacyName;
 

	
 
	EXEC(m_updateBuddy, updateBuddy(userId, buddyInfo));
 
}
 

	
 
bool MySQLBackend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 
//	SELECT id, uin, subscription, nickname, groups, flags FROM " + m_prefix + "buddies WHERE user_id=? ORDER BY id ASC
 
	*m_getBuddies << id;
 

	
 
// 	"SELECT buddy_id, type, var, value FROM " + m_prefix + "buddies_settings WHERE user_id=? ORDER BY buddy_id ASC"
 
	*m_getBuddiesSettings << id;
 

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

	
 
	EXEC(m_getBuddies, getBuddies(id, roster));
 
	if (!exec_ok)
 
		return false;
 

	
 
	while (m_getBuddies->fetch() == 0) {
 
		BuddyInfo b;
 

	
 
		std::string group;
 
		*m_getBuddies >> b.id >> b.legacyName >> b.subscription >> b.alias >> group >> b.flags;
 

	
 
		if (!group.empty()) {
 
			b.groups = Util::deserializeGroups(group);
 
		}
 

	
 
		roster.push_back(b);
 
	}
 

	
 
	EXEC(m_getBuddiesSettings, getBuddies(id, roster));
 
	if (!exec_ok)
 
		return false;
 

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

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

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

	
 
	while(m_getBuddiesSettings->fetch() == 0) {
 
		// TODO: probably remove those settings, because there's no buddy for them.
 
		// It should not happend, but one never know...
 
	}
 
	
 
	return true;
 
}
 

	
 
bool MySQLBackend::removeUser(long id) {
 
	*m_removeUser << (int) id;
 
	EXEC(m_removeUser, removeUser(id));
 
	if (!exec_ok)
 
		return false;
 

	
 
	*m_removeUserSettings << (int) id;
 
	EXEC(m_removeUserSettings, removeUser(id));
 
	if (!exec_ok)
 
		return false;
 

	
 
	*m_removeUserBuddies << (int) id;
 
	EXEC(m_removeUserBuddies, removeUser(id));
 
	if (!exec_ok)
 
		return false;
 

	
 
	*m_removeUserBuddiesSettings << (int) id;
 
	EXEC(m_removeUserBuddiesSettings, removeUser(id));
 
	if (!exec_ok)
 
		return false;
 

	
 
	return true;
 
}
 

	
 
void MySQLBackend::getUserSetting(long id, const std::string &variable, int &type, std::string &value) {
 
// 	"SELECT type, value FROM " + m_prefix + "users_settings WHERE user_id=? AND var=?"
 
	*m_getUserSetting << id << variable;
 
	EXEC(m_getUserSetting, getUserSetting(id, variable, type, value));
 
	if (m_getUserSetting->fetch() != 0) {
 
// 		"INSERT INTO " + m_prefix + "users_settings (user_id, var, type, value) VALUES (?,?,?,?)"
 
		*m_setUserSetting << id << variable << type << value;
 
		EXEC(m_setUserSetting, getUserSetting(id, variable, type, value));
 
	}
 
	else {
 
		*m_getUserSetting >> type >> value;
 
	}
 

	
 
	while (m_getUserSetting->fetch() == 0) {
 

	
 
	}
 
}
 

	
 
void MySQLBackend::updateUserSetting(long id, const std::string &variable, const std::string &value) {
 
// 	"UPDATE " + m_prefix + "users_settings SET value=? WHERE user_id=? AND var=?"
 
	*m_updateUserSetting << value << id << variable;
 
	EXEC(m_updateUserSetting, updateUserSetting(id, variable, value));
 
}
 

	
 
void MySQLBackend::beginTransaction() {
 
	exec("START TRANSACTION;");
 
	//exec("START TRANSACTION;");
 
}
 

	
 
void MySQLBackend::commitTransaction() {
 
	exec("COMMIT;");
 
	//exec("COMMIT;");
 
}
 

	
 
}
 

	
 
#endif
src/networkpluginserver.cpp
Show inline comments
 
@@ -64,292 +64,294 @@ static unsigned long bytestream_id;
 
static LoggerPtr logger = Logger::getLogger("NetworkPluginServer");
 

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

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

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

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

	
 
		// Creates new conversation (NetworkConversation in this case)
 
		Conversation *createConversation(ConversationManager *conversationManager, const std::string &legacyName) {
 
			NetworkConversation *nc = new NetworkConversation(conversationManager, legacyName);
 
			nc->onMessageToSend.connect(boost::bind(&NetworkPluginServer::handleMessageReceived, m_nps, _1, _2));
 
			return nc;
 
		}
 

	
 
		// Creates new LocalBuddy
 
		Buddy *createBuddy(RosterManager *rosterManager, const BuddyInfo &buddyInfo) {
 
			LocalBuddy *buddy = new LocalBuddy(rosterManager, buddyInfo.id);
 
			buddy->setAlias(buddyInfo.alias);
 
			buddy->setName(buddyInfo.legacyName);
 
			buddy->setSubscription(buddyInfo.subscription);
 
			buddy->setGroups(buddyInfo.groups);
 
			buddy->setFlags((BuddyFlag) (buddyInfo.flags));
 
			if (buddyInfo.settings.find("icon_hash") != buddyInfo.settings.end())
 
				buddy->setIconHash(buddyInfo.settings.find("icon_hash")->second.s);
 
			return buddy;
 
		}
 

	
 
	private:
 
		NetworkPluginServer *m_nps;
 
};
 

	
 
// Wraps google protobuf payload into WrapperMessage and serialize it to string
 
#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_(std::string path, const char *host, const char *port, const char *config) {
 
	std::string original_path = path;
 
	// BACKEND_ID is replaced with unique ID. The ID is increasing for every backend.
 
	boost::replace_all(path, "BACKEND_ID", boost::lexical_cast<std::string>(backend_id++));
 

	
 
	// Add host and port.
 
	path += std::string(" --host ") + host + " --port " + port + " " + config;
 
	LOG4CXX_INFO(logger, "Starting new backend " << path);
 

	
 
#ifdef _WIN32
 
	STARTUPINFO         si;
 
	PROCESS_INFORMATION pi;
 

	
 
	ZeroMemory (&si, sizeof(si));
 
	si.cb=sizeof (si);
 

	
 
	if (! CreateProcess(
 
	NULL,
 
	(LPSTR)path.c_str(),         // command line
 
	0,                    // process attributes
 
	0,                    // thread attributes
 
	0,                    // inherit handles
 
	0,                    // creation flags
 
	0,                    // environment
 
	0,                    // cwd
 
	&si,
 
	&pi
 
	)
 
	)  {
 
		LOG4CXX_ERROR(logger, "Could not start process");
 
	}
 

	
 
	return 0;
 
#else
 
	// Create array of char * from string using -lpopt library
 
	char *p = (char *) malloc(path.size() + 1);
 
	strcpy(p, path.c_str());
 
	int argc;
 
	char **argv;
 
	poptParseArgvString(p, &argc, (const char ***) &argv);
 

	
 
	// fork and exec
 
	pid_t pid = fork();
 
	if ( pid == 0 ) {
 
		setsid();
 
		// child process
 
		exit(execv(argv[0], argv));
 
	} else if ( pid < 0 ) {
 
		// fork failed
 
	}
 
	free(p);
 

	
 
	return (unsigned long) pid;
 
#endif
 
}
 

	
 
#ifndef _WIN32
 
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(0, &status, WNOHANG)) > 0) {
 
	while ((result = waitpid(-1, &status, WNOHANG)) > 0) {
 
		if (result != 0) {
 
			if (WIFEXITED(status)) {
 
				if (WEXITSTATUS(status) != 0) {
 
// 					LOG4CXX_ERROR(logger, "Backend can not be started, exit_code=" << WEXITSTATUS(status));
 
				}
 
			}
 
			else {
 
// 				LOG4CXX_ERROR(logger, "Backend can not be started");
 
			}
 
		}
 
	}
 
}
 
#endif
 

	
 
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()) {
 
		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++) {
 
		groups.push_back(payload.group(i));
 
	}
 
	if (!groups.empty()) {
 
		buddy->setGroups(groups);
 
	}
 

	
 
	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) {
 
	m_ftManager = ftManager;
 
	m_userManager = userManager;
 
	m_config = config;
 
	m_component = component;
 
	m_isNextLongRun = false;
 
	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));
 
	m_pingTimer->start();
 

	
 
	if (CONFIG_INT(m_config, "service.memory_collector_time") != 0) {
 
		m_collectTimer = component->getNetworkFactories()->getTimerFactory()->createTimer(CONFIG_INT(m_config, "service.memory_collector_time"));
 
		m_collectTimer->onTick.connect(boost::bind(&NetworkPluginServer::collectBackend, this));
 
		m_collectTimer->start();
 
	}
 

	
 
	m_vcardResponder = new VCardResponder(component->getIQRouter(), component->getNetworkFactories(), userManager);
 
	m_vcardResponder->onVCardRequired.connect(boost::bind(&NetworkPluginServer::handleVCardRequired, this, _1, _2, _3));
 
	m_vcardResponder->onVCardUpdated.connect(boost::bind(&NetworkPluginServer::handleVCardUpdated, this, _1, _2));
 
	m_vcardResponder->start();
 

	
 
	m_rosterResponder = new RosterResponder(component->getIQRouter(), userManager);
 
	m_rosterResponder->onBuddyAdded.connect(boost::bind(&NetworkPluginServer::handleBuddyAdded, this, _1, _2));
 
	m_rosterResponder->onBuddyRemoved.connect(boost::bind(&NetworkPluginServer::handleBuddyRemoved, this, _1));
 
	m_rosterResponder->onBuddyUpdated.connect(boost::bind(&NetworkPluginServer::handleBuddyUpdated, this, _1, _2));
 
	m_rosterResponder->start();
 

	
 
	m_blockResponder = new BlockResponder(component->getIQRouter(), userManager);
 
	m_blockResponder->onBlockToggled.connect(boost::bind(&NetworkPluginServer::handleBlockToggled, this, _1));
 
	m_blockResponder->start();
 

	
 
	m_server = component->getNetworkFactories()->getConnectionServerFactory()->createConnectionServer(Swift::HostAddress(CONFIG_STRING(m_config, "service.backend_host")), boost::lexical_cast<int>(CONFIG_STRING(m_config, "service.backend_port")));
 
	m_server->onNewConnection.connect(boost::bind(&NetworkPluginServer::handleNewClientConnection, this, _1));
 
	m_server->start();
 

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

	
 
#ifndef _WIN32
 
	signal(SIGCHLD, SigCatcher);
 
#endif
 

	
 
	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->getConfigFile().c_str());
 
	LOG4CXX_INFO(logger, "Backend should now connect to Spectrum2 instance. Spectrum2 won't accept any connection before backend connects");
 
}
 

	
 
NetworkPluginServer::~NetworkPluginServer() {
 
	for (std::list<Backend *>::const_iterator it = m_clients.begin(); it != m_clients.end(); it++) {
 
		LOG4CXX_INFO(logger, "Stopping backend " << *it);
 
		std::string message;
 
		pbnetwork::WrapperMessage wrap;
 
		wrap.set_type(pbnetwork::WrapperMessage_Type_TYPE_EXIT);
 
		wrap.SerializeToString(&message);
 

	
 
		Backend *c = (Backend *) *it;
 
		send(c->connection, message);
 
	}
 

	
 
	m_pingTimer->stop();
 
	m_server->stop();
 
	m_server.reset();
 
	delete m_component->m_factory;
 
	delete m_vcardResponder;
 
	delete m_rosterResponder;
 
	delete m_blockResponder;
 
}
 

	
 
void NetworkPluginServer::handleNewClientConnection(boost::shared_ptr<Swift::Connection> c) {
 
	// Create new Backend instance
 
	Backend *client = new Backend;
 
	client->pongReceived = -1;
 
	client->connection = c;
 
	client->res = 0;
 
	client->init_res = 0;
 
	client->shared = 0;
 
	client->willDie = 0;
 
	// 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 << " disconnected. Current backend count=" << (m_clients.size() - 1));
 

	
 
	// This backend will do, so we can't reconnect users to it in User::handleDisconnected call
 
	c->willDie = true;
 

	
 
	// If there are users associated with this backend, it must have crashed, so print error output
 
	// and disconnect users
 
	for (std::list<User *>::const_iterator it = c->users.begin(); it != c->users.end(); it++) {
 
		LOG4CXX_ERROR(logger, "Backend " << c << " disconnected (probably crashed) with active user " << (*it)->getJID().toString());
 
		(*it)->setData(NULL);
 
		(*it)->handleDisconnected("Internal Server Error, please reconnect.");
 
	}
 

	
 
	std::string message;
 
	pbnetwork::WrapperMessage wrap;
 
	wrap.set_type(pbnetwork::WrapperMessage_Type_TYPE_EXIT);
 
	wrap.SerializeToString(&message);
 

	
src/rostermanager.cpp
Show inline comments
 
@@ -192,250 +192,250 @@ 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();
 
	}
 
	else {
 
		LOG4CXX_WARN(logger, "handleBuddyRosterPushResponse called for unknown buddy " << key);
 
	}
 

	
 
	m_requests.remove(request);
 
	request->onResponse.disconnect_all_slots();
 
}
 

	
 
void RosterManager::handleRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref error) {
 
	m_remoteRosterRequest.reset();
 
	if (error) {
 
		m_supportRemoteRoster = false;
 
		LOG4CXX_INFO(logger, m_user->getJID().toString() << ": This server does not support remote roster protoXEP");
 
		return;
 
	}
 

	
 
	LOG4CXX_INFO(logger, m_user->getJID().toString() << ": This server supports remote roster protoXEP");
 
	m_supportRemoteRoster = true;
 
	return;
 

	
 
	BOOST_FOREACH(const Swift::RosterItemPayload &item, payload->getItems()) {
 
		std::string legacyName = Buddy::JIDToLegacyName(item.getJID());
 
		if (m_buddies.find(legacyName) != m_buddies.end()) {
 
			continue;
 
		}
 
		std::cout << "LEGACYNAME " << legacyName << "\n";
 

	
 
		BuddyInfo buddyInfo;
 
		buddyInfo.id = -1;
 
		buddyInfo.alias = item.getName();
 
		buddyInfo.legacyName = legacyName;
 
		buddyInfo.subscription = "both";
 
		buddyInfo.flags = Buddy::buddFlagsFromJID(item.getJID());
 

	
 
		Buddy *buddy = m_component->getFactory()->createBuddy(this, buddyInfo);
 
		setBuddy(buddy);
 
	}
 
}
 

	
 
Buddy *RosterManager::getBuddy(const std::string &name) {
 
	return m_buddies[name];
 
}
 

	
 
void RosterManager::sendRIE() {
 
	m_RIETimer->stop();
 

	
 
	// Check the feature, because proper resource could logout during RIETimer.
 
	Swift::JID jidWithRIE = m_user->getJIDWithFeature("http://jabber.org/protocol/rosterx");
 

	
 
	// fallback to normal subscribe
 
	if (!jidWithRIE.isValid()) {
 
		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;
 
			}
 
			sendBuddySubscribePresence(buddy);
 
		}
 
		return;
 
	}
 

	
 
	LOG4CXX_INFO(logger, "Sending RIE stanza to " << jidWithRIE.toString());
 

	
 
	Swift::RosterItemExchangePayload::ref payload = Swift::RosterItemExchangePayload::ref(new Swift::RosterItemExchangePayload());
 
	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::RosterItemExchangePayload::Item item;
 
		item.setJID(buddy->getJID().toBare());
 
		item.setName(buddy->getAlias());
 
		item.setAction(Swift::RosterItemExchangePayload::Item::Add);
 
		item.setGroups(buddy->getGroups());
 

	
 
		payload->addItem(item);
 
	}
 

	
 
	boost::shared_ptr<Swift::GenericRequest<Swift::RosterItemExchangePayload> > request(new Swift::GenericRequest<Swift::RosterItemExchangePayload>(Swift::IQ::Set, jidWithRIE, payload, m_component->getIQRouter()));
 
	request->send();
 
}
 

	
 
void RosterManager::handleSubscription(Swift::Presence::ref presence) {
 
	std::string legacyName = Buddy::JIDToLegacyName(presence->getTo());
 
	// For server mode the subscription changes are handler in rosterresponder.cpp
 
	// using roster pushes.
 
	if (m_component->inServerMode()) {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setTo(presence->getFrom());
 
		response->setFrom(presence->getTo());
 
		response->setTo(presence->getFrom().toBare());
 
		response->setFrom(presence->getTo().toBare());
 
		Buddy *buddy = getBuddy(Buddy::JIDToLegacyName(presence->getTo()));
 
		if (buddy) {
 
			LOG4CXX_INFO(logger, m_user->getJID().toString() << ": Subscription received and buddy " << Buddy::JIDToLegacyName(presence->getTo()) << " is already there => answering");
 
			switch (presence->getType()) {
 
				case Swift::Presence::Subscribe:
 
					onBuddyAdded(buddy);
 
					response->setType(Swift::Presence::Subscribed);
 
					break;
 
				case Swift::Presence::Unsubscribe:
 
					onBuddyRemoved(buddy);
 
					response->setType(Swift::Presence::Unsubscribed);
 
					break;
 
				case Swift::Presence::Subscribed:
 
					onBuddyAdded(buddy);
 
					break;
 
				default:
 
					return;
 
			}
 
			m_component->getStanzaChannel()->sendPresence(response);
 
			
 
		}
 
		else {
 
			BuddyInfo buddyInfo;
 
			switch (presence->getType()) {
 
				// buddy is not in roster, so add him
 
				case Swift::Presence::Subscribe:
 
					buddyInfo.id = -1;
 
					buddyInfo.alias = "";
 
					buddyInfo.legacyName = Buddy::JIDToLegacyName(presence->getTo());
 
					buddyInfo.subscription = "both";
 
					buddyInfo.flags = Buddy::buddFlagsFromJID(presence->getTo());
 
					LOG4CXX_INFO(logger, m_user->getJID().toString() << ": Subscription received for new buddy " << buddyInfo.legacyName << " => adding to legacy network");
 

	
 
					buddy = m_component->getFactory()->createBuddy(this, buddyInfo);
 
					setBuddy(buddy);
 
					onBuddyAdded(buddy);
 
					response->setType(Swift::Presence::Subscribed);
 
					break;
 
				case Swift::Presence::Subscribed:
 
					onBuddyAdded(buddy);
 
					break;
 
				// buddy is already there, so nothing to do, just answer
 
				case Swift::Presence::Unsubscribe:
 
					response->setType(Swift::Presence::Unsubscribed);
 
					break;
 
				default:
 
					return;
 
			}
 
			m_component->getStanzaChannel()->sendPresence(response);
 
		}
 
	}
 
	else {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		Swift::Presence::ref currentPresence;
 
		response->setTo(presence->getFrom().toBare());
 
		response->setFrom(presence->getTo().toBare().toString() + "/bot");
 
		response->setFrom(presence->getTo().toBare());
 

	
 
		Buddy *buddy = getBuddy(Buddy::JIDToLegacyName(presence->getTo()));
 
		if (buddy) {
 
			switch (presence->getType()) {
 
				// buddy is already there, so nothing to do, just answer
 
				case Swift::Presence::Subscribe:
 
					onBuddyAdded(buddy);
 
					response->setType(Swift::Presence::Subscribed);
 
					currentPresence = buddy->generatePresenceStanza(255);
 
					if (currentPresence) {
 
						currentPresence->setTo(presence->getFrom());
 
						m_component->getStanzaChannel()->sendPresence(currentPresence);
 
					}
 
					break;
 
				// remove buddy
 
				case Swift::Presence::Unsubscribe:
 
					response->setType(Swift::Presence::Unsubscribed);
 
					onBuddyRemoved(buddy);
 
					break;
 
				// just send response
 
				case Swift::Presence::Unsubscribed:
 
					response->setType(Swift::Presence::Unsubscribe);
 
					break;
 
				default:
 
					return;
 
			}
 
		}
 
		else {
 
			BuddyInfo buddyInfo;
 
			switch (presence->getType()) {
 
				// buddy is not in roster, so add him
 
				case Swift::Presence::Subscribe:
 
					buddyInfo.id = -1;
 
					buddyInfo.alias = "";
 
					buddyInfo.legacyName = Buddy::JIDToLegacyName(presence->getTo());
 
					buddyInfo.subscription = "both";
 
					buddyInfo.flags = Buddy::buddFlagsFromJID(presence->getTo());
 

	
 
					buddy = m_component->getFactory()->createBuddy(this, buddyInfo);
 
					setBuddy(buddy);
 
					onBuddyAdded(buddy);
 
					response->setType(Swift::Presence::Subscribed);
 
					break;
 
				// buddy is already there, so nothing to do, just answer
 
				case Swift::Presence::Unsubscribe:
 
					response->setType(Swift::Presence::Unsubscribed);
 
					onBuddyRemoved(buddy);
 
					break;
 
				// just send response
 
				case Swift::Presence::Unsubscribed:
 
					response->setType(Swift::Presence::Unsubscribe);
 
					break;
 
				// just send response
 
				default:
 
					return;
 
			}
 
		}
 

	
 
		m_component->getStanzaChannel()->sendPresence(response);
 

	
 
		// We have to act as buddy and send its subscribe/unsubscribe just to be sure...
 
		switch (response->getType()) {
 
			case Swift::Presence::Unsubscribed:
 
				response->setType(Swift::Presence::Unsubscribe);
 
				m_component->getStanzaChannel()->sendPresence(response);
 
				break;
 
			case Swift::Presence::Subscribed:
 
				response->setType(Swift::Presence::Subscribe);
 
				m_component->getStanzaChannel()->sendPresence(response);
 
				break;
 
			default:
 
				break;
 
		}
 
	}
 
}
 

	
 
void RosterManager::setStorageBackend(StorageBackend *storageBackend) {
 
	if (m_rosterStorage || !storageBackend) {
 
		return;
 
	}
 
	m_rosterStorage = new RosterStorage(m_user, storageBackend);
 

	
 
	std::list<BuddyInfo> roster;
 
	storageBackend->getBuddies(m_user->getUserInfo().id, roster);
 

	
 
	for (std::list<BuddyInfo>::const_iterator it = roster.begin(); it != roster.end(); it++) {
 
		Buddy *buddy = m_component->getFactory()->createBuddy(this, *it);
 
		LOG4CXX_INFO(logger, m_user->getJID().toString() << ": Adding cached buddy " << buddy->getName() << " fom database");
 
		m_buddies[buddy->getName()] = buddy;
 
		onBuddySet(buddy);
 
	}
 
}
 

	
 
Swift::RosterPayload::ref RosterManager::generateRosterPayload() {
 
	Swift::RosterPayload::ref payload = Swift::RosterPayload::ref(new Swift::RosterPayload());
 

	
src/sqlite3backend.cpp
Show inline comments
 
@@ -18,450 +18,461 @@
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#ifdef WITH_SQLITE
 

	
 
#include "transport/sqlite3backend.h"
 
#include "transport/util.h"
 
#include <boost/bind.hpp>
 
#include "log4cxx/logger.h"
 

	
 
using namespace log4cxx;
 

	
 
#define SQLITE_DB_VERSION 3
 
#define CHECK_DB_RESPONSE(stmt) \
 
	if(stmt) { \
 
		sqlite3_exec(m_db, "ROLLBACK;", NULL, NULL, NULL); \
 
		return 0; \
 
	}
 

	
 
// Prepare the SQL statement
 
#define PREP_STMT(sql, str) \
 
	if(sqlite3_prepare_v2(m_db, std::string(str).c_str(), -1, &sql, NULL)) { \
 
		LOG4CXX_ERROR(logger, str<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db))); \
 
		return false; \
 
	}
 

	
 
// Finalize the prepared statement
 
#define FINALIZE_STMT(prep) \
 
	if(prep != NULL) { \
 
		sqlite3_finalize(prep); \
 
	}
 
	
 
#define BEGIN(STATEMENT) 	sqlite3_reset(STATEMENT);\
 
							int STATEMENT##_id = 1;\
 
							int STATEMENT##_id_get = 0;\
 
							(void)STATEMENT##_id_get;
 

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

	
 
using namespace boost;
 

	
 
namespace Transport {
 

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

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

	
 
SQLite3Backend::~SQLite3Backend(){
 
	if (m_db) {
 
		// Would be nice to use this:
 
		//
 
		//   sqlite3_stmt *pStmt;
 
		//   while((pStmt = sqlite3_next_stmt(db, 0)) != 0 ) {
 
		//    sqlite3_finalize(pStmt);
 
		//   }
 
		//
 
		// But requires SQLite3 >= 3.6.0 beta
 
	
 
		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_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_setUserOnline);
 
		FINALIZE_STMT(m_getOnlineUsers);
 
		sqlite3_close(m_db);
 
	}
 
}
 

	
 
bool SQLite3Backend::connect() {
 
	LOG4CXX_INFO(logger, "Opening database " << CONFIG_STRING(m_config, "database.database"));
 
	if (sqlite3_open(CONFIG_STRING(m_config, "database.database").c_str(), &m_db)) {
 
		sqlite3_close(m_db);
 
		return false;
 
	}
 

	
 
	sqlite3_busy_timeout(m_db, 1500);
 

	
 
	if (createDatabase() == false)
 
		return false;
 

	
 
	PREP_STMT(m_setUser, "INSERT OR REPLACE INTO " + m_prefix + "users (jid, uin, password, language, encoding, last_login, vip) VALUES (?, ?, ?, ?, ?, DATETIME('NOW'), ?)");
 
	PREP_STMT(m_getUser, "SELECT id, jid, uin, password, encoding, language, vip FROM " + m_prefix + "users WHERE jid=?");
 

	
 
	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_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_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=?");
 
	PREP_STMT(m_getOnlineUsers, "SELECT jid FROM " + m_prefix + "users WHERE online=1");
 

	
 
	return true;
 
}
 

	
 
bool SQLite3Backend::createDatabase() {
 
	int not_exist = exec("CREATE TABLE " + m_prefix + "buddies ("
 
				"  id INTEGER PRIMARY KEY NOT NULL,"
 
				"  user_id int(10) NOT NULL,"
 
				"  uin varchar(255) NOT NULL,"
 
				"  subscription varchar(20) NOT NULL,"
 
				"  nickname varchar(255) NOT NULL,"
 
				"  groups varchar(255) NOT NULL,"
 
				"  flags int(4) NOT NULL DEFAULT '0'"
 
				");");
 

	
 
	if (not_exist) {
 
		exec("CREATE UNIQUE INDEX IF NOT EXISTS user_id ON " + m_prefix + "buddies (user_id, uin);");
 

	
 
		exec("CREATE TABLE IF NOT EXISTS " + m_prefix + "buddies_settings ("
 
					"  user_id int(10) NOT NULL,"
 
					"  buddy_id int(10) NOT NULL,"
 
					"  var varchar(50) NOT NULL,"
 
					"  type int(4) NOT NULL,"
 
					"  value varchar(255) NOT NULL,"
 
					"  PRIMARY KEY (buddy_id, var)"
 
					");");
 

	
 
		exec("CREATE INDEX IF NOT EXISTS user_id02 ON " + m_prefix + "buddies_settings (user_id);");
 

	
 
		exec("CREATE TABLE IF NOT EXISTS " + m_prefix + "users ("
 
					"  id INTEGER PRIMARY KEY NOT NULL,"
 
					"  jid varchar(255) NOT NULL,"
 
					"  uin varchar(4095) NOT NULL,"
 
					"  password varchar(255) NOT NULL,"
 
					"  language varchar(25) NOT NULL,"
 
					"  encoding varchar(50) NOT NULL DEFAULT 'utf8',"
 
					"  last_login datetime,"
 
					"  vip int(1) NOT NULL DEFAULT '0',"
 
					"  online int(1) NOT NULL DEFAULT '0'"
 
					");");
 

	
 
		exec("CREATE UNIQUE INDEX IF NOT EXISTS jid ON " + m_prefix + "users (jid);");
 

	
 
		exec("CREATE TABLE " + m_prefix + "users_settings ("
 
					"  user_id int(10) NOT NULL,"
 
					"  var varchar(50) NOT NULL,"
 
					"  type int(4) NOT NULL,"
 
					"  value varchar(4095) NOT NULL,"
 
					"  PRIMARY KEY (user_id, var)"
 
					");");
 
					
 
		exec("CREATE INDEX IF NOT EXISTS user_id03 ON " + m_prefix + "users_settings (user_id);");
 

	
 
		exec("CREATE TABLE IF NOT EXISTS " + m_prefix + "db_version ("
 
			"  ver INTEGER NOT NULL DEFAULT '3'"
 
			");");
 
		exec("REPLACE INTO " + m_prefix + "db_version (ver) values(3)");
 
	}
 
	return true;
 
}
 

	
 
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);
 
		sqlite3_free(errMsg);
 
		return false;
 
	}
 
	return true;
 
}
 

	
 
void SQLite3Backend::setUser(const UserInfo &user) {
 
	sqlite3_reset(m_setUser);
 
	sqlite3_bind_text(m_setUser, 1, user.jid.c_str(), -1, SQLITE_STATIC);
 
	sqlite3_bind_text(m_setUser, 2, user.uin.c_str(), -1, SQLITE_STATIC);
 
	sqlite3_bind_text(m_setUser, 3, user.password.c_str(), -1, SQLITE_STATIC);
 
	sqlite3_bind_text(m_setUser, 4, user.language.c_str(), -1, SQLITE_STATIC);
 
	sqlite3_bind_text(m_setUser, 5, user.encoding.c_str(), -1, SQLITE_STATIC);
 
	sqlite3_bind_int (m_setUser, 6, user.vip);
 

	
 
	if(sqlite3_step(m_setUser) != SQLITE_DONE) {
 
		LOG4CXX_ERROR(logger, "setUser query"<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
	}
 
}
 

	
 
bool SQLite3Backend::getUser(const std::string &barejid, UserInfo &user) {
 
// 	SELECT id, jid, uin, password, encoding, language, vip FROM " + m_prefix + "users WHERE jid=?
 
	sqlite3_reset(m_getUser);
 
	sqlite3_bind_text(m_getUser, 1, barejid.c_str(), -1, SQLITE_TRANSIENT);
 

	
 
	int ret;
 
	while((ret = sqlite3_step(m_getUser)) == SQLITE_ROW) {
 
		user.id = sqlite3_column_int(m_getUser, 0);
 
		user.jid = (const char *) sqlite3_column_text(m_getUser, 1);
 
		user.uin = (const char *) sqlite3_column_text(m_getUser, 2);
 
		user.password = (const char *) sqlite3_column_text(m_getUser, 3);
 
		user.encoding = (const char *) sqlite3_column_text(m_getUser, 4);
 
		user.language = (const char *) sqlite3_column_text(m_getUser, 5);
 
		user.vip = sqlite3_column_int(m_getUser, 6) != 0;
 
		while((ret = sqlite3_step(m_getUser)) == SQLITE_ROW) {
 
		}
 
		return true;
 
	}
 

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

	
 
	return false;
 
}
 

	
 
void SQLite3Backend::setUserOnline(long id, bool online) {
 
	BEGIN(m_setUserOnline);
 
	BIND_INT(m_setUserOnline, (int)online);
 
	BIND_INT(m_setUserOnline, id);
 
	EXECUTE_STATEMENT(m_setUserOnline, "setUserOnline query");
 
}
 

	
 
bool SQLite3Backend::getOnlineUsers(std::vector<std::string> &users) {
 
	sqlite3_reset(m_getOnlineUsers);
 

	
 
	int ret;
 
	while((ret = sqlite3_step(m_getOnlineUsers)) == SQLITE_ROW) {
 
		std::string jid = (const char *) sqlite3_column_text(m_getOnlineUsers, 0);
 
		users.push_back(jid);
 
	}
 

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

	
 
	return true;
 
}
 

	
 
long SQLite3Backend::addBuddy(long userId, const BuddyInfo &buddyInfo) {
 
// 	"INSERT INTO " + m_prefix + "buddies (user_id, uin, subscription, groups, nickname, flags) VALUES (?, ?, ?, ?, ?, ?)"
 
	BEGIN(m_addBuddy);
 
	BIND_INT(m_addBuddy, userId);
 
	BIND_STR(m_addBuddy, buddyInfo.legacyName);
 
	BIND_STR(m_addBuddy, buddyInfo.subscription);
 
	BIND_STR(m_addBuddy, Util::serializeGroups(buddyInfo.groups));
 
	BIND_STR(m_addBuddy, buddyInfo.alias);
 
	BIND_INT(m_addBuddy, buddyInfo.flags);
 

	
 
	if(sqlite3_step(m_addBuddy) != SQLITE_DONE) {
 
		LOG4CXX_ERROR(logger, "addBuddy query"<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
		return -1;
 
	}
 

	
 
	long id = (long) sqlite3_last_insert_rowid(m_db);
 

	
 
// 	INSERT OR REPLACE INTO " + m_prefix + "buddies_settings (user_id, buddy_id, var, type, value) VALUES (?, ?, ?, ?, ?)
 
	BEGIN(m_updateBuddySetting);
 
	BIND_INT(m_updateBuddySetting, userId);
 
	BIND_INT(m_updateBuddySetting, id);
 
	BIND_STR(m_updateBuddySetting, buddyInfo.settings.find("icon_hash")->first);
 
	BIND_INT(m_updateBuddySetting, TYPE_STRING);
 
	BIND_STR(m_updateBuddySetting, buddyInfo.settings.find("icon_hash")->second.s);
 

	
 
	EXECUTE_STATEMENT(m_updateBuddySetting, "updateBuddySetting query");
 
	return id;
 
}
 

	
 
void SQLite3Backend::updateBuddy(long userId, const BuddyInfo &buddyInfo) {
 
// 	UPDATE " + m_prefix + "buddies SET groups=?, nickname=?, flags=?, subscription=? WHERE user_id=? AND uin=?
 
	BEGIN(m_updateBuddy);
 
	BIND_STR(m_updateBuddy, Util::serializeGroups(buddyInfo.groups));
 
	BIND_STR(m_updateBuddy, buddyInfo.alias);
 
	BIND_INT(m_updateBuddy, buddyInfo.flags);
 
	BIND_STR(m_updateBuddy, buddyInfo.subscription);
 
	BIND_INT(m_updateBuddy, userId);
 
	BIND_STR(m_updateBuddy, buddyInfo.legacyName);
 

	
 
	EXECUTE_STATEMENT(m_updateBuddy, "updateBuddy query");
 

	
 
// 	INSERT OR REPLACE INTO " + m_prefix + "buddies_settings (user_id, buddy_id, var, type, value) VALUES (?, ?, ?, ?, ?)
 
	BEGIN(m_updateBuddySetting);
 
	BIND_INT(m_updateBuddySetting, userId);
 
	BIND_INT(m_updateBuddySetting, buddyInfo.id);
 
	BIND_STR(m_updateBuddySetting, buddyInfo.settings.find("icon_hash")->first);
 
	BIND_INT(m_updateBuddySetting, TYPE_STRING);
 
	BIND_STR(m_updateBuddySetting, buddyInfo.settings.find("icon_hash")->second.s);
 

	
 
	EXECUTE_STATEMENT(m_updateBuddySetting, "updateBuddySetting query");
 
}
 

	
 
bool SQLite3Backend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 
//	SELECT id, uin, subscription, nickname, groups, flags FROM " + m_prefix + "buddies WHERE user_id=? ORDER BY id ASC
 
	BEGIN(m_getBuddies);
 
	BIND_INT(m_getBuddies, id);
 

	
 
// 	"SELECT buddy_id, type, var, value FROM " + m_prefix + "buddies_settings WHERE user_id=? ORDER BY buddy_id ASC"
 
	BEGIN(m_getBuddiesSettings);
 
	BIND_INT(m_getBuddiesSettings, id);
 

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

	
 
	int ret;
 
	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);
 
		b.alias = GET_STR(m_getBuddies);
 
		std::string groups = GET_STR(m_getBuddies);
 
		b.groups = Util::deserializeGroups(groups);
 
		b.flags = GET_INT(m_getBuddies);
 

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

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

	
 
// 		if (ret != SQLITE_DONE) {
 
// 			LOG4CXX_ERROR(logger, "getBuddiesSettings query"<< (sqlite3_errmsg(m_db) == NULL ? "" : sqlite3_errmsg(m_db)));
 
// 			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)));
 
		return false;
 
	}
 
	
 
	return true;
 
}
 

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

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

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

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

	
 
	return true;
 
}
 

	
 
void SQLite3Backend::getUserSetting(long id, const std::string &variable, int &type, std::string &value) {
 
	BEGIN(m_getUserSetting);
 
	BIND_INT(m_getUserSetting, id);
 
	BIND_STR(m_getUserSetting, variable);
 
	if(sqlite3_step(m_getUserSetting) != SQLITE_ROW) {
 
		BEGIN(m_setUserSetting);
 
		BIND_INT(m_setUserSetting, id);
 
		BIND_STR(m_setUserSetting, variable);
 
		BIND_INT(m_setUserSetting, type);
 
		BIND_STR(m_setUserSetting, value);
 
		EXECUTE_STATEMENT(m_setUserSetting, "m_setUserSetting");
 
	}
 
	else {
 
		type = GET_INT(m_getUserSetting);
 
		value = GET_STR(m_getUserSetting);
 
	}
 

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

	
 
void SQLite3Backend::updateUserSetting(long id, const std::string &variable, const std::string &value) {
 
	BEGIN(m_updateUserSetting);
 
	BIND_STR(m_updateUserSetting, value);
 
	BIND_INT(m_updateUserSetting, id);
 
	BIND_STR(m_updateUserSetting, variable);
 
	EXECUTE_STATEMENT(m_updateUserSetting, "m_updateUserSetting");
 
}
 

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

	
 
void SQLite3Backend::commitTransaction() {
 
	exec("COMMIT TRANSACTION;");
 
}
 

	
 
}
 

	
 
#endif
src/usermanager.cpp
Show inline comments
 
@@ -213,194 +213,194 @@ void UserManager::handlePresence(Swift::Presence::ref presence) {
 
	// User can be handleDisconnected in addUser callback, so refresh the pointer
 
	user = getUser(userkey);
 
	if (!user) {
 
		m_userRegistry->onPasswordInvalid(presence->getFrom());
 
		return;
 
	}
 

	
 
	// Handle this presence
 
	user->handlePresence(presence);
 

	
 
	// Unavailable MUC presence should not trigger whole account disconnection, so block it here.
 
	bool isMUC = presence->getPayload<Swift::MUCPayload>() != NULL || *presence->getTo().getNode().c_str() == '#';
 
	if (isMUC)
 
		return;
 

	
 
	// Unavailable presence could remove this user, because he could be unavailable
 
	if (presence->getType() == Swift::Presence::Unavailable) {
 
		if (user) {
 
			Swift::Presence::ref highest = m_component->getPresenceOracle()->getHighestPriorityPresence(presence->getFrom().toBare());
 
			// There's no presence for this user, so disconnect
 
			if (!highest || (highest && highest->getType() == Swift::Presence::Unavailable)) {
 
				m_removeTimer->onTick.connect(boost::bind(&UserManager::handleRemoveTimeout, this, user->getJID().toBare().toString(), user, false));
 
				m_removeTimer->start();
 
			}
 
		}
 
	}
 
}
 

	
 
void UserManager::handleRemoveTimeout(const std::string jid, User *u, bool reconnect) {
 
	m_removeTimer->onTick.disconnect(boost::bind(&UserManager::handleRemoveTimeout, this, jid, u, reconnect));
 

	
 
	// Maybe this User instance has been deleted in mean time and we would remove new one,
 
	// so better check for it and ignore deletion if "u" does not exist anymore.
 
	User *user = getUser(jid);
 
	if (user != u) {
 
		return;
 
	}
 

	
 
	// Remove user
 
	if (user) {
 
		removeUser(user);
 
	}
 

	
 
	// Connect the user again when we're reconnecting.
 
	if (reconnect) {
 
		connectUser(jid);
 
	}
 
}
 

	
 
void UserManager::handleMessageReceived(Swift::Message::ref message) {
 
	User *user = getUser(message->getFrom().toBare().toString());
 
	if (!user ){
 
		return;
 
	}
 

	
 
	user->getConversationManager()->handleMessageReceived(message);
 
}
 

	
 
void UserManager::handleGeneralPresenceReceived(Swift::Presence::ref presence) {
 
	switch(presence->getType()) {
 
		case Swift::Presence::Subscribe:
 
		case Swift::Presence::Subscribed:
 
		case Swift::Presence::Unsubscribe:
 
		case Swift::Presence::Unsubscribed:
 
			handleSubscription(presence);
 
			break;
 
		case Swift::Presence::Available:
 
		case Swift::Presence::Unavailable:
 
			break;
 
		case Swift::Presence::Probe:
 
			handleProbePresence(presence);
 
			break;
 
		default:
 
			break;
 
	};
 
}
 

	
 
void UserManager::handleProbePresence(Swift::Presence::ref presence) {
 
	User *user = getUser(presence->getFrom().toBare().toString());
 

	
 
 	if (user) {
 
 		user->getRosterManager()->sendCurrentPresence(presence->getTo(), presence->getFrom());
 
 	}
 
 	else {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setFrom(presence->getTo());
 
		response->setTo(presence->getFrom());
 
		response->setType(Swift::Presence::Unavailable);
 
		m_component->getStanzaChannel()->sendPresence(response);
 
	}
 
}
 

	
 
void UserManager::handleSubscription(Swift::Presence::ref presence) {
 
	// answer to subscibe for transport itself
 
	if (presence->getType() == Swift::Presence::Subscribe && presence->getTo().getNode().empty()) {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setFrom(presence->getTo());
 
		response->setTo(presence->getFrom());
 
		response->setFrom(presence->getTo().toBare());
 
		response->setTo(presence->getFrom().toBare());
 
		response->setType(Swift::Presence::Subscribed);
 
		m_component->getStanzaChannel()->sendPresence(response);
 

	
 
// 		response = Swift::Presence::create();
 
// 		response->setFrom(presence->getTo());
 
// 		response->setTo(presence->getFrom());
 
// 		response->setType(Swift::Presence::Subscribe);
 
// 		m_component->getStanzaChannel()->sendPresence(response);
 
		return;
 
	}
 

	
 
	// Don't let RosterManager to handle presences for us
 
	if (presence->getTo().getNode().empty()) {
 
		return;
 
	}
 

	
 
	User *user = getUser(presence->getFrom().toBare().toString());
 

	
 
 	if (user) {
 
 		user->handleSubscription(presence);
 
 	}
 
 	else if (presence->getType() == Swift::Presence::Unsubscribe) {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setFrom(presence->getTo());
 
		response->setTo(presence->getFrom());
 
		response->setType(Swift::Presence::Unsubscribed);
 
		m_component->getStanzaChannel()->sendPresence(response);
 
	}
 
// 	else {
 
// // 		Log(presence->getFrom().toString().getUTF8String(), "Subscribe presence received, but this user is not logged in");
 
// 	}
 
}
 

	
 
void UserManager::connectUser(const Swift::JID &user) {
 
	// Called by UserRegistry in server mode when user connects the server and wants
 
	// to connect legacy network
 
	if (m_users.find(user.toBare().toString()) != m_users.end()) {
 
		if (!m_component->inServerMode()) {
 
			return;
 
		}
 

	
 
		User *u = m_users[user.toBare().toString()];
 
		if (u->isConnected()) {
 
			// User is already logged in, so his password is OK, but this new user has different password => bad password.
 
			// We can't call m_userRegistry->onPasswordInvalid() here, because this fuction is called from Swift::Parser
 
			// and onPasswordInvalid destroys whole session together with parser itself, which leads to crash.
 
			if (m_userRegistry->getUserPassword(user.toBare().toString()) != u->getUserInfo().password) {
 
				m_userRegistry->removeLater(user);
 
				return;
 
			}
 
			if (CONFIG_BOOL(m_component->getConfig(), "service.more_resources")) {
 
				m_userRegistry->onPasswordValid(user);
 
			}
 
			else {
 
				// Send message to currently logged in session
 
				boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
				msg->setBody("You have signed on from another location.");
 
				msg->setTo(user);
 
				msg->setFrom(m_component->getJID());
 
				m_component->getStanzaChannel()->sendMessage(msg);
 

	
 
				// Switch the session = accept new one, disconnect old one.
 
				// Unavailable presence from old session has to be ignored, otherwise it would disconnect the user from legacy network.
 
				m_userRegistry->onPasswordValid(user);
 
				m_component->onUserPresenceReceived.disconnect(bind(&UserManager::handlePresence, this, _1));
 
				dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getStanzaChannel())->finishSession(user, boost::shared_ptr<Swift::Element>(new Swift::StreamError()), true);
 
				m_component->onUserPresenceReceived.connect(bind(&UserManager::handlePresence, this, _1));
 
			}
 
		}
 
		else {
 
			// User is created, but not connected => he's loggin in or he just logged out, but hasn't been deleted yet.
 
			// Stop deletion process if there's any
 
			m_removeTimer->onTick.disconnect(boost::bind(&UserManager::handleRemoveTimeout, this, user.toBare().toString(), m_users[user.toBare().toString()], false));
 

	
 
			// Delete old User instance but create new one immediatelly
 
			m_removeTimer->onTick.connect(boost::bind(&UserManager::handleRemoveTimeout, this, user.toBare().toString(), m_users[user.toBare().toString()], true));
 
			m_removeTimer->start();
 
		}
 
	}
 
	else {
 
		// simulate initial available presence to start connecting this user.
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setTo(m_component->getJID());
 
		response->setFrom(user);
 
		response->setType(Swift::Presence::Available);
 
		dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getStanzaChannel())->onPresenceReceived(response);
 
	}
 
}
 

	
 

	
 
void UserManager::disconnectUser(const Swift::JID &user) {
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	response->setTo(m_component->getJID());
 
	response->setFrom(user);
 
	response->setType(Swift::Presence::Unavailable);
 
	dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getStanzaChannel())->onPresenceReceived(response);
src/userregistration.cpp
Show inline comments
 
/**
 
 * libtransport -- C++ library for easy XMPP Transports development
 
 *
 
 * Copyright (C) 2011, Jan Kaluza <hanzz.k@gmail.com>
 
 *
 
 * This program is free software; you can redistribute it and/or modify
 
 * it under the terms of the GNU General Public License as published by
 
 * the Free Software Foundation; either version 2 of the License, or
 
 * (at your option) any later version.
 
 *
 
 * This program is distributed in the hope that it will be useful,
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 * GNU General Public License for more details.
 
 *
 
 * You should have received a copy of the GNU General Public License
 
 * along with this program; if not, write to the Free Software
 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 
 */
 

	
 
#include "transport/userregistration.h"
 
#include "transport/usermanager.h"
 
#include "transport/storagebackend.h"
 
#include "transport/transport.h"
 
#include "transport/rostermanager.h"
 
#include "transport/user.h"
 
#include "Swiften/Elements/ErrorPayload.h"
 
#include <boost/shared_ptr.hpp>
 
#include <boost/thread.hpp>
 
#include <boost/date_time/posix_time/posix_time.hpp>
 
#include "log4cxx/logger.h"
 

	
 
using namespace Swift;
 
using namespace log4cxx;
 

	
 
namespace Transport {
 

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

	
 
UserRegistration::UserRegistration(Component *component, UserManager *userManager, StorageBackend *storageBackend) : Swift::Responder<Swift::InBandRegistrationPayload>(component->m_iqRouter) {
 
	m_component = component;
 
	m_config = m_component->m_config;
 
	m_storageBackend = storageBackend;
 
	m_userManager = userManager;
 
}
 

	
 
UserRegistration::~UserRegistration(){
 
}
 

	
 
bool UserRegistration::registerUser(const UserInfo &row) {
 
	UserInfo user;
 
	bool registered = m_storageBackend->getUser(row.jid, user);
 
	// 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);
 
	return true;
 
}
 

	
 
bool UserRegistration::unregisterUser(const std::string &barejid) {
 
	UserInfo userInfo;
 
	bool registered = m_storageBackend->getUser(barejid, userInfo);
 
	// This user is not registered
 
	if (!registered)
 
		return false;
 

	
 
	onUserUnregistered(userInfo);
 

	
 
	// We have to check if server supports remoteroster XEP and use it if it's supported or fallback to unsubscribe otherwise
 
	AddressedRosterRequest::ref request = AddressedRosterRequest::ref(new AddressedRosterRequest(m_component->getIQRouter(), barejid));
 
	request->onResponse.connect(boost::bind(&UserRegistration::handleUnregisterRemoteRosterResponse, this, _1, _2, barejid));
 
	request->send();
 

	
 
	return true;
 
}
 

	
 
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;
 

	
 
	if (remoteRosterNotSupported) {
 
		std::list <BuddyInfo> roster;
 
		m_storageBackend->getBuddies(userInfo.id, roster);
 
		for(std::list<BuddyInfo>::iterator u = roster.begin(); u != roster.end() ; u++){
 
			std::string name = Swift::JID::getEscapedNode((*u).legacyName);
 

	
 
			Swift::Presence::ref response;
 
			response = Swift::Presence::create();
 
			response->setTo(Swift::JID(barejid));
 
			response->setFrom(Swift::JID(name, m_component->getJID().toString()));
 
			response->setType(Swift::Presence::Unsubscribe);
 
			m_component->getStanzaChannel()->sendPresence(response);
 

	
 
			response = Swift::Presence::create();
 
			response->setTo(Swift::JID(barejid));
 
			response->setFrom(Swift::JID(name, m_component->getJID().toString()));
 
			response->setType(Swift::Presence::Unsubscribed);
 
			m_component->getStanzaChannel()->sendPresence(response);
 
		}
 
	}
 
	else {
 
		BOOST_FOREACH(Swift::RosterItemPayload it, payload->getItems()) {
 
			Swift::RosterPayload::ref p = Swift::RosterPayload::ref(new Swift::RosterPayload());
 
			Swift::RosterItemPayload item;
 
			item.setJID(it.getJID());
 
			item.setSubscription(Swift::RosterItemPayload::Remove);
 

	
 
			p->addItem(item);
 

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

	
 
@@ -148,258 +150,328 @@ void UserRegistration::handleUnregisterRemoteRosterResponse(boost::shared_ptr<Sw
 
	else {
 
		Swift::RosterPayload::ref payload = Swift::RosterPayload::ref(new Swift::RosterPayload());
 
		Swift::RosterItemPayload item;
 
		item.setJID(m_component->getJID());
 
		item.setSubscription(Swift::RosterItemPayload::Remove);
 
		payload->addItem(item);
 

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

	
 
bool UserRegistration::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::InBandRegistrationPayload> payload) {
 
	// TODO: backend should say itself if registration is needed or not...
 
	if (CONFIG_STRING(m_config, "service.protocol") == "irc") {
 
		sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
 
		return true;
 
	}
 

	
 
	std::string barejid = from.toBare().toString();
 

	
 
	if (!CONFIG_BOOL(m_config,"registration.enable_public_registration")) {
 
		std::list<std::string> const &x = CONFIG_LIST(m_config,"service.allowed_servers");
 
		if (std::find(x.begin(), x.end(), from.getDomain()) == x.end()) {
 
			LOG4CXX_INFO(logger, barejid << ": This user has no permissions to register an account")
 
			sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
 
			return true;
 
		}
 
	}
 

	
 
	boost::shared_ptr<InBandRegistrationPayload> reg(new InBandRegistrationPayload());
 

	
 
	UserInfo res;
 
	bool registered = m_storageBackend->getUser(barejid, res);
 

	
 
	std::string instructions = CONFIG_STRING(m_config, "registration.instructions");
 
	std::string usernameField = CONFIG_STRING(m_config, "registration.username_label");
 

	
 
	// normal jabber:iq:register
 
	reg->setInstructions(instructions);
 
	reg->setRegistered(registered);
 
	reg->setUsername(res.uin);
 
	if (CONFIG_STRING(m_config, "service.protocol") != "twitter" && CONFIG_STRING(m_config, "service.protocol") != "bonjour")
 
		reg->setPassword(res.password);
 

	
 

	
 
	// form
 
	Form::ref form(new Form(Form::FormType));
 
	form->setTitle((("Registration")));
 
	form->setInstructions((instructions));
 

	
 
	HiddenFormField::ref type = HiddenFormField::create();
 
	type->setName("FORM_TYPE");
 
	type->setValue("jabber:iq:register");
 
	form->addField(type);
 

	
 
	TextSingleFormField::ref username = TextSingleFormField::create();
 
	username->setName("username");
 
	username->setLabel((usernameField));
 
	username->setValue(res.uin);
 
	username->setRequired(true);
 
	form->addField(username);
 

	
 
	if (CONFIG_STRING(m_config, "service.protocol") != "twitter" && CONFIG_STRING(m_config, "service.protocol") != "bonjour") {
 
		TextPrivateFormField::ref password = TextPrivateFormField::create();
 
		password->setName("password");
 
		password->setLabel((("Password")));
 
		password->setRequired(true);
 
		form->addField(password);
 
	}
 

	
 
	ListSingleFormField::ref language = ListSingleFormField::create();
 
	language->setName("language");
 
	language->setLabel((("Language")));
 
	language->addOption(Swift::FormField::Option(CONFIG_STRING(m_config, "registration.language"), CONFIG_STRING(m_config, "registration.language")));
 
	if (registered)
 
		language->setValue(res.language);
 
	else
 
		language->setValue(CONFIG_STRING(m_config, "registration.language"));
 
	form->addField(language);
 

	
 
//	TextSingleFormField::ref encoding = TextSingleFormField::create();
 
//	encoding->setName("encoding");
 
//	encoding->setLabel((("Encoding")));
 
//	if (registered)
 
//		encoding->setValue(res.encoding);
 
//	else
 
//		encoding->setValue(CONFIG_STRING(m_config, "registration.encoding"));
 
//	form->addField(encoding);
 

	
 
	if (registered) {
 
		BooleanFormField::ref boolean = BooleanFormField::create();
 
		boolean->setName("unregister");
 
		boolean->setLabel((("Remove your registration")));
 
		boolean->setValue(0);
 
		form->addField(boolean);
 
	} else {
 
		if (CONFIG_BOOL(m_config,"registration.require_local_account")) {
 
			std::string localUsernameField = CONFIG_STRING(m_config, "registration.local_username_label");
 
			TextSingleFormField::ref local_username = TextSingleFormField::create();
 
			local_username->setName("local_username");
 
			local_username->setLabel((localUsernameField));
 
			local_username->setRequired(true);
 
			form->addField(local_username);
 
			TextPrivateFormField::ref local_password = TextPrivateFormField::create();
 
			local_password->setName("local_password");
 
			local_password->setLabel((("Local Password")));
 
			local_password->setRequired(true);
 
			form->addField(local_password);
 
		}
 
	}
 

	
 
	reg->setForm(form);
 

	
 
	sendResponse(from, id, reg);
 

	
 
	return true;
 
}
 

	
 
bool UserRegistration::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::InBandRegistrationPayload> payload) {
 
	// TODO: backend should say itself if registration is needed or not...
 
	if (CONFIG_STRING(m_config, "service.protocol") == "irc") {
 
		sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
 
		return true;
 
	}
 

	
 
	std::string barejid = from.toBare().toString();
 

	
 
	if (!CONFIG_BOOL(m_config,"registration.enable_public_registration")) {
 
		std::list<std::string> const &x = CONFIG_LIST(m_config,"service.allowed_servers");
 
		if (std::find(x.begin(), x.end(), from.getDomain()) == x.end()) {
 
			LOG4CXX_INFO(logger, barejid << ": This user has no permissions to register an account")
 
			sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
 
			return true;
 
		}
 
	}
 

	
 
	UserInfo res;
 
	bool registered = m_storageBackend->getUser(barejid, res);
 

	
 
	std::string encoding;
 
	std::string language;
 
	std::string local_username("");
 
	std::string local_password("");
 

	
 
	Form::ref form = payload->getForm();
 
	if (form) {
 
		const std::vector<FormField::ref> fields = form->getFields();
 
		for (std::vector<FormField::ref>::const_iterator it = fields.begin(); it != fields.end(); it++) {
 
			TextSingleFormField::ref textSingle = boost::dynamic_pointer_cast<TextSingleFormField>(*it);
 
			if (textSingle) {
 
				if (textSingle->getName() == "username") {
 
					payload->setUsername(textSingle->getValue());
 
				}
 
				else if (textSingle->getName() == "encoding") {
 
					encoding = textSingle->getValue();
 
				}
 
				// Pidgin sends it as textSingle, not sure why...
 
				else if (textSingle->getName() == "password") {
 
					payload->setPassword(textSingle->getValue());
 
				}
 
				else if (textSingle->getName() == "local_username") {
 
					local_username = textSingle->getValue();
 
				}
 
				// Pidgin sends it as textSingle, not sure why...
 
				else if (textSingle->getName() == "local_password") {
 
					local_password = textSingle->getValue();
 
				}
 
				continue;
 
			}
 

	
 
			TextPrivateFormField::ref textPrivate = boost::dynamic_pointer_cast<TextPrivateFormField>(*it);
 
			if (textPrivate) {
 
				if (textPrivate->getName() == "password") {
 
					payload->setPassword(textPrivate->getValue());
 
				}
 
				else if (textPrivate->getName() == "local_password") {
 
					local_password = textPrivate->getValue();
 
				}
 
				continue;
 
			}
 

	
 
			ListSingleFormField::ref listSingle = boost::dynamic_pointer_cast<ListSingleFormField>(*it);
 
			if (listSingle) {
 
				if (listSingle->getName() == "language") {
 
					language = listSingle->getValue();
 
				}
 
				continue;
 
			}
 

	
 
			BooleanFormField::ref boolean = boost::dynamic_pointer_cast<BooleanFormField>(*it);
 
			if (boolean) {
 
				if (boolean->getName() == "unregister") {
 
					if (boolean->getValue()) {
 
						payload->setRemove(true);
 
					}
 
				}
 
				continue;
 
			}
 
		}
 
	}
 

	
 
	if (payload->isRemove()) {
 
		unregisterUser(barejid);
 
		sendResponse(from, id, InBandRegistrationPayload::ref());
 
		return true;
 
	}
 

	
 
	if (CONFIG_BOOL(m_config,"registration.require_local_account")) {
 
	/*	if (!local_username || !local_password) {
 
			sendResponse(from, id, InBandRegistrationPayload::ref());
 
			return true
 
		} else */ if (local_username == "" || local_password == "") {
 
			sendResponse(from, id, InBandRegistrationPayload::ref());
 
			return true;
 
		} 
 
//		Swift::logging = true;
 
		bool validLocal = false;
 
		std::string localLookupServer = CONFIG_STRING(m_config, "registration.local_account_server");
 
		std::string localLookupJID = local_username + std::string("@") + localLookupServer;
 
		SimpleEventLoop localLookupEventLoop;
 
		BoostNetworkFactories localLookupNetworkFactories(&localLookupEventLoop);
 
		Client localLookupClient(localLookupJID, local_password, &localLookupNetworkFactories);
 
		
 
		// TODO: this is neccessary on my server ... but should maybe omitted
 
		localLookupClient.setAlwaysTrustCertificates();
 
		localLookupClient.connect();
 

	
 
		class SimpleLoopRunner {
 
			public:
 
				SimpleLoopRunner() {};
 

	
 
				static void run(SimpleEventLoop * loop) {
 
					loop->run();
 
				};
 
		};
 

	
 
		// TODO: Really ugly and hacky solution, any other ideas more than welcome!
 
		boost::thread thread(boost::bind(&(SimpleLoopRunner::run), &localLookupEventLoop));
 
		thread.timed_join(boost::posix_time::millisec(CONFIG_INT(m_config, "registration.local_account_server_timeout")));
 
		localLookupEventLoop.stop();
 
		thread.join();
 
		validLocal = localLookupClient.isAvailable();
 
		localLookupClient.disconnect();
 
		if (!validLocal) {
 
			sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Modify);
 
			return true;
 
		}
 
	}
 

	
 
	printf("here\n");
 

	
 
	if (!payload->getUsername() || !payload->getPassword()) {
 
		sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
 
		return true;
 
	}
 

	
 
	// Register or change password
 
	if (payload->getUsername()->empty()) {
 
		sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
 
		return true;
 
	}
 

	
 
	// TODO: Move this check to backend somehow
 
	if (CONFIG_STRING(m_config, "service.protocol") == "prpl-jabber") {
 
		// User tries to register himself.
 
		if ((Swift::JID(*payload->getUsername()).toBare() == from.toBare())) {
 
			sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
 
			return true;
 
		}
 

	
 
		// User tries to register someone who's already registered.
 
		UserInfo user_row;
 
		bool registered = m_storageBackend->getUser(Swift::JID(*payload->getUsername()).toBare().toString(), user_row);
 
		if (registered) {
 
			sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
 
			return true;
 
		}
 
	}
 

	
 
	std::string username = *payload->getUsername();
 

	
 
	std::string newUsername(username);
 
	if (!CONFIG_STRING(m_config, "registration.username_mask").empty()) {
 
		newUsername = CONFIG_STRING(m_config, "registration.username_mask");
 
		boost::replace_all(newUsername, "$username", username);
 
	}
 

	
 
//TODO: Part of spectrum1 registration stuff, this should be potentially rewritten for S2 too
 
// 	if (!m_component->protocol()->isValidUsername(newUsername)) {
 
// 		Log("UserRegistration", "This is not valid username: "<< newUsername);
 
// 		sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
 
// 		return true;
 
// 	}
 

	
 
//TODO: Part of spectrum1 registration stuff, this should be potentially rewritten for S2 too
 
// #if GLIB_CHECK_VERSION(2,14,0)
 
// 	if (!CONFIG_STRING(m_config, "registration.reg_allowed_usernames").empty() &&
 
// 		!g_regex_match_simple(CONFIG_STRING(m_config, "registration.reg_allowed_usernames"), newUsername.c_str(),(GRegexCompileFlags) (G_REGEX_CASELESS | G_REGEX_EXTENDED), (GRegexMatchFlags) 0)) {
 
// 		Log("UserRegistration", "This is not valid username: "<< newUsername);
 
// 		sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
 
// 		return true;
 
// 	}
 
// #endif
 
	if (!registered) {
 
		res.jid = barejid;
 
		res.uin = username;
 
		res.password = *payload->getPassword();
 
		res.language = language;
 
		res.encoding = encoding;
 
		res.vip = 0;
 
		registerUser(res);
 
	}
 
	else {
 
		res.jid = barejid;
 
		res.uin = username;
 
		res.password = *payload->getPassword();
 
		res.language = language;
 
		res.encoding = encoding;
 
		m_storageBackend->setUser(res);
 
		onUserUpdated(res);
 
	}
 

	
 
	sendResponse(from, id, InBandRegistrationPayload::ref());
 
	return true;
 
}
 

	
 
}
0 comments (0 inline, 0 general)