Changeset - cc64a76c8be5
[Not reviewed]
0 55 0
Jan Kaluza - 12 years ago 2013-01-23 11:29:43
hanzz.k@gmail.com
Replace #include "Swiften/Swiften.h" by particular headers. 25% compilation speedup.
55 files changed with 103 insertions and 58 deletions:
0 comments (0 inline, 0 general)
include/transport/adhoccommand.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 
#include "Swiften/Swiften.h"
 

	
 
#include "Swiften/Elements/FormField.h"
 
#include "Swiften/Elements/Command.h"
 

	
 
namespace Transport {
 

	
 
class Component;
 
class UserManager;
 
class StorageBackend;
 

	
 
class AdHocCommand {
 
	public:
 
		/// Creates new AdHocManager.
 

	
 
		/// \param component Transport instance associated with this AdHocManager.
 
		AdHocCommand(Component *component, UserManager *userManager, StorageBackend *storageBackend, const Swift::JID &initiator, const Swift::JID &to);
 

	
 
		/// Destructor.
 
		virtual ~AdHocCommand();
 

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

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

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

	
 
		void refreshLastActivity() {
 
			m_lastActivity = time(NULL);
 
		}
 

	
 
		time_t getLastActivity() {
 
			return m_lastActivity;
 
		}
 

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

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

	
 
}
include/transport/adhoccommandfactory.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 
#include "transport/adhoccommand.h"
 
#include "Swiften/Swiften.h"
 

	
 
namespace Transport {
 

	
 
class Component;
 
class UserManager;
 
class StorageBackend;
 

	
 
class AdHocCommandFactory {
 
	public:
 
		AdHocCommandFactory() {}
 

	
 
		/// Destructor.
 
		virtual ~AdHocCommandFactory() {}
 

	
 
		virtual AdHocCommand *createAdHocCommand(Component *component, UserManager *userManager, StorageBackend *storageBackend, const Swift::JID &initiator, const Swift::JID &to) = 0;
 

	
 
		virtual std::string getNode() = 0;
 

	
 
		virtual std::string getName() = 0;
 

	
 
		virtual std::map<std::string, std::string> &getUserSettings() {
 
			return m_userSettings;
 
		}
 

	
 
	protected:
 
		std::map<std::string, std::string> m_userSettings;
 
};
 

	
 
}
include/transport/adhocmanager.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 
#include "Swiften/Swiften.h"
 

	
 
#include "Swiften/Queries/Responder.h"
 
#include "Swiften/Elements/Command.h"
 
#include "Swiften/Network/Timer.h"
 

	
 
namespace Transport {
 

	
 
class Conversation;
 
class User;
 
class Component;
 
class DiscoItemsResponder;
 
class AdHocCommandFactory;
 
class AdHocCommand;
 
class UserManager;
 
class StorageBackend;
 

	
 
/// Listens for AdHoc commands and manages all AdHoc commands sessions
 
class AdHocManager : public Swift::Responder<Swift::Command> {
 
	public:
 
		typedef std::map<std::string, AdHocCommand *> CommandsMap;
 
		typedef std::map<Swift::JID, CommandsMap> SessionsMap;
 
		/// Creates new AdHocManager.
 

	
 
		/// \param component Transport instance associated with this AdHocManager.
 
		AdHocManager(Component *component, DiscoItemsResponder *discoItemsResponder, UserManager *userManager, StorageBackend *storageBackend = NULL);
 

	
 
		/// Destructor.
 
		virtual ~AdHocManager();
 

	
 
		/// Starts handling AdHoc commands payloads.
 
		void start();
 

	
 
		/// Stops handling AdHoc commands payloads and destroys all existing
 
		/// AdHoc commands sessions.
 
		void stop();
 

	
 
		/// Adds factory to create new AdHoc commands sessions of particular type.
 
		void addAdHocCommand(AdHocCommandFactory *factory);
 

	
 
		/// Remove sessions older than N seconds.
 
		void removeOldSessions();
 

	
 

	
 
	private:
 
		virtual bool handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::Command> payload);
 
		virtual bool handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::Command> payload);
 
		
 
		void handleUserCreated(User *user);
 

	
 
		Component *m_component;
 
		DiscoItemsResponder *m_discoItemsResponder;
 
		std::map<std::string, AdHocCommandFactory *> m_factories;
 
		SessionsMap m_sessions;
 
		Swift::Timer::ref m_collectTimer;
 
		UserManager *m_userManager;
 
		StorageBackend *m_storageBackend;
 
};
 

	
 
}
include/transport/admininterface.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 

	
 
#include "Swiften/Elements/Message.h"
 

	
 
namespace Transport {
 

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

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

	
 
		~AdminInterface();
 

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

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

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

	
 
}
include/transport/buddy.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include "transport/transport.h"
 
#include "Swiften/Elements/VCard.h"
 

	
 
#include "Swiften/Swiften.h"
 

	
 
namespace Transport {
 

	
 
class RosterManager;
 

	
 
typedef enum { 	BUDDY_NO_FLAG = 0,
 
				BUDDY_JID_ESCAPING = 2,
 
				BUDDY_IGNORE = 4,
 
				BUDDY_BLOCKED = 8,
 
			} BuddyFlag;
 

	
 
/// Represents one legacy network Buddy.
 
class Buddy {
 
	public:
 
		typedef enum { 	Ask,
 
						Both,
 
					} Subscription;
 
		/// Constructor.
 

	
 
		/// \param rosterManager RosterManager associated with this buddy.
 
		/// \param id ID which identifies the buddy in database or -1 if it's new buddy which is
 
		/// not in database yet.
 
		Buddy(RosterManager *rosterManager, long id = -1, BuddyFlag flags = BUDDY_NO_FLAG);
 

	
 
		/// Destructor
 
		virtual ~Buddy();
 
		
 
		/// Sets unique ID used to identify this buddy by StorageBackend.
 
		
 
		/// This is set
 
		/// by RosterStorage class once the buddy is stored into database or when the
 
		/// buddy is loaded from database.
 
		/// You should not need to set this ID manually.
 
		/// \param id ID
 
		void setID(long id);
 

	
 
		/// Returns unique ID used to identify this buddy by StorageBackend.
 

	
 
		/// \return ID which identifies the buddy in database or -1 if it's new buddy which is
 
		/// not in database yet.
 
		long getID();
 

	
 
		/// Returns full JID of this buddy.
 

	
 
		/// \param hostname hostname used as domain in returned JID
 
		/// \return full JID of this buddy
 
		const Swift::JID &getJID();
 

	
 
		/// Generates whole Presennce stanza with current status/show for this buddy.
 

	
 
		/// Presence stanza does not containt "to" attribute, it has to be added manually.
 
		/// \param features features used in returned stanza
 
		/// \param only_new if True, this function returns Presence stanza only if it's different
 
		/// than the previously generated one.
 
		/// \return Presence stanza or NULL.
 
		Swift::Presence::ref generatePresenceStanza(int features, bool only_new = false);
 

	
 
		void setBlocked(bool block) {
 
			if (block)
 
				m_flags = (BuddyFlag) (m_flags | BUDDY_BLOCKED);
 
			else
 
				m_flags = (BuddyFlag) (m_flags & ~BUDDY_BLOCKED);
 
		}
 

	
 
		bool isBlocked() {
 
			return (m_flags & BUDDY_BLOCKED)  != 0;
 
		}
 

	
 
		/// Sets current subscription.
 

	
 
		/// \param subscription "to", "from", "both", "ask"
 
		void setSubscription(Subscription subscription);
 

	
 
		/// Returns current subscription
 

	
 
		/// \return subscription "to", "from", "both", "ask"
 
		Subscription getSubscription();
 

	
 
		/// Sets this buddy's flags.
 

	
 
		/// \param flags flags
 
		void setFlags(BuddyFlag flags);
 

	
 
		/// Returns this buddy's flags.
 

	
 
		/// \param flags flags
 
		BuddyFlag getFlags();
 

	
 
		/// Returns RosterManager associated with this buddy.
 

	
 
		/// \return RosterManager associated with this buddy.
 
		RosterManager *getRosterManager() { return m_rosterManager; }
 

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

	
 
		void sendPresence();
 

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

	
 
		/// \param id ID used in IQ-result.
 
		/// \param vcard VCard which will be sent.
 
		void handleVCardReceived(const std::string &id, Swift::VCard::ref vcard);
 

	
 
		/// Returns legacy network username of this buddy. (for example UIN for ICQ, JID for Jabber, ...).
 

	
 
		/// \return legacy network username
 
		virtual std::string getName() = 0;
 

	
 
		/// Returns alias (nickname) of this buddy.
 

	
 
		/// \return alias (nickname)
 
		virtual std::string getAlias() = 0;
 

	
 
		/// Returns list of groups this buddy is in.
 

	
 
		/// \return groups
 
		virtual std::vector<std::string> getGroups() = 0;
 

	
 
		/// Returns current legacy network status and statuMessage of this buddy.
 

	
 
		/// \param status current status/show is stored here
 
		/// \param statusMessage current status message is stored here
 
		/// \return true if status was stored successfully
 
		virtual bool getStatus(Swift::StatusShow &status, std::string &statusMessage) = 0;
 

	
 
		/// Returns SHA-1 hash of buddy icon (avatar) or empty string if there is no avatar for this buddy.
 

	
 
		/// \return avatar hash or empty string.
 
		virtual std::string getIconHash() = 0;
 

	
 
		/// Returns legacy name of buddy from JID.
 

	
 
		/// \param jid Jabber ID.
 
		/// \return legacy name of buddy from JID.
 
		static std::string JIDToLegacyName(const Swift::JID &jid);
 
		static BuddyFlag buddyFlagsFromJID(const Swift::JID &jid);
 

	
 
	protected:
 
		void generateJID();
 
		Swift::JID m_jid;
 

	
 
	private:
 
		long m_id;
 
// 		Swift::Presence::ref m_lastPresence;
 
		BuddyFlag m_flags;
 
		RosterManager *m_rosterManager;
 
		Subscription m_subscription;
 
};
 

	
 
}
include/transport/conversation.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include "transport/transport.h"
 

	
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Elements/Message.h"
 

	
 
namespace Transport {
 

	
 
class ConversationManager;
 

	
 
/// Represents one XMPP-Legacy network conversation.
 
class Conversation {
 
	public:
 
		typedef struct _Participant {
 
			int flag;
 
			int status;
 
			std::string statusMessage;
 
		} Participant;
 

	
 
		/// Type of participants in MUC rooms.
 
		enum ParticipantFlag {None, Moderator};
 

	
 
		/// Creates new conversation.
 

	
 
		/// \param conversationManager ConversationManager associated with this Conversation.
 
		/// \param legacyName Legacy network name of recipient.
 
		/// \param muc True if this conversation is Multi-user chat.
 
		Conversation(ConversationManager *conversationManager, const std::string &legacyName, bool muc = false);
 

	
 
		/// Destructor.
 
		virtual ~Conversation();
 

	
 
		/// Returns legacy network name of this conversation.
 

	
 
		/// \return legacy network name of this conversation.
 
		const std::string &getLegacyName() { return m_legacyName; }
 

	
 
		/// Handles new message from Legacy network and forwards it to XMPP.
 

	
 
		/// \param message Message received from legacy network.
 
		/// \param nickname For MUC conversation this is nickname of room participant who sent this message.
 
		void handleMessage(boost::shared_ptr<Swift::Message> &message, const std::string &nickname = "");
 

	
 
		/// Handles participant change in MUC.
 

	
 
		/// \param nickname Nickname of participant which changed.
 
		/// \param flag ParticipantFlag.
 
		/// \param status Current status of this participant.
 
		/// \param statusMessage Current status message of this participant.
 
		/// \param newname If participant was renamed, this variable contains his new name.
 
		void handleParticipantChanged(const std::string &nickname, int flag, int status = Swift::StatusShow::None, const std::string &statusMessage = "", const std::string &newname = "");
 

	
 
		/// Sets XMPP user nickname in MUC rooms.
 

	
 
		/// \param nickname XMPP user nickname in MUC rooms.
 
		void setNickname(const std::string &nickname) {
 
			m_nickname = nickname;
 
		}
 

	
 
		const std::string &getNickname() {
 
			return m_nickname;
 
		}
 

	
 
		void setJID(const Swift::JID &jid) {
 
			m_jid = jid;
 
		}
 

	
 
		void addJID(const Swift::JID &jid) {
 
			m_jids.push_back(jid);
 
		}
 

	
 
		void clearJIDs() {
 
			m_jids.clear();
 
		}
 

	
 
		void removeJID(const Swift::JID &jid) {
 
			m_jids.remove(jid);
 
		}
 

	
 
		const std::list<Swift::JID> &getJIDs() {
 
			return m_jids;
 
		}
 

	
 
		/// Sends message to Legacy network.
 

	
 
		/// \param message Message.
 
		virtual void sendMessage(boost::shared_ptr<Swift::Message> &message) = 0;
 

	
 
		/// Returns ConversationManager associated with this Conversation.
 

	
 
		/// \return  ConversationManager associated with this Conversation.
 
		ConversationManager *getConversationManager() {
 
			return m_conversationManager;
 
		}
 

	
 
		/// Returns True if this conversation is MUC room.
 

	
 
		/// \return  True if this conversation is MUC room.
 
		bool isMUC() {
 
			return m_muc;
 
		}
 

	
 
		/// Sets room name associated with this Conversation.
 

	
 
		/// This is used to detect Private messages associated with particular room.
 
		/// \param room room name associated with this Conversation.
 
		void setRoom(const std::string &room);
 

	
 
		/// Returns room name associated with this Conversation.
 

	
 
		/// \return room name associated with this Conversation.
 
		const std::string &getRoom() {
 
			return m_room;
 
		}
 

	
 
		void destroyRoom();
 

	
 
		void sendParticipants(const Swift::JID &to);
 

	
 
		void sendCachedMessages(const Swift::JID &to = Swift::JID());
 

	
 
	private:
 
		Swift::Presence::ref generatePresence(const std::string &nick, int flag, int status, const std::string &statusMessage, const std::string &newname = "");
 

	
 
	private:
 
		ConversationManager *m_conversationManager;
 
		std::string m_legacyName;
 
		std::string m_nickname;
 
		std::string m_room;
 
		bool m_muc;
 
		Swift::JID m_jid;
 
		std::list<Swift::JID> m_jids;
 
		std::map<std::string, Participant> m_participants;
 
		boost::shared_ptr<Swift::Message> m_subject;
 
		bool m_sentInitialPresence;
 
		std::list<boost::shared_ptr<Swift::Message> > m_cachedMessages;
 
};
 

	
 
}
include/transport/conversationmanager.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 
#include "Swiften/Swiften.h"
 

	
 
#include "Swiften/Elements/Message.h"
 

	
 
namespace Transport {
 

	
 
class Conversation;
 
class User;
 
class Component;
 

	
 
/// Manages all Conversations of particular User.
 
class ConversationManager {
 
	public:
 
		/// Creates new ConversationManager.
 

	
 
		/// \param user User associated with this ConversationManager.
 
		/// \param component Transport instance associated with this ConversationManager.
 
		ConversationManager(User *user, Component *component);
 

	
 
		/// Destructor.
 
		virtual ~ConversationManager();
 

	
 
		/// Returns user associated with this manager.
 

	
 
		/// \return User
 
		User *getUser() { return m_user; }
 

	
 
		/// Returns component associated with this ConversationManager.
 

	
 
		/// \return component associated with this ConversationManager.
 
		Component *getComponent() { return m_component; }
 

	
 
		/// Returns Conversation by its legacy network name (for example by UIN in case of ICQ).
 

	
 
		/// \param name legacy network name.
 
		/// \return Conversation or NULL.
 
		Conversation *getConversation(const std::string &name);
 

	
 
		void sendCachedChatMessages();
 

	
 
		/// Adds new Conversation to the manager.
 

	
 
		/// \param conv Conversation.
 
		void addConversation(Conversation *conv);
 

	
 
		/// Removes Conversation from the manager.
 

	
 
		/// \param conv Conversation.
 
		void removeConversation(Conversation *conv);
 

	
 
		void deleteAllConversations();
 

	
 
		void resetResources();
 
		void removeJID(const Swift::JID &jid);
 
		void clearJIDs();
 

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

	
 
		Component *m_component;
 
		User *m_user;
 

	
 
		std::map<std::string, Conversation *> m_convs;
 
		friend class UserManager;
 
};
 

	
 
}
include/transport/discoitemsresponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/GetResponder.h"
 
#include "Swiften/Elements/DiscoItems.h"
 
#include "Swiften/Elements/CapsInfo.h"
 

	
 
namespace Transport {
 

	
 
class Component;
 
class DiscoInfoResponder;
 

	
 
class DiscoItemsResponder : public Swift::GetResponder<Swift::DiscoItems> {
 
	public:
 
		DiscoItemsResponder(Component *component);
 
		~DiscoItemsResponder();
 

	
 
		Swift::CapsInfo &getBuddyCapsInfo();
 

	
 
		void addAdHocCommand(const std::string &node, const std::string &name);
 
// 		void removeAdHocCommand(const std::string &node);
 

	
 
		void addRoom(const std::string &node, const std::string &name);
 
		void clearRooms();
 

	
 

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

	
 
	private:
 
		Component *m_component;
 
		boost::shared_ptr<Swift::DiscoItems> m_commands;
 
		boost::shared_ptr<Swift::DiscoItems> m_rooms;
 
		DiscoInfoResponder *m_discoInfoResponder;
 
};
 

	
 
}
include/transport/factory.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include "transport/transport.h"
 

	
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Elements/Message.h"
 
#include "transport/conversation.h"
 
#include "transport/buddy.h"
 
#include "transport/storagebackend.h"
 

	
 
namespace Transport {
 

	
 
class Conversation;
 
class Buddy;
 
class ConversationManager;
 
class RosterManager;
 

	
 
class Factory {
 
	public:
 
		
 
		virtual Conversation *createConversation(ConversationManager *conversationManager, const std::string &legacyName, bool isMuc = false) = 0;
 

	
 
		virtual Buddy *createBuddy(RosterManager *rosterManager, const BuddyInfo &buddyInfo) = 0;
 
};
 

	
 
}
include/transport/gatewayresponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/Responder.h"
 
#include "Swiften/Elements/GatewayPayload.h"
 

	
 
namespace Transport {
 

	
 
class UserManager;
 

	
 
class GatewayResponder : public Swift::Responder<Swift::GatewayPayload> {
 
	public:
 
		GatewayResponder(Swift::IQRouter *router, UserManager *userManager);
 
		~GatewayResponder();
 

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

	
 
}
include/transport/memoryreadbytestream.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 

	
 
#include "Swiften/FileTransfer/ReadBytestream.h"
 

	
 
namespace Transport {
 

	
 
class MemoryReadBytestream : public Swift::ReadBytestream {
 
	public:
 
		MemoryReadBytestream(unsigned long size);
 
		virtual ~MemoryReadBytestream();
 

	
 
		unsigned long appendData(const std::string &data);
 

	
 
		virtual boost::shared_ptr<std::vector<unsigned char> > read(size_t size);
 

	
 
		void setFinished() { m_finished = true; }
 
		bool isFinished() const;
 

	
 
		boost::signal<void ()> onDataNeeded;
 

	
 
	private:
 
		bool m_finished;
 
		std::string m_data;
 
		bool neededData;
 
		unsigned long m_sent;
 
		unsigned long m_size;
 
};
 

	
 
}
include/transport/mysqlbackend.h
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
 
 */
 

	
 
#pragma once
 

	
 
#ifdef WITH_MYSQL
 

	
 
#include <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 
#include "transport/storagebackend.h"
 
#include "transport/config.h"
 
#include "mysql.h"
 

	
 
namespace Transport {
 

	
 
/// Used to store transport data into SQLite3 database.
 
class MySQLBackend : public StorageBackend
 
{
 
	public:
 
		/// Creates new MySQLBackend instance.
 
		/// \param config cofiguration, this class uses following Config values:
 
		/// 	- database.database - path to SQLite3 database file, database file is created automatically
 
		/// 	- service.prefix - prefix for tables created by createDatabase method
 
		MySQLBackend(Config *config);
 

	
 
		/// Destructor.
 
		~MySQLBackend();
 

	
 
		/// Connects to the database and creates it if it's needed. This method call createDatabase() function
 
		/// automatically.
 
		/// \return true if database is opened successfully.
 
		bool connect();
 
		void disconnect();
 

	
 
		/// Creates database structure.
 
		/// \see connect()
 
		/// \return true if database structure has been created successfully. Note that it returns True also if database structure
 
		/// already exists.
 
		bool createDatabase();
 

	
 
		/// Stores user into database.
 
		/// \param user user struct containing all information about user which have to be stored
 
		void setUser(const UserInfo &user);
 

	
 
		/// Gets user data from database and stores them into user reference.
 
		/// \param barejid barejid of user
 
		/// \param user UserInfo object where user data will be stored
 
		/// \return true if user has been found in database
 
		bool getUser(const std::string &barejid, UserInfo &user);
 

	
 
		/// Changes users online state variable in database.
 
		/// \param id id of user - UserInfo.id
 
		/// \param online online state
 
		void setUserOnline(long id, bool online);
 

	
 
		/// Removes user and all connected data from database.
 
		/// \param id id of user - UserInfo.id
 
		/// \return true if user has been found in database and removed
 
		bool removeUser(long id);
 

	
 
		/// Returns JIDs of all buddies in user's roster.
 
		/// \param id id of user - UserInfo.id
 
		/// \param roster string list used to store user's roster
 
		/// \return true if user has been found in database and roster has been fetched
 
		bool getBuddies(long id, std::list<BuddyInfo> &roster);
 

	
 
		bool getOnlineUsers(std::vector<std::string> &users);
 

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

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

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

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

	
 
		void beginTransaction();
 
		void commitTransaction();
 

	
 
	private:
 
		bool exec(const std::string &query);
 

	
 
		class Statement {
 
			public:
 
				Statement(MYSQL *conn, const std::string &format, const std::string &statement);
 
				~Statement();
 

	
 
				int execute();
 

	
 
				int fetch();
 

	
 
				// Pushes new data used as input for the statement.
 
				template <typename T>
 
				Statement& operator << (const T& t);
 

	
 
				Statement& operator << (const std::string& str);
 

	
 
				// Pulls fetched data by previous execute(); call.
 
				template <typename T>
 
				Statement& operator >> (T& t);
 
				
 
				Statement& operator >> (std::string& t);
 
			private:
 
				MYSQL_STMT *m_stmt;
 
				MYSQL *m_conn;
 
				std::vector<MYSQL_BIND> m_params;
 
				std::vector<MYSQL_BIND> m_results;
 
				int m_resultOffset;
 
				int m_offset;
 
				int m_error;
 
				std::string m_string;
 
		};
 

	
 
		MYSQL m_conn;
 
		Config *m_config;
 
		std::string m_prefix;
 

	
 
		// statements
 
// 		MYSQL_STMT *m_setUser;
 
		Statement *m_setUser;
 
		Statement *m_getUser;
 
		Statement *m_getUserSetting;
 
		Statement *m_setUserSetting;
 
		Statement *m_updateUserSetting;
 
		Statement *m_removeUser;
 
		Statement *m_removeUserBuddies;
 
		Statement *m_removeUserSettings;
 
		Statement *m_removeUserBuddiesSettings;
 
		Statement *m_addBuddy;
 
		Statement *m_removeBuddy;
 
		Statement *m_removeBuddySettings;
 
		Statement *m_updateBuddy;
 
		Statement *m_updateBuddySetting;
 
		Statement *m_getBuddySetting;
 
		Statement *m_getBuddies;
 
		Statement *m_getBuddiesSettings;
 
		Statement *m_setUserOnline;
 
		Statement *m_getOnlineUsers;
 
};
 

	
 
}
 

	
 
#endif
include/transport/networkpluginserver.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <time.h>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Presence/PresenceOracle.h"
 
#include "Swiften/Disco/EntityCapsManager.h"
 
#include "Swiften/Network/BoostConnectionServer.h"
 
#include "Swiften/Network/Connection.h"
 
#include "Swiften/Elements/ChatState.h"
 
#include "Swiften/Elements/RosterItemPayload.h"
 
#include "Swiften/Elements/VCard.h"
 
#include "storagebackend.h"
 
#include "transport/filetransfermanager.h"
 

	
 
namespace Transport {
 

	
 
class UserManager;
 
class User;
 
class Component;
 
class Buddy;
 
class LocalBuddy;
 
class Config;
 
class NetworkConversation;
 
class VCardResponder;
 
class RosterResponder;
 
class BlockResponder;
 
class DummyReadBytestream;
 
class AdminInterface;
 
class DiscoItemsResponder;
 

	
 
class NetworkPluginServer {
 
