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

	
 
	std::cout << "dfrotz -p " << game << "\n";
 

	
 
	if ((p.pid = fork()) < 0) {
 
		/* FATAL: cannot fork child */
 
	}
 
	else if (p.pid == 0) {
 
		close(PARENT_WRITE);
 
		close(PARENT_READ);
 

	
 
		dup2(CHILD_READ,  0);  close(CHILD_READ);
 
		dup2(CHILD_WRITE, 1);  close(CHILD_WRITE);
 

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

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

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

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

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

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

	
 
		void handleLoginRequest(const std::string &user, const std::string &legacyName, const std::string &password) {
 
			np->handleConnected(user);
 
			np->handleBuddyChanged(user, "zcode", "ZCode", "ZCode", pbnetwork::STATUS_ONLINE);
 
// 			sleep(1);
 
// 			np->handleMessage(np->m_user, "zork", first_msg);
 
		}
 

	
 
		void handleLogoutRequest(const std::string &user, const std::string &legacyName) {
 
			if (games.find(user) != games.end()) {
 
				kill(games[user].pid, SIGTERM);
 
				games.erase(user);
 
			}
 
// 			exit(0);
 
		}
 

	
 
		void readMessage(const std::string &user) {
 
			static char buf[15000];
 
			buf[0] = 0;
 
			int repeated = 0;
 
			while (strlen(buf) == 0) {
 
				ssize_t len = read(games[user].readpipe[0], buf, 15000);
 
				if (len > 0) {
 
@@ -199,49 +218,50 @@ class FrotzNetworkPlugin : public NetworkPlugin {
 
				if (len > 0) {
 
					buf[len] = 0;
 
				}
 
				usleep(1000);
 
				repeated++;
 
				if (repeated > 30)
 
					return;
 
			}
 

	
 
			std::cout << "ignoring: " << buf << "\n";
 
		}
 

	
 
		std::vector<std::string> getGames() {
 
			std::vector<std::string> games;
 
			path p(".");
 
			directory_iterator end_itr;
 
			for (directory_iterator itr(p); itr != end_itr; ++itr) {
 
				if (extension(itr->path()) == ".z5") {
 
					games.push_back(itr->path().leaf());
 
				}
 
			}
 
			return games;
 
		}
 

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

	
 
				dfrotz d;
 
				d.game = game;
 
				start_dfrotz(d, game);
 
				games[user] = d;
 
				fcntl(games[user].readpipe[0], F_SETFL, O_NONBLOCK);
 

	
 
				if (boost::filesystem::exists(user + "_" + games[user].game + ".save")) {
 

	
 
					std::string msg = "restore\n";
 
					write(games[user].writepipe[1], msg.c_str(), msg.size());
 

	
 
					msg = user + "_" + games[user].game + ".save\n";
 
					write(games[user].writepipe[1], msg.c_str(), msg.size());
 

	
 
					ignoreMessage(user);
backends/libpurple/main.cpp
Show inline comments
 
@@ -479,89 +479,90 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
				name = name.substr(name.find(".") + 1);
 
			}
 
		}
 

	
 
		void setDefaultAvatar(PurpleAccount *account, const std::string &legacyName) {
 
			char* contents;
 
			gsize length;
 
			gboolean ret = false;
 
			if (!KEYFILE_STRING("backend", "avatars_directory").empty()) {
 
				std::string f = KEYFILE_STRING("backend", "avatars_directory") + "/" + legacyName;
 
				ret = g_file_get_contents (f.c_str(), &contents, &length, NULL);
 
			}
 

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

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

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

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

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

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

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

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

	
 
			if (password.empty()) {
 
				np->handleDisconnected(user, 0, "Empty password.");
 
				return;
 
			}
 

	
 
			if (!purple_find_prpl(protocol.c_str())) {
 
				np->handleDisconnected(user, 0, "Invalid protocol " + protocol);
 
				return;
 
			}
 

	
 
			LOG4CXX_INFO(logger,  "Creating account with name '" << name.c_str() << "' and protocol '" << protocol << "'");
 
			if (purple_accounts_find(name.c_str(), protocol.c_str()) != NULL){
 
				account = purple_accounts_find(name.c_str(), protocol.c_str());
 
			}
 
			else {
 
@@ -713,49 +714,48 @@ class SpectrumNetworkPlugin : public NetworkPlugin {
 
				PurpleConversation *conv = purple_find_conversation_with_account(PURPLE_CONV_TYPE_IM, legacyName.c_str(), account);
 
				if (!conv) {
 
					conv = purple_conversation_new(PURPLE_CONV_TYPE_IM, account, legacyName.c_str());
 
				}
 
				if (xhtml.empty()) {
 
					gchar *_markup = purple_markup_escape_text(message.c_str(), -1);
 
					purple_conv_im_send(PURPLE_CONV_IM(conv), _markup);
 
					g_free(_markup);
 
				}
 
				else {
 
					purple_conv_im_send(PURPLE_CONV_IM(conv), xhtml.c_str());
 
				}
 
			}
 
		}
 

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

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

	
 
		void handleVCardUpdatedRequest(const std::string &user, const std::string &image, const std::string &nickname) {
 
			PurpleAccount *account = m_sessions[user];
 
			if (account) {
 
				purple_account_set_alias(account, nickname.c_str());
 
				purple_account_set_public_alias(account, nickname.c_str(), NULL, NULL);
 
				gssize size = image.size();
 
				// this will be freed by libpurple
 
				guchar *photo = (guchar *) g_malloc(size * sizeof(guchar));
 
				memcpy(photo, image.c_str(), size);
 

	
 
				if (!photo)
 
					return;
 
@@ -995,49 +995,49 @@ static std::string getIconHash(PurpleBuddy *m_buddy) {
 
		}
 
		else {
 
			std::string ret(avatarHash);
 
			g_free(avatarHash);
 
			return ret;
 
		}
 
	}
 

	
 
	return "";
 
}
 

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

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

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

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

	
 
	bool blocked = false;
 
	if (KEYFILE_BOOL("service", "enable_privacy_lists")) {
 
		if (prpl_info && prpl_info->tooltip_text) {
 
			PurpleNotifyUserInfo *user_info = purple_notify_user_info_new();
 
			prpl_info->tooltip_text(buddy, user_info, true);
 
			GList *entries = purple_notify_user_info_get_entries(user_info);
 

	
 
			while (entries) {
 
				PurpleNotifyUserInfoEntry *entry = (PurpleNotifyUserInfoEntry *)(entries->data);
 
				if (purple_notify_user_info_entry_get_label(entry) && purple_notify_user_info_entry_get_value(entry)) {
 
					std::string label = purple_notify_user_info_entry_get_label(entry);
 
					if (label == "Blocked" ) {
 
						if (std::string(purple_notify_user_info_entry_get_value(entry)) == "Yes") {
 
							blocked = true;
 
							break;
 
						}
 
					}
 
@@ -1049,49 +1049,48 @@ static void buddyListNewNode(PurpleBlistNode *node) {
 

	
 
		if (!blocked) {
 
			blocked = purple_privacy_check(account, purple_buddy_get_name(buddy)) == false;
 
		}
 
		else {
 
			bool purpleBlocked = purple_privacy_check(account, purple_buddy_get_name(buddy)) == false;
 
			if (blocked != purpleBlocked) {
 
				purple_privacy_deny(account, purple_buddy_get_name(buddy), FALSE, FALSE);
 
			}
 
		}
 
	}
 

	
 
	np->handleBuddyChanged(np->m_accounts[account], purple_buddy_get_name(buddy), getAlias(buddy), getGroups(buddy)[0], status, message, getIconHash(buddy),
 
		blocked
 
	);
 
}
 

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

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

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

	
 
static PurpleBlistUiOps blistUiOps =
 
{
 
	NULL,
 
	buddyListNewNode,
 
	NULL,
 
	buddyListUpdate,
 
	NULL, //NodeRemoved,
 
	NULL,
 
	NULL,
 
	NULL, // buddyListAddBuddy,
 
	NULL,
 
	NULL,
 
	NULL, //buddyListSaveNode,
 
@@ -1238,49 +1237,48 @@ static void *notify_user_info(PurpleConnection *gc, const char *who, PurpleNotif
 
			else if (label == "Family Name" || label == "Last Name") {
 
				lastName = purple_notify_user_info_entry_get_value(vcardEntry);
 
			}
 
			else if (label=="Nickname" || label == "Nick") {
 
				nickname = purple_notify_user_info_entry_get_value(vcardEntry);
 
			}
 
			else if (label=="Full Name") {
 
				fullName = purple_notify_user_info_entry_get_value(vcardEntry);
 
			}
 
			else {
 
				LOG4CXX_WARN(logger, "Unhandled VCard Label '" << purple_notify_user_info_entry_get_label(vcardEntry) << "' " << purple_notify_user_info_entry_get_value(vcardEntry));
 
			}
 
		}
 
		vcardEntries = vcardEntries->next;
 
	}
 

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

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

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

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

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

	
 
		// avatar
 
		PurpleStoredImage *avatar = purple_buddy_icons_find_account_icon(account);
 
		if (avatar) {
 
			const gchar * data = (const gchar *) purple_imgstore_get_data(avatar);
 
			size_t len = purple_imgstore_get_size(avatar);
 
			if (len < 300000 && data) {
 
				photo = std::string(data, len);
 
			}
 
			purple_imgstore_unref(avatar);
 
		}
 
	}
 

	
 
	PurpleBuddy *buddy = purple_find_buddy(purple_connection_get_account(gc), who);
 
@@ -1679,57 +1677,62 @@ static bool initPurple() {
 
// 
 
// 		purple_commands_init();
 

	
 
	}
 
	return ret;
 
}
 

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

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

	
 
	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
 

	
 
@@ -1800,48 +1803,49 @@ int main(int argc, char **argv) {
 

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

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

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

	
 
		GMainLoop *m_loop;
 
#ifdef WITH_LIBEVENT
 
		if (!libev) {
 
			m_loop = g_main_loop_new(NULL, FALSE);
 
		}
 
		else {
 
			event_init();
 
		}
 
#endif
 
		m_loop = g_main_loop_new(NULL, FALSE);
 

	
 
		if (m_loop) {
 
			g_main_loop_run(m_loop);
 
		}
 
#ifdef WITH_LIBEVENT
 
		else {
 
			event_loop(0);
 
		}
 
#endif
 
	}
cmake_modules/SwiftenConfig.cmake
Show inline comments
 
FIND_LIBRARY(SWIFTEN_LIBRARY NAMES Swiften)
 
FIND_PATH(SWIFTEN_INCLUDE_DIR NAMES "Swiften.h" PATH_SUFFIXES libSwiften Swiften )
 

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

	
 
	set( SWIFTEN_INCLUDE_DIR ${SWIFTEN_INCLUDE_DIR}/.. )
 
	message( STATUS "Found libSwiften: ${SWIFTEN_LIBRARY}, ${SWIFTEN_INCLUDE_DIR}")
 
	set( SWIFTEN_FOUND 1 )
 
else( SWIFTEN_LIBRARY AND SWIFTEN_INCLUDE_DIR )
 
    message( FATAL_ERROR "Could NOT find libSwiften" )
 
endif( SWIFTEN_LIBRARY AND SWIFTEN_INCLUDE_DIR )
include/Swiften/Network/DummyNetworkFactories.cpp
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#include <Swiften/Network/DummyNetworkFactories.h>
 
#include <Swiften/Network/DummyTimerFactory.h>
 
#include <Swiften/Network/DummyConnectionFactory.h>
 
#include <Swiften/Network/PlatformDomainNameResolver.h>
 
#include <Swiften/Network/DummyConnectionServerFactory.h>
 

	
 
namespace Swift {
 

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

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

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

	
 
#pragma once
 

	
 
#include <Swiften/Network/NetworkFactories.h>
 
#include <Swiften/Parser/PlatformXMLParserFactory.h>
 

	
 
namespace Swift {
 
	class EventLoop;
 

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

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

	
 
			virtual ConnectionFactory* getConnectionFactory() const {
 
				return connectionFactory;
 
			}
 

	
 
			DomainNameResolver* getDomainNameResolver() const {
 
				return domainNameResolver;
 
			}
 

	
 
			ConnectionServerFactory* getConnectionServerFactory() const {
 
				return connectionServerFactory;
 
			}
 

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

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

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

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

	
 
		private:
 
			PlatformXMLParserFactory *m_platformXMLParserFactory;
 
			TimerFactory* timerFactory;
 
			ConnectionFactory* connectionFactory;
 
			DomainNameResolver* domainNameResolver;
 
			ConnectionServerFactory* connectionServerFactory;
 
	};
 
}
include/Swiften/Server/ServerFromClientSession.cpp
Show inline comments
 
/*
 
 * Copyright (c) 2010 Remko Tronçon
 
 * Licensed under the GNU General Public License v3.
 
 * See Documentation/Licenses/GPLv3.txt for more information.
 
 */
 

	
 
#include <Swiften/Server/ServerFromClientSession.h>
 

	
 
#include <boost/bind.hpp>
 

	
 
#include <Swiften/Elements/ProtocolHeader.h>
 
#include <Swiften/Elements/StreamError.h>
 
#include <Swiften/Elements/Message.h>
 
#include <Swiften/Server/UserRegistry.h>
 
#include <Swiften/Network/Connection.h>
 
#include <Swiften/StreamStack/XMPPLayer.h>
 
#include <Swiften/Elements/StreamFeatures.h>
 
#include <Swiften/Elements/ResourceBind.h>
 
#include <Swiften/Elements/StartSession.h>
 
#include <Swiften/Elements/IQ.h>
 
#include <Swiften/Elements/AuthSuccess.h>
 
#include <Swiften/Elements/AuthFailure.h>
 
#include <Swiften/Elements/AuthRequest.h>
 
#include <Swiften/SASL/PLAINMessage.h>
 
#include <Swiften/StreamStack/StreamStack.h>
 
#include <Swiften/StreamStack/TLSServerLayer.h>
 
#include <Swiften/Elements/StartTLSRequest.h>
 
#include <Swiften/Elements/TLSProceed.h>
 
#include <iostream>
 

	
 
namespace Swift {
 

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

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

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

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

	
 
void ServerFromClientSession::handleElement(boost::shared_ptr<Element> element) {
 
	if (isInitialized()) {
 
		onElementReceived(element);
 
	}
 
	else {
 
		if (AuthRequest* authRequest = dynamic_cast<AuthRequest*>(element.get())) {
 
			if (authRequest->getMechanism() == "PLAIN" || (allowSASLEXTERNAL && authRequest->getMechanism() == "EXTERNAL")) {
 
				if (authRequest->getMechanism() == "EXTERNAL") {
 
						getXMPPLayer()->writeElement(boost::shared_ptr<AuthSuccess>(new AuthSuccess()));
 
						authenticated_ = true;
 
						getXMPPLayer()->resetParser();
 
				}
 
				else {
 
					PLAINMessage plainMessage(authRequest->getMessage() ? *authRequest->getMessage() : createSafeByteArray(""));
 
					user_ = plainMessage.getAuthenticationID();
 
					userRegistry_->isValidUserPassword(JID(plainMessage.getAuthenticationID(), getLocalJID().getDomain()), this, plainMessage.getPassword());
 
				}
 
			}
 
			else {
 
				getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
include/Swiften/Server/ServerFromClientSession.h
Show inline comments
 
@@ -18,65 +18,66 @@
 

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

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

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

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

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

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

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

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

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

	
 
		private:
 
			std::string id_;
 
			UserRegistry* userRegistry_;
 
			bool authenticated_;
 
			bool initialized;
 
			bool allowSASLEXTERNAL;
 
			std::string user_;
 
			TLSServerLayer* tlsLayer;
 
			bool tlsConnected;
 
	};
include/Swiften/Server/ServerStanzaChannel.cpp
Show inline comments
 
@@ -8,49 +8,48 @@
 
#include "Swiften/Base/Error.h"
 
#include <iostream>
 

	
 
#include <boost/bind.hpp>
 

	
 
namespace Swift {
 

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

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

	
 
void ServerStanzaChannel::addSession(boost::shared_ptr<ServerFromClientSession> session) {
 
	std::cout << "ADDING SESSION\n";
 
	sessions[session->getRemoteJID().toBare().toString()].push_back(session);
 
	session->onSessionFinished.connect(boost::bind(&ServerStanzaChannel::handleSessionFinished, this, _1, session));
 
	session->onElementReceived.connect(boost::bind(&ServerStanzaChannel::handleElement, this, _1, session));
 
}
 

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

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

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

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

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

	
 
FILE(GLOB HEADERS *.h protocol.h)
 

	
 
INSTALL(FILES ${HEADERS} DESTINATION include/transport COMPONENT headers)
 
\ No newline at end of file
include/transport/userregistry.h
Show inline comments
 
@@ -61,49 +61,49 @@ class UserRegistry : public Swift::UserRegistry {
 
		/// 	- service.admin_username - username for admin account
 
		/// 	- service.admin_password - password for admin account
 
		UserRegistry(Config *cfg, Swift::NetworkFactories *factories);
 

	
 
		/// Destructor.
 
		virtual ~UserRegistry();
 

	
 
		/// Called to detect wheter the password is valid.
 
		/// \param user JID of user who is logging in.
 
		/// \param session Session associated with this user.
 
		/// \param password Password used for this session.
 
		void isValidUserPassword(const Swift::JID& user, Swift::ServerFromClientSession *session, const Swift::SafeByteArray& password);
 

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

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

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

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

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

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

	
 
		/// Emitted when user disconnected XMPP server and therefore should disconnect legacy network.
 
		boost::signal<void (const Swift::JID &user)> onDisconnectUser;
 

	
 
	private:
 
		typedef struct {
 
			std::string password;
 
			Swift::ServerFromClientSession *session;
 
		} Sess;
 

	
 
		void handleRemoveTimeout(const Swift::JID &user);
 

	
 
		mutable std::map<std::string, Sess> users;
plugin/CMakeLists.txt
Show inline comments
 
new file 100644
 
ADD_SUBDIRECTORY(src)
plugin/src/CMakeLists.txt
Show inline comments
 
new file 100644
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp *.h)
 
FILE(GLOB HEADERS ../include/transport/*.h)
 
 
ADD_LIBRARY(transport-plugin SHARED ${HEADERS} ${SRC} ${PROTOBUF_SRC} ${PROTOBUF_HDRS} ../../src/memoryusage.cpp ${CMAKE_CURRENT_BINARY_DIR}/../../include/transport/protocol.pb.cc)
 
ADD_DEPENDENCIES(transport-plugin pb)
 
SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_BINARY_DIR}/../../include/transport/protocol.pb.cc PROPERTIES GENERATED 1)
 
ADD_DEFINITIONS(-fPIC)
 
 
TARGET_LINK_LIBRARIES(transport-plugin ${PROTOBUF_LIBRARIES} ${LOG4CXX_LIBRARIES})
 
 
SET_TARGET_PROPERTIES(transport-plugin PROPERTIES
 
      VERSION ${TRANSPORT_VERSION} SOVERSION ${TRANSPORT_VERSION}
 
)
 
 
INSTALL(TARGETS transport-plugin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib COMPONENT libraries)
 
 
#CONFIGURE_FILE(transport.pc.in "${CMAKE_CURRENT_BINARY_DIR}/transport.pc")
 
#INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/transport.pc" DESTINATION lib/pkgconfig)
plugin/src/networkplugin.cpp
Show inline comments
 
@@ -466,49 +466,48 @@ void NetworkPlugin::handleDataRead(std::string &data) {
 
			expected_size = *((unsigned int*) &m_data[0]);
 
			expected_size = ntohl(expected_size);
 
			if (m_data.size() - 4 < expected_size)
 
				return;
 
		}
 
		else {
 
			return;
 
		}
 

	
 
		pbnetwork::WrapperMessage wrapper;
 
		if (wrapper.ParseFromArray(&m_data[4], expected_size) == false) {
 
			m_data.erase(m_data.begin(), m_data.begin() + 4 + expected_size);
 
			return;
 
		}
 
		m_data.erase(m_data.begin(), m_data.begin() + 4 + expected_size);
 

	
 
		switch(wrapper.type()) {
 
			case pbnetwork::WrapperMessage_Type_TYPE_LOGIN:
 
				handleLoginPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_LOGOUT:
 
				handleLogoutPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_PING:
 
				LOG4CXX_INFO(logger, "PING RECEIVED");
 
				sendPong();
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_CONV_MESSAGE:
 
				handleConvMessagePayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_JOIN_ROOM:
 
				handleJoinRoomPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_LEAVE_ROOM:
 
				handleLeaveRoomPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_VCARD:
 
				handleVCardPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_CHANGED:
 
				handleBuddyChangedPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_REMOVED:
 
				handleBuddyRemovedPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_STATUS_CHANGED:
 
				handleStatusChangedPayload(wrapper.payload());
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_BUDDY_TYPING:
 
@@ -537,49 +536,48 @@ void NetworkPlugin::handleDataRead(std::string &data) {
 
				break;
 
			case pbnetwork::WrapperMessage_Type_TYPE_EXIT:
 
				handleExitRequest();
 
				break;
 
			default:
 
				return;
 
		}
 
	}
 
}
 

	
 
void NetworkPlugin::send(const std::string &data) {
 
	char header[4];
 
	*((int*)(header)) = htonl(data.size());
 
	sendData(std::string(header, 4) + data);
 
}
 

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

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

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

	
 
	stats.set_init_res(m_init_res);
 
	double res;
 
	double shared;
 
#ifndef WIN32
 
	process_mem_usage(shared, res);
 
#endif
 
	stats.set_res(res);
 
	stats.set_shared(shared);
 

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

	
 
	WRAP(message, pbnetwork::WrapperMessage_Type_TYPE_STATS);
 

	
 
	send(message);
 
}
 

	
 
}
spectrum/src/CMakeLists.txt
Show inline comments
 
cmake_minimum_required(VERSION 2.6)
 
FILE(GLOB SRC *.cpp)
 
 
ADD_EXECUTABLE(spectrum2 ${SRC})
 
 
ADD_DEPENDENCIES(spectrum2 spectrum2_libpurple_backend)
 
ADD_DEPENDENCIES(spectrum2 spectrum2_libircclient-qt_backend)
 
 
target_link_libraries(spectrum2 transport)
 
target_link_libraries(spectrum2 transport ${Boost_LIBRARIES} ${SWIFTEN_LIBRARY} ${LOG4CXX_LIBRARIES})
 
 
INSTALL(TARGETS spectrum2 RUNTIME DESTINATION bin)
 
 
INSTALL(FILES
 
	sample2.cfg
 
	RENAME spectrum.cfg.example
 
	DESTINATION /etc/spectrum2
 
	)
 
 
INSTALL(FILES
 
	backend-logging.cfg
 
	DESTINATION /etc/spectrum2
 
	)
 
 
INSTALL(FILES
 
	logging.cfg
 
	DESTINATION /etc/spectrum2
 
	)
 
 
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} ../include/transport/protocol.pb.cc)
 
    ADD_LIBRARY(transport SHARED ${HEADERS} ${SRC} ${SWIFTEN_SRC} ${CMAKE_CURRENT_BINARY_DIR}/../include/transport/protocol.pb.cc)
 
else()
 
	ADD_LIBRARY(transport STATIC ${HEADERS} ${SRC} ${SWIFTEN_SRC} ../include/transport/protocol.pb.cc)
 
    ADD_LIBRARY(transport STATIC ${HEADERS} ${SRC} ${SWIFTEN_SRC} ${CMAKE_CURRENT_BINARY_DIR}/../include/transport/protocol.pb.cc)    
 
endif()    
 
	SET_SOURCE_FILES_PROPERTIES(${CMAKE_CURRENT_BINARY_DIR}/../include/transport/protocol.pb.cc PROPERTIES GENERATED 1)
 
endif()
 
	ADD_DEPENDENCIES(transport pb)
 
    ADD_DEPENDENCIES(transport pb) 
 
else()
 
	ADD_LIBRARY(transport SHARED ${HEADERS} ${SRC} ${SWIFTEN_SRC})
 
    ADD_LIBRARY(transport SHARED ${HEADERS} ${SRC} ${SWIFTEN_SRC})
 
endif()
 

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

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

	
 
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/buddy.cpp
Show inline comments
 
@@ -109,49 +109,48 @@ Swift::Presence::ref Buddy::generatePresenceStanza(int features, bool only_new)
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Transport::BlockPayload ()));
 
		}
 
	}
 

	
 
// 	if (only_new) {
 
// 		if (m_lastPresence)
 
// 			m_lastPresence->setTo(Swift::JID(""));
 
// 		if (m_lastPresence == presence) {
 
// 			return Swift::Presence::ref();
 
// 		}
 
// 		m_lastPresence = presence;
 
// 	}
 

	
 
	return presence;
 
}
 

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

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

	
 
void Buddy::handleVCardReceived(const std::string &id, Swift::VCard::ref vcard) {
 
	boost::shared_ptr<Swift::GenericRequest<Swift::VCard> > request(new Swift::GenericRequest<Swift::VCard>(Swift::IQ::Result, m_rosterManager->getUser()->getJID(), vcard, m_rosterManager->getUser()->getComponent()->getIQRouter()));
 
	request->send();
 
}
src/mysqlbackend.cpp
Show inline comments
 
@@ -236,48 +236,50 @@ MySQLBackend::Statement& MySQLBackend::Statement::operator >> (T& t) {
 
	}
 

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

	
 
MySQLBackend::Statement& MySQLBackend::Statement::operator >> (std::string& t) {
 
// 	std::cout << "getting " << m_resultOffset << "\n";
 
	if (m_resultOffset > m_results.size())
 
		return *this;
 

	
 
	if (!m_results[m_resultOffset].is_null) {
 
		t = (char *) m_results[m_resultOffset].buffer;
 
	}
 

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

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

	
 
MySQLBackend::~MySQLBackend(){
 
	delete m_setUser;
 
	delete m_getUser;
 
	delete m_removeUser;
 
	delete m_removeUserBuddies;
 
	delete m_removeUserSettings;
 
	delete m_removeUserBuddiesSettings;
 
	delete m_addBuddy;
 
	delete m_updateBuddy;
 
	delete m_getBuddies;
 
	delete m_getBuddiesSettings;
 
	delete m_getUserSetting;
 
	delete m_setUserSetting;
 
	delete m_updateUserSetting;
 
	delete m_updateBuddySetting;
 
	delete m_setUserOnline;
 
	mysql_close(&m_conn);
 
}
 

	
 
bool MySQLBackend::connect() {
 
	LOG4CXX_INFO(logger, "Connecting MySQL server " << CONFIG_STRING(m_config, "database.server") << ", user " <<
 
@@ -447,73 +449,73 @@ bool MySQLBackend::getBuddies(long id, std::list<BuddyInfo> &roster) {
 
	SettingVariableInfo var;
 
	long buddy_id = -1;
 
	std::string key;
 

	
 
	if (!m_getBuddies->execute())
 
		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.push_back(group);
 

	
 
		roster.push_back(b);
 
	}
 

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

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

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

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

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

	
 
bool MySQLBackend::removeUser(long id) {
 
	*m_removeUser << (int) id;
 
	if (!m_removeUser->execute())
 
		return false;
 

	
 
	*m_removeUserSettings << (int) id;
 
	if (!m_removeUserSettings->execute())
 
		return false;
 

	
 
	*m_removeUserBuddies << (int) id;
src/networkpluginserver.cpp
Show inline comments
 
@@ -348,49 +348,49 @@ void NetworkPluginServer::handleSessionFinished(Backend *c) {
 

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

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

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

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

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

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

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

	
 
	boost::shared_ptr<Swift::VCard> vcard(new Swift::VCard());
 
	vcard->setFullName(payload.fullname());
 
	vcard->setPhoto(Swift::createByteArray(payload.photo()));
 
	vcard->setNickname(payload.nickname());
 

	
 
	m_vcardResponder->sendVCard(payload.id(), vcard);
 
}
 

	
src/tests/component.cpp
Show inline comments
 
#include "transport/userregistry.h"
 
#include "transport/config.h"
 
#include "transport/transport.h"
 
#include "transport/conversation.h"
 
#include "transport/localbuddy.h"
 
#include <cppunit/TestFixture.h>
 
#include <cppunit/extensions/HelperMacros.h>
 
#include <Swiften/Swiften.h>
 
#include <Swiften/EventLoop/DummyEventLoop.h>
 
#include <Swiften/Server/Server.h>
 
#include <Swiften/Network/DummyNetworkFactories.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Server/ServerFromClientSession.h"
 
#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
 

	
 
using namespace Transport;
 

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

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

	
 
class TestingFactory : public Factory {
 
	public:
 
		TestingFactory() {
 
		}
 

	
 
		// Creates new conversation (NetworkConversation in this case)
 
		Conversation *createConversation(ConversationManager *conversationManager, const std::string &legacyName) {
 
			Conversation *nc = new TestingConversation(conversationManager, legacyName);
 
			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;
 
		}
 
};
 

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

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

	
 
			factory = new TestingFactory();
 

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

	
 
			userRegistry = new UserRegistry(cfg, factories);
 

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

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

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

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

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

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

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

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

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

	
 
	void handleStreamEnd() {
 
		
 
	}
 

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

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

	
 
CPPUNIT_TEST_SUITE_REGISTRATION (ComponentTest);
src/transport.cpp
Show inline comments
 
@@ -86,48 +86,60 @@ Component::Component(Swift::EventLoop *loop, Swift::NetworkFactories *factories,
 
		m_iqRouter = m_server->getIQRouter();
 

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

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

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

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

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

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

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

	
 
	m_discoInfoResponder = new DiscoInfoResponder(m_iqRouter, m_config);
 
	m_discoInfoResponder->start();
 

	
 
	m_discoItemsResponder = new DiscoItemsResponder(m_iqRouter);
 
	m_discoItemsResponder->start();
 

	
 
// 
 
// 	m_registerHandler = new SpectrumRegisterHandler(m_component);
 
// 	m_registerHandler->start();
 
}
 

	
 
Component::~Component() {
src/user.cpp
Show inline comments
 
@@ -143,49 +143,48 @@ void User::sendCurrentPresence() {
 
			response->setFrom(m_component->getJID());
 
			response->setType(Swift::Presence::Unavailable);
 
			m_component->getStanzaChannel()->sendPresence(response);
 
		}
 
	}
 
	else {
 
		Swift::Presence::ref response = Swift::Presence::create();
 
		response->setTo(m_jid.toBare());
 
		response->setFrom(m_component->getJID());
 
		response->setType(Swift::Presence::Unavailable);
 
		response->setStatus("Connecting");
 
		m_component->getStanzaChannel()->sendPresence(response);
 
	}
 
}
 

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

	
 
	sendCurrentPresence();
 
}
 

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

	
 
	if (error.empty()) {
 
		LOG4CXX_INFO(logger, m_jid.toString() << ": Disconnected from legacy network");
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, m_jid.toString() << ": Disconnected from legacy network with error " << error);
 
	}
 
	onDisconnected();
 

	
 
	boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
	msg->setBody(error);
 
	msg->setTo(m_jid.toBare());
 
	msg->setFrom(m_component->getJID());
 
	m_component->getStanzaChannel()->sendMessage(msg);
 

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

	
 
}
src/userregistry.cpp
Show inline comments
 
@@ -82,53 +82,53 @@ void UserRegistry::stopLogin(const Swift::JID& user, Swift::ServerFromClientSess
 
		}
 
	}
 
	else {
 
		LOG4CXX_WARN(logger, key << ": Stopping login process (user probably disconnected while logging in) for invalid user");
 
	}
 

	
 
	// ::removeLater can be called only by libtransport, not by Swift and libtransport
 
	// takes care about user disconnecting itself, so don't call our signal.
 
	if (!m_inRemoveLater)
 
		onDisconnectUser(user);
 
}
 

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

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

	
 
void UserRegistry::handleRemoveTimeout(const Swift::JID &user) {
 
	m_inRemoveLater = true;
 
	onPasswordInvalid(user);
 
	m_inRemoveLater = false;
 
}
 

	
 
void UserRegistry::removeLater(const Swift::JID &user) {
 
	m_removeTimer->onTick.connect(boost::bind(&UserRegistry::handleRemoveTimeout, this, user));
 
	m_removeTimer->start();
 
}
 

	
 
const std::string UserRegistry::getUserPassword(const std::string &barejid) {
 
	if (users.find(barejid) != users.end())
 
		return users[barejid].password;
 
	return "";
 
}
 

	
src/vcardresponder.cpp
Show inline comments
 
@@ -21,49 +21,49 @@
 
#include "transport/vcardresponder.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include "Swiften/Queries/IQRouter.h"
 
#include "Swiften/Swiften.h"
 
#include "transport/user.h"
 
#include "transport/usermanager.h"
 
#include "transport/rostermanager.h"
 
#include "transport/transport.h"
 
#include "log4cxx/logger.h"
 

	
 
using namespace log4cxx;
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

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

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

	
 
VCardResponder::~VCardResponder() {
 
}
 

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

	
 
	LOG4CXX_INFO(logger, m_queries[id].from.toString() << ": Forwarding VCard of " << m_queries[id].to.toString() << " from legacy network");
 

	
 
	sendResponse(m_queries[id].from, m_queries[id].to, m_queries[id].id, vcard);
 
	m_queries.erase(id);
 
}
 

	
 
void VCardResponder::collectTimeouted() {
 
	time_t now = time(NULL);
 

	
 
	std::vector<unsigned int> candidates;
 
	for(std::map<unsigned int, VCardData>::iterator it = m_queries.begin(); it != m_queries.end(); it++) {
0 comments (0 inline, 0 general)