	public:
 
		struct Backend {
 
			int pongReceived;
 
			std::list<User *> users;
 
			Swift::SafeByteArray data;
 
			boost::shared_ptr<Swift::Connection> connection;
 
			unsigned long res;
 
			unsigned long init_res;
 
			unsigned long shared;
 
			bool acceptUsers;
 
			bool longRun;
 
			bool willDie;
 
			std::string id;
 
		};
 

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

	
 
		virtual ~NetworkPluginServer();
 

	
 
		void start();
 

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

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

	
 
		const std::list<Backend *> &getBackends() {
 
			return m_clients;
 
		}
 

	
 
		const std::vector<std::string> &getCrashedBackends() {
 
			return m_crashedBackends;
 
		}
 

	
 
		void collectBackend();
 

	
 
		bool moveToLongRunBackend(User *user);
 

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

	
 
	public:
 
		void handleNewClientConnection(boost::shared_ptr<Swift::Connection> c);
 
		void handleSessionFinished(Backend *c);
 
		void handlePongReceived(Backend *c);
 
		void handleDataRead(Backend *c, boost::shared_ptr<Swift::SafeByteArray> data);
 

	
 
		void handleConnectedPayload(const std::string &payload);
 
		void handleDisconnectedPayload(const std::string &payload);
 
		void handleBuddyChangedPayload(const std::string &payload);
 
		void handleBuddyRemovedPayload(const std::string &payload);
 
		void handleConvMessagePayload(const std::string &payload, bool subject = false);
 
		void handleConvMessageAckPayload(const std::string &payload);
 
		void handleParticipantChangedPayload(const std::string &payload);
 
		void handleRoomChangedPayload(const std::string &payload);
 
		void handleVCardPayload(const std::string &payload);
 
		void handleChatStatePayload(const std::string &payload, Swift::ChatState::ChatStateType type);
 
		void handleAuthorizationPayload(const std::string &payload);
 
		void handleAttentionPayload(const std::string &payload);
 
		void handleStatsPayload(Backend *c, const std::string &payload);
 
		void handleFTStartPayload(const std::string &payload);
 
		void handleFTFinishPayload(const std::string &payload);
 
		void handleFTDataPayload(Backend *b, const std::string &payload);
 
		void handleQueryPayload(Backend *b, const std::string &payload);
 
		void handleBackendConfigPayload(const std::string &payload);
 
		void handleRoomListPayload(const std::string &payload);
 

	
 
		void handleUserCreated(User *user);
 
		void handleRoomJoined(User *user, const Swift::JID &who, const std::string &room, const std::string &nickname, const std::string &password);
 
		void handleRoomLeft(User *user, const std::string &room);
 
		void handleUserReadyToConnect(User *user);
 
		void handleUserPresenceChanged(User *user, Swift::Presence::ref presence);
 
		void handleUserDestroyed(User *user);
 

	
 
		void handleBuddyUpdated(Buddy *buddy, const Swift::RosterItemPayload &item);
 
		void handleBuddyRemoved(Buddy *buddy);
 
		void handleBuddyAdded(Buddy *buddy, const Swift::RosterItemPayload &item);
 

	
 
		void handleBlockToggled(Buddy *buddy);
 

	
 
		void handleVCardUpdated(User *user, boost::shared_ptr<Swift::VCard> vcard);
 
		void handleVCardRequired(User *user, const std::string &name, unsigned int id);
 

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

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

	
 
		void pingTimeout();
 
		void sendPing(Backend *c);
 
		Backend *getFreeClient(bool acceptUsers = true, bool longRun = false, bool check = false);
 
		void connectWaitingUsers();
 
		void loginDelayFinished();
 

	
 
		UserManager *m_userManager;
 
		VCardResponder *m_vcardResponder;
 
		RosterResponder *m_rosterResponder;
 
		BlockResponder *m_blockResponder;
 
		Config *m_config;
 
		boost::shared_ptr<Swift::ConnectionServer> m_server;
 
		std::list<Backend *>  m_clients;
 
		std::vector<unsigned long> m_pids;
 
		Swift::Timer::ref m_pingTimer;
 
		Swift::Timer::ref m_collectTimer;
 
		Swift::Timer::ref m_loginTimer;
 
		Component *m_component;
 
		std::list<User *> m_waitingUsers;
 
		bool m_isNextLongRun;
 
		std::map<unsigned long, FileTransferManager::Transfer> m_filetransfers;
 
		FileTransferManager *m_ftManager;
 
		std::vector<std::string> m_crashedBackends;
 
		AdminInterface *m_adminInterface;
 
		bool m_startingBackend;
 
		DiscoItemsResponder *m_discoItemsResponder;
 
		time_t m_lastLogin;
 
};
 

	
 
}
include/transport/pqxxbackend.h
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
 
 */
 

	
 
#pragma once
 

	
 
#ifdef WITH_PQXX
 

	
 
#include <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 
#include "transport/storagebackend.h"
 
#include "transport/config.h"
 
#include <pqxx/pqxx>
 

	
 
namespace Transport {
 

	
 
/// Used to store transport data into SQLite3 database.
 
class PQXXBackend : public StorageBackend
 
{
 
	public:
 
		/// Creates new PQXXBackend instance.
 
		/// \param config cofiguration, this class uses following Config values:
 
		/// 	- database.database - path to SQLite3 database file, database file is created automatically
 
		/// 	- service.prefix - prefix for tables created by createDatabase method
 
		PQXXBackend(Config *config);
 

	
 
		/// Destructor.
 
		~PQXXBackend();
 

	
 
		/// Connects to the database and creates it if it's needed. This method call createDatabase() function
 
		/// automatically.
 
		/// \return true if database is opened successfully.
 
		bool connect();
 
		void disconnect();
 

	
 
		/// Creates database structure.
 
		/// \see connect()
 
		/// \return true if database structure has been created successfully. Note that it returns True also if database structure
 
		/// already exists.
 
		bool createDatabase();
 

	
 
		/// Stores user into database.
 
		/// \param user user struct containing all information about user which have to be stored
 
		void setUser(const UserInfo &user);
 

	
 
		/// Gets user data from database and stores them into user reference.
 
		/// \param barejid barejid of user
 
		/// \param user UserInfo object where user data will be stored
 
		/// \return true if user has been found in database
 
		bool getUser(const std::string &barejid, UserInfo &user);
 

	
 
		/// Changes users online state variable in database.
 
		/// \param id id of user - UserInfo.id
 
		/// \param online online state
 
		void setUserOnline(long id, bool online);
 

	
 
		/// Removes user and all connected data from database.
 
		/// \param id id of user - UserInfo.id
 
		/// \return true if user has been found in database and removed
 
		bool removeUser(long id);
 

	
 
		/// Returns JIDs of all buddies in user's roster.
 
		/// \param id id of user - UserInfo.id
 
		/// \param roster string list used to store user's roster
 
		/// \return true if user has been found in database and roster has been fetched
 
		bool getBuddies(long id, std::list<BuddyInfo> &roster);
 

	
 
		bool getOnlineUsers(std::vector<std::string> &users);
 

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

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

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

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

	
 
		void beginTransaction();
 
		void commitTransaction();
 

	
 
	private:
 
		bool exec(const std::string &query, bool show_error = true);
 
		bool exec(pqxx::nontransaction &txn, const std::string &query, bool show_error = true);
 
		template<typename T>
 
		std::string quote(pqxx::nontransaction &txn, const T &t);
 

	
 
		Config *m_config;
 
		std::string m_prefix;
 

	
 
		pqxx::connection *m_conn;
 
};
 

	
 
}
 

	
 
#endif
include/transport/rostermanager.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 
#include <boost/pool/pool_alloc.hpp>
 
#include <boost/pool/object_pool.hpp>
 
#include "Swiften/Swiften.h"
 
// #include "rosterstorage.h"
 
#include "Swiften/Elements/RosterPayload.h"
 
#include "Swiften/Queries/GenericRequest.h"
 
#include "Swiften/Roster/SetRosterRequest.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/Network/Timer.h"
 

	
 
namespace Transport {
 

	
 
class Buddy;
 
class User;
 
class Component;
 
class StorageBackend;
 
class RosterStorage;
 

	
 
// TODO: Once Swiften GetRosterRequest will support setting to="", this can be removed
 
class AddressedRosterRequest : public Swift::GenericRequest<Swift::RosterPayload> {
 
	public:
 
		typedef boost::shared_ptr<AddressedRosterRequest> ref;
 

	
 
		AddressedRosterRequest(Swift::IQRouter* router, Swift::JID to) :
 
				Swift::GenericRequest<Swift::RosterPayload>(Swift::IQ::Get, to, boost::shared_ptr<Swift::Payload>(new Swift::RosterPayload()), router) {
 
		}
 
};
 

	
 
/// Manages roster of one XMPP user.
 
class RosterManager {
 
	public:
 
		typedef std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > > BuddiesMap;
 
		/// Creates new RosterManager.
 
		/// \param user User associated with this RosterManager.
 
		/// \param component Transport instance associated with this roster.
 
		RosterManager(User *user, Component *component);
 

	
 
		/// Destructor.
 
		virtual ~RosterManager();
 

	
 
		/// Associates the buddy with this roster,
 
		/// and if the buddy is not already in XMPP user's server-side roster, the proper requests
 
		/// are sent to XMPP user (subscribe presences, Roster Item Exchange stanza or
 
		/// the buddy is added to server-side roster using remote-roster protoXEP).
 
		/// \param buddy Buddy
 
		void setBuddy(Buddy *buddy);
 

	
 
		/// Deassociates the buddy with this roster.
 
		/// \param buddy Buddy.
 
		void unsetBuddy(Buddy *buddy);
 

	
 
		/// Removes buddy from this roster, sends proper XML to XMPP side and deletes it.
 
		/// \param name Buddy name.
 
		void removeBuddy(const std::string &name);
 

	
 
		Buddy *getBuddy(const std::string &name);
 

	
 
		void setStorageBackend(StorageBackend *storageBackend);
 

	
 
		void storeBuddy(Buddy *buddy);
 

	
 
		Swift::RosterPayload::ref generateRosterPayload();
 

	
 
		/// Returns user associated with this roster.
 
		/// \return User
 
		User *getUser() { return m_user; }
 

	
 
		const BuddiesMap &getBuddies() {
 
			return m_buddies;
 
		}
 

	
 
		bool isRemoteRosterSupported() {
 
			return m_supportRemoteRoster;
 
		}
 

	
 
		/// Called when new Buddy is added to this roster.
 
		/// \param buddy newly added Buddy
 
		boost::signal<void (Buddy *buddy)> onBuddySet;
 

	
 
		/// Called when Buddy has been removed from this roster.
 
		/// \param buddy removed Buddy
 
		boost::signal<void (Buddy *buddy)> onBuddyUnset;
 

	
 
		boost::signal<void (Buddy *buddy)> onBuddyAdded;
 
		
 
		boost::signal<void (Buddy *buddy)> onBuddyRemoved;
 

	
 
		void handleBuddyChanged(Buddy *buddy);
 

	
 
		void handleSubscription(Swift::Presence::ref presence);
 

	
 
		void sendBuddyRosterPush(Buddy *buddy);
 

	
 
		void sendBuddyRosterRemove(Buddy *buddy);
 

	
 
		void sendBuddySubscribePresence(Buddy *buddy);
 
		
 
		void sendBuddyUnsubscribePresence(Buddy *buddy);
 

	
 
		void sendCurrentPresences(const Swift::JID &to);
 

	
 
		void sendCurrentPresence(const Swift::JID &from, const Swift::JID &to);
 

	
 
		void sendUnavailablePresences(const Swift::JID &to);
 

	
 
	private:
 
		void setBuddyCallback(Buddy *buddy);
 

	
 
		void sendRIE();
 
		void handleBuddyRosterPushResponse(Swift::ErrorPayload::ref error, Swift::SetRosterRequest::ref request, const std::string &key);
 
		void handleRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> roster, Swift::ErrorPayload::ref error);
 

	
 
		std::map<std::string, Buddy *, std::less<std::string>, boost::pool_allocator< std::pair<std::string, Buddy *> > > m_buddies;
 
		Component *m_component;
 
		RosterStorage *m_rosterStorage;
 
		User *m_user;
 
		Swift::Timer::ref m_setBuddyTimer;
 
		Swift::Timer::ref m_RIETimer;
 
		std::list <Swift::SetRosterRequest::ref> m_requests;
 
		bool m_supportRemoteRoster;
 
		AddressedRosterRequest::ref m_remoteRosterRequest;
 
};
 

	
 
}
include/transport/rosterresponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/Responder.h"
 
#include "Swiften/Elements/RosterPayload.h"
 

	
 
#include <boost/signal.hpp>
 

	
 
namespace Transport {
 

	
 
class UserManager;
 
class Buddy;
 

	
 
class RosterResponder : public Swift::Responder<Swift::RosterPayload> {
 
	public:
 
		RosterResponder(Swift::IQRouter *router, UserManager *userManager);
 
		~RosterResponder();
 

	
 
		boost::signal<void (Buddy *, const Swift::RosterItemPayload &item)> onBuddyUpdated;
 

	
 
		boost::signal<void (Buddy *)> onBuddyRemoved;
 

	
 
		boost::signal<void (Buddy *, const Swift::RosterItemPayload &item)> onBuddyAdded;
 

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

	
 
}
include/transport/rosterstorage.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include "Swiften/Swiften.h"
 
#include <map>
 

	
 
#include "Swiften/Network/Timer.h"
 

	
 
namespace Transport {
 

	
 
class User;
 
class StorageBackend;
 
class Buddy;
 

	
 
// Stores buddies into DB Backend.
 
class RosterStorage {
 
	public:
 
		RosterStorage(User *user, StorageBackend *storageBackend);
 
		virtual ~RosterStorage();
 

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

	
 
		void removeBuddy(Buddy *buddy);
 

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

	
 
		// Remove buddy from storage queue.
 
		void removeBuddyFromQueue(Buddy *buddy);
 

	
 
	private:
 
		User *m_user;
 
		StorageBackend *m_storageBackend;
 
		std::map<std::string, Buddy *> m_buddies;
 
		Swift::Timer::ref m_storageTimer;
 
};
 

	
 
}
include/transport/settingsadhoccommand.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 
#include "Swiften/Swiften.h"
 
#include "transport/adhoccommand.h"
 
#include "transport/adhoccommandfactory.h"
 

	
 

	
 
namespace Transport {
 

	
 
class Component;
 
class UserManager;
 
class StorageBackend;
 

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

	
 
		SettingsAdHocCommand(Component *component, UserManager *userManager, StorageBackend *storageBackend, const Swift::JID &initiator, const Swift::JID &to);
 

	
 
		/// Destructor.
 
		virtual ~SettingsAdHocCommand();
 

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

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

	
 
class SettingsAdHocCommandFactory : public AdHocCommandFactory {
 
	public:
 
		SettingsAdHocCommandFactory() {
 
			m_userSettings["send_headlines"] = "0";
 
			m_userSettings["stay_connected"] = "0";
 
		}
 

	
 
		virtual ~SettingsAdHocCommandFactory() {}
 

	
 
		AdHocCommand *createAdHocCommand(Component *component, UserManager *userManager, StorageBackend *storageBackend, const Swift::JID &initiator, const Swift::JID &to) {
 
			return new SettingsAdHocCommand(component, userManager, storageBackend, initiator, to);
 
		}
 

	
 
		std::string getNode() {
 
			return "settings";
 
		}
 

	
 
		std::string getName() {
 
			return "Transport settings";
 
		}
 
};
 

	
 
}
include/transport/sqlite3backend.h
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
 
 */
 

	
 
#pragma once
 

	
 
#ifdef WITH_SQLITE
 

	
 
#include <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 
#include "transport/storagebackend.h"
 
#include "transport/config.h"
 
#include "sqlite3.h"
 

	
 
namespace Transport {
 

	
 
/// Used to store transport data into SQLite3 database.
 
class SQLite3Backend : public StorageBackend
 
{
 
	public:
 
		/// Creates new SQLite3Backend instance.
 
		/// \param config cofiguration, this class uses following Config values:
 
		/// 	- database.database - path to SQLite3 database file, database file is created automatically
 
		/// 	- service.prefix - prefix for tables created by createDatabase method
 
		SQLite3Backend(Config *config);
 

	
 
		/// Destructor.
 
		~SQLite3Backend();
 

	
 
		/// Connects to the database and creates it if it's needed. This method call createDatabase() function
 
		/// automatically.
 
		/// \return true if database is opened successfully.
 
		bool connect();
 

	
 
		/// Creates database structure.
 
		/// \see connect()
 
		/// \return true if database structure has been created successfully. Note that it returns True also if database structure
 
		/// already exists.
 
		bool createDatabase();
 

	
 
		/// Stores user into database.
 
		/// \param user user struct containing all information about user which have to be stored
 
		void setUser(const UserInfo &user);
 

	
 
		/// Gets user data from database and stores them into user reference.
 
		/// \param barejid barejid of user
 
		/// \param user UserInfo object where user data will be stored
 
		/// \return true if user has been found in database
 
		bool getUser(const std::string &barejid, UserInfo &user);
 

	
 
		/// Changes users online state variable in database.
 
		/// \param id id of user - UserInfo.id
 
		/// \param online online state
 
		void setUserOnline(long id, bool online);
 

	
 
		bool getOnlineUsers(std::vector<std::string> &users);
 

	
 
		/// Removes user and all connected data from database.
 
		/// \param id id of user - UserInfo.id
 
		/// \return true if user has been found in database and removed
 
		bool removeUser(long id);
 

	
 
		/// Returns JIDs of all buddies in user's roster.
 
		/// \param id id of user - UserInfo.id
 
		/// \param roster string list used to store user's roster
 
		/// \return true if user has been found in database and roster has been fetched
 
		bool getBuddies(long id, std::list<BuddyInfo> &roster);
 

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

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

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

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

	
 
		void beginTransaction();
 
		void commitTransaction();
 

	
 
	private:
 
		bool exec(const std::string &query);
 

	
 
		sqlite3 *m_db;
 
		Config *m_config;
 
		std::string m_prefix;
 

	
 
		// statements
 
		sqlite3_stmt *m_setUser;
 
		sqlite3_stmt *m_getUser;
 
		sqlite3_stmt *m_getUserSetting;
 
		sqlite3_stmt *m_setUserSetting;
 
		sqlite3_stmt *m_updateUserSetting;
 
		sqlite3_stmt *m_removeUser;
 
		sqlite3_stmt *m_removeUserBuddies;
 
		sqlite3_stmt *m_removeUserSettings;
 
		sqlite3_stmt *m_removeUserBuddiesSettings;
 
		sqlite3_stmt *m_removeBuddy;
 
		sqlite3_stmt *m_removeBuddySettings;
 
		sqlite3_stmt *m_addBuddy;
 
		sqlite3_stmt *m_updateBuddy;
 
		sqlite3_stmt *m_updateBuddySetting;
 
		sqlite3_stmt *m_getBuddySetting;
 
		sqlite3_stmt *m_getBuddies;
 
		sqlite3_stmt *m_getBuddiesSettings;
 
		sqlite3_stmt *m_setUserOnline;
 
		sqlite3_stmt *m_getOnlineUsers;
 
};
 

	
 
}
 

	
 
#endif
include/transport/statsresponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/SetResponder.h"
 
#include "Swiften/Elements/StatsPayload.h"
 

	
 
namespace Transport {
 

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

	
 
class StatsResponder : public Swift::Responder<Swift::StatsPayload> {
 
	public:
 
		StatsResponder(Component *component, UserManager *userManager, NetworkPluginServer *server, StorageBackend *storageBackend);
 
		~StatsResponder();
 

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

	
 
		unsigned long usedMemory();
 

	
 
		Component *m_component;
 
		UserManager *m_userManager;
 
		NetworkPluginServer *m_server;
 
		StorageBackend *m_storageBackend;
 
		time_t m_start;
 
};
 

	
 
}
include/transport/threadpool.h
Show inline comments
 
#ifndef THREAD_POOL
 
#define THREAD_POOL
 

	
 
#include <boost/thread.hpp>
 
#include <boost/thread/mutex.hpp>
 
#include <boost/signals2/signal.hpp>
 
#include <queue>
 
#include <iostream>
 
#include "transport/logging.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/EventLoop/EventLoop.h"
 

	
 

	
 
/*
 
 * Thread serves as a base class for any code that has to be excuted as a thread
 
 * by the ThreadPool class. The run method defines the code that has to be run
 
 * as a theard. For example, code in run could be sendinga request to a server
 
 * waiting for the response and storing the response. When the thread finishes
 
 * execution, the ThreadPool invokes finalize where one could have the code necessary
 
 * to collect all the responses and release any resources. 
 
 *
 
 * NOTE: The object of the Thread class must be valid (in scope) throughout the 
 
 * execution of the thread.
 
 */
 

	
 
class Thread
 
{
 
	int threadID;
 

	
 
	public:
 
	
 
	Thread() {}
 
	virtual ~Thread() {}
 
	virtual void run() = 0;
 
	virtual void finalize() {}
 
	int getThreadID() {return threadID;}
 
	void setThreadID(int tid) {threadID = tid;}
 
};
 

	
 
/*
 
 * ThreadPool provides the interface to manage a pool of threads. It schedules jobs
 
 * on free threads and when the thread completes it automatically deletes the object
 
 * corresponding to a Thread. If free threads are not available, the requests are 
 
 * added to a queue and scheduled later when threads become available.
 
 */
 

	
 
class ThreadPool
 
{
 
	const int MAX_THREADS;
 
	int activeThreads;
 
	std::queue<int> freeThreads;
 
	
 
	std::queue<Thread*> requestQueue;
 
	boost::thread **worker;
 

	
 
	boost::mutex count_lock;
 
	boost::mutex pool_lock;
 
	boost::mutex criticalregion;
 
	Swift::EventLoop *loop;
 

	
 
	boost::signals2::signal  < void () > onWorkerAvailable;
 

	
 
	public:
 
	ThreadPool(Swift::EventLoop *loop, int maxthreads);
 
	~ThreadPool();
 
	void runAsThread(Thread *t);
 
	int getActiveThreadCount(); 
 
	void updateActiveThreadCount(int k);
 
	void cleandUp(Thread *, int);
 
	void scheduleFromQueue();
 
	int getFreeThread();
 
	void releaseThread(int i);
 
};
 

	
 
#endif
include/transport/transport.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Server/Server.h"
 
#include "Swiften/Disco/GetDiscoInfoRequest.h"
 
#include "Swiften/Disco/EntityCapsManager.h"
 
#include "Swiften/Disco/CapsManager.h"
 
#include "Swiften/Disco/CapsMemoryStorage.h"
 
#include "Swiften/Network/BoostTimerFactory.h"
 
#include "Swiften/Network/BoostIOServiceThread.h"
 
#include "Swiften/Server/UserRegistry.h"
 
#include "Swiften/Base/SafeByteArray.h"
 
#include "Swiften/Jingle/JingleSessionManager.h"
 
#include "Swiften/Component/ComponentError.h"
 
#include "Swiften/Component/Component.h"
 

	
 
#include <boost/bind.hpp>
 
#include "transport/config.h"
 
#include "transport/factory.h"
 
#include "transport/presenceoracle.h"
 
#include <Swiften/Network/BoostConnectionServer.h>
 

	
 
namespace Transport {
 
	// typedef enum { 	CLIENT_FEATURE_ROSTERX = 2,
 
	// 				CLIENT_FEATURE_XHTML_IM = 4,
 
	// 				CLIENT_FEATURE_FILETRANSFER = 8,
 
	// 				CLIENT_FEATURE_CHATSTATES = 16
 
	// 				} SpectrumImportantFeatures;
 
	// 
 
	class StorageBackend;
 
	class Factory;
 
	class UserRegistry;
 

	
 
	/// Represents one transport instance.
 

	
 
	/// It's used to connect the Jabber server and provides transaction layer
 
	/// between Jabber server and other classes.
 
	///
 
	/// In server mode it represents Jabber server to which users can connect and use
 
	/// it as transport.
 
	class Component {
 
		public:
 
			/// Creates new Component instance.
 

	
 
			/// \param loop Main event loop.
 
			/// \param config Cofiguration; this class uses following Config values:
 
			/// 	- service.jid
 
			/// 	- service.password
 
			/// 	- service.server
 
			/// 	- service.port
 
			/// 	- service.server_mode
 
			/// \param factories Swift::NetworkFactories.
 
			/// \param factory Transport Abstract factory used to create basic transport structures.
 
			/// \param userRegistery UserRegistry class instance. It's needed only when running transport in server-mode.
 
			Component(Swift::EventLoop *loop, Swift::NetworkFactories *factories, Config *config, Factory *factory, Transport::UserRegistry *userRegistry = NULL);
 

	
 
			/// Component destructor.
 
			~Component();
 

	
 
			/// Returns Swift::StanzaChannel associated with this Transport::Component.
 

	
 
			/// It can be used to send presences and other stanzas.
 
			/// \return Swift::StanzaChannel associated with this Transport::Component.
 
			Swift::StanzaChannel *getStanzaChannel();
 

	
 
			/// Returns Swift::IQRouter associated with this Component.
 

	
 
			/// \return Swift::IQRouter associated with this Component.
 
			Swift::IQRouter *getIQRouter() { return m_iqRouter; }
 

	
 
			/// Returns Swift::PresenceOracle associated with this Transport::Component.
 

	
 
			/// You can use it to check current resource connected for particular user.
 
			/// \return Swift::PresenceOracle associated with this Transport::Component.
 
			PresenceOracle *getPresenceOracle();
 

	
 
			/// Returns True if the component is in server mode.
 

	
 
			/// \return True if the component is in server mode.
 
			bool inServerMode() { return m_server != NULL; }
 

	
 
			/// Connects the Jabber server.
 
			/// Starts the Component.
 
			
 
			/// In server-mode, it starts listening on particular port for new client connections.
 
			/// In gateway-mode, it connects the XMPP server.
 
			void start();
 

	
 
			/// Stops the component.
 
			void stop();
 

	
 
			/// Returns Jabber ID of this transport.
 

	
 
			/// \return Jabber ID of this transport
 
			Swift::JID &getJID() { return m_jid; }
 

	
 
			/// Returns Swift::NetworkFactories which can be used to create new connections.
 

	
 
			/// \return Swift::NetworkFactories which can be used to create new connections.
 
			Swift::NetworkFactories *getNetworkFactories() { return m_factories; }
 

	
 
			/// Returns Transport Factory used to create basic Transport components.
 

	
 
			/// \return Transport Factory used to create basic Transport components.
 
			Factory *getFactory() { return m_factory; }
 

	
 
			/// This signal is emitted when server disconnects the transport because of some error.
 

	
 
			/// \param error disconnection error
 
			boost::signal<void (const Swift::ComponentError &error)> onConnectionError;
 

	
 
			/// This signal is emitted when transport successfully connects the server.
 
			boost::signal<void ()> onConnected;
 

	
 
			/// This signal is emitted when XML stanza is sent to server.
 

	
 
			/// \param xml xml stanza
 
			boost::signal<void (const std::string &xml)> onXMLOut;
 

	
 
			/// This signal is emitted when XML stanza is received from server.
 

	
 
			/// \param xml xml stanza
 
			boost::signal<void (const std::string &xml)> onXMLIn;
 

	
 
			Config *getConfig() { return m_config; }
 

	
 
			/// This signal is emitted when presence from XMPP user is received.
 

	
 
			/// It's emitted only for presences addressed to transport itself
 
			/// (for example to="j2j.domain.tld").
 
			/// \param presence presence data
 
			/// (for example to="j2j.domain.tld") and for presences comming to
 
			/// MUC (for example to="#chat%irc.freenode.org@irc.domain.tld")
 
			/// \param presence Presence.
 
			boost::signal<void (Swift::Presence::ref presence)> onUserPresenceReceived;
 

	
 
			/// Component class asks the XMPP clients automatically for their capabilities.
 
			/// This signal is emitted when capabilities have been received or changed.
 
			/// \param jid JID of the client for which we received capabilities
 
			/// \param info disco#info with response.
 
			boost::signal<void (const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info)> onUserDiscoInfoReceived;
 

	
 
// 			boost::signal<void (boost::shared_ptr<Swift::DiscoInfo> info, Swift::ErrorPayload::ref error, const Swift::JID& jid)> onDiscoInfoResponse;
 

	
 
		private:
 
			void handleConnected();
 
			void handleConnectionError(const Swift::ComponentError &error);
 
			void handleServerStopped(boost::optional<Swift::BoostConnectionServer::Error> e);
 
			void handlePresence(Swift::Presence::ref presence);
 
			void handleDataRead(const Swift::SafeByteArray &data);
 
			void handleDataWritten(const Swift::SafeByteArray &data);
 

	
 
			void handleDiscoInfoResponse(boost::shared_ptr<Swift::DiscoInfo> info, Swift::ErrorPayload::ref error, const Swift::JID& jid);
 
			void handleCapsChanged(const Swift::JID& jid);
 

	
 
			Swift::NetworkFactories *m_factories;
 
			Swift::Component *m_component;
 
			Swift::Server *m_server;
 
			Swift::Timer::ref m_reconnectTimer;
 
			Swift::EntityCapsManager *m_entityCapsManager;
 
			Swift::CapsManager *m_capsManager;
 
			Swift::CapsMemoryStorage *m_capsMemoryStorage;
 
			PresenceOracle *m_presenceOracle;
 
			Swift::StanzaChannel *m_stanzaChannel;
 
			Swift::IQRouter *m_iqRouter;
 
			
 
			Transport::UserRegistry *m_userRegistry;
 
			StorageBackend *m_storageBackend;
 
			int m_reconnectCount;
 
			Config* m_config;
 
			std::string m_protocol;
 
			Swift::JID m_jid;
 
			Factory *m_factory;
 
			Swift::EventLoop *m_loop;
 

	
 
		friend class User;
 
		friend class UserRegistration;
 
		friend class NetworkPluginServer;
 
	};
 
}
include/transport/user.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <time.h>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Disco/EntityCapsManager.h"
 
#include "Swiften/Disco/EntityCapsProvider.h"
 
#include "storagebackend.h"
 
#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
 
#include "Swiften/Elements/SpectrumErrorPayload.h"
 
#include "Swiften/Network/Timer.h"
 
#include "Swiften/Network/Connection.h"
 

	
 
namespace Transport {
 

	
 
class Component;
 
class RosterManager;
 
class ConversationManager;
 
class UserManager;
 
class PresenceOracle;
 
struct UserInfo;
 

	
 
/// Represents online XMPP user.
 
class User : public Swift::EntityCapsProvider {
 
	public:
 
		/// Creates new User class.
 
		/// \param jid XMPP JID associated with this user
 
		/// \param userInfo UserInfo struct with informations needed to connect
 
		/// this user to legacy network
 
		/// \param component Component associated with this user
 
		User(const Swift::JID &jid, UserInfo &userInfo, Component * component, UserManager *userManager);
 

	
 
		/// Destroyes User.
 
		virtual ~User();
 

	
 
		/// Returns JID of XMPP user who is currently connected using this User class.
 
		/// \return full JID
 
		const Swift::JID &getJID();
 

	
 
		/// Returns full JID which supports particular feature or invalid JID.
 
		/// \param feature disco#info feature.
 
		/// \return full JID which supports particular feature or invalid JID.
 
		std::vector<Swift::JID> getJIDWithFeature(const std::string &feature);
 

	
 
		Swift::DiscoInfo::ref getCaps(const Swift::JID &jid) const;
 

	
 
		/// Returns UserInfo struct with informations needed to connect the legacy network.
 
		/// \return UserInfo struct
 
		UserInfo &getUserInfo() { return m_userInfo; }
 

	
 
		RosterManager *getRosterManager() { return m_rosterManager; }
 

	
 
		ConversationManager *getConversationManager() { return m_conversationManager; }
 

	
 
		Component *getComponent() { return m_component; }
 

	
 
		UserManager *getUserManager() { return m_userManager; }
 

	
 
		void setData(void *data) { m_data = data; }
 
		void *getData() { return m_data; }
 

	
 
		/// Handles presence from XMPP JID associated with this user.
 
		/// \param presence Swift::Presence.
 
		void handlePresence(Swift::Presence::ref presence, bool forceJoin = false);
 

	
 
		void handleSubscription(Swift::Presence::ref presence);
 

	
 
		void handleDiscoInfo(const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info);
 

	
 
		time_t &getLastActivity() {
 
			return m_lastActivity;
 
		}
 

	
 
		void updateLastActivity() {
 
			m_lastActivity = time(NULL);
 
		}
 

	
 
		/// Returns language.
 
		/// \return language
 
		const char *getLang() { return "en"; }
 

	
 
		void handleDisconnected(const std::string &error, Swift::SpectrumErrorPayload::Error e = Swift::SpectrumErrorPayload::CONNECTION_ERROR_OTHER_ERROR);
 

	
 
		bool isReadyToConnect() {
 
			return m_readyForConnect;
 
		}
 

	
 
		void setConnected(bool connected);
 

	
 
		void sendCurrentPresence();
 

	
 
		void setIgnoreDisconnect(bool ignoreDisconnect);
 

	
 
		bool isConnected() {
 
			return m_connected;
 
		}
 

	
 
		int getResourceCount() {
 
			return m_resources;
 
		}
 

	
 
		void addUserSetting(const std::string &key, const std::string &value) {
 
			m_settings[key] = value;
 
		}
 

	
 
		const std::string &getUserSetting(const std::string &key) {
 
			return m_settings[key];
 
		}
 

	
 
		void setCacheMessages(bool cacheMessages);
 

	
 
		bool shouldCacheMessages() {
 
			return m_cacheMessages;
 
		}
 

	
 
		boost::signal<void ()> onReadyToConnect;
 
		boost::signal<void (Swift::Presence::ref presence)> onPresenceChanged;
 
		boost::signal<void (const Swift::JID &who, const std::string &room, const std::string &nickname, const std::string &password)> onRoomJoined;
 
		boost::signal<void (const std::string &room)> onRoomLeft;
 
		boost::signal<void ()> onDisconnected;
 

	
 
	private:
 
		void onConnectingTimeout();
 

	
 
		Swift::JID m_jid;
 
		Component *m_component;
 
		RosterManager *m_rosterManager;
 
		UserManager *m_userManager;
 
		ConversationManager *m_conversationManager;
 
		Swift::EntityCapsManager *m_entityCapsManager;
 
		PresenceOracle *m_presenceOracle;
 
		UserInfo m_userInfo;
 
		void *m_data;
 
		bool m_connected;
 
		bool m_readyForConnect;
 
		bool m_ignoreDisconnect;
 
		Swift::Timer::ref m_reconnectTimer;
 
		boost::shared_ptr<Swift::Connection> connection;
 
		time_t m_lastActivity;
 
		std::map<Swift::JID, Swift::DiscoInfo::ref> m_legacyCaps;
 
		std::vector<boost::shared_ptr<Swift::OutgoingFileTransfer> > m_filetransfers;
 
		int m_resources;
 
		int m_reconnectCounter;
 
		std::list<Swift::Presence::ref> m_joinedRooms;
 
		std::map<std::string, std::string> m_settings;
 
		bool m_cacheMessages;
 
};
 

	
 
}
include/transport/usermanager.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 
#include "transport/userregistry.h"
 
#include "Swiften/Elements/Message.h"
 
#include "Swiften/Elements/Presence.h"
 
#include "Swiften/Disco/EntityCapsProvider.h"
 
#include "Swiften/Elements/DiscoInfo.h"
 
#include "Swiften/Network/Timer.h"
 

	
 
namespace Transport {
 

	
 
class User;
 
class Component;
 
class StorageBackend;
 
class StorageResponder;
 
class RosterResponder;
 
class DiscoItemsResponder;
 

	
 
/// Manages online XMPP Users.
 

	
 
/// This class handles presences and creates User classes when new user connects.
 
/// It also removes the User class once the last user's resource disconnected.
 

	
 
/// Basic user creation process:
 
/**
 
	\msc
 
	Component,UserManager,User,StorageBackend,Slot;
 
	---  [ label = "Available presence received"];
 
	Component->UserManager [label="handlePresence(...)", URL="\ref UserManager::handlePresence()"];
 
	UserManager->StorageBackend [label="getUser(...)", URL="\ref StorageBackend::getUser()"];
 
	UserManager->User [label="User::User(...)", URL="\ref User"];
 
	UserManager->Slot [label="onUserCreated(...)", URL="\ref UserManager::onUserCreated()"];
 
	UserManager->User [label="handlePresence(...)", URL="\ref User::handlePresence()"];
 
	\endmsc
 
*/
 
class UserManager : public Swift::EntityCapsProvider {
 
	public:
 
		/// Creates new UserManager.
 
		/// \param component Component which's presence will be handled
 
		/// \param storageBackend Storage backend used to fetch UserInfos
 
		UserManager(Component *component, UserRegistry *userRegistry, DiscoItemsResponder *discoItemsResponder, StorageBackend *storageBackend = NULL);
 

	
 
		/// Destroys UserManager.
 
		~UserManager();
 

	
 
		/// Returns user according to his bare JID.
 
		/// \param barejid bare JID of user
 
		/// \return User class associated with this user
 
		User *getUser(const std::string &barejid);
 

	
 
		/// Returns map with all connected users.
 
		/// \return All connected users.
 
		const std::map<std::string, User *> &getUsers() {
 
			return m_users;
 
		}
 

	
 
		/// Returns number of online users.
 
		/// \return number of online users
 
		int getUserCount();
 

	
 
		/// Removes user. This function disconnects user and safely removes
 
		/// User class. This does *not* remove user from StorageBackend.
 
		/// \param user User class to remove
 
		void removeUser(User *user, bool onUserBehalf = true);
 

	
 
		void removeAllUsers(bool onUserBehalf = true);
 

	
 
		Swift::DiscoInfo::ref getCaps(const Swift::JID&) const;
 

	
 
		DiscoItemsResponder *getDiscoResponder() { return m_discoItemsResponder; }
 

	
 
		/// Called when new User class is created.
 
		/// \param user newly created User class
 
		boost::signal<void (User *user)> onUserCreated;
 

	
 
		/// Called when User class is going to be removed
 
		/// \param user removed User class
 
		boost::signal<void (User *user)> onUserDestroyed;
 

	
 
		/// Returns true if user is connected.
 
		/// \return True if user is connected.
 
		bool isUserConnected(const std::string &barejid) const {
 
			return m_users.find(barejid) != m_users.end();
 
		}
 

	
 
		/// Returns pointer to UserRegistry.
 
		/// \return Pointer to UserRegistry.
 
		UserRegistry *getUserRegistry() {
 
			return m_userRegistry;
 
		}
 

	
 
		Component *getComponent() {
 
			return m_component;
 
		}
 

	
 
		/// Connects user manually.
 
		/// \param user JID of user.
 
		void connectUser(const Swift::JID &user);
 

	
 
		/// Disconnects user manually.
 
		/// \param user JID of user.
 
		void disconnectUser(const Swift::JID &user);
 

	
 
		void messageToXMPPSent() { m_sentToXMPP++; }
 
		void messageToBackendSent() { m_sentToBackend++; }
 

	
 
		unsigned long getMessagesToXMPP() { return m_sentToXMPP; }
 
		unsigned long getMessagesToBackend() { return m_sentToBackend; }
 
		
 

	
 
	private:
 
		void handlePresence(Swift::Presence::ref presence);
 
		void handleMessageReceived(Swift::Message::ref message);
 
		void handleGeneralPresenceReceived(Swift::Presence::ref presence);
 
		void handleProbePresence(Swift::Presence::ref presence);
 
		void handleErrorPresence(Swift::Presence::ref presence);
 
		void handleSubscription(Swift::Presence::ref presence);
 
		void handleRemoveTimeout(const std::string jid, User *user, bool reconnect);
 
		void handleDiscoInfo(const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info);
 
		void addUser(User *user);
 

	
 
		long m_onlineBuddies;
 
		User *m_cachedUser;
 
		std::map<std::string, User *> m_users;
 
		Component *m_component;
 
		StorageBackend *m_storageBackend;
 
		StorageResponder *m_storageResponder;
 
		UserRegistry *m_userRegistry;
 
		Swift::Timer::ref m_removeTimer;
 
		unsigned long m_sentToXMPP;
 
		unsigned long m_sentToBackend;
 
		DiscoItemsResponder *m_discoItemsResponder;
 
		friend class RosterResponder;
 
};
 

	
 
}
include/transport/userregistration.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/Responder.h"
 
#include "Swiften/Elements/InBandRegistrationPayload.h"
 
#include "Swiften/Elements/RosterPayload.h"
 
#include <boost/signal.hpp>
 

	
 
namespace Transport {
 

	
 
struct UserInfo;
 
class Component;
 
class StorageBackend;
 
class UserManager;
 
class Config;
 

	
 
/// Allows users to register the transport using service discovery.
 
class UserRegistration : public Swift::Responder<Swift::InBandRegistrationPayload> {
 
	public:
 
		/// Creates new UserRegistration handler.
 
		/// \param component Component associated with this class
 
		/// \param userManager UserManager associated with this class
 
		/// \param storageBackend StorageBackend where the registered users will be stored
 
		UserRegistration(Component *component, UserManager *userManager, StorageBackend *storageBackend);
 

	
 
		/// Destroys UserRegistration.
 
		~UserRegistration();
 

	
 
		/// Registers new user. This function stores user into database and subscribe user to transport.
 
		/// \param userInfo UserInfo struct with informations about registered user
 
		/// \return false if user is already registered
 
		bool registerUser(const UserInfo &userInfo);
 

	
 
		/// Unregisters user. This function removes all data about user from databa, unsubscribe all buddies
 
		/// managed by this transport and disconnects user if he's connected.
 
		/// \param barejid bare JID of user to unregister
 
		/// \return false if there is no such user registered
 
		bool unregisterUser(const std::string &barejid);
 

	
 
		/// Called when new user has been registered.
 
		/// \param userInfo UserInfo struct with informations about user
 
		boost::signal<void (const UserInfo &userInfo)> onUserRegistered;
 

	
 
		/// Called when user has been unregistered.
 
		/// \param userInfo UserInfo struct with informations about user
 
		boost::signal<void (const UserInfo &userInfo)> onUserUnregistered;
 

	
 
		/// Called when user's registration has been updated.
 
		/// \param userInfo UserInfo struct with informations about user
 
		boost::signal<void (const UserInfo &userInfo)> onUserUpdated;
 

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

	
 
		void handleRegisterRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref error, const UserInfo &row);
 
		void handleUnregisterRemoteRosterResponse(boost::shared_ptr<Swift::RosterPayload> payload, Swift::ErrorPayload::ref error, const std::string &barejid);
 
		
 
		Component *m_component;
 
		StorageBackend *m_storageBackend;
 
		UserManager *m_userManager;
 
		Config *m_config;
 

	
 
};
 

	
 
}
include/transport/userregistry.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Server/UserRegistry.h"
 
#include "Swiften/Network/NetworkFactories.h"
 
#include "Swiften/Network/Timer.h"
 
#include "Swiften/Network/TimerFactory.h"
 
#include "transport/config.h"
 

	
 
namespace Transport {
 

	
 
/// Validates passwords in Server mode.
 

	
 
/// Normal login workflow could work like following:
 
/**
 
	\msc
 
	UserManager,UserRegistry,ServerFromClientSession;
 
	ServerFromClientSession->UserRegistry [label="isValidUserPassword(...)", URL="\ref UserRegistry::isValidUserPassword()"];
 
	UserManager<-UserRegistry [label="onConnectUser(...)", URL="\ref UserRegistry::onConnectUser()"];
 
	---  [ label = "UserManager logins user and validates password"];
 
	UserManager->UserRegistry [label="onPasswordValid(...)", URL="\ref UserRegistry::onPasswordValid()"];
 
	ServerFromClientSession<-UserRegistry [label="handlePasswordValid(...)", URL="\ref ServerFromClientSession::handlePasswordValid()"];
 
	\endmsc
 
*/
 
/// User can of course disconnect during login process. In this case, stopLogin() method is called which informs upper layer
 
/// that user disconnected:
 
/**
 
	\msc
 
	UserManager,UserRegistry,ServerFromClientSession;
 
	ServerFromClientSession->UserRegistry [label="isValidUserPassword(...)", URL="\ref UserRegistry::isValidUserPassword()"];
 
	UserManager<-UserRegistry [label="onConnectUser(...)", URL="\ref UserRegistry::onConnectUser()"];
 
	---  [ label = "UserManager is logging in the user, but he disconnected"];
 
	ServerFromClientSession->UserRegistry [label="stopLogin(...)", URL="\ref UserRegistry::stopLogin()"];
 
	UserManager<-UserRegistry [label="onDisconnectUser(...)", URL="\ref UserRegistry::onDisconnectUser()"];
 
	---  [ label = "UserManager disconnects the user"];
 
	\endmsc
 
*/
 
class UserRegistry : public Swift::UserRegistry {
 
	public:
 
		/// Creates new UserRegistry.
 
		/// \param cfg Config file
 
		/// 	- 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, 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;
 
		mutable Config *config;
 
		Swift::Timer::ref m_removeTimer;
 
		bool m_inRemoveLater;
 
};
 

	
 
}
include/transport/usersreconnecter.h
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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
 
 */
 

	
 
#pragma once
 

	
 
#include <string>
 
#include <algorithm>
 
#include <vector>
 
#include "Swiften/Swiften.h"
 

	
 
#include "Swiften/Network/Timer.h"
 

	
 
namespace Transport {
 

	
 
class StorageBackend;
 
class Component;
 

	
 
/// Tries to reconnect users who have been online before crash/restart.
 
class UsersReconnecter {
 
	public:
 
		/// Creates new UsersReconnecter.
 
		/// \param component Transport instance associated with this roster.
 
		/// \param storageBackend StorageBackend from which the users will be fetched.
 
		UsersReconnecter(Component *component, StorageBackend *storageBackend);
 

	
 
		/// Destructor.
 
		virtual ~UsersReconnecter();
 

	
 
		void reconnectNextUser();
 

	
 
	private:
 
		void handleConnected();
 

	
 
		Component *m_component;
 
		StorageBackend *m_storageBackend;
 
		bool m_started;
 
		std::vector<std::string> m_users;
 
		Swift::Timer::ref m_nextUserTimer;
 
};
 

	
 
}
include/transport/vcardresponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/Responder.h"
 
#include "Swiften/Elements/VCard.h"
 
#include "Swiften/Network/NetworkFactories.h"
 
#include "Swiften/Network/Timer.h"
 
#include <boost/signal.hpp>
 

	
 
namespace Transport {
 

	
 
class StorageBackend;
 
class UserManager;
 
class User;
 

	
 
class VCardResponder : public Swift::Responder<Swift::VCard> {
 
	public:
 
		VCardResponder(Swift::IQRouter *router, Swift::NetworkFactories *factories, UserManager *userManager);
 
		~VCardResponder();
 

	
 
		void sendVCard(unsigned int id, boost::shared_ptr<Swift::VCard> vcard);
 

	
 
		boost::signal<void (User *, const std::string &name, unsigned int id)> onVCardRequired;
 
		boost::signal<void (User *, boost::shared_ptr<Swift::VCard> vcard)> onVCardUpdated;
 

	
 
		void collectTimeouted();
 

	
 
	private:
 
		struct VCardData {
 
			Swift::JID from;
 
			Swift::JID to;
 
			std::string id;
 
			time_t received;
 
		};
 

	
 
		virtual bool handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::VCard> payload);
 
		virtual bool handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::VCard> payload);
 
		UserManager *m_userManager;
 
		std::map<unsigned int, VCardData> m_queries;
 
		unsigned int m_id;
 
		Swift::Timer::ref m_collectTimer;
 
};
 

	
 
}
spectrum/src/main.cpp
Show inline comments
 
#include "transport/config.h"
 
#include "transport/transport.h"
 
#include "transport/filetransfermanager.h"
 
#include "transport/usermanager.h"
 
#include "transport/sqlite3backend.h"
 
#include "transport/mysqlbackend.h"
 
#include "transport/pqxxbackend.h"
 
#include "transport/userregistration.h"
 
#include "transport/networkpluginserver.h"
 
#include "transport/admininterface.h"
 
#include "transport/statsresponder.h"
 
#include "transport/usersreconnecter.h"
 
#include "transport/util.h"
 
#include "transport/gatewayresponder.h"
 
#include "transport/logging.h"
 
#include "transport/discoitemsresponder.h"
 
#include "transport/adhocmanager.h"
 
#include "transport/settingsadhoccommand.h"
 
#include "Swiften/EventLoop/SimpleEventLoop.h"
 
#include "Swiften/Network/BoostNetworkFactories.h"
 
#include <boost/filesystem.hpp>
 
#include <boost/algorithm/string.hpp>
 
#ifndef WIN32
 
#include "sys/signal.h"
 
#include "sys/stat.h"
 
#include <pwd.h>
 
#include <grp.h>
 
#include <sys/resource.h>
 
#include "libgen.h"
 
#ifndef __FreeBSD__
 
#include <malloc.h>
 
#endif
 
#else
 
#include <process.h>
 
#define getpid _getpid
 
#include "win32/ServiceWrapper.h"
 
#endif
 
#include <sys/stat.h>
 

	
 
using namespace Transport;
 
using namespace Transport::Util;
 

	
 
DEFINE_LOGGER(logger, "Spectrum");
 

	
 
Swift::SimpleEventLoop *eventLoop_ = NULL;
 
Component *component_ = NULL;
 
UserManager *userManager_ = NULL;
 
Config *config_ = NULL;
 

	
 
static void stop_spectrum() {
 
	userManager_->removeAllUsers(false);
 
	component_->stop();
 
	eventLoop_->stop();
 
}
 

	
 
static void spectrum_sigint_handler(int sig) {
 
	eventLoop_->postEvent(&stop_spectrum);
 
}
 

	
 
static void spectrum_sigterm_handler(int sig) {
 
	eventLoop_->postEvent(&stop_spectrum);
 
}
 

	
 
#ifdef WIN32
 
BOOL spectrum_control_handler( DWORD fdwCtrlType ) { 
 
	if (fdwCtrlType == CTRL_C_EVENT || fdwCtrlType == CTRL_CLOSE_EVENT) {
 
		eventLoop_->postEvent(&stop_spectrum);
 
		return TRUE;
 
	}
 
	return FALSE;
 
} 
 
#endif
 

	
 
static void removeOldIcons(std::string iconDir) {
 
	std::vector<std::string> dirs;
 
	dirs.push_back(iconDir);
 

	
 
	boost::thread thread(boost::bind(Util::removeEverythingOlderThan, dirs, time(NULL) - 3600*24*14));
 
}
 

	
 
#ifndef WIN32
 
static void daemonize(const char *cwd, const char *lock_file) {
 
	pid_t pid, sid;
 
	FILE* lock_file_f;
 
	char process_pid[20];
 
	/* already a daemon */
 
	if ( getppid() == 1 ) return;
 

	
 
	/* Fork off the parent process */
 
	pid = fork();
 
	if (pid < 0) {
 
		exit(1);
 
	}
 
	/* If we got a good PID, then we can exit the parent process. */
 
	if (pid > 0) {
 
		if (lock_file) {
 
			/* write our pid into it & close the file. */
 
			lock_file_f = fopen(lock_file, "w+");
 
			if (lock_file_f == NULL) {
 
				std::cerr << "Cannot create lock file " << lock_file << ". Exiting\n";
 
				exit(1);
 
			}
 
			sprintf(process_pid,"%d\n",pid);
 
			if (fwrite(process_pid,1,strlen(process_pid),lock_file_f) < strlen(process_pid)) {
 
				std::cerr << "Cannot write to lock file " << lock_file << ". Exiting\n";
 
				exit(1);
 
			}
 
			fclose(lock_file_f);
 
		}
 
		exit(0);
 
	}
 

	
 
	/* Change the file mode mask */
 
	umask(0);
 

	
 
	/* Create a new SID for the child process */
 
	sid = setsid();
 
	if (sid < 0) {
 
		exit(1);
 
	}
 

	
 
	/* Change the current working directory.  This prevents the current
 
		directory from being locked; hence not being able to remove it. */
 
	if ((chdir(cwd)) < 0) {
 
		exit(1);
 
	}
 
	
 
	if (freopen( "/dev/null", "r", stdin) == NULL) {
 
		std::cout << "EE cannot open /dev/null. Exiting\n";
 
		exit(1);
 
	}
 
}
 
#endif
 

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

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

	
 
#ifndef WIN32
 
	if (!CONFIG_STRING(config, "service.group").empty() && !CONFIG_STRING(config, "service.user").empty()) {
 
		struct group *gr;
 
		if ((gr = getgrnam(CONFIG_STRING(config, "service.group").c_str())) == NULL) {
 
			std::cerr << "Invalid service.group name " << CONFIG_STRING(config, "service.group") << "\n";
 
		}
 
		struct passwd *pw;
 
		if ((pw = getpwnam(CONFIG_STRING(config, "service.user").c_str())) == NULL) {
 
			std::cerr << "Invalid service.user name " << CONFIG_STRING(config, "service.user") << "\n";
 
		}
 
		chown(ph.string().c_str(), pw->pw_uid, gr->gr_gid);
 
	}
 
#endif
 
}
 

	
 
int mainloop() {
 

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

	
 
	Logging::initMainLogging(config_);
 

	
 
#ifndef WIN32
 
	if (!CONFIG_STRING(config_, "service.group").empty() ||!CONFIG_STRING(config_, "service.user").empty() ) {
 
		struct rlimit limit;
 
		getrlimit(RLIMIT_CORE, &limit);
 

	
 
		if (!CONFIG_STRING(config_, "service.group").empty()) {
 
			struct group *gr;
 
			if ((gr = getgrnam(CONFIG_STRING(config_, "service.group").c_str())) == NULL) {
 
				std::cerr << "Invalid service.group name " << CONFIG_STRING(config_, "service.group") << "\n";
 
				return 1;
 
			}
 

	
 
			if (((setgid(gr->gr_gid)) != 0) || (initgroups(CONFIG_STRING(config_, "service.user").c_str(), gr->gr_gid) != 0)) {
 
				std::cerr << "Failed to set service.group name " << CONFIG_STRING(config_, "service.group") << " - " << gr->gr_gid << ":" << strerror(errno) << "\n";
 
				return 1;
 
			}
 
		}
 

	
 
		if (!CONFIG_STRING(config_, "service.user").empty()) {
 
			struct passwd *pw;
 
			if ((pw = getpwnam(CONFIG_STRING(config_, "service.user").c_str())) == NULL) {
 
				std::cerr << "Invalid service.user name " << CONFIG_STRING(config_, "service.user") << "\n";
 
				return 1;
 
			}
 

	
 
			if ((setuid(pw->pw_uid)) != 0) {
 
				std::cerr << "Failed to set service.user name " << CONFIG_STRING(config_, "service.user") << " - " << pw->pw_uid << ":" << strerror(errno) << "\n";
 
				return 1;
 
			}
 
		}
 
		setrlimit(RLIMIT_CORE, &limit);
 
	}
 

	
 
	struct rlimit limit;
 
	limit.rlim_max = RLIM_INFINITY;
 
	limit.rlim_cur = RLIM_INFINITY;
 
	setrlimit(RLIMIT_CORE, &limit);
 
#endif
 

	
 
	Swift::SimpleEventLoop eventLoop;
 

	
 
	Swift::BoostNetworkFactories *factories = new Swift::BoostNetworkFactories(&eventLoop);
 
	UserRegistry userRegistry(config_, factories);
 

	
src/blockresponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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 "blockresponder.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include "Swiften/Queries/IQRouter.h"
 
#include "transport/BlockPayload.h"
 
#include "Swiften/Swiften.h"
 
#include "transport/usermanager.h"
 
#include "transport/user.h"
 
#include "transport/buddy.h"
 
#include "transport/rostermanager.h"
 
#include "transport/logging.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "BlockResponder");
 

	
 
BlockResponder::BlockResponder(Swift::IQRouter *router, UserManager *userManager) : Swift::SetResponder<BlockPayload>(router) {
 
	m_userManager = userManager;
 
}
 

	
 
BlockResponder::~BlockResponder() {
 
	
 
}
 

	
 
bool BlockResponder::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Transport::BlockPayload> info) {
 
	User *user = m_userManager->getUser(from.toBare().toString());
 
	if (!user) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": User is not logged in");
 
		return true;
 
	}
 

	
 
	Buddy *buddy = user->getRosterManager()->getBuddy(Buddy::JIDToLegacyName(to));
 
	if (!buddy) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": Buddy " << Buddy::JIDToLegacyName(to) << " does not exist");
 
		return true;
 
	}
 

	
 
	if (buddy->isBlocked()) {
 
		LOG4CXX_INFO(logger, from.toBare().toString() << ": Unblocking buddy " << Buddy::JIDToLegacyName(to));
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, from.toBare().toString() << ": Blocking buddy " << Buddy::JIDToLegacyName(to));
 
	}
 

	
 
	onBlockToggled(buddy);
 

	
 
	return true;
 
}
 

	
 
}
src/blockresponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/SetResponder.h"
 
#include "transport/BlockPayload.h"
 
#include <boost/signal.hpp>
 

	
 
namespace Transport {
 

	
 
class UserManager;
 
class Buddy;
 

	
 
class BlockResponder : public Swift::SetResponder<Transport::BlockPayload> {
 
	public:
 
		BlockResponder(Swift::IQRouter *router, UserManager *userManager);
 
		~BlockResponder();
 

	
 
		boost::signal<void (Buddy *)> onBlockToggled;
 

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

	
 
		UserManager *m_userManager;
 
};
 

	
 
}
src/buddy.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/buddy.h"
 
#include "transport/rostermanager.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/BlockPayload.h"
 
#include "transport/usermanager.h"
 
#include "transport/discoitemsresponder.h"
 

	
 
#include "Swiften/Elements/VCardUpdate.h"
 

	
 
namespace Transport {
 

	
 
Buddy::Buddy(RosterManager *rosterManager, long id, BuddyFlag flags) : m_id(id), m_flags(flags), m_rosterManager(rosterManager),
 
	m_subscription(Ask) {
 
// 	m_rosterManager->setBuddy(this);
 
}
 

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

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

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

	
 
void Buddy::setID(long id) {
 
	m_id = id;
 
}
 

	
 
long Buddy::getID() {
 
	return m_id;
 
}
 

	
 
void Buddy::setFlags(BuddyFlag flags) {
 
	m_flags = flags;
 

	
 
	if (!getSafeName().empty()) {
 
		try {
 
			generateJID();
 
		} catch (...) {
 
		}
 
	}
 
}
 

	
 
BuddyFlag Buddy::getFlags() {
 
	return m_flags;
 
}
 

	
 
const Swift::JID &Buddy::getJID() {
 
	if (!m_jid.isValid() || m_jid.getNode().empty()) {
 
		generateJID();
 
	}
 
	return m_jid;
 
}
 

	
 
void Buddy::setSubscription(Subscription subscription) {
 
	m_subscription = subscription;
 
}
 

	
 
Buddy::Subscription Buddy::getSubscription() {
 
	return m_subscription;
 
}
 

	
 
Swift::Presence::ref Buddy::generatePresenceStanza(int features, bool only_new) {
 
	std::string alias = getAlias();
 
	std::string name = getSafeName();
 

	
 
	Swift::StatusShow s;
 
	std::string statusMessage;
 
	if (!getStatus(s, statusMessage))
 
		return Swift::Presence::ref();
 

	
 
	if (m_jid.getNode().empty()) {
 
		generateJID();
 
	}
 

	
 
	Swift::Presence::ref presence = Swift::Presence::create();
 
 	presence->setFrom(m_jid);
 
	presence->setTo(m_rosterManager->getUser()->getJID().toBare());
 
	presence->setType(Swift::Presence::Available);
 

	
 
	if (!statusMessage.empty())
 
		presence->setStatus(statusMessage);
 

	
 
	if (s.getType() == Swift::StatusShow::None)
 
		presence->setType(Swift::Presence::Unavailable);
 
	presence->setShow(s.getType());
 

	
 
	if (presence->getType() != Swift::Presence::Unavailable) {
 
		// caps
 
		
 
		presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::CapsInfo(m_rosterManager->getUser()->getUserManager()->getDiscoResponder()->getBuddyCapsInfo())));
 

	
 
// 		if (features & 0/*TRANSPORT_FEATURE_AVATARS*/) {
 
			presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::VCardUpdate (getIconHash())));
 
// 		}
 
		if (isBlocked()) {
 
			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);
 
	}
 
	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::handleVCardReceived(const std::string &id, Swift::VCard::ref vcard) {
 
	boost::shared_ptr<Swift::GenericRequest<Swift::VCard> > request(new Swift::GenericRequest<Swift::VCard>(Swift::IQ::Result, m_rosterManager->getUser()->getJID(), vcard, m_rosterManager->getUser()->getComponent()->getIQRouter()));
 
	request->send();
 
}
 

	
 
std::string Buddy::JIDToLegacyName(const Swift::JID &jid) {
 
	std::string name;
 
	if (jid.getUnescapedNode() == jid.getNode()) {
 
		name = jid.getNode();
 
		if (name.find_last_of("%") != std::string::npos) {
 
			name.replace(name.find_last_of("%"), 1, "@"); // OK
 
		}
 
	}
 
	else {
 
		name = jid.getUnescapedNode();
 
		// Psi sucks...
 
// 		if (name.find_last_of("\\40") != std::string::npos) {
 
// 			name.replace(name.find_last_of("\\40"), 1, "@"); // OK
 
// 		}
 
	}
 
	return name;
 
}
 

	
 
BuddyFlag Buddy::buddyFlagsFromJID(const Swift::JID &jid) {
 
	if (jid.getUnescapedNode() == jid.getNode()) {
 
		return BUDDY_NO_FLAG;
 
	}
 
	return BUDDY_JID_ESCAPING;
 
}
 

	
 
}
src/conversation.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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 <iostream>
 
#include "transport/conversation.h"
 
#include "transport/conversationmanager.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/buddy.h"
 
#include "transport/rostermanager.h"
 

	
 
#include "Swiften/Elements/MUCItem.h"
 
#include "Swiften/Elements/MUCOccupant.h"
 
#include "Swiften/Elements/MUCUserPayload.h"
 
#include "Swiften/Elements/Delay.h"
 

	
 
namespace Transport {
 

	
 
Conversation::Conversation(ConversationManager *conversationManager, const std::string &legacyName, bool isMUC) : m_conversationManager(conversationManager) {
 
	m_legacyName = legacyName;
 
	m_muc = isMUC;
 
	m_jid = m_conversationManager->getUser()->getJID().toBare();
 
	m_sentInitialPresence = false;
 
}
 

	
 
Conversation::~Conversation() {
 
}
 

	
 
void Conversation::destroyRoom() {
 
	if (m_muc) {
 
		Swift::Presence::ref presence = Swift::Presence::create();
 
		std::string legacyName = m_legacyName;
 
		if (legacyName.find_last_of("@") != std::string::npos) {
 
			legacyName.replace(legacyName.find_last_of("@"), 1, "%"); // OK
 
		}
 
		presence->setFrom(Swift::JID(legacyName, m_conversationManager->getComponent()->getJID().toBare(), m_nickname));
 
		presence->setType(Swift::Presence::Unavailable);
 

	
 
		Swift::MUCItem item;
 
		item.affiliation = Swift::MUCOccupant::NoAffiliation;
 
		item.role = Swift::MUCOccupant::NoRole;
 
		item.actor = "Transport";
 
		item.reason = "Spectrum 2 transport is being shut down.";
 
		Swift::MUCUserPayload *p = new Swift::MUCUserPayload ();
 
		p->addItem(item);
 

	
 
		Swift::MUCUserPayload::StatusCode c;
 
		c.code = 332;
 
		p->addStatusCode(c);
 
		Swift::MUCUserPayload::StatusCode c2;
 
		c2.code = 307;
 
		p->addStatusCode(c2);
 

	
 
		presence->addPayload(boost::shared_ptr<Swift::Payload>(p));
 
		BOOST_FOREACH(const Swift::JID &jid, m_jids) {
 
			presence->setTo(jid);
 
			m_conversationManager->getComponent()->getStanzaChannel()->sendPresence(presence);
 
		}
 
	}
 
}
 

	
 
void Conversation::setRoom(const std::string &room) {
 
	m_room = room;
 
	m_legacyName = m_room + "/" + m_legacyName;
 
}
 

	
 
void Conversation::handleMessage(boost::shared_ptr<Swift::Message> &message, const std::string &nickname) {
 
	if (m_muc) {
 
		message->setType(Swift::Message::Groupchat);
 
	}
 
	else {
 
		if (message->getType() == Swift::Message::Headline) {
 
			if (m_conversationManager->getUser()->getUserSetting("send_headlines") != "1") {
 
				message->setType(Swift::Message::Chat);
 
			}
 
		}
 
		else {
 
			message->setType(Swift::Message::Chat);
 
		}
 
	}
 

	
 
	std::string n = nickname;
 
	if (n.empty() && !m_room.empty() && !m_muc) {
 
		n = m_nickname;
 
	}
 

	
 
	if (message->getType() != Swift::Message::Groupchat) {
 
		message->setTo(m_jid);
 
		// normal message
 
		if (n.empty()) {
 
			Buddy *buddy = m_conversationManager->getUser()->getRosterManager()->getBuddy(m_legacyName);
 
			if (buddy) {
 
				message->setFrom(buddy->getJID());
 
			}
 
			else {
 
				std::string name = m_legacyName;
 
				if (CONFIG_BOOL_DEFAULTED(m_conversationManager->getComponent()->getConfig(), "service.jid_escaping", true)) {
 
					name = Swift::JID::getEscapedNode(m_legacyName);
 
				}
 
				else {
 
					if (name.find_last_of("@") != std::string::npos) {
 
						name.replace(name.find_last_of("@"), 1, "%");
 
					}
 
				}
 

	
 
				message->setFrom(Swift::JID(name, m_conversationManager->getComponent()->getJID().toBare(), "bot"));
 
			}
 
		}
 
		// PM message
 
		else {
 
			if (m_room.empty()) {
 
				message->setFrom(Swift::JID(n, m_conversationManager->getComponent()->getJID().toBare(), "user"));
 
			}
 
			else {
 
				message->setFrom(Swift::JID(m_room, m_conversationManager->getComponent()->getJID().toBare(), n));
 
			}
 
		}
 

	
 
		if (m_conversationManager->getComponent()->inServerMode() && m_conversationManager->getUser()->shouldCacheMessages()) {
 
			boost::posix_time::ptime timestamp = boost::posix_time::second_clock::universal_time();
 
			boost::shared_ptr<Swift::Delay> delay(boost::make_shared<Swift::Delay>());
 
			delay->setStamp(timestamp);
 
			message->addPayload(delay);
 
			m_cachedMessages.push_back(message);
 
			if (m_cachedMessages.size() > 100) {
 
				m_cachedMessages.pop_front();
 
			}
 
		}
 
		else {
 
			m_conversationManager->getComponent()->getStanzaChannel()->sendMessage(message);
 
		}
 
	}
 
	else {
 
		std::string legacyName = m_legacyName;
 
		if (legacyName.find_last_of("@") != std::string::npos) {
 
			legacyName.replace(legacyName.find_last_of("@"), 1, "%"); // OK
 
		}
 

	
 
		std::string n = nickname;
 
		if (n.empty()) {
 
			n = " ";
 
		}
 

	
 
		message->setFrom(Swift::JID(legacyName, m_conversationManager->getComponent()->getJID().toBare(), n));
 

	
 
		if (m_jids.empty()) {
 
			boost::posix_time::ptime timestamp = boost::posix_time::second_clock::universal_time();
 
			boost::shared_ptr<Swift::Delay> delay(boost::make_shared<Swift::Delay>());
 
			delay->setStamp(timestamp);
 
			message->addPayload(delay);
 
			m_cachedMessages.push_back(message);
 
			if (m_cachedMessages.size() > 100) {
 
				m_cachedMessages.pop_front();
 
			}
 
		}
 
		else {
 
			BOOST_FOREACH(const Swift::JID &jid, m_jids) {
 
				message->setTo(jid);
 
				// Subject has to be sent after our own presence (the one with code 110)
 
				if (!message->getSubject().empty() && m_sentInitialPresence == false) {
 
					m_subject = message;
 
					return;
 
				}
 
				m_conversationManager->getComponent()->getStanzaChannel()->sendMessage(message);
 
			}
 
		}
 
	}
 
}
 

	
 
void Conversation::sendParticipants(const Swift::JID &to) {
 
	for (std::map<std::string, Participant>::iterator it = m_participants.begin(); it != m_participants.end(); it++) {
 
		Swift::Presence::ref presence = generatePresence(it->first, it->second.flag, it->second.status, it->second.statusMessage, "");
 
		presence->setTo(to);
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendPresence(presence);
 
	}
 
}
 

	
 
void Conversation::sendCachedMessages(const Swift::JID &to) {
 
	for (std::list<boost::shared_ptr<Swift::Message> >::const_iterator it = m_cachedMessages.begin(); it != m_cachedMessages.end(); it++) {
 
		if (to.isValid()) {
 
			(*it)->setTo(to);
 
		}
 
		else {
 
			(*it)->setTo(m_jid.toBare());
 
		}
 
		m_conversationManager->getComponent()->getStanzaChannel()->sendMessage(*it);
 
	}
 
	m_cachedMessages.clear();
 
}
 

	
 
Swift::Presence::ref Conversation::generatePresence(const std::string &nick, int flag, int status, const std::string &statusMessage, const std::string &newname) {
 
	std::string nickname = nick;
 
	Swift::Presence::ref presence = Swift::Presence::create();
 
	std::string legacyName = m_legacyName;
 
	if (m_muc) {
 
		if (legacyName.find_last_of("@") != std::string::npos) {
 
			legacyName.replace(legacyName.find_last_of("@"), 1, "%"); // OK
 
		}
 
	}
 
	presence->setFrom(Swift::JID(legacyName, m_conversationManager->getComponent()->getJID().toBare(), nickname));
 
	presence->setType(Swift::Presence::Available);
 

	
 
	if (!statusMessage.empty())
 
		presence->setStatus(statusMessage);
 

	
 
	Swift::StatusShow s((Swift::StatusShow::Type) status);
 

	
 
	if (s.getType() == Swift::StatusShow::None) {
src/discoinforesponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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 "discoinforesponder.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include <boost/algorithm/string.hpp>
 
#include "Swiften/Disco/DiscoInfoResponder.h"
 
#include "Swiften/Queries/IQRouter.h"
 
#include "Swiften/Elements/DiscoInfo.h"
 
#include "Swiften/Swiften.h"
 
#include "transport/config.h"
 
#include "transport/logging.h"
 
#include "Swiften/Disco/CapsInfoGenerator.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
DEFINE_LOGGER(logger, "DiscoInfoResponder");
 

	
 
namespace Transport {
 

	
 
DiscoInfoResponder::DiscoInfoResponder(Swift::IQRouter *router, Config *config) : Swift::GetResponder<DiscoInfo>(router) {
 
	m_config = config;
 
	m_config->onBackendConfigUpdated.connect(boost::bind(&DiscoInfoResponder::updateBuddyFeatures, this));
 
	m_buddyInfo = NULL;
 
	m_transportInfo.addIdentity(DiscoInfo::Identity(CONFIG_STRING(m_config, "identity.name"),
 
													CONFIG_STRING(m_config, "identity.category"),
 
													CONFIG_STRING(m_config, "identity.type")));
 

	
 
	std::list<std::string> features;
 
	features.push_back("jabber:iq:register");
 
	features.push_back("jabber:iq:gateway");
 
	features.push_back("jabber:iq:private");
 
	features.push_back("http://jabber.org/protocol/disco#info");
 
	features.push_back("http://jabber.org/protocol/commands");
 
	setTransportFeatures(features);
 

	
 
	updateBuddyFeatures();
 
}
 

	
 
DiscoInfoResponder::~DiscoInfoResponder() {
 
	delete m_buddyInfo;
 
}
 

	
 
void DiscoInfoResponder::updateBuddyFeatures() {
 
	std::list<std::string> features;
 
	features.push_back("http://jabber.org/protocol/disco#items");
 
	features.push_back("http://jabber.org/protocol/disco#info");
 
	features.push_back("http://jabber.org/protocol/chatstates");
 
	features.push_back("http://jabber.org/protocol/xhtml-im");
 
	if (CONFIG_BOOL_DEFAULTED(m_config, "features.receipts", false)) {
 
		features.push_back("urn:xmpp:receipts");
 
	}
 
	setBuddyFeatures(features);
 
}
 

	
 
void DiscoInfoResponder::setTransportFeatures(std::list<std::string> &features) {
 
	for (std::list<std::string>::iterator it = features.begin(); it != features.end(); it++) {
 
		if (!m_transportInfo.hasFeature(*it)) {
 
			m_transportInfo.addFeature(*it);
 
		}
 
	}
 
}
 

	
 
void DiscoInfoResponder::setBuddyFeatures(std::list<std::string> &f) {
 
	delete m_buddyInfo;
 
	m_buddyInfo = new Swift::DiscoInfo;
 
	m_buddyInfo->addIdentity(DiscoInfo::Identity(CONFIG_STRING(m_config, "identity.name"), "client", "pc"));
 

	
 
	for (std::list<std::string>::iterator it = f.begin(); it != f.end(); it++) {
 
		if (!m_buddyInfo->hasFeature(*it)) {
 
			m_buddyInfo->addFeature(*it);
 
		}
 
	}
 

	
 
	CapsInfoGenerator caps("spectrum");
 
	m_capsInfo = caps.generateCapsInfo(*m_buddyInfo);
 
	onBuddyCapsInfoChanged(m_capsInfo);
 
}
 

	
 
void DiscoInfoResponder::addRoom(const std::string &jid, const std::string &name) {
 
	std::string j = jid;
 
	boost::algorithm::to_lower(j);
 
	m_rooms[j] = name;
 
}
 

	
 
void DiscoInfoResponder::clearRooms() {
 
	m_rooms.clear();
 
}
 

	
 
void DiscoInfoResponder::addAdHocCommand(const std::string &node, const std::string &name) {
 
	m_commands[node] = node;
 
}
 

	
 
bool DiscoInfoResponder::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::DiscoInfo> info) {
 
	// disco#info for transport
 
	if (to.getNode().empty()) {
 
		// Adhoc command
 
		if (m_commands.find(info->getNode()) != m_commands.end()) {
 
			boost::shared_ptr<DiscoInfo> res(new DiscoInfo());
 
			res->addFeature("http://jabber.org/protocol/commands");
 
			res->addFeature("jabber:x:data");
 
			res->addIdentity(DiscoInfo::Identity(m_commands[info->getNode()], "automation", "command-node"));
 
			res->setNode(info->getNode());
 
			sendResponse(from, to, id, res);
 
		}
 
		else if (info->getNode() == "http://jabber.org/protocol/commands") {
 
			boost::shared_ptr<DiscoInfo> res(new DiscoInfo());
 
			res->addIdentity(DiscoInfo::Identity("Commands", "automation", "command-list"));
 
			res->setNode(info->getNode());
 
			sendResponse(from, to, id, res);
 
		}
 
		else {
 
			if (!info->getNode().empty()) {
 
				sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
 
				return true;
 
			}
 

	
 
			boost::shared_ptr<DiscoInfo> res(new DiscoInfo(m_transportInfo));
 
			res->setNode(info->getNode());
 
			sendResponse(from, id, res);
 
		}
 
	}
 
	// disco#info for room
 
	else if (m_rooms.find(to.toBare().toString()) != m_rooms.end()) {
 
		boost::shared_ptr<DiscoInfo> res(new DiscoInfo());
 
		res->addIdentity(DiscoInfo::Identity(m_rooms[to.toBare().toString()], "conference", "text"));
 
		res->setNode(info->getNode());
 
		sendResponse(from, to, id, res);
 
	}
 
	// disco#info for buddy
 
	else {
 
		boost::shared_ptr<DiscoInfo> res(new DiscoInfo(*m_buddyInfo));
 
		res->setNode(info->getNode());
 
		sendResponse(from, to, id, res);
 
	}
 
	return true;
 
}
 

	
 
}
src/discoinforesponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include <list>
 
#include <boost/signal.hpp>
 
#include "Swiften/Queries/GetResponder.h"
 
#include "Swiften/Elements/DiscoInfo.h"
 
#include "Swiften/Elements/CapsInfo.h"
 

	
 
namespace Transport {
 

	
 
class Config;
 

	
 
class DiscoInfoResponder : public Swift::GetResponder<Swift::DiscoInfo> {
 
	public:
 
		DiscoInfoResponder(Swift::IQRouter *router, Config *config);
 
		~DiscoInfoResponder();
 

	
 
		void setTransportFeatures(std::list<std::string> &features);
 
		void setBuddyFeatures(std::list<std::string> &features);
 

	
 
		void addRoom(const std::string &jid, const std::string &name);
 
		void clearRooms();
 

	
 
		void addAdHocCommand(const std::string &node, const std::string &name);
 

	
 
		boost::signal<void (const Swift::CapsInfo &capsInfo)> onBuddyCapsInfoChanged;
 

	
 
		Swift::CapsInfo &getBuddyCapsInfo() {
 
				return m_capsInfo;
 
		}
 

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

	
 
		Swift::DiscoInfo m_transportInfo;
 
		Swift::DiscoInfo *m_buddyInfo;
 
		Config *m_config;
 
		Swift::CapsInfo m_capsInfo;
 
		std::map<std::string, std::string> m_rooms;
 
		std::map<std::string, std::string> m_commands;
 
};
 

	
 
}
src/discoitemsresponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/discoitemsresponder.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include "Swiften/Queries/IQRouter.h"
 
#include "Swiften/Swiften.h"
 
#include "transport/transport.h"
 
#include "transport/logging.h"
 
#include "discoinforesponder.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "DiscoItemsResponder");
 

	
 
DiscoItemsResponder::DiscoItemsResponder(Component *component) : Swift::GetResponder<DiscoItems>(component->getIQRouter()) {
 
	m_component = component;
 
	m_commands = boost::shared_ptr<DiscoItems>(new DiscoItems());
 
	m_commands->setNode("http://jabber.org/protocol/commands");
 

	
 
	m_rooms = boost::shared_ptr<DiscoItems>(new DiscoItems());
 
	m_discoInfoResponder = new DiscoInfoResponder(component->getIQRouter(), component->getConfig());
 
	m_discoInfoResponder->start();
 
}
 

	
 
DiscoItemsResponder::~DiscoItemsResponder() {
 
	delete m_discoInfoResponder;
 
}
 

	
 
void DiscoItemsResponder::addAdHocCommand(const std::string &node, const std::string &name) {
 
	m_commands->addItem(DiscoItems::Item(name, m_component->getJID(), node));
 
	m_discoInfoResponder->addAdHocCommand(node, name);
 
}
 

	
 
void DiscoItemsResponder::addRoom(const std::string &node, const std::string &name) {
 
	if (m_rooms->getItems().size() > CONFIG_INT(m_component->getConfig(), "service.max_room_list_size")) {
 
		return;
 
	}
 
	m_rooms->addItem(DiscoItems::Item(name, node));
 
	m_discoInfoResponder->addRoom(node, name);
 
}
 

	
 
void DiscoItemsResponder::clearRooms() {
 
	m_rooms = boost::shared_ptr<DiscoItems>(new DiscoItems());
 
	m_discoInfoResponder->clearRooms();
 
}
 

	
 
Swift::CapsInfo &DiscoItemsResponder::getBuddyCapsInfo() {
 
	return m_discoInfoResponder->getBuddyCapsInfo();
 
}
 

	
 

	
 
bool DiscoItemsResponder::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::DiscoItems> info) {
 
	LOG4CXX_INFO(logger, "get request received with node " << info->getNode());
 
	if (info->getNode() == "http://jabber.org/protocol/commands") {
 
		sendResponse(from, id, m_commands);
 
	}
 
	else if (to.getNode().empty()) {
 
		sendResponse(from, id, m_rooms);
 
	}
 
	else {
 
		sendResponse(from, id, boost::shared_ptr<DiscoItems>(new DiscoItems()));
 
	}
 
	return true;
 
}
 

	
 
}
src/filetransfermanager.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/filetransfermanager.h"
 
#include "transport/transport.h"
 
#include "transport/usermanager.h"
 
#include "transport/user.h"
 
#include "transport/buddy.h"
 
#include "transport/logging.h"
 
#include "Swiften/Network/ConnectionServerFactory.h"
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "FileTransferManager");
 

	
 
FileTransferManager::FileTransferManager(Component *component, UserManager *userManager) {
 
	m_component = component;
 
	m_userManager = userManager;
 

	
 
	m_jingleSessionManager = new Swift::JingleSessionManager(m_component->getIQRouter());
 
	m_connectivityManager = new Swift::ConnectivityManager(m_component->getNetworkFactories()->getNATTraverser());
 
	m_bytestreamRegistry = new Swift::SOCKS5BytestreamRegistry();
 
	m_bytestreamProxy = new Swift::SOCKS5BytestreamProxy(m_component->getNetworkFactories()->getConnectionFactory(), m_component->getNetworkFactories()->getTimerFactory());
 

	
 
	m_localCandidateGeneratorFactory = new Swift::DefaultLocalJingleTransportCandidateGeneratorFactory(m_connectivityManager, m_bytestreamRegistry, m_bytestreamProxy, "thishouldnotbeused");
 
	m_remoteCandidateSelectorFactory = new Swift::DefaultRemoteJingleTransportCandidateSelectorFactory(m_component->getNetworkFactories()->getConnectionFactory(), m_component->getNetworkFactories()->getTimerFactory());
 

	
 
	boost::shared_ptr<Swift::ConnectionServer> server = m_component->getNetworkFactories()->getConnectionServerFactory()->createConnectionServer(19645);
 
	server->start();
 
	m_bytestreamServer = new Swift::SOCKS5BytestreamServer(server, m_bytestreamRegistry);
 
	m_bytestreamServer->start();
 

	
 
	m_outgoingFTManager = new Swift::CombinedOutgoingFileTransferManager(m_jingleSessionManager, m_component->getIQRouter(),
 
																	m_userManager, m_remoteCandidateSelectorFactory, 
 
																	m_localCandidateGeneratorFactory, m_bytestreamRegistry, 
 
																	m_bytestreamProxy, m_component->getPresenceOracle(),
 
																	m_bytestreamServer);
 

	
 
// WARNING: Swiften crashes when this is uncommented... But we probably need it for working Jingle FT
 
// 	m_connectivityManager->addListeningPort(19645);
 
}
 

	
 
FileTransferManager::~FileTransferManager() {
 
	m_bytestreamServer->stop();
 
	delete m_outgoingFTManager;
 
	delete m_remoteCandidateSelectorFactory;
 
	delete m_localCandidateGeneratorFactory;
 
	delete m_jingleSessionManager;
 
	delete m_bytestreamRegistry;
 
	delete m_bytestreamServer;
 
	delete m_bytestreamProxy;
 
	delete m_connectivityManager;
 
}
 

	
 
FileTransferManager::Transfer FileTransferManager::sendFile(User *user, Buddy *buddy, boost::shared_ptr<Swift::ReadBytestream> byteStream, const Swift::StreamInitiationFileInfo &info) {
 
	FileTransferManager::Transfer transfer;
 
	transfer.from = buddy->getJID();
 
	transfer.to = user->getJID();
 
	transfer.readByteStream = byteStream;
 

	
 
	LOG4CXX_INFO(logger, "Starting FT from '" << transfer.from << "' to '" << transfer.to << "'")
 

	
 
	transfer.ft = m_outgoingFTManager->createOutgoingFileTransfer(transfer.from, transfer.to, transfer.readByteStream, info);
 
// 	if (transfer.ft) {
 
// 		m_filetransfers.push_back(ft);
 
// 		ft->onStateChange.connect(boost::bind(&User::handleFTStateChanged, this, _1, Buddy::JIDToLegacyName(from), info.getName(), info.getSize(), id));
 
// 		transfer.ft->start();
 
// 	}
 
	return transfer;
 
}
 

	
 
}
src/gatewayresponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/gatewayresponder.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include "Swiften/Queries/IQRouter.h"
 
#include "Swiften/Elements/RawXMLPayload.h"
 
#include "Swiften/Swiften.h"
 
#include "transport/usermanager.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/logging.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "GatewayResponder");
 

	
 
GatewayResponder::GatewayResponder(Swift::IQRouter *router, UserManager *userManager) : Swift::Responder<GatewayPayload>(router) {
 
	m_userManager = userManager;
 
}
 

	
 
GatewayResponder::~GatewayResponder() {
 
}
 

	
 
bool GatewayResponder::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::GatewayPayload> payload) {
 
	std::string prompt = CONFIG_STRING(m_userManager->getComponent()->getConfig(), "gateway_responder.prompt");
 
	std::string label = CONFIG_STRING(m_userManager->getComponent()->getConfig(), "gateway_responder.label");
 
	sendResponse(from, id, boost::shared_ptr<GatewayPayload>(new GatewayPayload(Swift::JID(), label, prompt)));
 
	return true;
 
}
 

	
 
bool GatewayResponder::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::GatewayPayload> payload) {
 
	std::string prompt = payload->getPrompt();
 
	std::string escaped = Swift::JID::getEscapedNode(prompt);
 
	// This code is here to workaround Gajim (and probably other clients bug too) bug
 
	// https://trac.gajim.org/ticket/7277
 
	if (prompt.find("\\40") != std::string::npos) {
 
		LOG4CXX_WARN(logger, from.toString() << " Received already escaped JID " << prompt << ". Not escaping again.");
 
		escaped = prompt;
 
	}
 

	
 
	std::string jid = escaped + "@" + m_userManager->getComponent()->getJID().toBare().toString();
 

	
 
	sendResponse(from, id, boost::shared_ptr<GatewayPayload>(new GatewayPayload(jid)));
 
	return true;
 
}
 

	
 
}
src/networkpluginserver.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/networkpluginserver.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/storagebackend.h"
 
#include "transport/rostermanager.h"
 
#include "transport/usermanager.h"
 
#include "transport/conversationmanager.h"
 
#include "transport/localbuddy.h"
 
#include "transport/config.h"
 
#include "transport/conversation.h"
 
#include "transport/vcardresponder.h"
 
#include "transport/rosterresponder.h"
 
#include "transport/memoryreadbytestream.h"
 
#include "transport/logging.h"
 
#include "transport/admininterface.h"
 
#include "blockresponder.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Elements/StreamError.h"
 
#include "Swiften/Network/BoostConnectionServer.h"
 
#include "Swiften/Network/ConnectionServerFactory.h"
 
#include "Swiften/Elements/AttentionPayload.h"
 
#include "Swiften/Elements/XHTMLIMPayload.h"
 
#include "Swiften/Elements/Delay.h"
 
#include "Swiften/Elements/DeliveryReceipt.h"
 
#include "Swiften/Elements/DeliveryReceiptRequest.h"
 
#include "Swiften/Elements/InvisiblePayload.h"
 
#include "Swiften/Elements/SpectrumErrorPayload.h"
 
#include "transport/protocol.pb.h"
 
#include "transport/util.h"
 
#include "transport/discoitemsresponder.h"
 

	
 
#include "boost/date_time/posix_time/posix_time.hpp"
 
#include "boost/signal.hpp"
 

	
 
#include "utf8.h"
 

	
 
#include <Swiften/FileTransfer/ReadBytestream.h>
 
#include <Swiften/Elements/StreamInitiationFileInfo.h>
 

	
 
#ifdef _WIN32
 
#include "windows.h"
 
#include <stdint.h>
 
#else
 
#include "sys/wait.h"
 
#include "sys/signal.h"
 
#include <sys/types.h>
 
#include <signal.h>
 
#include "popt.h"
 
#endif
 

	
 
using namespace Transport::Util;
 

	
 
namespace Transport {
 

	
 
static unsigned long backend_id;
 
static unsigned long bytestream_id;
 

	
 
DEFINE_LOGGER(logger, "NetworkPluginServer");
 

	
 
static NetworkPluginServer *_server;
 

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

	
 
		// Called when there's new message to legacy network from XMPP network
 
		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;
 
		}
 

	
 
		virtual ~NetworkFactory() {}
 

	
 
		// Creates new conversation (NetworkConversation in this case)
 
		Conversation *createConversation(ConversationManager *conversationManager, const std::string &legacyName, bool isMuc) {
 
			NetworkConversation *nc = new NetworkConversation(conversationManager, legacyName, isMuc);
 
			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, buddyInfo.legacyName, buddyInfo.alias, buddyInfo.groups, (BuddyFlag) buddyInfo.flags);
 
			if (!buddy->isValid()) {
 
				delete buddy;
 
				return NULL;
 
			}
 
			if (buddyInfo.subscription == "both") {
 
				buddy->setSubscription(Buddy::Both);
 
			}
 
			else {
 
				buddy->setSubscription(Buddy::Ask);
 
			}
 
			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_(const std::string& exePath, const char *host, const char *port, const char *log_id, const char *cmdlineArgs) {
 
	// BACKEND_ID is replaced with unique ID. The ID is increasing for every backend.
 
	std::string finalExePath = boost::replace_all_copy(exePath, "BACKEND_ID", boost::lexical_cast<std::string>(backend_id++));	
 

	
 
#ifdef _WIN32
 
	// Add host and port.
 
	std::ostringstream fullCmdLine;
 
	fullCmdLine << "\"" << finalExePath << "\" --host " << host << " --port " << port;
 

	
 
	if (cmdlineArgs)
 
		fullCmdLine << " " << cmdlineArgs;
 

	
 
	LOG4CXX_INFO(logger, "Starting new backend " << fullCmdLine.str());
 

	
 
	// We must provide a non-const buffer to CreateProcess below
 
	std::vector<wchar_t> rawCommandLineArgs( fullCmdLine.str().size() + 1 );
 
	wcscpy_s(&rawCommandLineArgs[0], rawCommandLineArgs.size(), utf8ToUtf16(fullCmdLine.str()).c_str());
 

	
 
	STARTUPINFO         si;
 
	PROCESS_INFORMATION pi;
 

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

	
 
	if (! CreateProcess(
 
		utf8ToUtf16(finalExePath).c_str(),
 
		&rawCommandLineArgs[0],
 
		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
 
	// Add host and port.
 
	finalExePath += std::string(" --host ") + host + " --port " + port + " --service.backend_id=" + log_id + " " + cmdlineArgs;
 
	LOG4CXX_INFO(logger, "Starting new backend " << finalExePath);
 

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

	
 
	// fork and exec
 
	pid_t pid = fork();
 
	if ( pid == 0 ) {
 
		setsid();
 
		// close all files
 
		int maxfd=sysconf(_SC_OPEN_MAX);
 
		for(int fd=3; fd<maxfd; fd++) {
 
			close(fd);
 
		}
 
		// child process
 
		errno = 0;
 
		int ret = execv(argv[0], argv);
 
		if (ret == -1) {
 
			exit(errno);
 
		}
 
		exit(0);
 
	} else if ( pid < 0 ) {
 
		LOG4CXX_ERROR(logger, "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(-1, &status, WNOHANG)) > 0) {
 
		if (result != 0) {
 
			_server->handlePIDTerminated((unsigned long)result);
 
			if (WIFEXITED(status)) {
 
				if (WEXITSTATUS(status) != 0) {
 
// 					LOG4CXX_ERROR(logger, "Backend can not be started, exit_code=" << WEXITSTATUS(status));
 
				}
 
			}
 
			else {
 
// 				LOG4CXX_ERROR(logger, "Backend can not be started");
 
			}
 
		}
 
	}
 
}
 
#endif
 

	
 
static void handleBuddyPayload(LocalBuddy *buddy, const pbnetwork::Buddy &payload) {
 
	// 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...
src/presenceoracle.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/presenceoracle.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Elements/MUCPayload.h"
 

	
 
#include <boost/bind.hpp>
 

	
 
using namespace Swift;
 

	
 
namespace Transport {
 

	
 
PresenceOracle::PresenceOracle(StanzaChannel* stanzaChannel) {
 
	stanzaChannel_ = stanzaChannel;
 
	stanzaChannel_->onPresenceReceived.connect(boost::bind(&PresenceOracle::handleIncomingPresence, this, _1));
 
	stanzaChannel_->onAvailableChanged.connect(boost::bind(&PresenceOracle::handleStanzaChannelAvailableChanged, this, _1));
 
}
 

	
 
PresenceOracle::~PresenceOracle() {
 
	stanzaChannel_->onPresenceReceived.disconnect(boost::bind(&PresenceOracle::handleIncomingPresence, this, _1));
 
	stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&PresenceOracle::handleStanzaChannelAvailableChanged, this, _1));
 
}
 

	
 
void PresenceOracle::handleStanzaChannelAvailableChanged(bool available) {
 
	if (available) {
 
		entries_.clear();
 
	}
 
}
 

	
 
void PresenceOracle::clearPresences(const Swift::JID& bareJID) {
 
	std::map<JID, boost::shared_ptr<Presence> > jidMap = entries_[bareJID];
 
	jidMap.clear();
 
	entries_[bareJID] = jidMap;
 
}
 

	
 
void PresenceOracle::handleIncomingPresence(Presence::ref presence) {
 
	// ignore presences for some contact, we're checking only presences for the transport itself here.
 
	bool isMUC = presence->getPayload<MUCPayload>() != NULL || *presence->getTo().getNode().c_str() == '#';
 
	// filter out login/logout presence spam
 
	if (!presence->getTo().getNode().empty() && isMUC == false)
 
		return;
 

	
 
	JID bareJID(presence->getFrom().toBare());
 
	if (presence->getType() == Presence::Subscribe || presence->getType() == Presence::Subscribed) {
 
	}
 
	else {
 
		Presence::ref passedPresence = presence;
 
		if (!isMUC) {
 
			if (presence->getType() == Presence::Unsubscribe || presence->getType() == Presence::Unsubscribed) {
 
				/* 3921bis says that we don't follow up with an unavailable, so simulate this ourselves */
 
				passedPresence = Presence::ref(new Presence());
 
				passedPresence->setType(Presence::Unavailable);
 
				passedPresence->setFrom(bareJID);
 
				passedPresence->setStatus(presence->getStatus());
 
			}
 
			std::map<JID, boost::shared_ptr<Presence> > jidMap = entries_[bareJID];
 
			if (passedPresence->getFrom().isBare() && presence->getType() == Presence::Unavailable) {
 
				/* Have a bare-JID only presence of offline */
 
				jidMap.clear();
 
			} else if (passedPresence->getType() == Presence::Available) {
 
				/* Don't have a bare-JID only offline presence once there are available presences */
 
				jidMap.erase(bareJID);
 
			}
 
			if (passedPresence->getType() == Presence::Unavailable && jidMap.size() > 1) {
 
				jidMap.erase(passedPresence->getFrom());
 
			} else {
 
				jidMap[passedPresence->getFrom()] = passedPresence;
 
			}
 
			entries_[bareJID] = jidMap;
 
		}
 
		onPresenceChange(passedPresence);
 
	}
 
}
 

	
 
Presence::ref PresenceOracle::getLastPresence(const JID& jid) const {
 
	PresencesMap::const_iterator i = entries_.find(jid.toBare());
 
	if (i == entries_.end()) {
 
		return Presence::ref();
 
	}
 
	PresenceMap presenceMap = i->second;
 
	PresenceMap::const_iterator j = presenceMap.find(jid);
 
	if (j != presenceMap.end()) {
 
		return j->second;
 
	}
 
	else {
 
		return Presence::ref();
 
	}
 
}
 

	
 
std::vector<Presence::ref> PresenceOracle::getAllPresence(const JID& bareJID) const {
 
	std::vector<Presence::ref> results;
 
	PresencesMap::const_iterator i = entries_.find(bareJID);
 
	if (i == entries_.end()) {
 
		return results;
 
	}
 
	PresenceMap presenceMap = i->second;
 
	PresenceMap::const_iterator j = presenceMap.begin();
 
	for (; j != presenceMap.end(); ++j) {
 
		Presence::ref current = j->second;
 
		results.push_back(current);
 
	}
 
	return results;
 
}
 

	
 
Presence::ref PresenceOracle::getHighestPriorityPresence(const JID& bareJID) const {
 
	PresencesMap::const_iterator i = entries_.find(bareJID);
 
	if (i == entries_.end()) {
 
		return Presence::ref();
 
	}
 
	PresenceMap presenceMap = i->second;
 
	PresenceMap::const_iterator j = presenceMap.begin();
 
	Presence::ref highest;
 
	for (; j != presenceMap.end(); ++j) {
 
		Presence::ref current = j->second;
 
		if (!highest
 
				|| current->getPriority() > highest->getPriority()
 
				|| (current->getPriority() == highest->getPriority()
 
						&& StatusShow::typeToAvailabilityOrdering(current->getShow()) > StatusShow::typeToAvailabilityOrdering(highest->getShow()))) {
 
			highest = current;
 
		}
 

	
 
	}
 
	return highest;
 
}
 

	
 
}
src/rostermanager.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/rostermanager.h"
 
#include "transport/rosterstorage.h"
 
#include "transport/storagebackend.h"
 
#include "transport/buddy.h"
 
#include "transport/usermanager.h"
 
#include "transport/buddy.h"
 
#include "transport/user.h"
 
#include "transport/logging.h"
 
#include "Swiften/Roster/SetRosterRequest.h"
 
#include "Swiften/Elements/RosterPayload.h"
 
#include "Swiften/Elements/RosterItemPayload.h"
 
#include "Swiften/Elements/RosterItemExchangePayload.h"
 
#include "Swiften/Elements/Nickname.h"
 
#include "Swiften/Queries/IQRouter.h"
 
#include <boost/foreach.hpp>
 
#include <boost/make_shared.hpp>
 

	
 
#include <map>
 
#include <iterator>
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "RosterManager");
 

	
 
RosterManager::RosterManager(User *user, Component *component){
 
	m_rosterStorage = NULL;
 
	m_user = user;
 
	m_component = component;
 
	m_setBuddyTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(1000);
 
	m_RIETimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(5000);
 
	m_RIETimer->onTick.connect(boost::bind(&RosterManager::sendRIE, this));
 

	
 
	m_supportRemoteRoster = false;
 

	
 
	if (!m_component->inServerMode()) {
 
		m_remoteRosterRequest = AddressedRosterRequest::ref(new AddressedRosterRequest(m_component->getIQRouter(), m_user->getJID().toBare()));
 
		m_remoteRosterRequest->onResponse.connect(boost::bind(&RosterManager::handleRemoteRosterResponse, this, _1, _2));
 
		m_remoteRosterRequest->send();
 
	}
 
}
 

	
 
RosterManager::~RosterManager() {
 
	m_setBuddyTimer->stop();
 
	m_RIETimer->stop();
 
	if (m_rosterStorage) {
 
		m_rosterStorage->storeBuddies();
 
	}
 

	
 
	sendUnavailablePresences(m_user->getJID().toBare());
 

	
 
	if (m_remoteRosterRequest) {
 
		m_remoteRosterRequest->onResponse.disconnect_all_slots();
 
		m_component->getIQRouter()->removeHandler(m_remoteRosterRequest);
 
	}
 

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

	
 
	if (m_requests.size() != 0) {
 
		LOG4CXX_INFO(logger, m_user->getJID().toString() <<  ": Removing " << m_requests.size() << " unresponded IQs");
 
		BOOST_FOREACH(Swift::SetRosterRequest::ref request, m_requests) {
 
			request->onResponse.disconnect_all_slots();
 
			m_component->getIQRouter()->removeHandler(request);
 
		}
 
		m_requests.clear();
 
	}
 

	
 
	boost::singleton_pool<boost::pool_allocator_tag, sizeof(unsigned int)>::release_memory();
 

	
 
	if (m_rosterStorage)
 
		delete m_rosterStorage;
 
}
 

	
 
void RosterManager::setBuddy(Buddy *buddy) {
 
// 	m_setBuddyTimer->onTick.connect(boost::bind(&RosterManager::setBuddyCallback, this, buddy));
 
// 	m_setBuddyTimer->start();
 
	setBuddyCallback(buddy);
 
}
 

	
 
void RosterManager::removeBuddy(const std::string &name) {
 
	Buddy *buddy = getBuddy(name);
 
	if (!buddy) {
 
		LOG4CXX_WARN(logger, m_user->getJID().toString() << ": Tried to remove unknown buddy " << name);
 
		return;
 
	}
 

	
 
	if (m_component->inServerMode() || m_remoteRosterRequest) {
 
		sendBuddyRosterRemove(buddy);
 
	}
 
	else {
 
		sendBuddyUnsubscribePresence(buddy);
 
	}
 

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

	
 
	unsetBuddy(buddy);
 
	delete buddy;
 
}
 

	
 
void RosterManager::sendBuddyRosterRemove(Buddy *buddy) {
 
	Swift::RosterPayload::ref p = Swift::RosterPayload::ref(new Swift::RosterPayload());
 
	Swift::RosterItemPayload item;
 
	item.setJID(buddy->getJID().toBare());
 
	item.setSubscription(Swift::RosterItemPayload::Remove);
 

	
 
	p->addItem(item);
 

	
 
	// In server mode we have to send pushes to all resources, but in gateway-mode we send it only to bare JID
 
	if (m_component->inServerMode()) {
 
		std::vector<Swift::Presence::ref> presences = m_component->getPresenceOracle()->getAllPresence(m_user->getJID().toBare());
 
		BOOST_FOREACH(Swift::Presence::ref presence, presences) {
 
			Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(p, presence->getFrom(), m_component->getIQRouter());
 
			request->send();
 
		}
 
	}
 
	else {
 
		Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(p, m_user->getJID().toBare(), m_component->getIQRouter());
 
		request->send();
 
	}
 
}
 

	
 
void RosterManager::sendBuddyRosterPush(Buddy *buddy) {
 
	// user can't receive anything in server mode if he's not logged in.
 
	// He will ask for roster later (handled in rosterreponsder.cpp)
 
	if (m_component->inServerMode() && (!m_user->isConnected() || m_user->shouldCacheMessages()))
 
		return;
 

	
 
	Swift::RosterPayload::ref payload = Swift::RosterPayload::ref(new Swift::RosterPayload());
 
	Swift::RosterItemPayload item;
 
	item.setJID(buddy->getJID().toBare());
 
	if (buddy->getAlias().empty()) {
 
		item.setName(buddy->getJID().toBare().toString());
 
	}
 
	else {
 
		item.setName(buddy->getAlias());
 
	}
 
	item.setGroups(buddy->getGroups());
 
	item.setSubscription(Swift::RosterItemPayload::Both);
 

	
 
	payload->addItem(item);
 

	
 
	// In server mode we have to send pushes to all resources, but in gateway-mode we send it only to bare JID
 
	if (m_component->inServerMode()) {
 
		std::vector<Swift::Presence::ref> presences = m_component->getPresenceOracle()->getAllPresence(m_user->getJID().toBare());
 
		BOOST_FOREACH(Swift::Presence::ref presence, presences) {
 
			Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(payload, presence->getFrom(), m_component->getIQRouter());
 
			request->onResponse.connect(boost::bind(&RosterManager::handleBuddyRosterPushResponse, this, _1, request, buddy->getName()));
 
			request->send();
 
			m_requests.push_back(request);
 
		}
 
	}
 
	else {
 
		Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(payload, m_user->getJID().toBare(), m_component->getIQRouter());
 
		request->onResponse.connect(boost::bind(&RosterManager::handleBuddyRosterPushResponse, this, _1, request, buddy->getName()));
 
		request->send();
 
		m_requests.push_back(request);
 
	}
 

	
 
	if (buddy->getSubscription() != Buddy::Both) {
 
		buddy->setSubscription(Buddy::Both);
 
		storeBuddy(buddy);
 
	}
 
}
 

	
 
void RosterManager::sendBuddyUnsubscribePresence(Buddy *buddy) {
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	response->setTo(m_user->getJID());
 
	response->setFrom(buddy->getJID());
 
	response->setType(Swift::Presence::Unsubscribe);
 
	m_component->getStanzaChannel()->sendPresence(response);
 

	
 
	response = Swift::Presence::create();
 
	response->setTo(m_user->getJID());
 
	response->setFrom(buddy->getJID());
 
	response->setType(Swift::Presence::Unsubscribed);
 
	m_component->getStanzaChannel()->sendPresence(response);
 
}
 

	
 
void RosterManager::sendBuddySubscribePresence(Buddy *buddy) {
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	response->setTo(m_user->getJID());
 
	response->setFrom(buddy->getJID());
 
	response->setType(Swift::Presence::Subscribe);
 
	if (!buddy->getAlias().empty()) {
 
		response->addPayload(boost::make_shared<Swift::Nickname>(buddy->getAlias()));
 
	}
 
	m_component->getStanzaChannel()->sendPresence(response);
 
}
 

	
 
void RosterManager::handleBuddyChanged(Buddy *buddy) {
 
}
 

	
 
void RosterManager::setBuddyCallback(Buddy *buddy) {
 
	LOG4CXX_INFO(logger, "Associating buddy " << buddy->getName() << " with " << m_user->getJID().toString());
 
	m_buddies[buddy->getName()] = buddy;
 
	onBuddySet(buddy);
 

	
 
	// In server mode the only way is to send jabber:iq:roster push.
 
	// In component mode we send RIE or Subscribe presences, based on features.
 
	if (m_component->inServerMode()) {
 
		sendBuddyRosterPush(buddy);
 
	}
src/rosterresponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/rosterresponder.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/buddy.h"
 
#include "transport/logging.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "RosterResponder");
 

	
 
RosterResponder::RosterResponder(Swift::IQRouter *router, UserManager *userManager) : Swift::Responder<RosterPayload>(router) {
 
	m_userManager = userManager;
 
}
 

	
 
RosterResponder::~RosterResponder() {
 
}
 

	
 
bool RosterResponder::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::RosterPayload> payload) {
 
	// Get means we're in server mode and user wants to fetch his roster.
 
	// For now we send empty reponse, but TODO: Get buddies from database and send proper stored roster.
 
	User *user = m_userManager->getUser(from.toBare().toString());
 
	if (!user) {
 
		sendResponse(from, id, boost::shared_ptr<RosterPayload>(new RosterPayload()));
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": User is not logged in");
 
		return true;
 
	}
 
	sendResponse(from, id, user->getRosterManager()->generateRosterPayload());
 
	user->getRosterManager()->sendCurrentPresences(from);
 
	return true;
 
}
 

	
 
bool RosterResponder::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::RosterPayload> payload) {
 
	sendResponse(from, id, boost::shared_ptr<RosterPayload>(new RosterPayload()));
 

	
 
	User *user = m_userManager->getUser(from.toBare().toString());
 
	if (!user) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": User is not logged in");
 
		return true;
 
	}
 

	
 
	if (payload->getItems().size() == 0) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": Roster push with no item");
 
		return true;
 
	}
 

	
 
	Swift::RosterItemPayload item = payload->getItems()[0];
 

	
 
	if (item.getJID().getNode().empty()) {
 
		return true;
 
	}
 

	
 
	Buddy *buddy = user->getRosterManager()->getBuddy(Buddy::JIDToLegacyName(item.getJID()));
 
	if (buddy) {
 
		if (item.getSubscription() == Swift::RosterItemPayload::Remove) {
 
			LOG4CXX_INFO(logger, from.toBare().toString() << ": Removing buddy " << buddy->getName());
 
			onBuddyRemoved(buddy);
 

	
 
			// send roster push here
 
			Swift::SetRosterRequest::ref request = Swift::SetRosterRequest::create(payload, user->getJID().toBare(), user->getComponent()->getIQRouter());
 
			request->send();
 
		}
 
		else {
 
			LOG4CXX_INFO(logger, from.toBare().toString() << ": Updating buddy " << buddy->getName());
 
			onBuddyUpdated(buddy, item);
 
		}
 
	}
 
	else if (item.getSubscription() != Swift::RosterItemPayload::Remove) {
 
		// Roster push for this new buddy is sent by RosterManager
 
		BuddyInfo buddyInfo;
 
		buddyInfo.id = -1;
 
		buddyInfo.alias = item.getName();
 
		buddyInfo.legacyName = Buddy::JIDToLegacyName(item.getJID());
 
		buddyInfo.subscription = "both";
 
		buddyInfo.flags = Buddy::buddyFlagsFromJID(item.getJID());
 
		LOG4CXX_INFO(logger, from.toBare().toString() << ": Adding buddy " << buddyInfo.legacyName);
 

	
 
		buddy = user->getComponent()->getFactory()->createBuddy(user->getRosterManager(), buddyInfo);
 
		user->getRosterManager()->setBuddy(buddy);
 
		onBuddyAdded(buddy, item);
 
	}
 

	
 
	return true;
 
}
 

	
 
}
src/rosterstorage.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/rosterstorage.h"
 
#include "transport/buddy.h"
 
#include "transport/user.h"
 
#include "transport/storagebackend.h"
 
#include "transport/logging.h"
 

	
 
#include "Swiften/Network/NetworkFactories.h"
 

	
 
DEFINE_LOGGER(logger, "RosterStorage");
 

	
 
namespace Transport {
 

	
 
// static void save_settings(gpointer k, gpointer v, gpointer data) {
 
// 	PurpleValue *value = (PurpleValue *) v;
 
// 	std::string key((char *) k);
 
// 	SaveData *s = (SaveData *) data;
 
// 	AbstractUser *user = s->user;
 
// 	long id = s->id;
 
// 	if (purple_value_get_type(value) == PURPLE_TYPE_BOOLEAN) {
 
// 		if (purple_value_get_boolean(value))
 
// 			Transport::instance()->sql()->addBuddySetting(user->storageId(), id, key, "1", purple_value_get_type(value));
 
// 		else
 
// 			Transport::instance()->sql()->addBuddySetting(user->storageId(), id, key, "0", purple_value_get_type(value));
 
// 	}
 
// 	else if (purple_value_get_type(value) == PURPLE_TYPE_STRING) {
 
// 		const char *str = purple_value_get_string(value);
 
// 		Transport::instance()->sql()->addBuddySetting(user->storageId(), id, key, str ? str : "", purple_value_get_type(value));
 
// 	}
 
// }
 
// 
 
// static gboolean storeAbstractSpectrumBuddy(gpointer key, gpointer v, gpointer data) {
 
// 	AbstractUser *user = (AbstractUser *) data;
 
// 	AbstractSpectrumBuddy *s_buddy = (AbstractSpectrumBuddy *) v;
 
// 	if (s_buddy->getFlags() & SPECTRUM_BUDDY_IGNORE)
 
// 		return TRUE;
 
// 	
 
// 	// save PurpleBuddy
 
// 	std::string alias = s_buddy->getAlias();
 
// 	std::string name = s_buddy->getName();
 
// 	long id = s_buddy->getId();
 
// 
 
// 	// Buddy is not in DB
 
// 	if (id != -1) {
 
// 		Transport::instance()->sql()->addBuddy(user->storageId(), name, s_buddy->getSubscription(), s_buddy->getGroup(), alias, s_buddy->getFlags());
 
// 	}
 
// 	else {
 
// 		id = Transport::instance()->sql()->addBuddy(user->storageId(), name, s_buddy->getSubscription(), s_buddy->getGroup(), alias, s_buddy->getFlags());
 
// 		s_buddy->setId(id);
 
// 	}
 
// 	Log("buddyListSaveNode", id << " " << name << " " << alias << " " << s_buddy->getSubscription());
 
// 	if (s_buddy->getBuddy() && id != -1) {
 
// 		PurpleBuddy *buddy = s_buddy->getBuddy();
 
// 		SaveData *s = new SaveData;
 
// 		s->user = user;
 
// 		s->id = id;
 
// 		g_hash_table_foreach(buddy->node.settings, save_settings, s);
 
// 		delete s;
 
// 	}
 
// 	return TRUE;
 
// }
 

	
 
RosterStorage::RosterStorage(User *user, StorageBackend *storageBackend) {
 
	m_user = user;
 
	m_storageBackend = storageBackend;
 
	m_storageTimer = m_user->getComponent()->getNetworkFactories()->getTimerFactory()->createTimer(5000);
 
	m_storageTimer->onTick.connect(boost::bind(&RosterStorage::storeBuddies, this));
 
}
 

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

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

	
 
void RosterStorage::storeBuddy(Buddy *buddy) {
 
	if (!buddy) {
 
		return;
 
	}
 
	if (buddy->getName().empty()) {
 
		return;
 
	}
 

	
 
	m_buddies[buddy->getName()] = buddy;
 
	m_storageTimer->start();
 
}
 

	
 
bool RosterStorage::storeBuddies() {
 
	if (m_buddies.size() == 0) {
 
		return false;
 
	}
 
	
 
	m_storageBackend->beginTransaction();
 

	
 
	for (std::map<std::string, Buddy *>::const_iterator it = m_buddies.begin(); it != m_buddies.end(); it++) {
 
		Buddy *buddy = (*it).second;
 
		BuddyInfo buddyInfo;
 
		buddyInfo.alias = buddy->getAlias();
 
		buddyInfo.legacyName = buddy->getName();
 
		buddyInfo.groups = buddy->getGroups();
 
		buddyInfo.subscription = buddy->getSubscription() == Buddy::Ask ? "ask" : "both";
 
		buddyInfo.id = buddy->getID();
 
		buddyInfo.flags = buddy->getFlags();
 
		buddyInfo.settings["icon_hash"].s = buddy->getIconHash();
 
		buddyInfo.settings["icon_hash"].type = TYPE_STRING;
 

	
 
		// Buddy is in DB
 
		if (buddyInfo.id != -1) {
 
			m_storageBackend->updateBuddy(m_user->getUserInfo().id, buddyInfo);
 
		}
 
		else {
 
			buddyInfo.id = m_storageBackend->addBuddy(m_user->getUserInfo().id, buddyInfo);
 
			buddy->setID(buddyInfo.id);
 
		}
 

	
 
// 		Log("buddyListSaveNode", id << " " << name << " " << alias << " " << s_buddy->getSubscription());
 
// 		if (s_buddy->getBuddy() && id != -1) {
 
// 			PurpleBuddy *buddy = s_buddy->getBuddy();
 
// 			SaveData *s = new SaveData;
 
// 			s->user = user;
 
// 			s->id = id;
 
// 			g_hash_table_foreach(buddy->node.settings, save_settings, s);
 
// 			delete s;
 
// 		}
 
	}
 

	
 
	m_buddies.clear();
 
	m_storageBackend->commitTransaction();
 
	return true;
 
}
 

	
 
void RosterStorage::removeBuddyFromQueue(Buddy *buddy) {
 
	m_buddies.erase(buddy->getName());
 
}
 

	
 
}
src/statsresponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/statsresponder.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include "Swiften/Queries/IQRouter.h"
 
#include "transport/BlockPayload.h"
 
#include "Swiften/Swiften.h"
 
#include "transport/usermanager.h"
 
#include "transport/user.h"
 
#include "transport/buddy.h"
 
#include "transport/rostermanager.h"
 
#include "transport/memoryusage.h"
 
#include "transport/conversationmanager.h"
 
#include "transport/rostermanager.h"
 
#include "transport/usermanager.h"
 
#include "transport/networkpluginserver.h"
 
#include "transport/logging.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "StatsResponder");
 

	
 
StatsResponder::StatsResponder(Component *component, UserManager *userManager, NetworkPluginServer *server, StorageBackend *storageBackend) : Swift::Responder<StatsPayload>(component->getIQRouter()) {
 
	m_component = component;
 
	m_userManager = userManager;
 
	m_server = server;
 
	m_storageBackend = storageBackend;
 
	m_start = time(0);
 
}
 

	
 
StatsResponder::~StatsResponder() {
 
	
 
}
 

	
 
unsigned long StatsResponder::usedMemory() {
 
	double shared = 0;
 
	double rss = 0;
 
#ifndef WIN32
 
	process_mem_usage(shared, rss);
 
#endif
 
	rss -= shared;
 

	
 
	const std::list <NetworkPluginServer::Backend *> &backends = m_server->getBackends();
 
	BOOST_FOREACH(NetworkPluginServer::Backend * backend, backends) {
 
		rss += backend->res - backend->shared;
 
	}
 

	
 
	return (unsigned long) rss;
 
}
 

	
 
bool StatsResponder::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<StatsPayload> stats) {
 
	boost::shared_ptr<StatsPayload> response(new StatsPayload());
 

	
 
	if (stats->getItems().empty()) {
 
		response->addItem(StatsPayload::Item("uptime"));
 
		response->addItem(StatsPayload::Item("users/online"));
 
		response->addItem(StatsPayload::Item("contacts/online"));
 
		response->addItem(StatsPayload::Item("contacts/total"));
 
		response->addItem(StatsPayload::Item("messages/from-xmpp"));
 
		response->addItem(StatsPayload::Item("messages/to-xmpp"));
 
		response->addItem(StatsPayload::Item("backends/running"));
 
		response->addItem(StatsPayload::Item("backends/crashed"));
 
		response->addItem(StatsPayload::Item("memory-usage"));
 
	}
 
	else {
 
		unsigned long contactsOnline = 0;
 
		unsigned long contactsTotal = 0;
 

	
 
		Swift::StatusShow s;
 
		std::string statusMessage;
 
		for (std::map<std::string, User *>::const_iterator it = m_userManager->getUsers().begin(); it != m_userManager->getUsers().end(); it++) {
 
			if (!(*it).second) {
 
				continue;
 
			}
 
			const RosterManager::BuddiesMap &buddies = (*it).second->getRosterManager()->getBuddies();
 
			contactsTotal += buddies.size();
 
			for(RosterManager::BuddiesMap::const_iterator bt = buddies.begin(); bt != buddies.end(); bt++) {
 
				if (!(*bt).second) {
 
					continue;
 
				}
 
				if (!(*bt).second->getStatus(s, statusMessage))
 
					continue;
 
				if (s.getType() != Swift::StatusShow::None) {
 
					contactsOnline++;
 
				}
 
			}
 
		}
 

	
 
		BOOST_FOREACH(const StatsPayload::Item &item, stats->getItems()) {
 
			if (item.getName() == "uptime") {
 
				response->addItem(StatsPayload::Item("uptime", "seconds", boost::lexical_cast<std::string>(time(0) - m_start)));
 
			}
 
			else if (item.getName() == "users/online") {
 
				response->addItem(StatsPayload::Item("users/online", "users", boost::lexical_cast<std::string>(m_userManager->getUserCount())));
 
			}
 
			else if (item.getName() == "backends/running") {
 
				response->addItem(StatsPayload::Item("backends/running", "backends", boost::lexical_cast<std::string>(m_server->getBackendCount())));
 
			}
 
			else if (item.getName() == "backends/crashed") {
 
				response->addItem(StatsPayload::Item("backends/crashed", "backends", boost::lexical_cast<std::string>(m_server->getCrashedBackends().size())));
 
			}
 
			else if (item.getName() == "memory-usage") {
 
				response->addItem(StatsPayload::Item("memory-usage", "KB", boost::lexical_cast<std::string>(usedMemory())));
 
			}
 
			else if (item.getName() == "contacts/online") {
 
				response->addItem(StatsPayload::Item("contacts/online", "contacts", boost::lexical_cast<std::string>(contactsOnline)));
 
			}
 
			else if (item.getName() == "contacts/total") {
 
				response->addItem(StatsPayload::Item("contacts/total", "contacts", boost::lexical_cast<std::string>(contactsTotal)));
 
			}
 
			else if (item.getName() == "messages/from-xmpp") {
 
				response->addItem(StatsPayload::Item("messages/from-xmpp", "messages", boost::lexical_cast<std::string>(m_userManager->getMessagesToBackend())));
 
			}
 
			else if (item.getName() == "messages/to-xmpp") {
 
				response->addItem(StatsPayload::Item("messages/to-xmpp", "messages", boost::lexical_cast<std::string>(m_userManager->getMessagesToXMPP())));
 
			}
 
		}
 
	}
 

	
 
	sendResponse(from, id, response);
 

	
 
	return true;
 
}
 

	
 
bool StatsResponder::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<StatsPayload> stats) {
 
	return false;
 
}
 

	
 
}
src/storagebackend.cpp
Show inline comments
 
#include "transport/storagebackend.h"
 
#include "transport/config.h"
 

	
 
#include "transport/sqlite3backend.h"
 
#include "transport/mysqlbackend.h"
 
#include "transport/pqxxbackend.h"
 
#include "Swiften/StringCodecs/Base64.h"
 

	
 
#include "Swiften/Swiften.h"
 

	
 
namespace Transport {
 

	
 
StorageBackend *StorageBackend::createBackend(Config *config, std::string &error) {
 
	StorageBackend *storageBackend = NULL;
 
#ifdef WITH_SQLITE
 
	if (CONFIG_STRING(config, "database.type") == "sqlite3") {
 
		storageBackend = new SQLite3Backend(config);
 
	}
 
#else
 
	if (CONFIG_STRING(config, "database.type") == "sqlite3") {
 
		error = "Libtransport is not compiled with sqlite3 backend support.";
 
	}
 
#endif
 

	
 
#ifdef WITH_MYSQL
 
	if (CONFIG_STRING(config, "database.type") == "mysql") {
 
		storageBackend = new MySQLBackend(config);
 
	}
 
#else
 
	if (CONFIG_STRING(config, "database.type") == "mysql") {
 
		error = "Spectrum2 is not compiled with mysql backend support.";
 
	}
 
#endif
 

	
 
#ifdef WITH_PQXX
 
	if (CONFIG_STRING(config, "database.type") == "pqxx") {
 
		storageBackend = new PQXXBackend(config);
 
	}
 
#else
 
	if (CONFIG_STRING(config, "database.type") == "pqxx") {
 
		error = "Spectrum2 is not compiled with pqxx backend support.";
 
	}
 
#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") {
 
		error = "Unknown storage backend " + CONFIG_STRING(config, "database.type");
 
	}
 

	
 
	return storageBackend;
 
}
 

	
 
std::string StorageBackend::encryptPassword(const std::string &password, const std::string &key) {
 
	std::string encrypted;
 
	encrypted.resize(password.size());
 
	for (int i = 0; i < password.size(); i++) {
 
		char c = password[i];
 
		char keychar = key[i % key.size()];
 
		c += keychar;
 
		encrypted[i] = c;
 
	}
 

	
 
	encrypted = Swift::Base64::encode(Swift::createByteArray(encrypted));
 
	return encrypted;
 
}
 

	
 
std::string StorageBackend::decryptPassword(std::string &encrypted, const std::string &key) {
 
	encrypted = Swift::byteArrayToString(Swift::Base64::decode(encrypted));
 
	std::string password;
 
	password.resize(encrypted.size());
 
	for (int i = 0; i < encrypted.size(); i++) {
 
		char c = encrypted[i];
 
		char keychar = key[i % key.size()];
 
		c -= keychar;
 
		password[i] = c;
 
	}
 

	
 
	return password;
 
}
 

	
 
std::string StorageBackend::serializeGroups(const std::vector<std::string> &groups) {
 
	std::string ret;
 
	BOOST_FOREACH(const std::string &group, groups) {
 
		ret += group + "\n";
 
	}
 
	if (!ret.empty()) {
 
		ret.erase(ret.end() - 1);
 
	}
 
	return ret;
 
}
 

	
 
std::vector<std::string> StorageBackend::deserializeGroups(std::string &groups) {
 
	std::vector<std::string> ret;
 
	if (groups.empty()) {
 
		return ret;
 
	}
 

	
 
	boost::split(ret, groups, boost::is_any_of("\n"));
 
	if (ret.back().empty()) {
 
		ret.erase(ret.end() - 1);
 
	}
 
	return ret;
 
}
 

	
 
}
src/storageresponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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 "storageresponder.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include "Swiften/Queries/IQRouter.h"
 
#include "Swiften/Elements/RawXMLPayload.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Elements/Storage.h"
 
#include "Swiften/Elements/Storage.h"
 
#include "Swiften/Serializer/PayloadSerializers/StorageSerializer.h"
 
#include "transport/usermanager.h"
 
#include "transport/user.h"
 
#include "transport/logging.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "StorageResponder");
 

	
 
StorageResponder::StorageResponder(Swift::IQRouter *router, StorageBackend *storageBackend, UserManager *userManager) : Swift::Responder<PrivateStorage>(router) {
 
	m_storageBackend = storageBackend;
 
	m_userManager = userManager;
 
}
 

	
 
StorageResponder::~StorageResponder() {
 
}
 

	
 
bool StorageResponder::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::PrivateStorage> payload) {
 
	User *user = m_userManager->getUser(from.toBare().toString());
 
	if (!user) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": User is not logged in");
 
		sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel);
 
		return true;
 
	}
 

	
 
	int type = 0;
 
	std::string value = "";
 
	m_storageBackend->getUserSetting(user->getUserInfo().id, "storage", type, value);
 
	LOG4CXX_INFO(logger, from.toBare().toString() << ": Sending jabber:iq:storage");
 

	
 
	sendResponse(from, id, boost::shared_ptr<PrivateStorage>(new PrivateStorage(boost::shared_ptr<RawXMLPayload>(new RawXMLPayload(value)))));
 
	return true;
 
}
 

	
 
bool StorageResponder::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::PrivateStorage> payload) {
 
	User *user = m_userManager->getUser(from.toBare().toString());
 
	if (!user) {
 
		sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel);
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": User is not logged in");
 
		return true;
 
	}
 

	
 
	boost::shared_ptr<Storage> storage = boost::dynamic_pointer_cast<Storage>(payload->getPayload());
 

	
 
	if (storage) {
 
		StorageSerializer serializer;
 
		std::string value = serializer.serializePayload(boost::dynamic_pointer_cast<Storage>(payload->getPayload()));
 
		m_storageBackend->updateUserSetting(user->getUserInfo().id, "storage", value);
 
		LOG4CXX_INFO(logger, from.toBare().toString() << ": Storing jabber:iq:storage");
 
		sendResponse(from, id, boost::shared_ptr<PrivateStorage>());
 
	}
 
	else {
 
		LOG4CXX_INFO(logger, from.toBare().toString() << ": Unknown element. Libtransport does not support serialization of this.");
 
		sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel);
 
	}
 
	return true;
 
}
 

	
 
}
src/storageresponder.h
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
 
 */
 

	
 
#pragma once
 

	
 
#include <vector>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Queries/Responder.h"
 
#include "Swiften/Elements/RosterPayload.h"
 
#include "Swiften/Elements/PrivateStorage.h"
 

	
 
namespace Transport {
 

	
 
class StorageBackend;
 
class UserManager;
 

	
 
class StorageResponder : public Swift::Responder<Swift::PrivateStorage> {
 
	public:
 
		StorageResponder(Swift::IQRouter *router, StorageBackend *storageBackend, UserManager *userManager);
 
		~StorageResponder();
 

	
 
	private:
 
		virtual bool handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::PrivateStorage> payload);
 
		virtual bool handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::PrivateStorage> payload);
 
		StorageBackend *m_storageBackend;
 
		UserManager *m_userManager;
 
};
 

	
 
}
src/tests/userregistry.cpp
Show inline comments
 
#include "transport/userregistry.h"
 
#include "transport/config.h"
 
#include <cppunit/TestFixture.h>
 
#include <cppunit/extensions/HelperMacros.h>
 
#include <Swiften/EventLoop/DummyEventLoop.h>
 
#include <Swiften/Server/Server.h>
 
#include <Swiften/Network/DummyNetworkFactories.h>
 
#include <Swiften/Network/DummyConnectionServer.h>
 
#include <Swiften/Network/ConnectionFactory.h>
 
#include <Swiften/Network/DummyTimerFactory.h>
 

	
 
using namespace Transport;
 

	
 
class UserRegistryTest : public CPPUNIT_NS :: TestFixture {
 
	CPPUNIT_TEST_SUITE(UserRegistryTest);
 
	CPPUNIT_TEST(login);
 
	CPPUNIT_TEST(loginInvalidPassword);
 
	CPPUNIT_TEST(loginTwoClientsValidPasswords);
 
	CPPUNIT_TEST(loginTwoClientsDifferentPasswords);
 
	CPPUNIT_TEST(loginDisconnect);
 
	CPPUNIT_TEST(removeLater);
 
	CPPUNIT_TEST_SUITE_END();
 

	
 
	public:
 
		void setUp (void) {
 
			state1 = Init;
 
			state2 = Init;
 
			std::istringstream ifs;
 
			cfg = new Config();
 
			cfg->load(ifs);
 

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

	
 
			userRegistry = new UserRegistry(cfg, factories);
 
			userRegistry->onConnectUser.connect(bind(&UserRegistryTest::handleConnectUser, this, _1));
 
			userRegistry->onDisconnectUser.connect(bind(&UserRegistryTest::handleDisconnectUser, this, _1));
 

	
 
			server = new Swift::Server(loop, factories, userRegistry, "localhost", 5222);
 
			server->start();
 
			connectionServer = server->getConnectionServer();
 

	
 
			client1 = factories->getConnectionFactory()->createConnection();
 
			dynamic_cast<Swift::DummyConnectionServer *>(connectionServer.get())->acceptConnection(client1);
 

	
 
			dynamic_cast<Swift::DummyConnection *>(client1.get())->onDataSent.connect(boost::bind(&UserRegistryTest::handleDataReceived, this, _1, client1));
 

	
 
			client2 = factories->getConnectionFactory()->createConnection();
 
			dynamic_cast<Swift::DummyConnectionServer *>(connectionServer.get())->acceptConnection(client2);
 

	
 
			dynamic_cast<Swift::DummyConnection *>(client2.get())->onDataSent.connect(boost::bind(&UserRegistryTest::handleDataReceived, this, _1, client2));
 

	
 
			loop->processEvents();
 
		}
 

	
 
		void tearDown (void) {
 
			delete server;
 
			dynamic_cast<Swift::DummyConnection *>(client1.get())->onDataSent.disconnect(boost::bind(&UserRegistryTest::handleDataReceived, this, _1, client1));
 
			client1.reset();
 
			dynamic_cast<Swift::DummyConnection *>(client2.get())->onDataSent.disconnect(boost::bind(&UserRegistryTest::handleDataReceived, this, _1, client2));
 
			client2.reset();
 
			connectionServer.reset();
 
			delete userRegistry;
 
			delete factories;
 
			delete loop;
 
			delete cfg;
 
			received1.clear();
 
			received2.clear();
 
		}
 

	
 
		void send(boost::shared_ptr<Swift::Connection> conn, const std::string &data) {
 
			dynamic_cast<Swift::DummyConnection *>(conn.get())->receive(Swift::createSafeByteArray(data));
 
			loop->processEvents();
 
		}
 

	
 
		void sendCredentials(boost::shared_ptr<Swift::Connection> conn, const std::string &username, const std::string &password, const std::string &b64) {
 
			std::vector<std::string> &received = conn == client1 ? received1 : received2;
 
			send(conn, "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='localhost' version='1.0'>");
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 
			CPPUNIT_ASSERT(received[0].find("<?xml version=\"1.0\"?>") == 0);
 
			CPPUNIT_ASSERT(received[1].find("PLAIN") != std::string::npos);
 
			received.clear();
 

	
 
			// username:test
 
			send(conn, "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" + b64 + "</auth>");
 
			if (conn == client1)
 
				CPPUNIT_ASSERT_EQUAL(Connecting, state1);
 
// 			else
 
// 				CPPUNIT_ASSERT_EQUAL(Connecting, state2);
 
			CPPUNIT_ASSERT_EQUAL(password, userRegistry->getUserPassword(username));
 
			CPPUNIT_ASSERT_EQUAL(std::string(""), userRegistry->getUserPassword("unknown@localhost"));
 
		}
 

	
 
		void bindSession(boost::shared_ptr<Swift::Connection> conn) {
 
			std::vector<std::string> &received = conn == client1 ? received1 : received2;
 

	
 
			send(conn, "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='localhost' version='1.0'>");
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received.size());
 
			CPPUNIT_ASSERT(received[0].find("<?xml version=\"1.0\"?>") == 0);
 
			CPPUNIT_ASSERT(received[1].find("urn:ietf:params:xml:ns:xmpp-bind") != std::string::npos);
 
			CPPUNIT_ASSERT(received[1].find("urn:ietf:params:xml:ns:xmpp-session") != std::string::npos);
 
			
 
		}
 

	
 
		void handleDataReceived(const Swift::SafeByteArray &data, boost::shared_ptr<Swift::Connection> conn) {
 
			if (conn == client1) {
 
				received1.push_back(safeByteArrayToString(data));
 
// 				std::cout << received1.back() << "\n";
 
			}
 
			else {
 
				received2.push_back(safeByteArrayToString(data));
 
// 				std::cout << received2.back() << "\n";
 
			}
 
		}
 

	
 
		void handleConnectUser(const Swift::JID &user) {
 
			state1 = Connecting;
 
		}
 

	
 
		void handleDisconnectUser(const Swift::JID &user) {
 
			state1 = Disconnected;
 
		}
 

	
 
		void login() {
 
			sendCredentials(client1, "username@localhost", "test", "AHVzZXJuYW1lAHRlc3Q=");
 

	
 
			userRegistry->onPasswordValid("username@localhost");
 
			loop->processEvents();
 
			CPPUNIT_ASSERT_EQUAL(std::string(""), userRegistry->getUserPassword("username@localhost"));
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received1.size());
 
			CPPUNIT_ASSERT_EQUAL(std::string("<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"></success>"), received1[0]);
 
			received1.clear();
 

	
 
			bindSession(client1);
 
			
 
		}
 

	
 
		void loginInvalidPassword() {
 
			sendCredentials(client1, "username@localhost", "test", "AHVzZXJuYW1lAHRlc3Q=");
 

	
 
			userRegistry->onPasswordInvalid("username@localhost");
 
			loop->processEvents();
 
			CPPUNIT_ASSERT_EQUAL(std::string(""), userRegistry->getUserPassword("username@localhost"));
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received1.size());
 
			CPPUNIT_ASSERT_EQUAL(std::string("<failure xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"/>"), received1[0]);
 
			CPPUNIT_ASSERT_EQUAL(std::string("</stream:stream>"), received1[1]);
 
		}
 

	
 
		void loginTwoClientsValidPasswords() {
 
			sendCredentials(client1, "username@localhost", "test", "AHVzZXJuYW1lAHRlc3Q=");
 
			sendCredentials(client2, "username@localhost", "test", "AHVzZXJuYW1lAHRlc3Q=");
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received1.size());
 
			CPPUNIT_ASSERT_EQUAL(0, (int) received2.size());
 
			CPPUNIT_ASSERT_EQUAL(std::string("<failure xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"/>"), received1[0]);
 
			CPPUNIT_ASSERT_EQUAL(std::string("</stream:stream>"), received1[1]);
 

	
 
			userRegistry->onPasswordValid("username@localhost");
 
			loop->processEvents();
 
			CPPUNIT_ASSERT_EQUAL(std::string(""), userRegistry->getUserPassword("username@localhost"));
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received2.size());
 
			CPPUNIT_ASSERT_EQUAL(std::string("<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"></success>"), received2[0]);
 
		}
 

	
 
		void loginTwoClientsDifferentPasswords() {
 
			// first is valid, second invalid.
 
			sendCredentials(client1, "username@localhost", "test", "AHVzZXJuYW1lAHRlc3Q=");
 
			sendCredentials(client2, "username@localhost", "test2", "AHVzZXJuYW1lAHRlc3Qy");
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received1.size());
 
			CPPUNIT_ASSERT_EQUAL(0, (int) received2.size());
 
			CPPUNIT_ASSERT_EQUAL(std::string("<failure xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"/>"), received1[0]);
 
			CPPUNIT_ASSERT_EQUAL(std::string("</stream:stream>"), received1[1]);
 
			userRegistry->onPasswordValid("username@localhost");
 
			loop->processEvents();
 
			CPPUNIT_ASSERT_EQUAL(std::string(""), userRegistry->getUserPassword("username@localhost"));
 
			CPPUNIT_ASSERT_EQUAL(1, (int) received2.size());
 
			CPPUNIT_ASSERT_EQUAL(std::string("<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"></success>"), received2[0]);
 
		}
 

	
 
		void loginDisconnect() {
 
			sendCredentials(client1, "username@localhost", "test", "AHVzZXJuYW1lAHRlc3Q=");
 

	
 
			client1->onDisconnected(boost::optional<Swift::Connection::Error>());
 
			loop->processEvents();
 
			CPPUNIT_ASSERT_EQUAL(Disconnected, state1);
 
		}
 

	
 
		void removeLater() {
 
			sendCredentials(client1, "username@localhost", "test", "AHVzZXJuYW1lAHRlc3Q=");
 

	
 
			userRegistry->removeLater("username@localhost");
 
			loop->processEvents();
 
			CPPUNIT_ASSERT_EQUAL(0, (int) received1.size());
 

	
 
			dynamic_cast<Swift::DummyTimerFactory *>(factories->getTimerFactory())->setTime(10);
 
			loop->processEvents();
 

	
 
			CPPUNIT_ASSERT_EQUAL(2, (int) received1.size());
 
			CPPUNIT_ASSERT_EQUAL(std::string("<failure xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"/>"), received1[0]);
 
			CPPUNIT_ASSERT_EQUAL(std::string("</stream:stream>"), received1[1]);
 
		}
 
		
 
		
src/transport.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/transport.h"
 
#include <boost/bind.hpp>
 
#include <boost/smart_ptr/make_shared.hpp>
 
#include <boost/algorithm/string/predicate.hpp>
 
#include "transport/storagebackend.h"
 
#include "transport/factory.h"
 
#include "transport/userregistry.h"
 
#include "transport/logging.h"
 
#include "storageparser.h"
 
#ifdef _WIN32
 
#include <Swiften/TLS/CAPICertificate.h>
 
#include "Swiften/TLS/Schannel/SchannelServerContext.h"
 
#include "Swiften/TLS/Schannel/SchannelServerContextFactory.h"
 
#else
 
#include "Swiften/TLS/PKCS12Certificate.h"
 
#include "Swiften/TLS/CertificateWithKey.h"
 
#include "Swiften/TLS/OpenSSL/OpenSSLServerContext.h"
 
#include "Swiften/TLS/OpenSSL/OpenSSLServerContextFactory.h"
 
#endif
 
#include "Swiften/Parser/PayloadParsers/AttentionParser.h"
 
#include "Swiften/Serializer/PayloadSerializers/AttentionSerializer.h"
 
#include "Swiften/Parser/PayloadParsers/XHTMLIMParser.h"
 
#include "Swiften/Serializer/PayloadSerializers/XHTMLIMSerializer.h"
 
#include "Swiften/Parser/PayloadParsers/StatsParser.h"
 
#include "Swiften/Serializer/PayloadSerializers/StatsSerializer.h"
 
#include "Swiften/Parser/PayloadParsers/GatewayPayloadParser.h"
 
#include "Swiften/Serializer/PayloadSerializers/GatewayPayloadSerializer.h"
 
#include "Swiften/Serializer/PayloadSerializers/SpectrumErrorSerializer.h"
 
#include "Swiften/Parser/PayloadParsers/MUCPayloadParser.h"
 
#include "transport/BlockParser.h"
 
#include "transport/BlockSerializer.h"
 
#include "Swiften/Parser/PayloadParsers/InvisibleParser.h"
 
#include "Swiften/Serializer/PayloadSerializers/InvisibleSerializer.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Parser/GenericPayloadParserFactory.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 
	
 
DEFINE_LOGGER(logger, "Component");
 
DEFINE_LOGGER(logger_xml, "Component.XML");
 

	
 
Component::Component(Swift::EventLoop *loop, Swift::NetworkFactories *factories, Config *config, Factory *factory, Transport::UserRegistry *userRegistry) {
 
	m_component = NULL;
 
	m_userRegistry = NULL;
 
	m_server = NULL;
 
	m_reconnectCount = 0;
 
	m_config = config;
 
	m_factory = factory;
 
	m_loop = loop;
 
	m_userRegistry = userRegistry;
 

	
 
	m_jid = Swift::JID(CONFIG_STRING(m_config, "service.jid"));
 

	
 
	m_factories = factories;
 

	
 
	m_reconnectTimer = m_factories->getTimerFactory()->createTimer(3000);
 
	m_reconnectTimer->onTick.connect(bind(&Component::start, this)); 
 

	
 
	if (CONFIG_BOOL(m_config, "service.server_mode")) {
 
		LOG4CXX_INFO(logger, "Creating component in server mode on port " << CONFIG_INT(m_config, "service.port"));
 
		m_server = new Swift::Server(loop, m_factories, m_userRegistry, m_jid, CONFIG_INT(m_config, "service.port"));
 
		if (!CONFIG_STRING(m_config, "service.cert").empty()) {
 
#ifndef _WIN32
 
//TODO: fix
 
			LOG4CXX_INFO(logger, "Using PKCS#12 certificate " << CONFIG_STRING(m_config, "service.cert"));
 
			LOG4CXX_INFO(logger, "SSLv23_server_method used.");
 
			TLSServerContextFactory *f = new OpenSSLServerContextFactory();
 
			CertificateWithKey::ref certificate = boost::make_shared<PKCS12Certificate>(CONFIG_STRING(m_config, "service.cert"), createSafeByteArray(CONFIG_STRING(m_config, "service.cert_password")));
 
			m_server->addTLSEncryption(f, certificate);
 
#endif
 
			
 
		}
 
		else {
 
			LOG4CXX_WARN(logger, "No PKCS#12 certificate used. TLS is disabled.");
 
		}
 
// 		m_server->start();
 
		m_stanzaChannel = m_server->getStanzaChannel();
 
		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->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::StatsParser>("query", "http://jabber.org/protocol/stats"));
 
		m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::GatewayPayloadParser>("query", "jabber:iq:gateway"));
 
		m_server->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::MUCPayloadParser>("x", "http://jabber.org/protocol/muc"));
 

	
 
		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->addPayloadSerializer(new Swift::StatsSerializer());
 
		m_server->addPayloadSerializer(new Swift::SpectrumErrorSerializer());
 
		m_server->addPayloadSerializer(new Swift::GatewayPayloadSerializer());
 

	
 
		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("Spectrum", SPECTRUM_VERSION);
 
		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->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::StatsParser>("query", "http://jabber.org/protocol/stats"));
 
		m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::GatewayPayloadParser>("query", "jabber:iq:gateway"));
 
		m_component->addPayloadParserFactory(new GenericPayloadParserFactory<Swift::MUCPayloadParser>("x", "http://jabber.org/protocol/muc"));
 

	
 
		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_component->addPayloadSerializer(new Swift::StatsSerializer());
 
		m_component->addPayloadSerializer(new Swift::SpectrumErrorSerializer());
 
		m_component->addPayloadSerializer(new Swift::GatewayPayloadSerializer());
 

	
 
		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 Transport::PresenceOracle(m_stanzaChannel);
 
	m_presenceOracle->onPresenceChange.connect(bind(&Component::handlePresence, this, _1));
 

	
 

	
 

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

	
 
Component::~Component() {
 
	delete m_presenceOracle;
 
	delete m_entityCapsManager;
 
	delete m_capsManager;
 
	delete m_capsMemoryStorage;
 
	if (m_component)
 
		delete m_component;
 
	if (m_server) {
 
		m_server->stop();
 
		delete m_server;
 
	}
 
}
 

	
 
Swift::StanzaChannel *Component::getStanzaChannel() {
 
	return m_stanzaChannel;
 
}
 

	
 
Transport::PresenceOracle *Component::getPresenceOracle() {
 
	return m_presenceOracle;
 
}
 

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

	
 
		//Type casting to BoostConnectionServer since onStopped signal is not defined in ConnectionServer
 
		//Ideally, onStopped must be defined in ConnectionServer
 
		if (boost::dynamic_pointer_cast<Swift::BoostConnectionServer>(m_server->getConnectionServer())) {
 
			boost::dynamic_pointer_cast<Swift::BoostConnectionServer>(m_server->getConnectionServer())->onStopped.connect(boost::bind(&Component::handleServerStopped, this, _1));
 
		}
 
		
 
		// We're connected right here, because we're in server mode...
 
		handleConnected();
 
	}
 
}
 

	
 
void Component::stop() {
 
	if (m_component) {
 
		m_reconnectCount = 0;
 
		// TODO: Call this once swiften will fix assert(!session_);
 
// 		m_component->disconnect();
 
		m_reconnectTimer->stop();
 
	}
 
	else if (m_server) {
 
		LOG4CXX_INFO(logger, "Stopping component in server mode on port " << CONFIG_INT(m_config, "service.port"));
 
		m_server->stop();
 
	}
 
}
 

	
 
void Component::handleConnected() {
 
	onConnected();
 
	m_reconnectCount = 0;
 
	m_reconnectTimer->stop();
 
}
 

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

	
 

	
src/user.cpp
Show inline comments
 
/**
 
 * 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/user.h"
 
#include "transport/transport.h"
 
#include "transport/storagebackend.h"
 
#include "transport/rostermanager.h"
 
#include "transport/usermanager.h"
 
#include "transport/conversationmanager.h"
 
#include "transport/presenceoracle.h"
 
#include "transport/logging.h"
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Elements/StreamError.h"
 
#include "Swiften/Elements/MUCPayload.h"
 
#include "Swiften/Elements/SpectrumErrorPayload.h"
 
#include <boost/foreach.hpp>
 
#include <stdio.h>
 
#include <stdlib.h>
 

	
 
using namespace boost;
 

	
 
#define foreach         BOOST_FOREACH
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "User");
 

	
 
User::User(const Swift::JID &jid, UserInfo &userInfo, Component *component, UserManager *userManager) {
 
	m_jid = jid.toBare();
 
	m_data = NULL;
 

	
 
	m_cacheMessages = false;
 
	m_component = component;
 
	m_presenceOracle = component->m_presenceOracle;
 
	m_entityCapsManager = component->m_entityCapsManager;
 
	m_userManager = userManager;
 
	m_userInfo = userInfo;
 
	m_connected = false;
 
	m_readyForConnect = false;
 
	m_ignoreDisconnect = false;
 
	m_resources = 0;
 
	m_reconnectCounter = 0;
 

	
 
	m_reconnectTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(5000);
 
	m_reconnectTimer->onTick.connect(boost::bind(&User::onConnectingTimeout, this)); 
 

	
 
	m_rosterManager = new RosterManager(this, m_component);
 
	m_conversationManager = new ConversationManager(this, m_component);
 
	LOG4CXX_INFO(logger, m_jid.toString() << ": Created");
 
	updateLastActivity();
 
}
 

	
 
User::~User(){
 
	LOG4CXX_INFO(logger, m_jid.toString() << ": Destroying");
 
	if (m_component->inServerMode()) {
 
		dynamic_cast<Swift::ServerStanzaChannel *>(m_component->getStanzaChannel())->finishSession(m_jid, boost::shared_ptr<Swift::Element>());
 
	}
 

	
 
	m_reconnectTimer->stop();
 
	delete m_rosterManager;
 
	delete m_conversationManager;
 
}
 

	
 
const Swift::JID &User::getJID() {
 
	return m_jid;
 
}
 

	
 
std::vector<Swift::JID> User::getJIDWithFeature(const std::string &feature) {
 
	std::vector<Swift::JID> jid;
 
	std::vector<Swift::Presence::ref> presences = m_presenceOracle->getAllPresence(m_jid);
 

	
 
	foreach(Swift::Presence::ref presence, presences) {
 
		if (presence->getType() == Swift::Presence::Unavailable)
 
			continue;
 

	
 
		Swift::DiscoInfo::ref discoInfo = m_entityCapsManager->getCaps(presence->getFrom());
 
		if (!discoInfo) {
 
#ifdef SUPPORT_LEGACY_CAPS
 
			if (m_legacyCaps.find(presence->getFrom()) != m_legacyCaps.end()) {
 
				discoInfo = m_legacyCaps[presence->getFrom()];
 
			}
 
			else {
 
				continue;
 
			}
 

	
 
			if (!discoInfo) {
 
				continue;
 
			}
 
#else
 
			continue;
 
#endif
 
		}
 

	
 
		if (discoInfo->hasFeature(feature)) {
 
			LOG4CXX_INFO(logger, m_jid.toString() << ": Found JID with " << feature << " feature: " << presence->getFrom().toString());
 
			jid.push_back(presence->getFrom());
 
		}
 
	}
 

	
 
	if (jid.empty()) {
 
		LOG4CXX_INFO(logger, m_jid.toString() << ": No JID with " << feature << " feature " << m_legacyCaps.size());
 
	}
 
	return jid;
 
}
 

	
 
Swift::DiscoInfo::ref User::getCaps(const Swift::JID &jid) const {
 
	Swift::DiscoInfo::ref discoInfo = m_entityCapsManager->getCaps(jid);
 
#ifdef SUPPORT_LEGACY_CAPS
 
	if (!discoInfo) {
 
		std::map<Swift::JID, Swift::DiscoInfo::ref>::const_iterator it = m_legacyCaps.find(jid);
 
		if (it != m_legacyCaps.end()) {
 
			discoInfo = it->second;
 
		}
 
	}
 
#endif
 
	return discoInfo;
 
}
 

	
 
void User::sendCurrentPresence() {
 
	if (m_component->inServerMode()) {
 
		return;
 
	}
 

	
 
	std::vector<Swift::Presence::ref> presences = m_presenceOracle->getAllPresence(m_jid);
 
	foreach(Swift::Presence::ref presence, presences) {
 
		if (presence->getType() == Swift::Presence::Unavailable) {
 
			continue;
 
		}
 

	
 
		if (m_connected) {
 
			Swift::Presence::ref highest = m_presenceOracle->getHighestPriorityPresence(m_jid.toBare());
 
			if (highest) {
 
				Swift::Presence::ref response = Swift::Presence::create(highest);
 
				response->setTo(presence->getFrom());
 
				response->setFrom(m_component->getJID());
 
				m_component->getStanzaChannel()->sendPresence(response);
 
			}
 
			else {
 
				Swift::Presence::ref response = Swift::Presence::create();
 
				response->setTo(presence->getFrom());
 
				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(presence->getFrom());
 
			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;
 
	m_reconnectCounter = 0;
 
	setIgnoreDisconnect(false);
 
	updateLastActivity();
 

	
 
	sendCurrentPresence();
 

	
 
	if (m_connected) {
 
		BOOST_FOREACH(Swift::Presence::ref &presence, m_joinedRooms) {
 
			handlePresence(presence, true);
 
		}
 
	}
 
}
 

	
 
void User::setCacheMessages(bool cacheMessages) {
 
	if (m_component->inServerMode() && !m_cacheMessages && cacheMessages) {
 
		m_conversationManager->sendCachedChatMessages();
 
	}
 
	m_cacheMessages = cacheMessages;
 
}
 

	
 
void User::handlePresence(Swift::Presence::ref presence, bool forceJoin) {
 

	
 
	int currentResourcesCount = m_presenceOracle->getAllPresence(m_jid).size();
 

	
 
	m_conversationManager->resetResources();
 

	
 
	LOG4CXX_INFO(logger, "PRESENCE " << presence->getFrom().toString() << " " << presence->getTo().toString());
 
	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 {
 
					m_reconnectTimer->start();
 
				}
src/usermanager.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/usermanager.h"
 
#include "transport/user.h"
 
#include "transport/transport.h"
 
#include "transport/storagebackend.h"
 
#include "transport/conversationmanager.h"
 
#include "transport/rostermanager.h"
 
#include "transport/userregistry.h"
 
#include "transport/logging.h"
 
#include "transport/discoitemsresponder.h"
 
#include "storageresponder.h"
 

	
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Server/ServerStanzaChannel.h"
 
#include "Swiften/Elements/StreamError.h"
 
#include "Swiften/Elements/MUCPayload.h"
 
#include "Swiften/Elements/ChatState.h"
 
#ifndef __FreeBSD__
 
#include "malloc.h"
 
#endif
 
// #include "valgrind/memcheck.h"
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "UserManager");
 

	
 
UserManager::UserManager(Component *component, UserRegistry *userRegistry, DiscoItemsResponder *discoItemsResponder, StorageBackend *storageBackend) {
 
	m_cachedUser = NULL;
 
	m_onlineBuddies = 0;
 
	m_sentToXMPP = 0;
 
	m_sentToBackend = 0;
 
	m_component = component;
 
	m_storageBackend = storageBackend;
 
	m_storageResponder = NULL;
 
	m_userRegistry = userRegistry;
 
	m_discoItemsResponder = discoItemsResponder;
 

	
 
	if (m_storageBackend) {
 
		m_storageResponder = new StorageResponder(component->getIQRouter(), m_storageBackend, this);
 
		m_storageResponder->start();
 
	}
 

	
 
	component->onUserPresenceReceived.connect(bind(&UserManager::handlePresence, this, _1));
 
	component->onUserDiscoInfoReceived.connect(bind(&UserManager::handleDiscoInfo, this, _1, _2));
 
	m_component->getStanzaChannel()->onMessageReceived.connect(bind(&UserManager::handleMessageReceived, this, _1));
 
	m_component->getStanzaChannel()->onPresenceReceived.connect(bind(&UserManager::handleGeneralPresenceReceived, this, _1));
 

	
 
	m_userRegistry->onConnectUser.connect(bind(&UserManager::connectUser, this, _1));
 
	m_userRegistry->onDisconnectUser.connect(bind(&UserManager::disconnectUser, this, _1));
 

	
 
	m_removeTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(1);
 
}
 

	
 
UserManager::~UserManager(){
 
	if (m_storageResponder) {
 
		m_storageResponder->stop();
 
		delete m_storageResponder;
 
	}
 
}
 

	
 
void UserManager::addUser(User *user) {
 
	m_users[user->getJID().toBare().toString()] = user;
 
	if (m_storageBackend) {
 
		m_storageBackend->setUserOnline(user->getUserInfo().id, true);
 
	}
 
	onUserCreated(user);
 
}
 

	
 
User *UserManager::getUser(const std::string &barejid){
 
	if (m_cachedUser && barejid == m_cachedUser->getJID().toBare().toString()) {
 
		return m_cachedUser;
 
	}
 

	
 
	if (m_users.find(barejid) != m_users.end()) {
 
		User *user = m_users[barejid];
 
		m_cachedUser = user;
 
		return user;
 
	}
 
	return NULL;
 
}
 

	
 
Swift::DiscoInfo::ref UserManager::getCaps(const Swift::JID &jid) const {
 
	std::map<std::string, User *>::const_iterator it = m_users.find(jid.toBare().toString());
 
	if (it == m_users.end()) {
 
		return Swift::DiscoInfo::ref();
 
	}
 

	
 
	User *user = it->second;
 
	return user->getCaps(jid);
 
}
 

	
 
void UserManager::removeUser(User *user, bool onUserBehalf) {
 
	m_users.erase(user->getJID().toBare().toString());
 
	if (m_cachedUser == user)
 
		m_cachedUser = NULL;
 

	
 
	if (m_component->inServerMode()) {
 
		disconnectUser(user->getJID());
 
	}
 
	else {
 
		// User could be disconnected by User::handleDisconnect() method, but
 
		// Transport::PresenceOracle could still contain his last presence.
 
		// We have to clear all received presences for this user in PresenceOracle.
 
		m_component->getPresenceOracle()->clearPresences(user->getJID().toBare());
 
	}
 

	
 
	if (m_storageBackend && onUserBehalf) {
 
		m_storageBackend->setUserOnline(user->getUserInfo().id, false);
 
	}
 

	
 
	onUserDestroyed(user);
 
	delete user;
 
#ifndef WIN32
 
#ifndef __FreeBSD__
 
	malloc_trim(0);
 
#endif
 
#endif
 
// 	VALGRIND_DO_LEAK_CHECK;
 
}
 

	
 
void UserManager::removeAllUsers(bool onUserBehalf) {
 
	while(m_users.begin() != m_users.end()) {
 
		removeUser((*m_users.begin()).second, onUserBehalf);
 
	}
 
}
 

	
 
int UserManager::getUserCount() {
 
	return m_users.size();
 
}
 

	
 
void UserManager::handleDiscoInfo(const Swift::JID& jid, boost::shared_ptr<Swift::DiscoInfo> info) {
 
	User *user = getUser(jid.toBare().toString());
 
	if (!user) {
 
		return;
 
	}
 

	
 
	user->handleDiscoInfo(jid, info);
 
}
 

	
 
void UserManager::handlePresence(Swift::Presence::ref presence) {
 
	std::string barejid = presence->getTo().toBare().toString();
 
	std::string userkey = presence->getFrom().toBare().toString();
 

	
 
	User *user = getUser(userkey);
 
	// Create user class if it's not there
 
	if (!user) {
 
		// Admin user is not legacy network user, so do not create User class instance for him
 
		if (m_component->inServerMode()) {
 
			std::vector<std::string> const &x = CONFIG_VECTOR(m_component->getConfig(),"service.admin_jid");
 
			if (std::find(x.begin(), x.end(), presence->getFrom().toBare().toString()) != x.end()) {
 
				// Send admin contact to the user.
 
				Swift::RosterPayload::ref payload = Swift::RosterPayload::ref(new Swift::RosterPayload());
 
				Swift::RosterItemPayload item;
 
				item.setJID(m_component->getJID());
 
				item.setName("Admin");
 
				item.setSubscription(Swift::RosterItemPayload::Both);
 
				payload->addItem(item);
 

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

	
 
				Swift::Presence::ref response = Swift::Presence::create();
 
				response->setTo(presence->getFrom());
 
				response->setFrom(m_component->getJID());
 
				m_component->getStanzaChannel()->sendPresence(response);
 
				return;
 
		    }
 
		}
 

	
 
		UserInfo res;
 
		bool registered = m_storageBackend ? m_storageBackend->getUser(userkey, res) : false;
 

	
 
		// No user and unavailable presence -> answer with unavailable
 
		if (presence->getType() == Swift::Presence::Unavailable || presence->getType() == Swift::Presence::Probe) {
 
			Swift::Presence::ref response = Swift::Presence::create();
 
			response->setTo(presence->getFrom());
 
			response->setFrom(presence->getTo());
 
			response->setType(Swift::Presence::Unavailable);
 
			m_component->getStanzaChannel()->sendPresence(response);
 

	
 
			// bother him with probe presence, just to be
 
			// sure he is subscribed to us.
 
			if (/*registered && */presence->getType() == Swift::Presence::Probe) {
 
				Swift::Presence::ref response = Swift::Presence::create();
 
				response->setTo(presence->getFrom());
 
				response->setFrom(presence->getTo());
 
				response->setType(Swift::Presence::Probe);
 
				m_component->getStanzaChannel()->sendPresence(response);
 
			}
 

	
 
			// Set user offline in database
 
			if (m_storageBackend) {
 
				UserInfo res;
 
				bool registered = m_storageBackend->getUser(userkey, res);
 
				if (registered) {
 
					m_storageBackend->setUserOnline(res.id, false);
 
				}
 
			}
 
			return;
 
		}
 

	
 
		// In server mode, we don't need registration normally, but for networks like IRC
 
		// or Twitter where there's no real authorization using password, we have to force
 
		// registration otherwise some data (like bookmarked rooms) could leak.
 
		if (m_component->inServerMode()) {
 
			if (!registered) {
 
				// If we need registration, stop login process because user is not registered
 
				if (CONFIG_BOOL_DEFAULTED(m_component->getConfig(), "registration.needRegistration", false)) {
 
					m_userRegistry->onPasswordInvalid(presence->getFrom());
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 "transport/logging.h"
 
#include "Swiften/Elements/ErrorPayload.h"
 
#include "Swiften/EventLoop/SimpleEventLoop.h"
 
#include "Swiften/Network/BoostNetworkFactories.h"
 
#include "Swiften/Client/Client.h"
 
#include <boost/shared_ptr.hpp>
 
#include <boost/thread.hpp>
 
#include <boost/date_time/posix_time/posix_time.hpp>
 
#include <boost/regex.hpp> 
 

	
 
using namespace Swift;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "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);
 

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

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

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

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

	
 
	if (remoteRosterNotSupported || !payload) {
 
		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 = (*u).legacyName;
 
			if ((*u).flags & BUDDY_JID_ESCAPING) {
 
				name = Swift::JID::getEscapedNode((*u).legacyName);
 
			}
 
			else {
 
				if (name.find_last_of("@") != std::string::npos) {
 
					name.replace(name.find_last_of("@"), 1, "%");
 
				}
 
			}
 

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

	
 
	// Remove user from database
 
	m_storageBackend->removeUser(userInfo.id);
 

	
 
	// Disconnect the user
 
	User *user = m_userManager->getUser(barejid);
 
	if (user) {
 
		m_userManager->removeUser(user);
 
	}
 

	
 
	if (remoteRosterNotSupported || !payload) {
 
		Swift::Presence::ref response;
 
		response = Swift::Presence::create();
 
		response->setTo(Swift::JID(barejid));
 
		response->setFrom(m_component->getJID());
 
		response->setType(Swift::Presence::Unsubscribe);
 
		m_component->getStanzaChannel()->sendPresence(response);
 

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

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

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

	
 
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::vector<std::string> const &x = CONFIG_VECTOR(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;
src/userregistry.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 <string>
 
#include <map>
 
#include "Swiften/Swiften.h"
 
#include "Swiften/Server/UserRegistry.h"
 
#include "transport/userregistry.h"
 
#include "transport/logging.h"
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "UserRegistry");
 

	
 
UserRegistry::UserRegistry(Config *cfg, Swift::NetworkFactories *factories) {
 
	config = cfg;
 
	m_removeTimer = factories->getTimerFactory()->createTimer(1);
 
	m_inRemoveLater = false;
 
}
 

	
 
UserRegistry::~UserRegistry() { m_removeTimer->stop(); }
 

	
 
void UserRegistry::isValidUserPassword(const Swift::JID& user, Swift::ServerFromClientSession *session, const Swift::SafeByteArray& password) {
 
	std::vector<std::string> const &x = CONFIG_VECTOR(config,"service.admin_jid");
 
	if (std::find(x.begin(), x.end(), user.toBare().toString()) != x.end()) {
 
		if (Swift::safeByteArrayToString(password) == CONFIG_STRING(config, "service.admin_password")) {
 
			session->handlePasswordValid();
 
		}
 
		else {
 
			session->handlePasswordInvalid();
 
		}
 
		return;
 
	}
 
	std::string key = user.toBare().toString();
 

	
 
	// Users try to connect twice
 
	if (users.find(key) != users.end()) {
 
		// Kill the first session
 
		LOG4CXX_INFO(logger, key << ": Removing previous session and making this one active");
 
		Swift::ServerFromClientSession *tmp = users[key].session;
 
		users[key].session = session;
 
		tmp->handlePasswordInvalid();
 
	}
 

	
 
	LOG4CXX_INFO(logger, key << ": Connecting this user to find if password is valid");
 

	
 
	users[key].password = Swift::safeByteArrayToString(password);
 
	users[key].session = session;
 
	onConnectUser(user);
 

	
 
	return;
 
}
 

	
 
void UserRegistry::stopLogin(const Swift::JID& user, Swift::ServerFromClientSession *session) {
 
	std::string key = user.toBare().toString();
 
	if (users.find(key) != users.end()) {
 
		if (users[key].session == session) {
 
			LOG4CXX_INFO(logger, key << ": Stopping login process (user probably disconnected while logging in)");
 
			users.erase(key);
 
		}
 
		else {
 
			LOG4CXX_WARN(logger, key << ": Stopping login process (user probably disconnected while logging in), but this is not active session");
 
		}
 
	}
 

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

	
 
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 or there was an error when connecting the legacy network");
 
		users[key].session->handlePasswordInvalid(error);
 
		users.erase(key);
 
	}
 
}
 

	
 
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/usersreconnecter.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/usersreconnecter.h"
 

	
 
#include <iostream>
 
#include <boost/bind.hpp>
 
#include "Swiften/Queries/IQRouter.h"
 
#include "Swiften/Swiften.h"
 
#include "transport/storagebackend.h"
 
#include "transport/transport.h"
 
#include "transport/logging.h"
 

	
 
#include "Swiften/Network/NetworkFactories.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "UserReconnecter");
 

	
 
UsersReconnecter::UsersReconnecter(Component *component, StorageBackend *storageBackend) {
 
	m_component = component;
 
	m_storageBackend = storageBackend;
 
	m_started = false;
 

	
 
	m_nextUserTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(1000);
 
	m_nextUserTimer->onTick.connect(boost::bind(&UsersReconnecter::reconnectNextUser, this));
 

	
 
	m_component->onConnected.connect(bind(&UsersReconnecter::handleConnected, this));
 
}
 

	
 
UsersReconnecter::~UsersReconnecter() {
 
	m_component->onConnected.disconnect(bind(&UsersReconnecter::handleConnected, this));
 
	m_nextUserTimer->stop();
 
	m_nextUserTimer->onTick.disconnect(boost::bind(&UsersReconnecter::reconnectNextUser, this));
 
}
 

	
 
void UsersReconnecter::reconnectNextUser() {
 
	if (m_users.empty()) {
 
		LOG4CXX_INFO(logger, "All users reconnected, stopping UserReconnecter.");
 
		return;
 
	}
 

	
 
	std::string user = m_users.back();
 
	m_users.pop_back();
 

	
 
	LOG4CXX_INFO(logger, "Sending probe presence to " << user);
 
	Swift::Presence::ref response = Swift::Presence::create();
 
	try {
 
		response->setTo(user);
 
	}
 
	catch (...) { return; }
 
	
 
	response->setFrom(m_component->getJID());
 
	response->setType(Swift::Presence::Probe);
 

	
 
	m_component->getStanzaChannel()->sendPresence(response);
 
	m_nextUserTimer->start();
 
}
 

	
 
void UsersReconnecter::handleConnected() {
 
	if (m_started)
 
		return;
 

	
 
	LOG4CXX_INFO(logger, "Starting UserReconnecter.");
 
	m_started = true;
 

	
 
	m_storageBackend->getOnlineUsers(m_users);
 

	
 
	reconnectNextUser();
 
}
 

	
 

	
 
}
src/vcardresponder.cpp
Show inline comments
 
/**
 
 * XMPP - libpurple transport
 
 *
 
 * Copyright (C) 2009, Jan Kaluza <hanzz@soc.pidgin.im>
 
 *
 
 * 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/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 "transport/logging.h"
 

	
 
using namespace Swift;
 
using namespace boost;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "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(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++) {
 
		if (now - (*it).second.received > 40) {
 
			candidates.push_back((*it).first);
 
		}
 
	}
 

	
 
	if (candidates.size() != 0) {
 
		LOG4CXX_INFO(logger, "Removing " << candidates.size() << " timeouted VCard requests");
 
	}
 

	
 
	BOOST_FOREACH(unsigned int id, candidates) {
 
		sendVCard(id, boost::shared_ptr<Swift::VCard>(new Swift::VCard()));
 
	}
 
	m_collectTimer->start();
 
}
 

	
 
bool VCardResponder::handleGetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::VCard> payload) {
 
	User *user = m_userManager->getUser(from.toBare().toString());
 
	if (!user) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": User is not logged in");
 
		return false;
 
	}
 

	
 
	Swift::JID to_ = to;
 

	
 
	std::string name = to_.getUnescapedNode();
 
	if (name.empty()) {
 
		to_ = user->getJID();
 
	}
 

	
 
	name = Buddy::JIDToLegacyName(to_);
 

	
 
	LOG4CXX_INFO(logger, from.toBare().toString() << ": Requested VCard of " << name);
 

	
 
	m_queries[m_id].from = from;
 
	m_queries[m_id].to = to;
 
	m_queries[m_id].id = id; 
 
	m_queries[m_id].received = time(NULL);
 
	onVCardRequired(user, name, m_id++);
 
	return true;
 
}
 

	
 
bool VCardResponder::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::VCard> payload) {
 
	if (!to.getNode().empty()) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": Tried to set VCard of somebody else");
 
		return false;
 
	}
 

	
 
	User *user = m_userManager->getUser(from.toBare().toString());
 
	if (!user) {
 
		LOG4CXX_WARN(logger, from.toBare().toString() << ": User is not logged in");
 
		return false;
 
	}
 

	
 
	LOG4CXX_INFO(logger, from.toBare().toString() << ": Setting VCard");
 
	onVCardUpdated(user, payload);
 

	
 
	sendResponse(from, id, boost::shared_ptr<VCard>(new VCard()));
 
	return true;
 
}
 

	
 
}
0 comments (0 inline, 0 general)