diff options
Diffstat (limited to 'Swiften')
1592 files changed, 62941 insertions, 62941 deletions
diff --git a/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp b/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp index a1f3d4c..1cdf467 100644 --- a/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp +++ b/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp @@ -18,83 +18,83 @@ OutgoingAdHocCommandSession::OutgoingAdHocCommandSession(const JID& to, const st } OutgoingAdHocCommandSession::~OutgoingAdHocCommandSession() { - connection_.disconnect(); + connection_.disconnect(); } void OutgoingAdHocCommandSession::handleResponse(boost::shared_ptr<Command> payload, ErrorPayload::ref error) { - if (error) { - onError(error); - } else { - const std::vector<Command::Action>& actions = payload->getAvailableActions(); - actionStates_.clear(); - if (payload->getStatus() == Command::Executing ) { - actionStates_[Command::Cancel] = EnabledAndPresent; - actionStates_[Command::Complete] = Present; - if (std::find(actions.begin(), actions.end(), Command::Complete) != actions.end()) { - actionStates_[Command::Complete] = EnabledAndPresent; - } - - if (getIsMultiStage()) { - actionStates_[Command::Next] = Present; - actionStates_[Command::Prev] = Present; - } - - if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end()) { - actionStates_[Command::Next] = EnabledAndPresent; - } - if (std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) { - actionStates_[Command::Prev] = EnabledAndPresent; - } - } - - sessionID_ = payload->getSessionID(); - if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end() - || std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) { - isMultiStage_ = true; - } - onNextStageReceived(payload); - } + if (error) { + onError(error); + } else { + const std::vector<Command::Action>& actions = payload->getAvailableActions(); + actionStates_.clear(); + if (payload->getStatus() == Command::Executing ) { + actionStates_[Command::Cancel] = EnabledAndPresent; + actionStates_[Command::Complete] = Present; + if (std::find(actions.begin(), actions.end(), Command::Complete) != actions.end()) { + actionStates_[Command::Complete] = EnabledAndPresent; + } + + if (getIsMultiStage()) { + actionStates_[Command::Next] = Present; + actionStates_[Command::Prev] = Present; + } + + if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end()) { + actionStates_[Command::Next] = EnabledAndPresent; + } + if (std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) { + actionStates_[Command::Prev] = EnabledAndPresent; + } + } + + sessionID_ = payload->getSessionID(); + if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end() + || std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) { + isMultiStage_ = true; + } + onNextStageReceived(payload); + } } bool OutgoingAdHocCommandSession::getIsMultiStage() const { - return isMultiStage_; + return isMultiStage_; } void OutgoingAdHocCommandSession::start() { - boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, boost::make_shared<Command>(commandNode_), iqRouter_); - connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2)); - commandRequest->send(); + boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, boost::make_shared<Command>(commandNode_), iqRouter_); + connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2)); + commandRequest->send(); } void OutgoingAdHocCommandSession::cancel() { - if (!sessionID_.empty()) { - submitForm(Form::ref(), Command::Cancel); - } + if (!sessionID_.empty()) { + submitForm(Form::ref(), Command::Cancel); + } } void OutgoingAdHocCommandSession::goBack() { - submitForm(Form::ref(), Command::Prev); + submitForm(Form::ref(), Command::Prev); } void OutgoingAdHocCommandSession::complete(Form::ref form) { - submitForm(form, Command::Complete); + submitForm(form, Command::Complete); } void OutgoingAdHocCommandSession::goNext(Form::ref form) { - submitForm(form, Command::Next); + submitForm(form, Command::Next); } void OutgoingAdHocCommandSession::submitForm(Form::ref form, Command::Action action) { - boost::shared_ptr<Command> command(boost::make_shared<Command>(commandNode_, sessionID_, action)); - command->setForm(form); - boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, command, iqRouter_); - connection_.disconnect(); - connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2)); - commandRequest->send(); + boost::shared_ptr<Command> command(boost::make_shared<Command>(commandNode_, sessionID_, action)); + command->setForm(form); + boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, command, iqRouter_); + connection_.disconnect(); + connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2)); + commandRequest->send(); } OutgoingAdHocCommandSession::ActionState OutgoingAdHocCommandSession::getActionState(Command::Action action) const { - return get(actionStates_, action, Absent); + return get(actionStates_, action, Absent); } } diff --git a/Swiften/AdHoc/OutgoingAdHocCommandSession.h b/Swiften/AdHoc/OutgoingAdHocCommandSession.h index 73dc7a1..fdb6e35 100644 --- a/Swiften/AdHoc/OutgoingAdHocCommandSession.h +++ b/Swiften/AdHoc/OutgoingAdHocCommandSession.h @@ -18,82 +18,82 @@ #include <Swiften/JID/JID.h> namespace Swift { - class IQRouter; - class MainWindow; - class UIEventStream; + class IQRouter; + class MainWindow; + class UIEventStream; - class SWIFTEN_API OutgoingAdHocCommandSession { - public: + class SWIFTEN_API OutgoingAdHocCommandSession { + public: - /** - * Availability of action. - */ - enum ActionState { - Absent /** Action isn't applicable to this command. */ = 0, - Present /** Action is applicable to this command */= 1, - Enabled /** Action is applicable and currently available */ = 2, - EnabledAndPresent = 3}; + /** + * Availability of action. + */ + enum ActionState { + Absent /** Action isn't applicable to this command. */ = 0, + Present /** Action is applicable to this command */= 1, + Enabled /** Action is applicable and currently available */ = 2, + EnabledAndPresent = 3}; - OutgoingAdHocCommandSession(const JID& to, const std::string& commandNode, IQRouter* iqRouter); - ~OutgoingAdHocCommandSession(); - /** - * Send initial request to the target. - */ - void start(); - /** - * Cancel command session with the target. - */ - void cancel(); - /** - * Return to the previous stage. - */ - void goBack(); - /** - * Send the form to complete the command. - * \param form Form for submission - if missing the command will be submitted with no form. - */ - void complete(Form::ref form); - /** - * Send the form to advance to the next stage of the command. - * \param form Form for submission - if missing the command will be submitted with no form. - */ - void goNext(Form::ref form); + OutgoingAdHocCommandSession(const JID& to, const std::string& commandNode, IQRouter* iqRouter); + ~OutgoingAdHocCommandSession(); + /** + * Send initial request to the target. + */ + void start(); + /** + * Cancel command session with the target. + */ + void cancel(); + /** + * Return to the previous stage. + */ + void goBack(); + /** + * Send the form to complete the command. + * \param form Form for submission - if missing the command will be submitted with no form. + */ + void complete(Form::ref form); + /** + * Send the form to advance to the next stage of the command. + * \param form Form for submission - if missing the command will be submitted with no form. + */ + void goNext(Form::ref form); - /** - * Is the form multi-stage? - */ - bool getIsMultiStage() const; + /** + * Is the form multi-stage? + */ + bool getIsMultiStage() const; - /** - * Emitted when the form for the next stage is available. - */ - boost::signal<void (Command::ref)> onNextStageReceived; + /** + * Emitted when the form for the next stage is available. + */ + boost::signal<void (Command::ref)> onNextStageReceived; - /** - * Emitted on error. - */ - boost::signal<void (ErrorPayload::ref)> onError; + /** + * Emitted on error. + */ + boost::signal<void (ErrorPayload::ref)> onError; - /** - * Get the state of a given action. - * This is useful for a UI to determine which buttons should be visible, - * and which enabled. - * Use for Next, Prev, Cancel and Complete only. - * If no actions are available, the command has completed. - */ - ActionState getActionState(Command::Action action) const; + /** + * Get the state of a given action. + * This is useful for a UI to determine which buttons should be visible, + * and which enabled. + * Use for Next, Prev, Cancel and Complete only. + * If no actions are available, the command has completed. + */ + ActionState getActionState(Command::Action action) const; - private: - void handleResponse(boost::shared_ptr<Command> payload, ErrorPayload::ref error); - void submitForm(Form::ref, Command::Action action); + private: + void handleResponse(boost::shared_ptr<Command> payload, ErrorPayload::ref error); + void submitForm(Form::ref, Command::Action action); - private: - JID to_; - std::string commandNode_; - IQRouter* iqRouter_; - bool isMultiStage_; - std::string sessionID_; - std::map<Command::Action, ActionState> actionStates_; - boost::bsignals::connection connection_; - }; + private: + JID to_; + std::string commandNode_; + IQRouter* iqRouter_; + bool isMultiStage_; + std::string sessionID_; + std::map<Command::Action, ActionState> actionStates_; + boost::bsignals::connection connection_; + }; } diff --git a/Swiften/Avatars/AvatarManager.h b/Swiften/Avatars/AvatarManager.h index 20b4725..ffd6608 100644 --- a/Swiften/Avatars/AvatarManager.h +++ b/Swiften/Avatars/AvatarManager.h @@ -13,15 +13,15 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - class JID; + class JID; - class SWIFTEN_API AvatarManager { - public: - virtual ~AvatarManager(); + class SWIFTEN_API AvatarManager { + public: + virtual ~AvatarManager(); - virtual ByteArray getAvatar(const JID&) const = 0; - virtual boost::filesystem::path getAvatarPath(const JID&) const = 0; + virtual ByteArray getAvatar(const JID&) const = 0; + virtual boost::filesystem::path getAvatarPath(const JID&) const = 0; - boost::signal<void (const JID&)> onAvatarChanged; - }; + boost::signal<void (const JID&)> onAvatarChanged; + }; } diff --git a/Swiften/Avatars/AvatarManagerImpl.cpp b/Swiften/Avatars/AvatarManagerImpl.cpp index f15c16c..6e98b1b 100644 --- a/Swiften/Avatars/AvatarManagerImpl.cpp +++ b/Swiften/Avatars/AvatarManagerImpl.cpp @@ -17,50 +17,50 @@ namespace Swift { AvatarManagerImpl::AvatarManagerImpl(VCardManager* vcardManager, StanzaChannel* stanzaChannel, AvatarStorage* avatarStorage, CryptoProvider* crypto, MUCRegistry* mucRegistry) : avatarStorage(avatarStorage) { - vcardUpdateAvatarManager = new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto, mucRegistry); - combinedAvatarProvider.addProvider(vcardUpdateAvatarManager); + vcardUpdateAvatarManager = new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto, mucRegistry); + combinedAvatarProvider.addProvider(vcardUpdateAvatarManager); - vcardAvatarManager = new VCardAvatarManager(vcardManager, avatarStorage, crypto, mucRegistry); - combinedAvatarProvider.addProvider(vcardAvatarManager); + vcardAvatarManager = new VCardAvatarManager(vcardManager, avatarStorage, crypto, mucRegistry); + combinedAvatarProvider.addProvider(vcardAvatarManager); - offlineAvatarManager = new OfflineAvatarManager(avatarStorage); - combinedAvatarProvider.addProvider(offlineAvatarManager); + offlineAvatarManager = new OfflineAvatarManager(avatarStorage); + combinedAvatarProvider.addProvider(offlineAvatarManager); - combinedAvatarProvider.onAvatarChanged.connect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1)); + combinedAvatarProvider.onAvatarChanged.connect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1)); } AvatarManagerImpl::~AvatarManagerImpl() { - combinedAvatarProvider.onAvatarChanged.disconnect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1)); + combinedAvatarProvider.onAvatarChanged.disconnect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1)); - combinedAvatarProvider.removeProvider(offlineAvatarManager); - delete offlineAvatarManager; - combinedAvatarProvider.removeProvider(vcardAvatarManager); - delete vcardAvatarManager; - combinedAvatarProvider.removeProvider(vcardUpdateAvatarManager); - delete vcardUpdateAvatarManager; + combinedAvatarProvider.removeProvider(offlineAvatarManager); + delete offlineAvatarManager; + combinedAvatarProvider.removeProvider(vcardAvatarManager); + delete vcardAvatarManager; + combinedAvatarProvider.removeProvider(vcardUpdateAvatarManager); + delete vcardUpdateAvatarManager; } boost::filesystem::path AvatarManagerImpl::getAvatarPath(const JID& jid) const { - boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid); - if (hash && !hash->empty()) { - return avatarStorage->getAvatarPath(*hash); - } - return boost::filesystem::path(); + boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid); + if (hash && !hash->empty()) { + return avatarStorage->getAvatarPath(*hash); + } + return boost::filesystem::path(); } ByteArray AvatarManagerImpl::getAvatar(const JID& jid) const { - boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid); - if (hash && !hash->empty()) { - return avatarStorage->getAvatar(*hash); - } - return ByteArray(); + boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid); + if (hash && !hash->empty()) { + return avatarStorage->getAvatar(*hash); + } + return ByteArray(); } void AvatarManagerImpl::handleCombinedAvatarChanged(const JID& jid) { - boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid); - assert(hash); - offlineAvatarManager->setAvatar(jid, *hash); - onAvatarChanged(jid); + boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid); + assert(hash); + offlineAvatarManager->setAvatar(jid, *hash); + onAvatarChanged(jid); } } diff --git a/Swiften/Avatars/AvatarManagerImpl.h b/Swiften/Avatars/AvatarManagerImpl.h index 69af924..7176c25 100644 --- a/Swiften/Avatars/AvatarManagerImpl.h +++ b/Swiften/Avatars/AvatarManagerImpl.h @@ -10,32 +10,32 @@ #include <Swiften/Avatars/CombinedAvatarProvider.h> namespace Swift { - class MUCRegistry; - class AvatarStorage; - class StanzaChannel; - class VCardManager; - class VCardUpdateAvatarManager; - class VCardAvatarManager; - class OfflineAvatarManager; - class CryptoProvider; - - class AvatarManagerImpl : public AvatarManager { - public: - AvatarManagerImpl(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL); - virtual ~AvatarManagerImpl(); - - virtual boost::filesystem::path getAvatarPath(const JID&) const; - virtual ByteArray getAvatar(const JID&) const; - - private: - void handleCombinedAvatarChanged(const JID& jid); - - - private: - CombinedAvatarProvider combinedAvatarProvider; - AvatarStorage* avatarStorage; - VCardUpdateAvatarManager* vcardUpdateAvatarManager; - VCardAvatarManager* vcardAvatarManager; - OfflineAvatarManager* offlineAvatarManager; - }; + class MUCRegistry; + class AvatarStorage; + class StanzaChannel; + class VCardManager; + class VCardUpdateAvatarManager; + class VCardAvatarManager; + class OfflineAvatarManager; + class CryptoProvider; + + class AvatarManagerImpl : public AvatarManager { + public: + AvatarManagerImpl(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL); + virtual ~AvatarManagerImpl(); + + virtual boost::filesystem::path getAvatarPath(const JID&) const; + virtual ByteArray getAvatar(const JID&) const; + + private: + void handleCombinedAvatarChanged(const JID& jid); + + + private: + CombinedAvatarProvider combinedAvatarProvider; + AvatarStorage* avatarStorage; + VCardUpdateAvatarManager* vcardUpdateAvatarManager; + VCardAvatarManager* vcardAvatarManager; + OfflineAvatarManager* offlineAvatarManager; + }; } diff --git a/Swiften/Avatars/AvatarMemoryStorage.h b/Swiften/Avatars/AvatarMemoryStorage.h index 7a4bdd3..bc40a26 100644 --- a/Swiften/Avatars/AvatarMemoryStorage.h +++ b/Swiften/Avatars/AvatarMemoryStorage.h @@ -15,30 +15,30 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API AvatarMemoryStorage : public AvatarStorage { - public: - virtual bool hasAvatar(const std::string& hash) const { return avatars.find(hash) != avatars.end(); } - virtual void addAvatar(const std::string& hash, const ByteArray& avatar) { avatars[hash] = avatar; } - virtual ByteArray getAvatar(const std::string& hash) const { - std::map<std::string, ByteArray>::const_iterator i = avatars.find(hash); - return i == avatars.end() ? ByteArray() : i->second; - } - - virtual boost::filesystem::path getAvatarPath(const std::string& hash) const { - return boost::filesystem::path("/avatars") / hash; - } - - virtual void setAvatarForJID(const JID& jid, const std::string& hash) { - jidAvatars[jid] = hash; - } - - virtual std::string getAvatarForJID(const JID& jid) const { - std::map<JID, std::string>::const_iterator i = jidAvatars.find(jid); - return i == jidAvatars.end() ? "" : i->second; - } - - private: - std::map<std::string, ByteArray> avatars; - std::map<JID, std::string> jidAvatars; - }; + class SWIFTEN_API AvatarMemoryStorage : public AvatarStorage { + public: + virtual bool hasAvatar(const std::string& hash) const { return avatars.find(hash) != avatars.end(); } + virtual void addAvatar(const std::string& hash, const ByteArray& avatar) { avatars[hash] = avatar; } + virtual ByteArray getAvatar(const std::string& hash) const { + std::map<std::string, ByteArray>::const_iterator i = avatars.find(hash); + return i == avatars.end() ? ByteArray() : i->second; + } + + virtual boost::filesystem::path getAvatarPath(const std::string& hash) const { + return boost::filesystem::path("/avatars") / hash; + } + + virtual void setAvatarForJID(const JID& jid, const std::string& hash) { + jidAvatars[jid] = hash; + } + + virtual std::string getAvatarForJID(const JID& jid) const { + std::map<JID, std::string>::const_iterator i = jidAvatars.find(jid); + return i == jidAvatars.end() ? "" : i->second; + } + + private: + std::map<std::string, ByteArray> avatars; + std::map<JID, std::string> jidAvatars; + }; } diff --git a/Swiften/Avatars/AvatarProvider.h b/Swiften/Avatars/AvatarProvider.h index 8289ecd..77d9cba 100644 --- a/Swiften/Avatars/AvatarProvider.h +++ b/Swiften/Avatars/AvatarProvider.h @@ -12,14 +12,14 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - class JID; + class JID; - class SWIFTEN_API AvatarProvider { - public: - virtual ~AvatarProvider(); + class SWIFTEN_API AvatarProvider { + public: + virtual ~AvatarProvider(); - virtual boost::optional<std::string> getAvatarHash(const JID&) const = 0; + virtual boost::optional<std::string> getAvatarHash(const JID&) const = 0; - boost::signal<void (const JID&)> onAvatarChanged; - }; + boost::signal<void (const JID&)> onAvatarChanged; + }; } diff --git a/Swiften/Avatars/AvatarStorage.h b/Swiften/Avatars/AvatarStorage.h index 2885dd0..dc3eb34 100644 --- a/Swiften/Avatars/AvatarStorage.h +++ b/Swiften/Avatars/AvatarStorage.h @@ -14,19 +14,19 @@ #include <Swiften/Base/ByteArray.h> namespace Swift { - class JID; + class JID; - class SWIFTEN_API AvatarStorage { - public: - virtual ~AvatarStorage(); + class SWIFTEN_API AvatarStorage { + public: + virtual ~AvatarStorage(); - virtual bool hasAvatar(const std::string& hash) const = 0; - virtual void addAvatar(const std::string& hash, const ByteArray& avatar) = 0; - virtual ByteArray getAvatar(const std::string& hash) const = 0; - virtual boost::filesystem::path getAvatarPath(const std::string& hash) const = 0; + virtual bool hasAvatar(const std::string& hash) const = 0; + virtual void addAvatar(const std::string& hash, const ByteArray& avatar) = 0; + virtual ByteArray getAvatar(const std::string& hash) const = 0; + virtual boost::filesystem::path getAvatarPath(const std::string& hash) const = 0; - virtual void setAvatarForJID(const JID& jid, const std::string& hash) = 0; - virtual std::string getAvatarForJID(const JID& jid) const = 0; - }; + virtual void setAvatarForJID(const JID& jid, const std::string& hash) = 0; + virtual std::string getAvatarForJID(const JID& jid) const = 0; + }; } diff --git a/Swiften/Avatars/CombinedAvatarProvider.cpp b/Swiften/Avatars/CombinedAvatarProvider.cpp index 896346f..465512f 100644 --- a/Swiften/Avatars/CombinedAvatarProvider.cpp +++ b/Swiften/Avatars/CombinedAvatarProvider.cpp @@ -15,48 +15,48 @@ namespace Swift { boost::optional<std::string> CombinedAvatarProvider::getAvatarHash(const JID& jid) const { - return getCombinedAvatarAndCache(jid); + return getCombinedAvatarAndCache(jid); } void CombinedAvatarProvider::addProvider(AvatarProvider* provider) { - provider->onAvatarChanged.connect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1)); - providers.push_back(provider); + provider->onAvatarChanged.connect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1)); + providers.push_back(provider); } void CombinedAvatarProvider::removeProvider(AvatarProvider* provider) { - std::vector<AvatarProvider*>::iterator i = std::remove(providers.begin(), providers.end(), provider); - for(std::vector<AvatarProvider*>::iterator j = i; j < providers.end(); ++j) { - provider->onAvatarChanged.disconnect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1)); - } - providers.erase(i, providers.end()); + std::vector<AvatarProvider*>::iterator i = std::remove(providers.begin(), providers.end(), provider); + for(std::vector<AvatarProvider*>::iterator j = i; j < providers.end(); ++j) { + provider->onAvatarChanged.disconnect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1)); + } + providers.erase(i, providers.end()); } void CombinedAvatarProvider::handleAvatarChanged(const JID& jid) { - std::string oldHash; - std::map<JID, std::string>::const_iterator i = avatars.find(jid); - if (i != avatars.end()) { - oldHash = i->second; - } - boost::optional<std::string> newHash = getCombinedAvatarAndCache(jid); - if (newHash != oldHash) { - SWIFT_LOG(debug) << "Avatar changed: " << jid << ": " << oldHash << " -> " << (newHash ? newHash.get() : "NULL") << std::endl; - onAvatarChanged(jid); - } + std::string oldHash; + std::map<JID, std::string>::const_iterator i = avatars.find(jid); + if (i != avatars.end()) { + oldHash = i->second; + } + boost::optional<std::string> newHash = getCombinedAvatarAndCache(jid); + if (newHash != oldHash) { + SWIFT_LOG(debug) << "Avatar changed: " << jid << ": " << oldHash << " -> " << (newHash ? newHash.get() : "NULL") << std::endl; + onAvatarChanged(jid); + } } boost::optional<std::string> CombinedAvatarProvider::getCombinedAvatarAndCache(const JID& jid) const { - SWIFT_LOG(debug) << "JID: " << jid << std::endl; - boost::optional<std::string> hash; - for (size_t i = 0; i < providers.size() && !hash; ++i) { - hash = providers[i]->getAvatarHash(jid); - SWIFT_LOG(debug) << "Provider " << providers[i] << ": " << (hash ? hash.get() : "NULL") << std::endl; - } - if (hash) { - avatars[jid] = *hash; - } else { - avatars[jid] = ""; - } - return hash; + SWIFT_LOG(debug) << "JID: " << jid << std::endl; + boost::optional<std::string> hash; + for (size_t i = 0; i < providers.size() && !hash; ++i) { + hash = providers[i]->getAvatarHash(jid); + SWIFT_LOG(debug) << "Provider " << providers[i] << ": " << (hash ? hash.get() : "NULL") << std::endl; + } + if (hash) { + avatars[jid] = *hash; + } else { + avatars[jid] = ""; + } + return hash; } } diff --git a/Swiften/Avatars/CombinedAvatarProvider.h b/Swiften/Avatars/CombinedAvatarProvider.h index c458514..f667ad2 100644 --- a/Swiften/Avatars/CombinedAvatarProvider.h +++ b/Swiften/Avatars/CombinedAvatarProvider.h @@ -14,19 +14,19 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API CombinedAvatarProvider : public AvatarProvider { - public: - virtual boost::optional<std::string> getAvatarHash(const JID&) const; + class SWIFTEN_API CombinedAvatarProvider : public AvatarProvider { + public: + virtual boost::optional<std::string> getAvatarHash(const JID&) const; - void addProvider(AvatarProvider*); - void removeProvider(AvatarProvider*); + void addProvider(AvatarProvider*); + void removeProvider(AvatarProvider*); - private: - void handleAvatarChanged(const JID&); - boost::optional<std::string> getCombinedAvatarAndCache(const JID&) const; + private: + void handleAvatarChanged(const JID&); + boost::optional<std::string> getCombinedAvatarAndCache(const JID&) const; - private: - std::vector<AvatarProvider*> providers; - mutable std::map<JID, std::string> avatars; - }; + private: + std::vector<AvatarProvider*> providers; + mutable std::map<JID, std::string> avatars; + }; } diff --git a/Swiften/Avatars/DummyAvatarManager.h b/Swiften/Avatars/DummyAvatarManager.h index 7d0793c..f079be1 100644 --- a/Swiften/Avatars/DummyAvatarManager.h +++ b/Swiften/Avatars/DummyAvatarManager.h @@ -12,22 +12,22 @@ #include <Swiften/JID/JID.h> namespace Swift { - class DummyAvatarManager : public AvatarManager { - public: - virtual boost::filesystem::path getAvatarPath(const JID& j) const { - return boost::filesystem::path("/avatars") / j.toString(); - } + class DummyAvatarManager : public AvatarManager { + public: + virtual boost::filesystem::path getAvatarPath(const JID& j) const { + return boost::filesystem::path("/avatars") / j.toString(); + } - virtual ByteArray getAvatar(const JID& jid) const { - std::map<JID, ByteArray>::const_iterator i = avatars.find(jid); - if (i != avatars.end()) { - return i->second; - } - else { - return ByteArray(); - } - } + virtual ByteArray getAvatar(const JID& jid) const { + std::map<JID, ByteArray>::const_iterator i = avatars.find(jid); + if (i != avatars.end()) { + return i->second; + } + else { + return ByteArray(); + } + } - std::map<JID, ByteArray> avatars; - }; + std::map<JID, ByteArray> avatars; + }; } diff --git a/Swiften/Avatars/NullAvatarManager.h b/Swiften/Avatars/NullAvatarManager.h index e9f3028..adc1acc 100644 --- a/Swiften/Avatars/NullAvatarManager.h +++ b/Swiften/Avatars/NullAvatarManager.h @@ -9,14 +9,14 @@ #include <Swiften/Avatars/AvatarManager.h> namespace Swift { - class NullAvatarManager : public AvatarManager { - public: - virtual boost::filesystem::path getAvatarPath(const JID&) const { - return boost::filesystem::path(); - } + class NullAvatarManager : public AvatarManager { + public: + virtual boost::filesystem::path getAvatarPath(const JID&) const { + return boost::filesystem::path(); + } - virtual ByteArray getAvatar(const JID&) const { - return ByteArray(); - } - }; + virtual ByteArray getAvatar(const JID&) const { + return ByteArray(); + } + }; } diff --git a/Swiften/Avatars/OfflineAvatarManager.cpp b/Swiften/Avatars/OfflineAvatarManager.cpp index d462f08..e2468e6 100644 --- a/Swiften/Avatars/OfflineAvatarManager.cpp +++ b/Swiften/Avatars/OfflineAvatarManager.cpp @@ -19,14 +19,14 @@ OfflineAvatarManager::~OfflineAvatarManager() { } boost::optional<std::string> OfflineAvatarManager::getAvatarHash(const JID& jid) const { - return avatarStorage->getAvatarForJID(jid); + return avatarStorage->getAvatarForJID(jid); } void OfflineAvatarManager::setAvatar(const JID& jid, const std::string& hash) { - if (getAvatarHash(jid) != hash) { - avatarStorage->setAvatarForJID(jid, hash); - onAvatarChanged(jid); - } + if (getAvatarHash(jid) != hash) { + avatarStorage->setAvatarForJID(jid, hash); + onAvatarChanged(jid); + } } } diff --git a/Swiften/Avatars/OfflineAvatarManager.h b/Swiften/Avatars/OfflineAvatarManager.h index 22345ae..11b1d5f 100644 --- a/Swiften/Avatars/OfflineAvatarManager.h +++ b/Swiften/Avatars/OfflineAvatarManager.h @@ -10,17 +10,17 @@ #include <Swiften/Base/API.h> namespace Swift { - class AvatarStorage; + class AvatarStorage; - class SWIFTEN_API OfflineAvatarManager : public AvatarProvider { - public: - OfflineAvatarManager(AvatarStorage*); - ~OfflineAvatarManager(); + class SWIFTEN_API OfflineAvatarManager : public AvatarProvider { + public: + OfflineAvatarManager(AvatarStorage*); + ~OfflineAvatarManager(); - virtual boost::optional<std::string> getAvatarHash(const JID&) const; - void setAvatar(const JID&, const std::string& hash); + virtual boost::optional<std::string> getAvatarHash(const JID&) const; + void setAvatar(const JID&, const std::string& hash); - private: - AvatarStorage* avatarStorage; - }; + private: + AvatarStorage* avatarStorage; + }; } diff --git a/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp b/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp index d3004cd..79769a8 100644 --- a/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp +++ b/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp @@ -31,113 +31,113 @@ using namespace Swift; class AvatarManagerImplTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(AvatarManagerImplTest); - CPPUNIT_TEST(testGetSetAvatar); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - ownerJID = JID("owner@domain.com/theowner"); - stanzaChannel = boost::make_shared<DummyStanzaChannel>(); - iqRouter = boost::make_shared<IQRouter>(stanzaChannel.get()); - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - vcardStorage = boost::make_shared<VCardMemoryStorage>(crypto.get()); - vcardManager = boost::make_shared<VCardManager>(ownerJID, iqRouter.get(), vcardStorage.get()); - avatarStorage = boost::make_shared<AvatarMemoryStorage>(); - mucRegistry = boost::make_shared<DummyMUCRegistry>(); - avatarManager = boost::make_shared<AvatarManagerImpl>(vcardManager.get(), stanzaChannel.get(), avatarStorage.get(), crypto.get(), mucRegistry.get()); - } - - void testGetSetAvatar() { - /* initially we have no knowledge of the user or their avatar */ - JID personJID("person@domain.com/theperson"); - ByteArray avatar = avatarManager->getAvatar(personJID.toBare()); - CPPUNIT_ASSERT(!avatar.size()); - - /* notify the 'owner' JID that our avatar has changed */ - - ByteArray fullAvatar = createByteArray("abcdefg"); - boost::shared_ptr<VCardUpdate> vcardUpdate = boost::make_shared<VCardUpdate>(); - vcardUpdate->setPhotoHash(Hexify::hexify(crypto->getSHA1Hash(fullAvatar))); - boost::shared_ptr<Presence> presence = boost::make_shared<Presence>(); - presence->setTo(ownerJID); - presence->setFrom(personJID); - presence->setType(Presence::Available); - presence->addPayload(vcardUpdate); - stanzaChannel->onPresenceReceived(presence); - - /* reply to the avatar request with our new avatar */ - - CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); - boost::shared_ptr<IQ> request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]); - stanzaChannel->sentStanzas.pop_back(); - CPPUNIT_ASSERT(!!request); - boost::shared_ptr<VCard> vcard = request->getPayload<VCard>(); - CPPUNIT_ASSERT(!!vcard); - - boost::shared_ptr<IQ> reply = boost::make_shared<IQ>(IQ::Result); - reply->setTo(request->getFrom()); - reply->setFrom(request->getTo()); - reply->setID(request->getID()); - vcard->setPhoto(fullAvatar); - reply->addPayload(vcard); - stanzaChannel->onIQReceived(reply); - - /* check hash through avatarManager that it received the correct photo */ - - ByteArray reportedAvatar = avatarManager->getAvatar(personJID.toBare()); - CPPUNIT_ASSERT_EQUAL(byteArrayToString(fullAvatar), byteArrayToString(reportedAvatar)); - - /* send new presence to notify of blank avatar */ - - vcardUpdate = boost::make_shared<VCardUpdate>(); - presence = boost::make_shared<Presence>(); - presence->setTo(ownerJID); - presence->setFrom(personJID); - presence->setType(Presence::Available); - presence->addPayload(vcardUpdate); - stanzaChannel->onPresenceReceived(presence); - - /* reply to the avatar request with our EMPTY avatar */ - - CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); - request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]); - stanzaChannel->sentStanzas.pop_back(); - CPPUNIT_ASSERT(!!request); - vcard = request->getPayload<VCard>(); - CPPUNIT_ASSERT(!!vcard); - - ByteArray blankAvatar = createByteArray(""); - reply = boost::make_shared<IQ>(IQ::Result); - reply->setTo(request->getFrom()); - reply->setFrom(request->getTo()); - reply->setID(request->getID()); - vcard->setPhoto(blankAvatar); - reply->addPayload(vcard); - stanzaChannel->onIQReceived(reply); - - /* check hash through avatarManager that it received the correct photo */ - - reportedAvatar = avatarManager->getAvatar(personJID.toBare()); - CPPUNIT_ASSERT_EQUAL(byteArrayToString(blankAvatar), byteArrayToString(reportedAvatar)); - } - - struct DummyMUCRegistry : public MUCRegistry { - bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } - std::vector<JID> mucs_; - }; - - private: - - JID ownerJID; - boost::shared_ptr<DummyStanzaChannel> stanzaChannel; - boost::shared_ptr<IQRouter> iqRouter; - boost::shared_ptr<CryptoProvider> crypto; - boost::shared_ptr<VCardMemoryStorage> vcardStorage; - boost::shared_ptr<VCardManager> vcardManager; - boost::shared_ptr<AvatarMemoryStorage> avatarStorage; - boost::shared_ptr<DummyMUCRegistry> mucRegistry; - boost::shared_ptr<AvatarManagerImpl> avatarManager; + CPPUNIT_TEST_SUITE(AvatarManagerImplTest); + CPPUNIT_TEST(testGetSetAvatar); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + ownerJID = JID("owner@domain.com/theowner"); + stanzaChannel = boost::make_shared<DummyStanzaChannel>(); + iqRouter = boost::make_shared<IQRouter>(stanzaChannel.get()); + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + vcardStorage = boost::make_shared<VCardMemoryStorage>(crypto.get()); + vcardManager = boost::make_shared<VCardManager>(ownerJID, iqRouter.get(), vcardStorage.get()); + avatarStorage = boost::make_shared<AvatarMemoryStorage>(); + mucRegistry = boost::make_shared<DummyMUCRegistry>(); + avatarManager = boost::make_shared<AvatarManagerImpl>(vcardManager.get(), stanzaChannel.get(), avatarStorage.get(), crypto.get(), mucRegistry.get()); + } + + void testGetSetAvatar() { + /* initially we have no knowledge of the user or their avatar */ + JID personJID("person@domain.com/theperson"); + ByteArray avatar = avatarManager->getAvatar(personJID.toBare()); + CPPUNIT_ASSERT(!avatar.size()); + + /* notify the 'owner' JID that our avatar has changed */ + + ByteArray fullAvatar = createByteArray("abcdefg"); + boost::shared_ptr<VCardUpdate> vcardUpdate = boost::make_shared<VCardUpdate>(); + vcardUpdate->setPhotoHash(Hexify::hexify(crypto->getSHA1Hash(fullAvatar))); + boost::shared_ptr<Presence> presence = boost::make_shared<Presence>(); + presence->setTo(ownerJID); + presence->setFrom(personJID); + presence->setType(Presence::Available); + presence->addPayload(vcardUpdate); + stanzaChannel->onPresenceReceived(presence); + + /* reply to the avatar request with our new avatar */ + + CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); + boost::shared_ptr<IQ> request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]); + stanzaChannel->sentStanzas.pop_back(); + CPPUNIT_ASSERT(!!request); + boost::shared_ptr<VCard> vcard = request->getPayload<VCard>(); + CPPUNIT_ASSERT(!!vcard); + + boost::shared_ptr<IQ> reply = boost::make_shared<IQ>(IQ::Result); + reply->setTo(request->getFrom()); + reply->setFrom(request->getTo()); + reply->setID(request->getID()); + vcard->setPhoto(fullAvatar); + reply->addPayload(vcard); + stanzaChannel->onIQReceived(reply); + + /* check hash through avatarManager that it received the correct photo */ + + ByteArray reportedAvatar = avatarManager->getAvatar(personJID.toBare()); + CPPUNIT_ASSERT_EQUAL(byteArrayToString(fullAvatar), byteArrayToString(reportedAvatar)); + + /* send new presence to notify of blank avatar */ + + vcardUpdate = boost::make_shared<VCardUpdate>(); + presence = boost::make_shared<Presence>(); + presence->setTo(ownerJID); + presence->setFrom(personJID); + presence->setType(Presence::Available); + presence->addPayload(vcardUpdate); + stanzaChannel->onPresenceReceived(presence); + + /* reply to the avatar request with our EMPTY avatar */ + + CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); + request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]); + stanzaChannel->sentStanzas.pop_back(); + CPPUNIT_ASSERT(!!request); + vcard = request->getPayload<VCard>(); + CPPUNIT_ASSERT(!!vcard); + + ByteArray blankAvatar = createByteArray(""); + reply = boost::make_shared<IQ>(IQ::Result); + reply->setTo(request->getFrom()); + reply->setFrom(request->getTo()); + reply->setID(request->getID()); + vcard->setPhoto(blankAvatar); + reply->addPayload(vcard); + stanzaChannel->onIQReceived(reply); + + /* check hash through avatarManager that it received the correct photo */ + + reportedAvatar = avatarManager->getAvatar(personJID.toBare()); + CPPUNIT_ASSERT_EQUAL(byteArrayToString(blankAvatar), byteArrayToString(reportedAvatar)); + } + + struct DummyMUCRegistry : public MUCRegistry { + bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } + std::vector<JID> mucs_; + }; + + private: + + JID ownerJID; + boost::shared_ptr<DummyStanzaChannel> stanzaChannel; + boost::shared_ptr<IQRouter> iqRouter; + boost::shared_ptr<CryptoProvider> crypto; + boost::shared_ptr<VCardMemoryStorage> vcardStorage; + boost::shared_ptr<VCardManager> vcardManager; + boost::shared_ptr<AvatarMemoryStorage> avatarStorage; + boost::shared_ptr<DummyMUCRegistry> mucRegistry; + boost::shared_ptr<AvatarManagerImpl> avatarManager; }; diff --git a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp index 1a18585..fb4cd8f 100644 --- a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp +++ b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp @@ -29,351 +29,351 @@ using namespace Swift; class CombinedAvatarProviderTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(CombinedAvatarProviderTest); - CPPUNIT_TEST(testGetAvatarWithNoAvatarProviderReturnsEmpty); - CPPUNIT_TEST(testGetAvatarWithSingleAvatarProvider); - CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar); - CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar); - CPPUNIT_TEST(testProviderUpdateTriggersChange); - CPPUNIT_TEST(testProviderUpdateWithoutChangeDoesNotTriggerChange); - CPPUNIT_TEST(testProviderSecondUpdateTriggersChange); - CPPUNIT_TEST(testProviderUpdateWithAvatarDisappearingTriggersChange); - CPPUNIT_TEST(testProviderUpdateAfterAvatarDisappearedTriggersChange); - CPPUNIT_TEST(testProviderUpdateAfterGetDoesNotTriggerChange); - CPPUNIT_TEST(testProviderUpdateBareJIDAfterGetFullJID); - CPPUNIT_TEST(testRemoveProviderDisconnectsUpdates); - CPPUNIT_TEST(testAddRemoveFallthrough); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - avatarProvider1 = new DummyAvatarProvider(); - avatarProvider2 = new DummyAvatarProvider(); - user1 = JID("user1@bar.com/bla"); - user2 = JID("user2@foo.com/baz"); - avatarHash1 = "ABCDEFG"; - avatarHash2 = "XYZU"; - avatarHash3 = "IDGH"; - } - - void tearDown() { - delete avatarProvider1; - delete avatarProvider2; - } - - void testGetAvatarWithNoAvatarProviderReturnsEmpty() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - - boost::optional<std::string> hash = testling->getAvatarHash(user1); - CPPUNIT_ASSERT(!hash); - } - - void testGetAvatarWithSingleAvatarProvider() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - avatarProvider1->avatars[user1] = avatarHash1; - testling->addProvider(avatarProvider1); - - boost::optional<std::string> hash = testling->getAvatarHash(user1); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash); - } - - void testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider2->avatars[user1] = avatarHash2; - testling->addProvider(avatarProvider1); - testling->addProvider(avatarProvider2); - - boost::optional<std::string> hash = testling->getAvatarHash(user1); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash); - } - - void testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - avatarProvider2->avatars[user1] = avatarHash2; - testling->addProvider(avatarProvider1); - testling->addProvider(avatarProvider2); - - boost::optional<std::string> hash = testling->getAvatarHash(user1); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash); - } - - void testProviderUpdateTriggersChange() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - testling->addProvider(avatarProvider1); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider1->onAvatarChanged(user1); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - } - - void testProviderUpdateWithoutChangeDoesNotTriggerChange() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - testling->addProvider(avatarProvider1); - testling->addProvider(avatarProvider2); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider1->onAvatarChanged(user1); - changes.clear(); - - avatarProvider2->avatars[user1] = avatarHash2; - avatarProvider2->onAvatarChanged(user1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); - } - - void testProviderSecondUpdateTriggersChange() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - testling->addProvider(avatarProvider1); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider1->onAvatarChanged(user1); - changes.clear(); - avatarProvider1->avatars[user1] = avatarHash2; - avatarProvider1->onAvatarChanged(user1); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - } - - - void testProviderUpdateWithAvatarDisappearingTriggersChange() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - testling->addProvider(avatarProvider1); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider1->onAvatarChanged(user1); - changes.clear(); - avatarProvider1->avatars.clear(); - avatarProvider1->onAvatarChanged(user1); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - } - - void testProviderUpdateAfterAvatarDisappearedTriggersChange() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - testling->addProvider(avatarProvider1); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider1->onAvatarChanged(user1); - avatarProvider1->avatars.clear(); - avatarProvider1->onAvatarChanged(user1); - changes.clear(); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider1->onAvatarChanged(user1); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - } - - - void testProviderUpdateAfterGetDoesNotTriggerChange() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - testling->addProvider(avatarProvider1); - avatarProvider1->avatars[user1] = avatarHash1; - - testling->getAvatarHash(user1); - avatarProvider1->onAvatarChanged(user1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); - } - - void testRemoveProviderDisconnectsUpdates() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - testling->addProvider(avatarProvider1); - testling->addProvider(avatarProvider2); - testling->removeProvider(avatarProvider1); - avatarProvider1->avatars[user1] = avatarHash1; - avatarProvider2->avatars[user1] = avatarHash2; - avatarProvider1->onAvatarChanged(user1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); - } - - void testProviderUpdateBareJIDAfterGetFullJID() { - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - avatarProvider1->useBare = true; - testling->addProvider(avatarProvider1); - - avatarProvider1->avatars[user1.toBare()] = avatarHash1; - testling->getAvatarHash(user1); - avatarProvider1->avatars[user1.toBare()] = avatarHash2; - avatarProvider1->onAvatarChanged(user1.toBare()); - - boost::optional<std::string> hash = testling->getAvatarHash(user1); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash); - } - - void testAddRemoveFallthrough() { - JID ownJID = JID("user0@own.com/res"); - JID user1 = JID("user1@bar.com/bla"); - - boost::shared_ptr<CryptoProvider> crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - DummyStanzaChannel* stanzaChannel = new DummyStanzaChannel(); - stanzaChannel->setAvailable(true); - IQRouter* iqRouter = new IQRouter(stanzaChannel); - DummyMUCRegistry* mucRegistry = new DummyMUCRegistry(); - AvatarMemoryStorage* avatarStorage = new AvatarMemoryStorage(); - VCardMemoryStorage* vcardStorage = new VCardMemoryStorage(crypto.get()); - VCardManager* vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage); - - boost::shared_ptr<VCardUpdateAvatarManager> updateManager(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry)); - updateManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); - - boost::shared_ptr<VCardAvatarManager> manager(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry)); - manager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); - - boost::shared_ptr<OfflineAvatarManager> offlineManager(new OfflineAvatarManager(avatarStorage)); - offlineManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); - - boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); - avatarProvider1->useBare = true; - testling->addProvider(updateManager.get()); - testling->addProvider(manager.get()); - testling->addProvider(offlineManager.get()); - - /* place an avatar in the cache, check that it reads back OK */ - - CPPUNIT_ASSERT_EQUAL(size_t(0), changes.size()); - - ByteArray avatar1 = createByteArray("abcdefg"); - std::string avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1)); - VCard::ref vcard1(new VCard()); - vcard1->setPhoto(avatar1); - - vcardStorage->setVCard(user1.toBare(), vcard1); - boost::optional<std::string> testHash = testling->getAvatarHash(user1.toBare()); - CPPUNIT_ASSERT(testHash); - CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash); - - VCard::ref storedVCard = vcardStorage->getVCard(user1.toBare()); - CPPUNIT_ASSERT(!!storedVCard); - testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto())); - CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash); - - /* change the avatar by sending an VCard IQ */ - - vcardManager->requestVCard(user1.toBare()); - CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); - IQ::ref request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back()); - VCard::ref payload = request->getPayload<VCard>(); - CPPUNIT_ASSERT(!!payload); - stanzaChannel->sentStanzas.pop_back(); - - ByteArray avatar2 = createByteArray("1234567"); - std::string avatar2Hash = Hexify::hexify(crypto->getSHA1Hash(avatar2)); - VCard::ref vcard2(new VCard()); - vcard2->setPhoto(avatar2); - - IQ::ref reply = boost::make_shared<IQ>(); - reply->setTo(request->getFrom()); - reply->setFrom(request->getTo()); - reply->setID(request->getID()); - reply->addPayload(vcard2); - reply->setType(IQ::Result); - - stanzaChannel->onIQReceived(reply); - - /* check that we changed the avatar successfully and that we were notified about the changes */ - - testHash = testling->getAvatarHash(user1.toBare()); - CPPUNIT_ASSERT(testHash); - CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash); - CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size()); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]); - changes.clear(); - storedVCard = vcardStorage->getVCard(user1.toBare()); - CPPUNIT_ASSERT(!!storedVCard); - testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto())); - CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash); - - /* change the avatar to the empty avatar */ - - vcardManager->requestVCard(user1.toBare()); - CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); - request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back()); - payload = request->getPayload<VCard>(); - CPPUNIT_ASSERT(!!payload); - stanzaChannel->sentStanzas.pop_back(); - - VCard::ref vcard3(new VCard()); - reply = boost::make_shared<IQ>(); - reply->setTo(request->getFrom()); - reply->setFrom(request->getTo()); - reply->setID(request->getID()); - reply->addPayload(vcard3); - reply->setType(IQ::Result); - stanzaChannel->onIQReceived(reply); - - /* check that we changed the avatar successfully */ - - testHash = testling->getAvatarHash(user1.toBare()); - CPPUNIT_ASSERT(testHash); - CPPUNIT_ASSERT_EQUAL(std::string(""), *testHash); - CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size()); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]); - changes.clear(); - storedVCard = vcardStorage->getVCard(user1.toBare()); - CPPUNIT_ASSERT(!!storedVCard); - CPPUNIT_ASSERT(!storedVCard->getPhoto().size()); - - delete vcardManager; - delete vcardStorage; - delete mucRegistry; - delete iqRouter; - delete stanzaChannel; - } - - private: - boost::shared_ptr<CombinedAvatarProvider> createProvider() { - boost::shared_ptr<CombinedAvatarProvider> result(new CombinedAvatarProvider()); - result->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); - return result; - } - - void handleAvatarChanged(const JID& jid) { - changes.push_back(jid); - } - - private: - struct DummyAvatarProvider : public AvatarProvider { - DummyAvatarProvider() : useBare(false) { - } - - boost::optional<std::string> getAvatarHash(const JID& jid) const { - JID actualJID = useBare ? jid.toBare() : jid; - std::map<JID, std::string>::const_iterator i = avatars.find(actualJID); - if (i != avatars.end()) { - return i->second; - } - else { - return boost::optional<std::string>(); - } - } - - bool useBare; - std::map<JID, std::string> avatars; - }; - - struct DummyMUCRegistry : public MUCRegistry { - bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } - std::vector<JID> mucs_; - }; - - DummyAvatarProvider* avatarProvider1; - DummyAvatarProvider* avatarProvider2; - JID user1; - JID user2; - std::string avatarHash1; - std::string avatarHash2; - std::string avatarHash3; - std::vector<JID> changes; + CPPUNIT_TEST_SUITE(CombinedAvatarProviderTest); + CPPUNIT_TEST(testGetAvatarWithNoAvatarProviderReturnsEmpty); + CPPUNIT_TEST(testGetAvatarWithSingleAvatarProvider); + CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar); + CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar); + CPPUNIT_TEST(testProviderUpdateTriggersChange); + CPPUNIT_TEST(testProviderUpdateWithoutChangeDoesNotTriggerChange); + CPPUNIT_TEST(testProviderSecondUpdateTriggersChange); + CPPUNIT_TEST(testProviderUpdateWithAvatarDisappearingTriggersChange); + CPPUNIT_TEST(testProviderUpdateAfterAvatarDisappearedTriggersChange); + CPPUNIT_TEST(testProviderUpdateAfterGetDoesNotTriggerChange); + CPPUNIT_TEST(testProviderUpdateBareJIDAfterGetFullJID); + CPPUNIT_TEST(testRemoveProviderDisconnectsUpdates); + CPPUNIT_TEST(testAddRemoveFallthrough); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + avatarProvider1 = new DummyAvatarProvider(); + avatarProvider2 = new DummyAvatarProvider(); + user1 = JID("user1@bar.com/bla"); + user2 = JID("user2@foo.com/baz"); + avatarHash1 = "ABCDEFG"; + avatarHash2 = "XYZU"; + avatarHash3 = "IDGH"; + } + + void tearDown() { + delete avatarProvider1; + delete avatarProvider2; + } + + void testGetAvatarWithNoAvatarProviderReturnsEmpty() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + + boost::optional<std::string> hash = testling->getAvatarHash(user1); + CPPUNIT_ASSERT(!hash); + } + + void testGetAvatarWithSingleAvatarProvider() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + avatarProvider1->avatars[user1] = avatarHash1; + testling->addProvider(avatarProvider1); + + boost::optional<std::string> hash = testling->getAvatarHash(user1); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash); + } + + void testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider2->avatars[user1] = avatarHash2; + testling->addProvider(avatarProvider1); + testling->addProvider(avatarProvider2); + + boost::optional<std::string> hash = testling->getAvatarHash(user1); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash); + } + + void testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + avatarProvider2->avatars[user1] = avatarHash2; + testling->addProvider(avatarProvider1); + testling->addProvider(avatarProvider2); + + boost::optional<std::string> hash = testling->getAvatarHash(user1); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash); + } + + void testProviderUpdateTriggersChange() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + testling->addProvider(avatarProvider1); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider1->onAvatarChanged(user1); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + } + + void testProviderUpdateWithoutChangeDoesNotTriggerChange() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + testling->addProvider(avatarProvider1); + testling->addProvider(avatarProvider2); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider1->onAvatarChanged(user1); + changes.clear(); + + avatarProvider2->avatars[user1] = avatarHash2; + avatarProvider2->onAvatarChanged(user1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); + } + + void testProviderSecondUpdateTriggersChange() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + testling->addProvider(avatarProvider1); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider1->onAvatarChanged(user1); + changes.clear(); + avatarProvider1->avatars[user1] = avatarHash2; + avatarProvider1->onAvatarChanged(user1); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + } + + + void testProviderUpdateWithAvatarDisappearingTriggersChange() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + testling->addProvider(avatarProvider1); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider1->onAvatarChanged(user1); + changes.clear(); + avatarProvider1->avatars.clear(); + avatarProvider1->onAvatarChanged(user1); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + } + + void testProviderUpdateAfterAvatarDisappearedTriggersChange() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + testling->addProvider(avatarProvider1); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider1->onAvatarChanged(user1); + avatarProvider1->avatars.clear(); + avatarProvider1->onAvatarChanged(user1); + changes.clear(); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider1->onAvatarChanged(user1); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + } + + + void testProviderUpdateAfterGetDoesNotTriggerChange() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + testling->addProvider(avatarProvider1); + avatarProvider1->avatars[user1] = avatarHash1; + + testling->getAvatarHash(user1); + avatarProvider1->onAvatarChanged(user1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); + } + + void testRemoveProviderDisconnectsUpdates() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + testling->addProvider(avatarProvider1); + testling->addProvider(avatarProvider2); + testling->removeProvider(avatarProvider1); + avatarProvider1->avatars[user1] = avatarHash1; + avatarProvider2->avatars[user1] = avatarHash2; + avatarProvider1->onAvatarChanged(user1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); + } + + void testProviderUpdateBareJIDAfterGetFullJID() { + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + avatarProvider1->useBare = true; + testling->addProvider(avatarProvider1); + + avatarProvider1->avatars[user1.toBare()] = avatarHash1; + testling->getAvatarHash(user1); + avatarProvider1->avatars[user1.toBare()] = avatarHash2; + avatarProvider1->onAvatarChanged(user1.toBare()); + + boost::optional<std::string> hash = testling->getAvatarHash(user1); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash); + } + + void testAddRemoveFallthrough() { + JID ownJID = JID("user0@own.com/res"); + JID user1 = JID("user1@bar.com/bla"); + + boost::shared_ptr<CryptoProvider> crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + DummyStanzaChannel* stanzaChannel = new DummyStanzaChannel(); + stanzaChannel->setAvailable(true); + IQRouter* iqRouter = new IQRouter(stanzaChannel); + DummyMUCRegistry* mucRegistry = new DummyMUCRegistry(); + AvatarMemoryStorage* avatarStorage = new AvatarMemoryStorage(); + VCardMemoryStorage* vcardStorage = new VCardMemoryStorage(crypto.get()); + VCardManager* vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage); + + boost::shared_ptr<VCardUpdateAvatarManager> updateManager(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry)); + updateManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); + + boost::shared_ptr<VCardAvatarManager> manager(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry)); + manager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); + + boost::shared_ptr<OfflineAvatarManager> offlineManager(new OfflineAvatarManager(avatarStorage)); + offlineManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); + + boost::shared_ptr<CombinedAvatarProvider> testling(createProvider()); + avatarProvider1->useBare = true; + testling->addProvider(updateManager.get()); + testling->addProvider(manager.get()); + testling->addProvider(offlineManager.get()); + + /* place an avatar in the cache, check that it reads back OK */ + + CPPUNIT_ASSERT_EQUAL(size_t(0), changes.size()); + + ByteArray avatar1 = createByteArray("abcdefg"); + std::string avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1)); + VCard::ref vcard1(new VCard()); + vcard1->setPhoto(avatar1); + + vcardStorage->setVCard(user1.toBare(), vcard1); + boost::optional<std::string> testHash = testling->getAvatarHash(user1.toBare()); + CPPUNIT_ASSERT(testHash); + CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash); + + VCard::ref storedVCard = vcardStorage->getVCard(user1.toBare()); + CPPUNIT_ASSERT(!!storedVCard); + testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto())); + CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash); + + /* change the avatar by sending an VCard IQ */ + + vcardManager->requestVCard(user1.toBare()); + CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); + IQ::ref request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back()); + VCard::ref payload = request->getPayload<VCard>(); + CPPUNIT_ASSERT(!!payload); + stanzaChannel->sentStanzas.pop_back(); + + ByteArray avatar2 = createByteArray("1234567"); + std::string avatar2Hash = Hexify::hexify(crypto->getSHA1Hash(avatar2)); + VCard::ref vcard2(new VCard()); + vcard2->setPhoto(avatar2); + + IQ::ref reply = boost::make_shared<IQ>(); + reply->setTo(request->getFrom()); + reply->setFrom(request->getTo()); + reply->setID(request->getID()); + reply->addPayload(vcard2); + reply->setType(IQ::Result); + + stanzaChannel->onIQReceived(reply); + + /* check that we changed the avatar successfully and that we were notified about the changes */ + + testHash = testling->getAvatarHash(user1.toBare()); + CPPUNIT_ASSERT(testHash); + CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash); + CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size()); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]); + changes.clear(); + storedVCard = vcardStorage->getVCard(user1.toBare()); + CPPUNIT_ASSERT(!!storedVCard); + testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto())); + CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash); + + /* change the avatar to the empty avatar */ + + vcardManager->requestVCard(user1.toBare()); + CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size()); + request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back()); + payload = request->getPayload<VCard>(); + CPPUNIT_ASSERT(!!payload); + stanzaChannel->sentStanzas.pop_back(); + + VCard::ref vcard3(new VCard()); + reply = boost::make_shared<IQ>(); + reply->setTo(request->getFrom()); + reply->setFrom(request->getTo()); + reply->setID(request->getID()); + reply->addPayload(vcard3); + reply->setType(IQ::Result); + stanzaChannel->onIQReceived(reply); + + /* check that we changed the avatar successfully */ + + testHash = testling->getAvatarHash(user1.toBare()); + CPPUNIT_ASSERT(testHash); + CPPUNIT_ASSERT_EQUAL(std::string(""), *testHash); + CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size()); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]); + changes.clear(); + storedVCard = vcardStorage->getVCard(user1.toBare()); + CPPUNIT_ASSERT(!!storedVCard); + CPPUNIT_ASSERT(!storedVCard->getPhoto().size()); + + delete vcardManager; + delete vcardStorage; + delete mucRegistry; + delete iqRouter; + delete stanzaChannel; + } + + private: + boost::shared_ptr<CombinedAvatarProvider> createProvider() { + boost::shared_ptr<CombinedAvatarProvider> result(new CombinedAvatarProvider()); + result->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1)); + return result; + } + + void handleAvatarChanged(const JID& jid) { + changes.push_back(jid); + } + + private: + struct DummyAvatarProvider : public AvatarProvider { + DummyAvatarProvider() : useBare(false) { + } + + boost::optional<std::string> getAvatarHash(const JID& jid) const { + JID actualJID = useBare ? jid.toBare() : jid; + std::map<JID, std::string>::const_iterator i = avatars.find(actualJID); + if (i != avatars.end()) { + return i->second; + } + else { + return boost::optional<std::string>(); + } + } + + bool useBare; + std::map<JID, std::string> avatars; + }; + + struct DummyMUCRegistry : public MUCRegistry { + bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } + std::vector<JID> mucs_; + }; + + DummyAvatarProvider* avatarProvider1; + DummyAvatarProvider* avatarProvider2; + JID user1; + JID user2; + std::string avatarHash1; + std::string avatarHash2; + std::string avatarHash3; + std::vector<JID> changes; }; CPPUNIT_TEST_SUITE_REGISTRATION(CombinedAvatarProviderTest); diff --git a/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp b/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp index 2f585aa..5a28995 100644 --- a/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp +++ b/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp @@ -27,150 +27,150 @@ using namespace Swift; class VCardAvatarManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(VCardAvatarManagerTest); - CPPUNIT_TEST(testGetAvatarHashKnownAvatar); - CPPUNIT_TEST(testGetAvatarHashEmptyAvatar); - CPPUNIT_TEST(testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar); - CPPUNIT_TEST(testGetAvatarHashUnknownAvatarUnknownVCard); - CPPUNIT_TEST(testVCardUpdateTriggersUpdate); - CPPUNIT_TEST(testGetAvatarHashKnownAvatarUnknownVCard); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - ownJID = JID("foo@fum.com/bum"); - stanzaChannel = new DummyStanzaChannel(); - stanzaChannel->setAvailable(true); - iqRouter = new IQRouter(stanzaChannel); - mucRegistry = new DummyMUCRegistry(); - avatarStorage = new AvatarMemoryStorage(); - vcardStorage = new VCardMemoryStorage(crypto.get()); - vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage); - avatar1 = createByteArray("abcdefg"); - avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1)); - user1 = JID("user1@bar.com/bla"); - user2 = JID("user2@foo.com/baz"); - } - - void tearDown() { - delete vcardManager; - delete vcardStorage; - delete avatarStorage; - delete mucRegistry; - delete iqRouter; - delete stanzaChannel; - } - - void testGetAvatarHashKnownAvatar() { - boost::shared_ptr<VCardAvatarManager> testling = createManager(); - storeVCardWithPhoto(user1.toBare(), avatar1); - avatarStorage->addAvatar(avatar1Hash, avatar1); - - boost::optional<std::string> result = testling->getAvatarHash(user1); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result); - } - - void testGetAvatarHashEmptyAvatar() { - boost::shared_ptr<VCardAvatarManager> testling = createManager(); - storeEmptyVCard(user1.toBare()); - - boost::optional<std::string> result = testling->getAvatarHash(user1); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(std::string(), *result); - } - - void testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar() { - boost::shared_ptr<VCardAvatarManager> testling = createManager(); - storeVCardWithPhoto(user1.toBare(), avatar1); - - boost::optional<std::string> result = testling->getAvatarHash(user1); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result); - CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash)); - CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash)); - } - - void testGetAvatarHashUnknownAvatarUnknownVCard() { - boost::shared_ptr<VCardAvatarManager> testling = createManager(); - - boost::optional<std::string> result = testling->getAvatarHash(user1); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(std::string(), *result); - } - - void testGetAvatarHashKnownAvatarUnknownVCard() { - boost::shared_ptr<VCardAvatarManager> testling = createManager(); - - avatarStorage->setAvatarForJID(user1, avatar1Hash); - - boost::optional<std::string> result = testling->getAvatarHash(user1); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(std::string(), *result); - } - - - void testVCardUpdateTriggersUpdate() { - boost::shared_ptr<VCardAvatarManager> testling = createManager(); - vcardManager->requestVCard(user1); - sendVCardResult(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - } - - private: - boost::shared_ptr<VCardAvatarManager> createManager() { - boost::shared_ptr<VCardAvatarManager> result(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry)); - result->onAvatarChanged.connect(boost::bind(&VCardAvatarManagerTest::handleAvatarChanged, this, _1)); - return result; - } - - void storeVCardWithPhoto(const JID& jid, const ByteArray& avatar) { - VCard::ref vcard(new VCard()); - vcard->setPhoto(avatar); - vcardStorage->setVCard(jid, vcard); - } - - void storeEmptyVCard(const JID& jid) { - VCard::ref vcard(new VCard()); - vcardStorage->setVCard(jid, vcard); - } - - void handleAvatarChanged(const JID& jid) { - changes.push_back(jid); - } - - void sendVCardResult() { - VCard::ref vcard(new VCard()); - vcard->setFullName("Foo Bar"); - stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard)); - } - - private: - struct DummyMUCRegistry : public MUCRegistry { - bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } - std::vector<JID> mucs_; - }; - - JID ownJID; - DummyStanzaChannel* stanzaChannel; - IQRouter* iqRouter; - DummyMUCRegistry* mucRegistry; - AvatarMemoryStorage* avatarStorage; - VCardManager* vcardManager; - VCardMemoryStorage* vcardStorage; - ByteArray avatar1; - std::string avatar1Hash; - std::vector<JID> changes; - JID user1; - JID user2; - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(VCardAvatarManagerTest); + CPPUNIT_TEST(testGetAvatarHashKnownAvatar); + CPPUNIT_TEST(testGetAvatarHashEmptyAvatar); + CPPUNIT_TEST(testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar); + CPPUNIT_TEST(testGetAvatarHashUnknownAvatarUnknownVCard); + CPPUNIT_TEST(testVCardUpdateTriggersUpdate); + CPPUNIT_TEST(testGetAvatarHashKnownAvatarUnknownVCard); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + ownJID = JID("foo@fum.com/bum"); + stanzaChannel = new DummyStanzaChannel(); + stanzaChannel->setAvailable(true); + iqRouter = new IQRouter(stanzaChannel); + mucRegistry = new DummyMUCRegistry(); + avatarStorage = new AvatarMemoryStorage(); + vcardStorage = new VCardMemoryStorage(crypto.get()); + vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage); + avatar1 = createByteArray("abcdefg"); + avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1)); + user1 = JID("user1@bar.com/bla"); + user2 = JID("user2@foo.com/baz"); + } + + void tearDown() { + delete vcardManager; + delete vcardStorage; + delete avatarStorage; + delete mucRegistry; + delete iqRouter; + delete stanzaChannel; + } + + void testGetAvatarHashKnownAvatar() { + boost::shared_ptr<VCardAvatarManager> testling = createManager(); + storeVCardWithPhoto(user1.toBare(), avatar1); + avatarStorage->addAvatar(avatar1Hash, avatar1); + + boost::optional<std::string> result = testling->getAvatarHash(user1); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result); + } + + void testGetAvatarHashEmptyAvatar() { + boost::shared_ptr<VCardAvatarManager> testling = createManager(); + storeEmptyVCard(user1.toBare()); + + boost::optional<std::string> result = testling->getAvatarHash(user1); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(std::string(), *result); + } + + void testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar() { + boost::shared_ptr<VCardAvatarManager> testling = createManager(); + storeVCardWithPhoto(user1.toBare(), avatar1); + + boost::optional<std::string> result = testling->getAvatarHash(user1); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result); + CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash)); + CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash)); + } + + void testGetAvatarHashUnknownAvatarUnknownVCard() { + boost::shared_ptr<VCardAvatarManager> testling = createManager(); + + boost::optional<std::string> result = testling->getAvatarHash(user1); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(std::string(), *result); + } + + void testGetAvatarHashKnownAvatarUnknownVCard() { + boost::shared_ptr<VCardAvatarManager> testling = createManager(); + + avatarStorage->setAvatarForJID(user1, avatar1Hash); + + boost::optional<std::string> result = testling->getAvatarHash(user1); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(std::string(), *result); + } + + + void testVCardUpdateTriggersUpdate() { + boost::shared_ptr<VCardAvatarManager> testling = createManager(); + vcardManager->requestVCard(user1); + sendVCardResult(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + } + + private: + boost::shared_ptr<VCardAvatarManager> createManager() { + boost::shared_ptr<VCardAvatarManager> result(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry)); + result->onAvatarChanged.connect(boost::bind(&VCardAvatarManagerTest::handleAvatarChanged, this, _1)); + return result; + } + + void storeVCardWithPhoto(const JID& jid, const ByteArray& avatar) { + VCard::ref vcard(new VCard()); + vcard->setPhoto(avatar); + vcardStorage->setVCard(jid, vcard); + } + + void storeEmptyVCard(const JID& jid) { + VCard::ref vcard(new VCard()); + vcardStorage->setVCard(jid, vcard); + } + + void handleAvatarChanged(const JID& jid) { + changes.push_back(jid); + } + + void sendVCardResult() { + VCard::ref vcard(new VCard()); + vcard->setFullName("Foo Bar"); + stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard)); + } + + private: + struct DummyMUCRegistry : public MUCRegistry { + bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } + std::vector<JID> mucs_; + }; + + JID ownJID; + DummyStanzaChannel* stanzaChannel; + IQRouter* iqRouter; + DummyMUCRegistry* mucRegistry; + AvatarMemoryStorage* avatarStorage; + VCardManager* vcardManager; + VCardMemoryStorage* vcardStorage; + ByteArray avatar1; + std::string avatar1Hash; + std::vector<JID> changes; + JID user1; + JID user2; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(VCardAvatarManagerTest); diff --git a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp index f9747a1..5f6c691 100644 --- a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp +++ b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp @@ -27,186 +27,186 @@ using namespace Swift; class VCardUpdateAvatarManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(VCardUpdateAvatarManagerTest); - CPPUNIT_TEST(testUpdate_NewHashNewVCardRequestsVCard); - CPPUNIT_TEST(testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive); - CPPUNIT_TEST(testUpdate_KnownHash); - CPPUNIT_TEST(testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification); - CPPUNIT_TEST(testVCardWithEmptyPhoto); - CPPUNIT_TEST(testStanzaChannelReset_ClearsHash); - CPPUNIT_TEST(testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - ownJID = JID("foo@fum.com/bum"); - stanzaChannel = new DummyStanzaChannel(); - stanzaChannel->setAvailable(true); - iqRouter = new IQRouter(stanzaChannel); - mucRegistry = new DummyMUCRegistry(); - avatarStorage = new AvatarMemoryStorage(); - vcardStorage = new VCardMemoryStorage(crypto.get()); - vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage); - avatar1 = createByteArray("abcdefg"); - avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1)); - user1 = JID("user1@bar.com/bla"); - user2 = JID("user2@foo.com/baz"); - } - - - void tearDown() { - delete vcardManager; - delete vcardStorage; - delete avatarStorage; - delete mucRegistry; - delete iqRouter; - delete stanzaChannel; - } - - void testUpdate_NewHashNewVCardRequestsVCard() { - boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size())); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, user1.toBare(), IQ::Get)); - } - - void testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive() { - boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - stanzaChannel->onIQReceived(createVCardResult(avatar1)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); - boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare()); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash); - CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash)); - CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash)); - } - - void testUpdate_KnownHash() { - boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - stanzaChannel->onIQReceived(createVCardResult(avatar1)); - changes.clear(); - stanzaChannel->sentStanzas.clear(); - - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); - } - - void testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification() { - boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - stanzaChannel->onIQReceived(createVCardResult(avatar1)); - changes.clear(); - stanzaChannel->sentStanzas.clear(); - - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user2, avatar1Hash)); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user2.toBare(), changes[0]); - boost::optional<std::string> hash = testling->getAvatarHash(user2.toBare()); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash); - } - - void testVCardWithEmptyPhoto() { - boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); - vcardManager->requestVCard(JID("foo@bar.com")); - stanzaChannel->onIQReceived(createVCardResult(ByteArray())); - - CPPUNIT_ASSERT(!avatarStorage->hasAvatar(Hexify::hexify(crypto->getSHA1Hash(ByteArray())))); - boost::optional<std::string> hash = testling->getAvatarHash(JID("foo@bar.com")); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(std::string(), *hash); - } - - void testStanzaChannelReset_ClearsHash() { - boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - stanzaChannel->onIQReceived(createVCardResult(avatar1)); - changes.clear(); - stanzaChannel->sentStanzas.clear(); - - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); - boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare()); - CPPUNIT_ASSERT(!hash); - //CPPUNIT_ASSERT_EQUAL(std::string(""), *hash); - } - - void testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash() { - boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - stanzaChannel->onIQReceived(createVCardResult(avatar1)); - changes.clear(); - stanzaChannel->sentStanzas.clear(); - - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]); - boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare()); - CPPUNIT_ASSERT(hash); - CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash); - } - - private: - boost::shared_ptr<VCardUpdateAvatarManager> createManager() { - boost::shared_ptr<VCardUpdateAvatarManager> result(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry)); - result->onAvatarChanged.connect(boost::bind(&VCardUpdateAvatarManagerTest::handleAvatarChanged, this, _1)); - return result; - } - - boost::shared_ptr<Presence> createPresenceWithPhotoHash(const JID& jid, const std::string& hash) { - boost::shared_ptr<Presence> presence(new Presence()); - presence->setFrom(jid); - presence->addPayload(boost::make_shared<VCardUpdate>(hash)); - return presence; - } - - IQ::ref createVCardResult(const ByteArray& avatar) { - VCard::ref vcard(new VCard()); - if (!avatar.empty()) { - vcard->setPhoto(avatar); - } - return IQ::createResult(JID("baz@fum.com"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard); - } - - void handleAvatarChanged(const JID& jid) { - changes.push_back(jid); - } - - private: - struct DummyMUCRegistry : public MUCRegistry { - bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } - std::vector<JID> mucs_; - }; - - JID ownJID; - DummyStanzaChannel* stanzaChannel; - IQRouter* iqRouter; - DummyMUCRegistry* mucRegistry; - AvatarMemoryStorage* avatarStorage; - VCardManager* vcardManager; - VCardMemoryStorage* vcardStorage; - ByteArray avatar1; - std::string avatar1Hash; - std::vector<JID> changes; - JID user1; - JID user2; - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(VCardUpdateAvatarManagerTest); + CPPUNIT_TEST(testUpdate_NewHashNewVCardRequestsVCard); + CPPUNIT_TEST(testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive); + CPPUNIT_TEST(testUpdate_KnownHash); + CPPUNIT_TEST(testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification); + CPPUNIT_TEST(testVCardWithEmptyPhoto); + CPPUNIT_TEST(testStanzaChannelReset_ClearsHash); + CPPUNIT_TEST(testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + ownJID = JID("foo@fum.com/bum"); + stanzaChannel = new DummyStanzaChannel(); + stanzaChannel->setAvailable(true); + iqRouter = new IQRouter(stanzaChannel); + mucRegistry = new DummyMUCRegistry(); + avatarStorage = new AvatarMemoryStorage(); + vcardStorage = new VCardMemoryStorage(crypto.get()); + vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage); + avatar1 = createByteArray("abcdefg"); + avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1)); + user1 = JID("user1@bar.com/bla"); + user2 = JID("user2@foo.com/baz"); + } + + + void tearDown() { + delete vcardManager; + delete vcardStorage; + delete avatarStorage; + delete mucRegistry; + delete iqRouter; + delete stanzaChannel; + } + + void testUpdate_NewHashNewVCardRequestsVCard() { + boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size())); + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, user1.toBare(), IQ::Get)); + } + + void testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive() { + boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + stanzaChannel->onIQReceived(createVCardResult(avatar1)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); + boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare()); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash); + CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash)); + CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash)); + } + + void testUpdate_KnownHash() { + boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + stanzaChannel->onIQReceived(createVCardResult(avatar1)); + changes.clear(); + stanzaChannel->sentStanzas.clear(); + + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); + } + + void testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification() { + boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + stanzaChannel->onIQReceived(createVCardResult(avatar1)); + changes.clear(); + stanzaChannel->sentStanzas.clear(); + + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user2, avatar1Hash)); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user2.toBare(), changes[0]); + boost::optional<std::string> hash = testling->getAvatarHash(user2.toBare()); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash); + } + + void testVCardWithEmptyPhoto() { + boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); + vcardManager->requestVCard(JID("foo@bar.com")); + stanzaChannel->onIQReceived(createVCardResult(ByteArray())); + + CPPUNIT_ASSERT(!avatarStorage->hasAvatar(Hexify::hexify(crypto->getSHA1Hash(ByteArray())))); + boost::optional<std::string> hash = testling->getAvatarHash(JID("foo@bar.com")); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(std::string(), *hash); + } + + void testStanzaChannelReset_ClearsHash() { + boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + stanzaChannel->onIQReceived(createVCardResult(avatar1)); + changes.clear(); + stanzaChannel->sentStanzas.clear(); + + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]); + boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare()); + CPPUNIT_ASSERT(!hash); + //CPPUNIT_ASSERT_EQUAL(std::string(""), *hash); + } + + void testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash() { + boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager(); + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + stanzaChannel->onIQReceived(createVCardResult(avatar1)); + changes.clear(); + stanzaChannel->sentStanzas.clear(); + + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash)); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]); + boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare()); + CPPUNIT_ASSERT(hash); + CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash); + } + + private: + boost::shared_ptr<VCardUpdateAvatarManager> createManager() { + boost::shared_ptr<VCardUpdateAvatarManager> result(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry)); + result->onAvatarChanged.connect(boost::bind(&VCardUpdateAvatarManagerTest::handleAvatarChanged, this, _1)); + return result; + } + + boost::shared_ptr<Presence> createPresenceWithPhotoHash(const JID& jid, const std::string& hash) { + boost::shared_ptr<Presence> presence(new Presence()); + presence->setFrom(jid); + presence->addPayload(boost::make_shared<VCardUpdate>(hash)); + return presence; + } + + IQ::ref createVCardResult(const ByteArray& avatar) { + VCard::ref vcard(new VCard()); + if (!avatar.empty()) { + vcard->setPhoto(avatar); + } + return IQ::createResult(JID("baz@fum.com"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard); + } + + void handleAvatarChanged(const JID& jid) { + changes.push_back(jid); + } + + private: + struct DummyMUCRegistry : public MUCRegistry { + bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); } + std::vector<JID> mucs_; + }; + + JID ownJID; + DummyStanzaChannel* stanzaChannel; + IQRouter* iqRouter; + DummyMUCRegistry* mucRegistry; + AvatarMemoryStorage* avatarStorage; + VCardManager* vcardManager; + VCardMemoryStorage* vcardStorage; + ByteArray avatar1; + std::string avatar1Hash; + std::vector<JID> changes; + JID user1; + JID user2; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(VCardUpdateAvatarManagerTest); diff --git a/Swiften/Avatars/VCardAvatarManager.cpp b/Swiften/Avatars/VCardAvatarManager.cpp index 675cd00..919d833 100644 --- a/Swiften/Avatars/VCardAvatarManager.cpp +++ b/Swiften/Avatars/VCardAvatarManager.cpp @@ -19,44 +19,44 @@ namespace Swift { VCardAvatarManager::VCardAvatarManager(VCardManager* vcardManager, AvatarStorage* avatarStorage, CryptoProvider* crypto, MUCRegistry* mucRegistry) : vcardManager_(vcardManager), avatarStorage_(avatarStorage), crypto_(crypto), mucRegistry_(mucRegistry) { - vcardManager_->onVCardChanged.connect(boost::bind(&VCardAvatarManager::handleVCardChanged, this, _1)); + vcardManager_->onVCardChanged.connect(boost::bind(&VCardAvatarManager::handleVCardChanged, this, _1)); } void VCardAvatarManager::handleVCardChanged(const JID& from) { - // We don't check whether the avatar actually changed. Direct use of this - // manager could cause unnecessary updates, but in practice, this will be - // caught by the wrapping CombinedAvatarManager anyway. - onAvatarChanged(from); + // We don't check whether the avatar actually changed. Direct use of this + // manager could cause unnecessary updates, but in practice, this will be + // caught by the wrapping CombinedAvatarManager anyway. + onAvatarChanged(from); } boost::optional<std::string> VCardAvatarManager::getAvatarHash(const JID& jid) const { - JID avatarJID = getAvatarJID(jid); - std::string hash = vcardManager_->getPhotoHash(avatarJID); - if (!hash.empty()) { - if (!avatarStorage_->hasAvatar(hash)) { - VCard::ref vCard = vcardManager_->getVCard(avatarJID); - if (vCard) { - std::string newHash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto())); - if (newHash != hash) { - // Shouldn't happen, but sometimes seem to. Might be fixed if we - // move to a safer backend. - SWIFT_LOG(warning) << "Inconsistent vCard photo hash cache"; - hash = newHash; - } - avatarStorage_->addAvatar(hash, vCard->getPhoto()); - } - else { - // Can happen if the cache is inconsistent. - hash = ""; - } - } - } - return hash; + JID avatarJID = getAvatarJID(jid); + std::string hash = vcardManager_->getPhotoHash(avatarJID); + if (!hash.empty()) { + if (!avatarStorage_->hasAvatar(hash)) { + VCard::ref vCard = vcardManager_->getVCard(avatarJID); + if (vCard) { + std::string newHash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto())); + if (newHash != hash) { + // Shouldn't happen, but sometimes seem to. Might be fixed if we + // move to a safer backend. + SWIFT_LOG(warning) << "Inconsistent vCard photo hash cache"; + hash = newHash; + } + avatarStorage_->addAvatar(hash, vCard->getPhoto()); + } + else { + // Can happen if the cache is inconsistent. + hash = ""; + } + } + } + return hash; } JID VCardAvatarManager::getAvatarJID(const JID& jid) const { - JID bareFrom = jid.toBare(); - return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom; + JID bareFrom = jid.toBare(); + return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom; } } diff --git a/Swiften/Avatars/VCardAvatarManager.h b/Swiften/Avatars/VCardAvatarManager.h index d914da3..03b3afa 100644 --- a/Swiften/Avatars/VCardAvatarManager.h +++ b/Swiften/Avatars/VCardAvatarManager.h @@ -11,25 +11,25 @@ #include <Swiften/JID/JID.h> namespace Swift { - class MUCRegistry; - class AvatarStorage; - class VCardManager; - class CryptoProvider; + class MUCRegistry; + class AvatarStorage; + class VCardManager; + class CryptoProvider; - class SWIFTEN_API VCardAvatarManager : public AvatarProvider { - public: - VCardAvatarManager(VCardManager*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL); + class SWIFTEN_API VCardAvatarManager : public AvatarProvider { + public: + VCardAvatarManager(VCardManager*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL); - boost::optional<std::string> getAvatarHash(const JID&) const; + boost::optional<std::string> getAvatarHash(const JID&) const; - private: - void handleVCardChanged(const JID& from); - JID getAvatarJID(const JID& o) const; + private: + void handleVCardChanged(const JID& from); + JID getAvatarJID(const JID& o) const; - private: - VCardManager* vcardManager_; - AvatarStorage* avatarStorage_; - CryptoProvider* crypto_; - MUCRegistry* mucRegistry_; - }; + private: + VCardManager* vcardManager_; + AvatarStorage* avatarStorage_; + CryptoProvider* crypto_; + MUCRegistry* mucRegistry_; + }; } diff --git a/Swiften/Avatars/VCardUpdateAvatarManager.cpp b/Swiften/Avatars/VCardUpdateAvatarManager.cpp index 42c210d..e40eee3 100644 --- a/Swiften/Avatars/VCardUpdateAvatarManager.cpp +++ b/Swiften/Avatars/VCardUpdateAvatarManager.cpp @@ -21,84 +21,84 @@ namespace Swift { VCardUpdateAvatarManager::VCardUpdateAvatarManager(VCardManager* vcardManager, StanzaChannel* stanzaChannel, AvatarStorage* avatarStorage, CryptoProvider* crypto, MUCRegistry* mucRegistry) : vcardManager_(vcardManager), avatarStorage_(avatarStorage), crypto_(crypto), mucRegistry_(mucRegistry) { - stanzaChannel->onPresenceReceived.connect(boost::bind(&VCardUpdateAvatarManager::handlePresenceReceived, this, _1)); - stanzaChannel->onAvailableChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleStanzaChannelAvailableChanged, this, _1)); - vcardManager_->onVCardChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleVCardChanged, this, _1, _2)); + stanzaChannel->onPresenceReceived.connect(boost::bind(&VCardUpdateAvatarManager::handlePresenceReceived, this, _1)); + stanzaChannel->onAvailableChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleStanzaChannelAvailableChanged, this, _1)); + vcardManager_->onVCardChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleVCardChanged, this, _1, _2)); } void VCardUpdateAvatarManager::handlePresenceReceived(boost::shared_ptr<Presence> presence) { - boost::shared_ptr<VCardUpdate> update = presence->getPayload<VCardUpdate>(); - if (!update || presence->getPayload<ErrorPayload>()) { - return; - } - JID from = getAvatarJID(presence->getFrom()); - if (getAvatarHash(from) == update->getPhotoHash()) { - return; - } - SWIFT_LOG(debug) << "Updated hash: " << from << " -> " << update->getPhotoHash() << std::endl; - if (avatarStorage_->hasAvatar(update->getPhotoHash())) { - setAvatarHash(from, update->getPhotoHash()); - } - else { - vcardManager_->requestVCard(from); - } + boost::shared_ptr<VCardUpdate> update = presence->getPayload<VCardUpdate>(); + if (!update || presence->getPayload<ErrorPayload>()) { + return; + } + JID from = getAvatarJID(presence->getFrom()); + if (getAvatarHash(from) == update->getPhotoHash()) { + return; + } + SWIFT_LOG(debug) << "Updated hash: " << from << " -> " << update->getPhotoHash() << std::endl; + if (avatarStorage_->hasAvatar(update->getPhotoHash())) { + setAvatarHash(from, update->getPhotoHash()); + } + else { + vcardManager_->requestVCard(from); + } } void VCardUpdateAvatarManager::handleVCardChanged(const JID& from, VCard::ref vCard) { - if (!vCard) { - SWIFT_LOG(debug) << "Missing element: " << from << ": null vcard payload" << std::endl; - return; - } + if (!vCard) { + SWIFT_LOG(debug) << "Missing element: " << from << ": null vcard payload" << std::endl; + return; + } - if (vCard->getPhoto().empty()) { - setAvatarHash(from, ""); - } - else { - std::string hash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto())); - if (!avatarStorage_->hasAvatar(hash)) { - avatarStorage_->addAvatar(hash, vCard->getPhoto()); - } - setAvatarHash(from, hash); - } + if (vCard->getPhoto().empty()) { + setAvatarHash(from, ""); + } + else { + std::string hash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto())); + if (!avatarStorage_->hasAvatar(hash)) { + avatarStorage_->addAvatar(hash, vCard->getPhoto()); + } + setAvatarHash(from, hash); + } } void VCardUpdateAvatarManager::setAvatarHash(const JID& from, const std::string& hash) { - SWIFT_LOG(debug) << "Updating hash: " << from << " -> " << hash << std::endl; - avatarHashes_[from] = hash; - onAvatarChanged(from); + SWIFT_LOG(debug) << "Updating hash: " << from << " -> " << hash << std::endl; + avatarHashes_[from] = hash; + onAvatarChanged(from); } /* void VCardUpdateAvatarManager::setAvatar(const JID& jid, const ByteArray& avatar) { - std::string hash = Hexify::hexify(SHA1::getHash(avatar)); - avatarStorage_->addAvatar(hash, avatar); - setAvatarHash(getAvatarJID(jid), hash); + std::string hash = Hexify::hexify(SHA1::getHash(avatar)); + avatarStorage_->addAvatar(hash, avatar); + setAvatarHash(getAvatarJID(jid), hash); } */ boost::optional<std::string> VCardUpdateAvatarManager::getAvatarHash(const JID& jid) const { - std::map<JID, std::string>::const_iterator i = avatarHashes_.find(getAvatarJID(jid)); - if (i != avatarHashes_.end()) { - return i->second; - } - else { - return boost::optional<std::string>(); - } + std::map<JID, std::string>::const_iterator i = avatarHashes_.find(getAvatarJID(jid)); + if (i != avatarHashes_.end()) { + return i->second; + } + else { + return boost::optional<std::string>(); + } } JID VCardUpdateAvatarManager::getAvatarJID(const JID& jid) const { - JID bareFrom = jid.toBare(); - return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom; + JID bareFrom = jid.toBare(); + return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom; } void VCardUpdateAvatarManager::handleStanzaChannelAvailableChanged(bool available) { - if (available) { - std::map<JID, std::string> oldAvatarHashes; - avatarHashes_.swap(oldAvatarHashes); - for(std::map<JID, std::string>::const_iterator i = oldAvatarHashes.begin(); i != oldAvatarHashes.end(); ++i) { - onAvatarChanged(i->first); - } - } + if (available) { + std::map<JID, std::string> oldAvatarHashes; + avatarHashes_.swap(oldAvatarHashes); + for(std::map<JID, std::string>::const_iterator i = oldAvatarHashes.begin(); i != oldAvatarHashes.end(); ++i) { + onAvatarChanged(i->first); + } + } } diff --git a/Swiften/Avatars/VCardUpdateAvatarManager.h b/Swiften/Avatars/VCardUpdateAvatarManager.h index ffc615e..07fe011 100644 --- a/Swiften/Avatars/VCardUpdateAvatarManager.h +++ b/Swiften/Avatars/VCardUpdateAvatarManager.h @@ -18,30 +18,30 @@ #include <Swiften/JID/JID.h> namespace Swift { - class MUCRegistry; - class AvatarStorage; - class StanzaChannel; - class VCardManager; - class CryptoProvider; - - class SWIFTEN_API VCardUpdateAvatarManager : public AvatarProvider, public boost::bsignals::trackable { - public: - VCardUpdateAvatarManager(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL); - - boost::optional<std::string> getAvatarHash(const JID&) const; - - private: - void handlePresenceReceived(boost::shared_ptr<Presence>); - void handleStanzaChannelAvailableChanged(bool); - void handleVCardChanged(const JID& from, VCard::ref); - void setAvatarHash(const JID& from, const std::string& hash); - JID getAvatarJID(const JID& o) const; - - private: - VCardManager* vcardManager_; - AvatarStorage* avatarStorage_; - CryptoProvider* crypto_; - MUCRegistry* mucRegistry_; - std::map<JID, std::string> avatarHashes_; - }; + class MUCRegistry; + class AvatarStorage; + class StanzaChannel; + class VCardManager; + class CryptoProvider; + + class SWIFTEN_API VCardUpdateAvatarManager : public AvatarProvider, public boost::bsignals::trackable { + public: + VCardUpdateAvatarManager(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL); + + boost::optional<std::string> getAvatarHash(const JID&) const; + + private: + void handlePresenceReceived(boost::shared_ptr<Presence>); + void handleStanzaChannelAvailableChanged(bool); + void handleVCardChanged(const JID& from, VCard::ref); + void setAvatarHash(const JID& from, const std::string& hash); + JID getAvatarJID(const JID& o) const; + + private: + VCardManager* vcardManager_; + AvatarStorage* avatarStorage_; + CryptoProvider* crypto_; + MUCRegistry* mucRegistry_; + std::map<JID, std::string> avatarHashes_; + }; } diff --git a/Swiften/Base/API.h b/Swiften/Base/API.h index 729b88b..06359ba 100644 --- a/Swiften/Base/API.h +++ b/Swiften/Base/API.h @@ -10,7 +10,7 @@ #include <boost/config.hpp> #ifdef SWIFTEN_STATIC -# define SWIFTEN_API +# define SWIFTEN_API #else # ifdef SWIFTEN_PLATFORM_WINDOWS # ifdef SWIFTEN_BUILDING @@ -21,7 +21,7 @@ # elif __GNUC__ >= 4 # define SWIFTEN_API __attribute__((visibility("default"))) # else -# define SWIFTEN_API +# define SWIFTEN_API # endif #endif @@ -30,9 +30,9 @@ # define SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(cls) #else # define SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(cls) \ - cls(const cls&) = default; + cls(const cls&) = default; # define SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(cls) \ - cls& operator=(const cls&) = default; + cls& operator=(const cls&) = default; #endif #ifdef BOOST_NO_NOEXCEPT diff --git a/Swiften/Base/Algorithm.h b/Swiften/Base/Algorithm.h index 99a0053..c481aa8 100644 --- a/Swiften/Base/Algorithm.h +++ b/Swiften/Base/Algorithm.h @@ -14,142 +14,142 @@ namespace Swift { - /* - * Generic erase() - */ - namespace Detail { - struct VectorCategory {}; - struct ListCategory {}; - struct MapCategory {}; - - template<typename T> - struct ContainerTraits; - - template<typename A, typename B> - struct ContainerTraits< std::vector<A, B> > { - typedef VectorCategory Category; - }; - - template<> - struct ContainerTraits< std::string > { - typedef VectorCategory Category; - }; - - template<typename A, typename B> - struct ContainerTraits< std::list<A, B> > { - typedef ListCategory Category; - }; - - template<typename A, typename B, typename C, typename D> - struct ContainerTraits< std::map<A, B, C, D> > { - typedef MapCategory Category; - }; - - template<typename C, typename V> - void eraseImpl(C& c, const V& v, VectorCategory) { - c.erase(std::remove(c.begin(), c.end(), v), c.end()); - } - - template<typename C, typename V> - void eraseImpl(C& c, const V& v, ListCategory) { - c.remove(v); - } - - template<typename C, typename V> - void eraseImpl(C& c, const V& v, MapCategory) { - for (typename C::iterator it = c.begin(); it != c.end(); ) { - if (it->second == v) { - c.erase(it++); - } - else { - ++it; - } - } - } - - template<typename C, typename P> - void eraseIfImpl(C& c, const P& p, MapCategory) { - for (typename C::iterator it = c.begin(); it != c.end(); ) { - if (p(*it)) { - c.erase(it++); - } - else { - ++it; - } - } - } - - template<typename C, typename P> - void eraseIfImpl(C& c, const P& p, VectorCategory) { - c.erase(std::remove_if(c.begin(), c.end(), p), c.end()); - } - } - - template<typename C, typename V> - void erase(C& container, const V& value) { - Detail::eraseImpl(container, value, typename Detail::ContainerTraits<C>::Category()); - } - - template<typename C, typename P> - void eraseIf(C& container, const P& predicate) { - Detail::eraseIfImpl(container, predicate, typename Detail::ContainerTraits<C>::Category()); - } - - template<typename Source, typename Target> - void append(Target& target, const Source& source) { - target.insert(target.end(), source.begin(), source.end()); - } - - template<typename Source, typename Target> - void assign(Target& target, const Source& source) { - target.assign(source.begin(), source.end()); - } - - template<typename A, typename B, typename C, typename D> - B get(const std::map<A, B, C, D>& map, const A& key, const B& defaultValue) { - typename std::map<A, B, C, D>::const_iterator i = map.find(key); - if (i != map.end()) { - return i->second; - } - else { - return defaultValue; - } - } - - template<typename Container> - void safeClear(Container& c) { - std::fill(c.begin(), c.end(), 0); - c.clear(); - } - - /* - * Functors - */ - template<typename K, typename V> - class PairFirstEquals { - public: - PairFirstEquals(const K& value) : value(value) { - } - - bool operator()(const std::pair<K,V>& pair) const { - return pair.first == value; - } - - private: - K value; - }; - - template<typename K, typename V> - class PairSecondEquals { - public: - PairSecondEquals(const V& value) : value(value) { - } - - bool operator()(const std::pair<K,V>& pair) const { - return pair.second == value; - } - - private: - V value; - }; + /* + * Generic erase() + */ + namespace Detail { + struct VectorCategory {}; + struct ListCategory {}; + struct MapCategory {}; + + template<typename T> + struct ContainerTraits; + + template<typename A, typename B> + struct ContainerTraits< std::vector<A, B> > { + typedef VectorCategory Category; + }; + + template<> + struct ContainerTraits< std::string > { + typedef VectorCategory Category; + }; + + template<typename A, typename B> + struct ContainerTraits< std::list<A, B> > { + typedef ListCategory Category; + }; + + template<typename A, typename B, typename C, typename D> + struct ContainerTraits< std::map<A, B, C, D> > { + typedef MapCategory Category; + }; + + template<typename C, typename V> + void eraseImpl(C& c, const V& v, VectorCategory) { + c.erase(std::remove(c.begin(), c.end(), v), c.end()); + } + + template<typename C, typename V> + void eraseImpl(C& c, const V& v, ListCategory) { + c.remove(v); + } + + template<typename C, typename V> + void eraseImpl(C& c, const V& v, MapCategory) { + for (typename C::iterator it = c.begin(); it != c.end(); ) { + if (it->second == v) { + c.erase(it++); + } + else { + ++it; + } + } + } + + template<typename C, typename P> + void eraseIfImpl(C& c, const P& p, MapCategory) { + for (typename C::iterator it = c.begin(); it != c.end(); ) { + if (p(*it)) { + c.erase(it++); + } + else { + ++it; + } + } + } + + template<typename C, typename P> + void eraseIfImpl(C& c, const P& p, VectorCategory) { + c.erase(std::remove_if(c.begin(), c.end(), p), c.end()); + } + } + + template<typename C, typename V> + void erase(C& container, const V& value) { + Detail::eraseImpl(container, value, typename Detail::ContainerTraits<C>::Category()); + } + + template<typename C, typename P> + void eraseIf(C& container, const P& predicate) { + Detail::eraseIfImpl(container, predicate, typename Detail::ContainerTraits<C>::Category()); + } + + template<typename Source, typename Target> + void append(Target& target, const Source& source) { + target.insert(target.end(), source.begin(), source.end()); + } + + template<typename Source, typename Target> + void assign(Target& target, const Source& source) { + target.assign(source.begin(), source.end()); + } + + template<typename A, typename B, typename C, typename D> + B get(const std::map<A, B, C, D>& map, const A& key, const B& defaultValue) { + typename std::map<A, B, C, D>::const_iterator i = map.find(key); + if (i != map.end()) { + return i->second; + } + else { + return defaultValue; + } + } + + template<typename Container> + void safeClear(Container& c) { + std::fill(c.begin(), c.end(), 0); + c.clear(); + } + + /* + * Functors + */ + template<typename K, typename V> + class PairFirstEquals { + public: + PairFirstEquals(const K& value) : value(value) { + } + + bool operator()(const std::pair<K,V>& pair) const { + return pair.first == value; + } + + private: + K value; + }; + + template<typename K, typename V> + class PairSecondEquals { + public: + PairSecondEquals(const V& value) : value(value) { + } + + bool operator()(const std::pair<K,V>& pair) const { + return pair.second == value; + } + + private: + V value; + }; } diff --git a/Swiften/Base/Atomic.h b/Swiften/Base/Atomic.h index bca3683..9640500 100644 --- a/Swiften/Base/Atomic.h +++ b/Swiften/Base/Atomic.h @@ -12,34 +12,34 @@ namespace Swift { /** - * This class template provides a read/write access synchronized wrapper for other types. + * This class template provides a read/write access synchronized wrapper for other types. */ template <typename ValueType> class Atomic { - public: - Atomic(const ValueType& v) : value_(v) { - } - - /** - * Synchronized write access. - */ - Atomic<ValueType>& operator=(const ValueType& newValue) { - boost::lock_guard<boost::mutex> lock(valueMutex_); - value_ = newValue; - return *this; - } - - /** - * Synchronized read access. - */ - operator ValueType() { - boost::lock_guard<boost::mutex> lock(valueMutex_); - return value_; - } - - private: - boost::mutex valueMutex_; - ValueType value_; + public: + Atomic(const ValueType& v) : value_(v) { + } + + /** + * Synchronized write access. + */ + Atomic<ValueType>& operator=(const ValueType& newValue) { + boost::lock_guard<boost::mutex> lock(valueMutex_); + value_ = newValue; + return *this; + } + + /** + * Synchronized read access. + */ + operator ValueType() { + boost::lock_guard<boost::mutex> lock(valueMutex_); + return value_; + } + + private: + boost::mutex valueMutex_; + ValueType value_; }; } diff --git a/Swiften/Base/BoostRandomGenerator.cpp b/Swiften/Base/BoostRandomGenerator.cpp index 8826680..8db3ca6 100644 --- a/Swiften/Base/BoostRandomGenerator.cpp +++ b/Swiften/Base/BoostRandomGenerator.cpp @@ -15,13 +15,13 @@ namespace Swift { BoostRandomGenerator::BoostRandomGenerator() { - // FIXME: Not a good seed - generator.seed(static_cast<unsigned int>(std::time(0))); + // FIXME: Not a good seed + generator.seed(static_cast<unsigned int>(std::time(0))); } int BoostRandomGenerator::generateRandomInteger(int maximum) { - boost::uniform_int<> distribution(0, maximum); - return distribution(generator); + boost::uniform_int<> distribution(0, maximum); + return distribution(generator); } } diff --git a/Swiften/Base/BoostRandomGenerator.h b/Swiften/Base/BoostRandomGenerator.h index 5f1786b..ff715c3 100644 --- a/Swiften/Base/BoostRandomGenerator.h +++ b/Swiften/Base/BoostRandomGenerator.h @@ -13,13 +13,13 @@ #include <Swiften/Base/RandomGenerator.h> namespace Swift { - class SWIFTEN_API BoostRandomGenerator : public RandomGenerator { - public: - BoostRandomGenerator(); + class SWIFTEN_API BoostRandomGenerator : public RandomGenerator { + public: + BoostRandomGenerator(); - int generateRandomInteger(int max) SWIFTEN_OVERRIDE; + int generateRandomInteger(int max) SWIFTEN_OVERRIDE; - private: - boost::mt19937 generator; - }; + private: + boost::mt19937 generator; + }; } diff --git a/Swiften/Base/ByteArray.cpp b/Swiften/Base/ByteArray.cpp index 5fc0752..882421d 100644 --- a/Swiften/Base/ByteArray.cpp +++ b/Swiften/Base/ByteArray.cpp @@ -14,37 +14,37 @@ namespace Swift { static const int BUFFER_SIZE = 4096; void readByteArrayFromFile(ByteArray& data, const boost::filesystem::path& file) { - boost::filesystem::ifstream input(file, std::ios_base::in|std::ios_base::binary); - while (input.good()) { - size_t oldSize = data.size(); - data.resize(oldSize + BUFFER_SIZE); - input.read(reinterpret_cast<char*>(&data[oldSize]), BUFFER_SIZE); - data.resize(oldSize + boost::numeric_cast<size_t>(input.gcount())); - } - input.close(); + boost::filesystem::ifstream input(file, std::ios_base::in|std::ios_base::binary); + while (input.good()) { + size_t oldSize = data.size(); + data.resize(oldSize + BUFFER_SIZE); + input.read(reinterpret_cast<char*>(&data[oldSize]), BUFFER_SIZE); + data.resize(oldSize + boost::numeric_cast<size_t>(input.gcount())); + } + input.close(); } std::vector<unsigned char> createByteArray(const std::string& s) { - return std::vector<unsigned char>(s.begin(), s.end()); + return std::vector<unsigned char>(s.begin(), s.end()); } std::vector<unsigned char> createByteArray(const char* c) { - std::vector<unsigned char> data; - while (*c) { - data.push_back(static_cast<unsigned char>(*c)); - ++c; - } - return data; + std::vector<unsigned char> data; + while (*c) { + data.push_back(static_cast<unsigned char>(*c)); + ++c; + } + return data; } std::string byteArrayToString(const ByteArray& b) { - size_t i; - for (i = b.size(); i > 0; --i) { - if (b[i - 1] != 0) { - break; - } - } - return i > 0 ? std::string(reinterpret_cast<const char*>(vecptr(b)), i) : ""; + size_t i; + for (i = b.size(); i > 0; --i) { + if (b[i - 1] != 0) { + break; + } + } + return i > 0 ? std::string(reinterpret_cast<const char*>(vecptr(b)), i) : ""; } } diff --git a/Swiften/Base/ByteArray.h b/Swiften/Base/ByteArray.h index 75f184a..c0babdf 100644 --- a/Swiften/Base/ByteArray.h +++ b/Swiften/Base/ByteArray.h @@ -14,35 +14,35 @@ #include <Swiften/Base/API.h> namespace Swift { - typedef std::vector<unsigned char> ByteArray; + typedef std::vector<unsigned char> ByteArray; - SWIFTEN_API ByteArray createByteArray(const std::string& s); - SWIFTEN_API ByteArray createByteArray(const char* c); + SWIFTEN_API ByteArray createByteArray(const std::string& s); + SWIFTEN_API ByteArray createByteArray(const char* c); - inline ByteArray createByteArray(const unsigned char* c, size_t n) { - return ByteArray(c, c + n); - } + inline ByteArray createByteArray(const unsigned char* c, size_t n) { + return ByteArray(c, c + n); + } - inline ByteArray createByteArray(const char* c, size_t n) { - return ByteArray(c, c + n); - } + inline ByteArray createByteArray(const char* c, size_t n) { + return ByteArray(c, c + n); + } - inline ByteArray createByteArray(char c) { - return std::vector<unsigned char>(1, static_cast<unsigned char>(c)); - } + inline ByteArray createByteArray(char c) { + return std::vector<unsigned char>(1, static_cast<unsigned char>(c)); + } - template<typename T, typename A> - static const T* vecptr(const std::vector<T, A>& v) { - return v.empty() ? NULL : &v[0]; - } + template<typename T, typename A> + static const T* vecptr(const std::vector<T, A>& v) { + return v.empty() ? NULL : &v[0]; + } - template<typename T, typename A> - static T* vecptr(std::vector<T, A>& v) { - return v.empty() ? NULL : &v[0]; - } - - SWIFTEN_API std::string byteArrayToString(const ByteArray& b); + template<typename T, typename A> + static T* vecptr(std::vector<T, A>& v) { + return v.empty() ? NULL : &v[0]; + } - SWIFTEN_API void readByteArrayFromFile(ByteArray&, const boost::filesystem::path& file); + SWIFTEN_API std::string byteArrayToString(const ByteArray& b); + + SWIFTEN_API void readByteArrayFromFile(ByteArray&, const boost::filesystem::path& file); } diff --git a/Swiften/Base/Concat.h b/Swiften/Base/Concat.h index 1d158d5..df5d77b 100644 --- a/Swiften/Base/Concat.h +++ b/Swiften/Base/Concat.h @@ -9,67 +9,67 @@ #include <algorithm> namespace Swift { - template<typename C> - C concat(const C& c1, const C& c2) { - C result; - result.resize(c1.size() + c2.size()); - std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2) { + C result; + result.resize(c1.size() + c2.size()); + std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())); + return result; + } - template<typename C> - C concat(const C& c1, const C& c2, const C& c3) { - C result; - result.resize(c1.size() + c2.size() + c3.size()); - std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2, const C& c3) { + C result; + result.resize(c1.size() + c2.size() + c3.size()); + std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))); + return result; + } - template<typename C> - C concat(const C& c1, const C& c2, const C& c3, const C& c4) { - C result; - result.resize(c1.size() + c2.size() + c3.size() + c4.size()); - std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2, const C& c3, const C& c4) { + C result; + result.resize(c1.size() + c2.size() + c3.size() + c4.size()); + std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))); + return result; + } - template<typename C> - C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5) { - C result; - result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size()); - std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5) { + C result; + result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size()); + std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))); + return result; + } - template<typename C> - C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6) { - C result; - result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size()); - std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6) { + C result; + result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size()); + std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))); + return result; + } - template<typename C> - C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7) { - C result; - result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size()); - std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))))); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7) { + C result; + result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size()); + std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))))); + return result; + } - template<typename C> - C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8) { - C result; - result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size()); - std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))))); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8) { + C result; + result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size()); + std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))))); + return result; + } - template<typename C> - C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8, const C& c9) { - C result; - result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size() + c9.size()); - std::copy(c9.begin(), c9.end(), std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))))))); - return result; - } + template<typename C> + C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8, const C& c9) { + C result; + result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size() + c9.size()); + std::copy(c9.begin(), c9.end(), std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))))))); + return result; + } } diff --git a/Swiften/Base/DateTime.cpp b/Swiften/Base/DateTime.cpp index 9ca5fac..4443566 100644 --- a/Swiften/Base/DateTime.cpp +++ b/Swiften/Base/DateTime.cpp @@ -19,30 +19,30 @@ namespace Swift { boost::posix_time::ptime stringToDateTime(const std::string& string) { - static std::locale locale(std::locale::classic(), new boost::local_time::local_time_input_facet("%Y-%m-%d %H:%M:%S%F%ZP")); - std::istringstream stream(string); - stream.imbue(locale); - boost::local_time::local_date_time result(boost::date_time::not_a_date_time); - stream >> result; - return result.utc_time(); + static std::locale locale(std::locale::classic(), new boost::local_time::local_time_input_facet("%Y-%m-%d %H:%M:%S%F%ZP")); + std::istringstream stream(string); + stream.imbue(locale); + boost::local_time::local_date_time result(boost::date_time::not_a_date_time); + stream >> result; + return result.utc_time(); } std::string dateTimeToString(const boost::posix_time::ptime& time) { - std::string stampString = std::string(boost::posix_time::to_iso_extended_string(time)); - String::replaceAll(stampString, ',', "."); - stampString += "Z"; - return stampString; + std::string stampString = std::string(boost::posix_time::to_iso_extended_string(time)); + String::replaceAll(stampString, ',', "."); + stampString += "Z"; + return stampString; } std::string dateTimeToLocalString(const boost::posix_time::ptime& time) { - std::string localString; - try { - localString = boost::posix_time::to_simple_string(boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(time)); - } - catch(std::out_of_range& exception) { - SWIFT_LOG(debug) << exception.what() << std::endl; - } - return localString; + std::string localString; + try { + localString = boost::posix_time::to_simple_string(boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(time)); + } + catch(std::out_of_range& exception) { + SWIFT_LOG(debug) << exception.what() << std::endl; + } + return localString; } } diff --git a/Swiften/Base/DateTime.h b/Swiften/Base/DateTime.h index 8f07982..36cff65 100644 --- a/Swiften/Base/DateTime.h +++ b/Swiften/Base/DateTime.h @@ -11,19 +11,19 @@ #include <Swiften/Base/API.h> namespace Swift { - /** - * Converts a date formatted according to XEP-0082 into a ptime - * object (in UTC). - */ - SWIFTEN_API boost::posix_time::ptime stringToDateTime(const std::string& string); + /** + * Converts a date formatted according to XEP-0082 into a ptime + * object (in UTC). + */ + SWIFTEN_API boost::posix_time::ptime stringToDateTime(const std::string& string); - /** - * Converts a UTC ptime object to a XEP-0082 formatted string. - */ - SWIFTEN_API std::string dateTimeToString(const boost::posix_time::ptime& time); + /** + * Converts a UTC ptime object to a XEP-0082 formatted string. + */ + SWIFTEN_API std::string dateTimeToString(const boost::posix_time::ptime& time); - /** - * Converts a UTC ptime object to a localized human readable string. - */ - SWIFTEN_API std::string dateTimeToLocalString(const boost::posix_time::ptime& time); + /** + * Converts a UTC ptime object to a localized human readable string. + */ + SWIFTEN_API std::string dateTimeToLocalString(const boost::posix_time::ptime& time); } diff --git a/Swiften/Base/Debug.cpp b/Swiften/Base/Debug.cpp index 82dbec6..2d306d5 100644 --- a/Swiften/Base/Debug.cpp +++ b/Swiften/Base/Debug.cpp @@ -16,126 +16,126 @@ #include <Swiften/Serializer/XMPPSerializer.h> std::ostream& operator<<(std::ostream& os, const Swift::ClientError& error) { - os << "ClientError("; - switch(error.getType()) { - case Swift::ClientError::UnknownError: - os << "UnknownError"; - break; - case Swift::ClientError::DomainNameResolveError: - os << "DomainNameResolveError"; - break; - case Swift::ClientError::ConnectionError: - os << "ConnectionError"; - break; - case Swift::ClientError::ConnectionReadError: - os << "ConnectionReadError"; - break; - case Swift::ClientError::ConnectionWriteError: - os << "ConnectionWriteError"; - break; - case Swift::ClientError::XMLError: - os << "XMLError"; - break; - case Swift::ClientError::AuthenticationFailedError: - os << "AuthenticationFailedError"; - break; - case Swift::ClientError::CompressionFailedError: - os << "CompressionFailedError"; - break; - case Swift::ClientError::ServerVerificationFailedError: - os << "ServerVerificationFailedError"; - break; - case Swift::ClientError::NoSupportedAuthMechanismsError: - os << "NoSupportedAuthMechanismsError"; - break; - case Swift::ClientError::UnexpectedElementError: - os << "UnexpectedElementError"; - break; - case Swift::ClientError::ResourceBindError: - os << "ResourceBindError"; - break; - case Swift::ClientError::SessionStartError: - os << "SessionStartError"; - break; - case Swift::ClientError::StreamError: - os << "StreamError"; - break; - case Swift::ClientError::TLSError: - os << "TLSError"; - break; - case Swift::ClientError::ClientCertificateLoadError: - os << "ClientCertificateLoadError"; - break; - case Swift::ClientError::ClientCertificateError: - os << "ClientCertificateError"; - break; - case Swift::ClientError::CertificateCardRemoved: - os << "CertificateCardRemoved"; - break; - case Swift::ClientError::UnknownCertificateError: - os << "UnknownCertificateError"; - break; - case Swift::ClientError::CertificateExpiredError: - os << "CertificateExpiredError"; - break; - case Swift::ClientError::CertificateNotYetValidError: - os << "CertificateNotYetValidError"; - break; - case Swift::ClientError::CertificateSelfSignedError: - os << "CertificateSelfSignedError"; - break; - case Swift::ClientError::CertificateRejectedError: - os << "CertificateRejectedError"; - break; - case Swift::ClientError::CertificateUntrustedError: - os << "CertificateUntrustedError"; - break; - case Swift::ClientError::InvalidCertificatePurposeError: - os << "InvalidCertificatePurposeError"; - break; - case Swift::ClientError::CertificatePathLengthExceededError: - os << "CertificatePathLengthExceededError"; - break; - case Swift::ClientError::InvalidCertificateSignatureError: - os << "InvalidCertificateSignatureError"; - break; - case Swift::ClientError::InvalidCAError: - os << "InvalidCAError"; - break; - case Swift::ClientError::InvalidServerIdentityError: - os << "InvalidServerIdentityError"; - break; - case Swift::ClientError::RevokedError: - os << "RevokedError"; - break; - case Swift::ClientError::RevocationCheckFailedError: - os << "RevocationCheckFailedError"; - break; - } - os << ")"; - return os; + os << "ClientError("; + switch(error.getType()) { + case Swift::ClientError::UnknownError: + os << "UnknownError"; + break; + case Swift::ClientError::DomainNameResolveError: + os << "DomainNameResolveError"; + break; + case Swift::ClientError::ConnectionError: + os << "ConnectionError"; + break; + case Swift::ClientError::ConnectionReadError: + os << "ConnectionReadError"; + break; + case Swift::ClientError::ConnectionWriteError: + os << "ConnectionWriteError"; + break; + case Swift::ClientError::XMLError: + os << "XMLError"; + break; + case Swift::ClientError::AuthenticationFailedError: + os << "AuthenticationFailedError"; + break; + case Swift::ClientError::CompressionFailedError: + os << "CompressionFailedError"; + break; + case Swift::ClientError::ServerVerificationFailedError: + os << "ServerVerificationFailedError"; + break; + case Swift::ClientError::NoSupportedAuthMechanismsError: + os << "NoSupportedAuthMechanismsError"; + break; + case Swift::ClientError::UnexpectedElementError: + os << "UnexpectedElementError"; + break; + case Swift::ClientError::ResourceBindError: + os << "ResourceBindError"; + break; + case Swift::ClientError::SessionStartError: + os << "SessionStartError"; + break; + case Swift::ClientError::StreamError: + os << "StreamError"; + break; + case Swift::ClientError::TLSError: + os << "TLSError"; + break; + case Swift::ClientError::ClientCertificateLoadError: + os << "ClientCertificateLoadError"; + break; + case Swift::ClientError::ClientCertificateError: + os << "ClientCertificateError"; + break; + case Swift::ClientError::CertificateCardRemoved: + os << "CertificateCardRemoved"; + break; + case Swift::ClientError::UnknownCertificateError: + os << "UnknownCertificateError"; + break; + case Swift::ClientError::CertificateExpiredError: + os << "CertificateExpiredError"; + break; + case Swift::ClientError::CertificateNotYetValidError: + os << "CertificateNotYetValidError"; + break; + case Swift::ClientError::CertificateSelfSignedError: + os << "CertificateSelfSignedError"; + break; + case Swift::ClientError::CertificateRejectedError: + os << "CertificateRejectedError"; + break; + case Swift::ClientError::CertificateUntrustedError: + os << "CertificateUntrustedError"; + break; + case Swift::ClientError::InvalidCertificatePurposeError: + os << "InvalidCertificatePurposeError"; + break; + case Swift::ClientError::CertificatePathLengthExceededError: + os << "CertificatePathLengthExceededError"; + break; + case Swift::ClientError::InvalidCertificateSignatureError: + os << "InvalidCertificateSignatureError"; + break; + case Swift::ClientError::InvalidCAError: + os << "InvalidCAError"; + break; + case Swift::ClientError::InvalidServerIdentityError: + os << "InvalidServerIdentityError"; + break; + case Swift::ClientError::RevokedError: + os << "RevokedError"; + break; + case Swift::ClientError::RevocationCheckFailedError: + os << "RevocationCheckFailedError"; + break; + } + os << ")"; + return os; } std::ostream& operator<<(std::ostream& os, Swift::Element* ele) { - using namespace Swift; + using namespace Swift; - boost::shared_ptr<Element> element = boost::shared_ptr<Element>(ele); + boost::shared_ptr<Element> element = boost::shared_ptr<Element>(ele); - boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element); - if (payload) { - FullPayloadSerializerCollection payloadSerializerCollection; - PayloadSerializer *serializer = payloadSerializerCollection.getPayloadSerializer(payload); - os << "Payload(" << serializer->serialize(payload) << ")"; - return os; - } - boost::shared_ptr<ToplevelElement> topLevelElement = boost::dynamic_pointer_cast<ToplevelElement>(element); - if (topLevelElement) { - FullPayloadSerializerCollection payloadSerializerCollection; - XMPPSerializer xmppSerializer(&payloadSerializerCollection, ClientStreamType, false); - SafeByteArray serialized = xmppSerializer.serializeElement(topLevelElement); - os << "TopLevelElement(" << safeByteArrayToString(serialized) << ")"; - return os; - } - os << "Element(Unknown)"; - return os; + boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element); + if (payload) { + FullPayloadSerializerCollection payloadSerializerCollection; + PayloadSerializer *serializer = payloadSerializerCollection.getPayloadSerializer(payload); + os << "Payload(" << serializer->serialize(payload) << ")"; + return os; + } + boost::shared_ptr<ToplevelElement> topLevelElement = boost::dynamic_pointer_cast<ToplevelElement>(element); + if (topLevelElement) { + FullPayloadSerializerCollection payloadSerializerCollection; + XMPPSerializer xmppSerializer(&payloadSerializerCollection, ClientStreamType, false); + SafeByteArray serialized = xmppSerializer.serializeElement(topLevelElement); + os << "TopLevelElement(" << safeByteArrayToString(serialized) << ")"; + return os; + } + os << "Element(Unknown)"; + return os; } diff --git a/Swiften/Base/Debug.h b/Swiften/Base/Debug.h index 33d439e..18e7fb4 100644 --- a/Swiften/Base/Debug.h +++ b/Swiften/Base/Debug.h @@ -7,12 +7,12 @@ #include <iosfwd> namespace Swift { - class ClientError; - class Element; + class ClientError; + class Element; } namespace boost { - template<class T> class shared_ptr; + template<class T> class shared_ptr; } std::ostream& operator<<(std::ostream& os, const Swift::ClientError& error); diff --git a/Swiften/Base/Error.h b/Swiften/Base/Error.h index 3589bf0..d470b89 100644 --- a/Swiften/Base/Error.h +++ b/Swiften/Base/Error.h @@ -9,10 +9,10 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API Error { - public: - Error() {} - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Error) - virtual ~Error(); - }; + class SWIFTEN_API Error { + public: + Error() {} + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Error) + virtual ~Error(); + }; } diff --git a/Swiften/Base/FileSize.cpp b/Swiften/Base/FileSize.cpp index 32ab5f5..d9ab5ec 100644 --- a/Swiften/Base/FileSize.cpp +++ b/Swiften/Base/FileSize.cpp @@ -11,14 +11,14 @@ namespace Swift { std::string formatSize(const boost::uintmax_t bytes) { - static const char *siPrefix[] = {"k", "M", "G", "T", "P", "E", "Z", "Y", NULL}; - int power = 0; - double engBytes = bytes; - while (engBytes >= 1000) { - ++power; - engBytes = engBytes / 1000.0; - } - return str( boost::format("%.1lf %sB") % engBytes % (power > 0 ? siPrefix[power-1] : "") ); + static const char *siPrefix[] = {"k", "M", "G", "T", "P", "E", "Z", "Y", NULL}; + int power = 0; + double engBytes = bytes; + while (engBytes >= 1000) { + ++power; + engBytes = engBytes / 1000.0; + } + return str( boost::format("%.1lf %sB") % engBytes % (power > 0 ? siPrefix[power-1] : "") ); } } diff --git a/Swiften/Base/IDGenerator.cpp b/Swiften/Base/IDGenerator.cpp index 6e5ed88..5aa471c 100644 --- a/Swiften/Base/IDGenerator.cpp +++ b/Swiften/Base/IDGenerator.cpp @@ -17,8 +17,8 @@ IDGenerator::IDGenerator() { } std::string IDGenerator::generateID() { - static boost::uuids::random_generator generator; - return boost::lexical_cast<std::string>(generator()); + static boost::uuids::random_generator generator; + return boost::lexical_cast<std::string>(generator()); } } diff --git a/Swiften/Base/IDGenerator.h b/Swiften/Base/IDGenerator.h index d5407df..d1b5964 100644 --- a/Swiften/Base/IDGenerator.h +++ b/Swiften/Base/IDGenerator.h @@ -11,10 +11,10 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API IDGenerator { - public: - IDGenerator(); + class SWIFTEN_API IDGenerator { + public: + IDGenerator(); - std::string generateID(); - }; + std::string generateID(); + }; } diff --git a/Swiften/Base/Listenable.h b/Swiften/Base/Listenable.h index 655599a..ae83f4e 100644 --- a/Swiften/Base/Listenable.h +++ b/Swiften/Base/Listenable.h @@ -14,42 +14,42 @@ #include <Swiften/Base/API.h> namespace Swift { - template<typename T> - class SWIFTEN_API Listenable { - public: - void addListener(T* listener) { - listeners.push_back(listener); - } - - void removeListener(T* listener) { - listeners.erase(std::remove(listeners.begin(), listeners.end(), listener), listeners.end()); - } - - protected: - template<typename F> - void notifyListeners(F event) { - for (typename std::vector<T*>::iterator i = listeners.begin(); i != listeners.end(); ++i) { - event(*i); - } - } - - template<typename F, typename A1> - void notifyListeners(F f, const A1& a1) { - notifyListeners(boost::bind(f, _1, a1)); - } - - template<typename F, typename A1, typename A2> - void notifyListeners(F f, const A1& a1, const A2& a2) { - notifyListeners(boost::bind(f, _1, a1, a2)); - } - - template<typename F, typename A1, typename A2, typename A3> - void notifyListeners(F f, const A1& a1, const A2& a2, const A3& a3) { - notifyListeners(boost::bind(f, _1, a1, a2, a3)); - } - - private: - std::vector<T*> listeners; - }; + template<typename T> + class SWIFTEN_API Listenable { + public: + void addListener(T* listener) { + listeners.push_back(listener); + } + + void removeListener(T* listener) { + listeners.erase(std::remove(listeners.begin(), listeners.end(), listener), listeners.end()); + } + + protected: + template<typename F> + void notifyListeners(F event) { + for (typename std::vector<T*>::iterator i = listeners.begin(); i != listeners.end(); ++i) { + event(*i); + } + } + + template<typename F, typename A1> + void notifyListeners(F f, const A1& a1) { + notifyListeners(boost::bind(f, _1, a1)); + } + + template<typename F, typename A1, typename A2> + void notifyListeners(F f, const A1& a1, const A2& a2) { + notifyListeners(boost::bind(f, _1, a1, a2)); + } + + template<typename F, typename A1, typename A2, typename A3> + void notifyListeners(F f, const A1& a1, const A2& a2, const A3& a3) { + notifyListeners(boost::bind(f, _1, a1, a2, a3)); + } + + private: + std::vector<T*> listeners; + }; } diff --git a/Swiften/Base/Log.cpp b/Swiften/Base/Log.cpp index 4879766..0efac7e 100644 --- a/Swiften/Base/Log.cpp +++ b/Swiften/Base/Log.cpp @@ -22,30 +22,30 @@ Log::Log() { Log::~Log() { #if defined(SWIFT_ANDROID_LOGGING) && defined(__ANDROID__) - __android_log_print(ANDROID_LOG_VERBOSE, "Swift", stream.str().c_str(), 1); + __android_log_print(ANDROID_LOG_VERBOSE, "Swift", stream.str().c_str(), 1); #else - // Using stdio for thread safety (POSIX file i/o calls are guaranteed to be atomic) - fprintf(stderr, "%s", stream.str().c_str()); - fflush(stderr); + // Using stdio for thread safety (POSIX file i/o calls are guaranteed to be atomic) + fprintf(stderr, "%s", stream.str().c_str()); + fflush(stderr); #endif } std::ostringstream& Log::getStream( - Severity /*severity*/, - const std::string& severityString, - const std::string& file, - int line, - const std::string& function) { - stream << "[" << severityString << "] " << file << ":" << line << " " << function << ": "; - return stream; + Severity /*severity*/, + const std::string& severityString, + const std::string& file, + int line, + const std::string& function) { + stream << "[" << severityString << "] " << file << ":" << line << " " << function << ": "; + return stream; } Log::Severity Log::getLogLevel() { - return logLevel; + return logLevel; } void Log::setLogLevel(Severity level) { - logLevel = level; + logLevel = level; } } diff --git a/Swiften/Base/Log.h b/Swiften/Base/Log.h index 76251df..33c969d 100644 --- a/Swiften/Base/Log.h +++ b/Swiften/Base/Log.h @@ -11,34 +11,34 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API Log { - public: - enum Severity { - error, warning, info, debug - }; - - Log(); - ~Log(); - - std::ostringstream& getStream( - Severity severity, - const std::string& severityString, - const std::string& file, - int line, - const std::string& function); - - static Severity getLogLevel(); - static void setLogLevel(Severity level); - - private: - std::ostringstream stream; - }; + class SWIFTEN_API Log { + public: + enum Severity { + error, warning, info, debug + }; + + Log(); + ~Log(); + + std::ostringstream& getStream( + Severity severity, + const std::string& severityString, + const std::string& file, + int line, + const std::string& function); + + static Severity getLogLevel(); + static void setLogLevel(Severity level); + + private: + std::ostringstream stream; + }; } #define SWIFT_LOG(severity) \ - if (Log::severity > Log::getLogLevel()) ; \ - else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__) + if (Log::severity > Log::getLogLevel()) ; \ + else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__) #define SWIFT_LOG_ASSERT(test, severity) \ - if (Log::severity > Log::getLogLevel() || (test)) ; \ - else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__) << "Assertion failed: " << #test << ". " + if (Log::severity > Log::getLogLevel() || (test)) ; \ + else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__) << "Assertion failed: " << #test << ". " diff --git a/Swiften/Base/Path.cpp b/Swiften/Base/Path.cpp index 448efd8..ffee09b 100644 --- a/Swiften/Base/Path.cpp +++ b/Swiften/Base/Path.cpp @@ -13,16 +13,16 @@ using namespace Swift; boost::filesystem::path Swift::stringToPath(const std::string& path) { #ifdef SWIFTEN_PLATFORM_WINDOWS - return boost::filesystem::path(convertStringToWString(path)); + return boost::filesystem::path(convertStringToWString(path)); #else - return boost::filesystem::path(path); + return boost::filesystem::path(path); #endif } std::string Swift::pathToString(const boost::filesystem::path& path) { #ifdef SWIFTEN_PLATFORM_WINDOWS - return convertWStringToString(path.native()); + return convertWStringToString(path.native()); #else - return path.native(); + return path.native(); #endif } diff --git a/Swiften/Base/Path.h b/Swiften/Base/Path.h index 1567a1d..40141b5 100644 --- a/Swiften/Base/Path.h +++ b/Swiften/Base/Path.h @@ -13,17 +13,17 @@ #include <Swiften/Base/API.h> namespace Swift { - /** - * Creates a path for the given UTF-8 encoded string. - * This works independently of global locale settings. - */ - SWIFTEN_API boost::filesystem::path stringToPath(const std::string&); - - /** - * Returns the UTF-8 representation of the given path - * This works independently of global locale settings. - */ - SWIFTEN_API std::string pathToString(const boost::filesystem::path&); + /** + * Creates a path for the given UTF-8 encoded string. + * This works independently of global locale settings. + */ + SWIFTEN_API boost::filesystem::path stringToPath(const std::string&); + + /** + * Returns the UTF-8 representation of the given path + * This works independently of global locale settings. + */ + SWIFTEN_API std::string pathToString(const boost::filesystem::path&); } diff --git a/Swiften/Base/Paths.cpp b/Swiften/Base/Paths.cpp index c0256e5..cbb16f3 100644 --- a/Swiften/Base/Paths.cpp +++ b/Swiften/Base/Paths.cpp @@ -21,28 +21,28 @@ namespace Swift { boost::filesystem::path Paths::getExecutablePath() { #if defined(SWIFTEN_PLATFORM_MACOSX) - ByteArray path; - uint32_t size = 4096; - path.resize(size); - if (_NSGetExecutablePath(const_cast<char*>(reinterpret_cast<const char*>(vecptr(path))), &size) == 0) { - return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path(); - } + ByteArray path; + uint32_t size = 4096; + path.resize(size); + if (_NSGetExecutablePath(const_cast<char*>(reinterpret_cast<const char*>(vecptr(path))), &size) == 0) { + return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path(); + } #elif defined(SWIFTEN_PLATFORM_LINUX) - ByteArray path; - path.resize(4096); - size_t size = static_cast<size_t>(readlink("/proc/self/exe", reinterpret_cast<char*>(vecptr(path)), path.size())); - if (size > 0) { - path.resize(size); - return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path(); - } + ByteArray path; + path.resize(4096); + size_t size = static_cast<size_t>(readlink("/proc/self/exe", reinterpret_cast<char*>(vecptr(path)), path.size())); + if (size > 0) { + path.resize(size); + return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path(); + } #elif defined(SWIFTEN_PLATFORM_WINDOWS) - std::vector<wchar_t> data; - data.resize(2048); - GetModuleFileNameW(NULL, vecptr(data), data.size()); - return boost::filesystem::path( - std::wstring(vecptr(data), data.size())).parent_path(); + std::vector<wchar_t> data; + data.resize(2048); + GetModuleFileNameW(NULL, vecptr(data), data.size()); + return boost::filesystem::path( + std::wstring(vecptr(data), data.size())).parent_path(); #endif - return boost::filesystem::path(); + return boost::filesystem::path(); } } diff --git a/Swiften/Base/Paths.h b/Swiften/Base/Paths.h index 0a11b48..71b55fb 100644 --- a/Swiften/Base/Paths.h +++ b/Swiften/Base/Paths.h @@ -11,8 +11,8 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API Paths { - public: - static boost::filesystem::path getExecutablePath(); - }; + class SWIFTEN_API Paths { + public: + static boost::filesystem::path getExecutablePath(); + }; } diff --git a/Swiften/Base/RandomGenerator.h b/Swiften/Base/RandomGenerator.h index b322245..06677ec 100644 --- a/Swiften/Base/RandomGenerator.h +++ b/Swiften/Base/RandomGenerator.h @@ -11,14 +11,14 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API RandomGenerator { - public: - virtual ~RandomGenerator(); + class SWIFTEN_API RandomGenerator { + public: + virtual ~RandomGenerator(); - /** - * Generates a random integer between 0 and 'max', - * 'max' inclusive. - */ - virtual int generateRandomInteger(int max) = 0; - }; + /** + * Generates a random integer between 0 and 'max', + * 'max' inclusive. + */ + virtual int generateRandomInteger(int max) = 0; + }; } diff --git a/Swiften/Base/Regex.cpp b/Swiften/Base/Regex.cpp index bc7f3ac..7843833 100644 --- a/Swiften/Base/Regex.cpp +++ b/Swiften/Base/Regex.cpp @@ -18,20 +18,20 @@ namespace Swift { - namespace Regex { - std::string escape(const std::string& source) { - // escape regex special characters: ^.$| etc - // these need to be escaped: [\^\$\|.........] - // and then C++ requires '\' to be escaped, too.... - static const boost::regex esc("([\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\{\\}\\\\])"); - // matched character should be prepended with '\' - // replace matched special character with \\\1 - // and escape once more for C++ rules... - static const std::string rep("\\\\\\1"); - return boost::regex_replace(source, esc, rep); - } - - } + namespace Regex { + std::string escape(const std::string& source) { + // escape regex special characters: ^.$| etc + // these need to be escaped: [\^\$\|.........] + // and then C++ requires '\' to be escaped, too.... + static const boost::regex esc("([\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\{\\}\\\\])"); + // matched character should be prepended with '\' + // replace matched special character with \\\1 + // and escape once more for C++ rules... + static const std::string rep("\\\\\\1"); + return boost::regex_replace(source, esc, rep); + } + + } } - + diff --git a/Swiften/Base/Regex.h b/Swiften/Base/Regex.h index 4bffc4d..7d352c0 100644 --- a/Swiften/Base/Regex.h +++ b/Swiften/Base/Regex.h @@ -12,8 +12,8 @@ namespace Swift { - namespace Regex { - SWIFTEN_API std::string escape(const std::string& source); - } + namespace Regex { + SWIFTEN_API std::string escape(const std::string& source); + } } diff --git a/Swiften/Base/SafeAllocator.cpp b/Swiften/Base/SafeAllocator.cpp index 87d5fbe..446ed2d 100644 --- a/Swiften/Base/SafeAllocator.cpp +++ b/Swiften/Base/SafeAllocator.cpp @@ -15,12 +15,12 @@ namespace Swift { void secureZeroMemory(char* memory, size_t numberOfBytes) { #ifdef SWIFTEN_PLATFORM_WINDOWS - SecureZeroMemory(memory, numberOfBytes); + SecureZeroMemory(memory, numberOfBytes); #else - volatile char* p = memory; - for (size_t i = 0; i < numberOfBytes; ++i) { - *(p++) = 0; - } + volatile char* p = memory; + for (size_t i = 0; i < numberOfBytes; ++i) { + *(p++) = 0; + } #endif } diff --git a/Swiften/Base/SafeAllocator.h b/Swiften/Base/SafeAllocator.h index 07bec70..0369ec4 100644 --- a/Swiften/Base/SafeAllocator.h +++ b/Swiften/Base/SafeAllocator.h @@ -12,25 +12,25 @@ #include <Swiften/Base/API.h> namespace Swift { - void secureZeroMemory(char* memory, size_t numberOfBytes); - - template<typename T> - class SWIFTEN_API SafeAllocator : public std::allocator<T> { - public: - template <class U> struct rebind { - typedef SafeAllocator<U> other; - }; - - SafeAllocator() SWIFTEN_NOEXCEPT {} - SafeAllocator(const SafeAllocator&) SWIFTEN_NOEXCEPT : std::allocator<T>() {} - template <class U> SafeAllocator(const SafeAllocator<U>&) SWIFTEN_NOEXCEPT {} - ~SafeAllocator() SWIFTEN_NOEXCEPT {} - - void deallocate (T* p, size_t num) { - secureZeroMemory(reinterpret_cast<char*>(p), num); - std::allocator<T>::deallocate(p, num); - } - - SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(SafeAllocator) - }; + void secureZeroMemory(char* memory, size_t numberOfBytes); + + template<typename T> + class SWIFTEN_API SafeAllocator : public std::allocator<T> { + public: + template <class U> struct rebind { + typedef SafeAllocator<U> other; + }; + + SafeAllocator() SWIFTEN_NOEXCEPT {} + SafeAllocator(const SafeAllocator&) SWIFTEN_NOEXCEPT : std::allocator<T>() {} + template <class U> SafeAllocator(const SafeAllocator<U>&) SWIFTEN_NOEXCEPT {} + ~SafeAllocator() SWIFTEN_NOEXCEPT {} + + void deallocate (T* p, size_t num) { + secureZeroMemory(reinterpret_cast<char*>(p), num); + std::allocator<T>::deallocate(p, num); + } + + SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(SafeAllocator) + }; } diff --git a/Swiften/Base/SafeByteArray.cpp b/Swiften/Base/SafeByteArray.cpp index 9ae73f6..dd3736e 100644 --- a/Swiften/Base/SafeByteArray.cpp +++ b/Swiften/Base/SafeByteArray.cpp @@ -11,12 +11,12 @@ using namespace Swift; namespace Swift { SafeByteArray createSafeByteArray(const char* c) { - SafeByteArray data; - while (*c) { - data.push_back(static_cast<unsigned char>(*c)); - ++c; - } - return data; + SafeByteArray data; + while (*c) { + data.push_back(static_cast<unsigned char>(*c)); + ++c; + } + return data; } } diff --git a/Swiften/Base/SafeByteArray.h b/Swiften/Base/SafeByteArray.h index 77be012..f824194 100644 --- a/Swiften/Base/SafeByteArray.h +++ b/Swiften/Base/SafeByteArray.h @@ -15,46 +15,46 @@ #include <Swiften/Base/SafeAllocator.h> namespace Swift { - typedef std::vector<unsigned char, SafeAllocator<unsigned char> > SafeByteArray; + typedef std::vector<unsigned char, SafeAllocator<unsigned char> > SafeByteArray; - inline SafeByteArray createSafeByteArray(const ByteArray& a) { - return SafeByteArray(a.begin(), a.end()); - } + inline SafeByteArray createSafeByteArray(const ByteArray& a) { + return SafeByteArray(a.begin(), a.end()); + } - SWIFTEN_API SafeByteArray createSafeByteArray(const char* c); + SWIFTEN_API SafeByteArray createSafeByteArray(const char* c); - inline SafeByteArray createSafeByteArray(const std::string& s) { - return SafeByteArray(s.begin(), s.end()); - } + inline SafeByteArray createSafeByteArray(const std::string& s) { + return SafeByteArray(s.begin(), s.end()); + } - inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const std::string& s) { - return boost::make_shared<SafeByteArray>(s.begin(), s.end()); - } + inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const std::string& s) { + return boost::make_shared<SafeByteArray>(s.begin(), s.end()); + } - inline SafeByteArray createSafeByteArray(char c) { - return SafeByteArray(1, static_cast<unsigned char>(c)); - } + inline SafeByteArray createSafeByteArray(char c) { + return SafeByteArray(1, static_cast<unsigned char>(c)); + } - inline SafeByteArray createSafeByteArray(const char* c, size_t n) { - return SafeByteArray(c, c + n); - } + inline SafeByteArray createSafeByteArray(const char* c, size_t n) { + return SafeByteArray(c, c + n); + } - inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const char* c, size_t n) { - return boost::make_shared<SafeByteArray>(c, c + n); - } + inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const char* c, size_t n) { + return boost::make_shared<SafeByteArray>(c, c + n); + } - inline SafeByteArray createSafeByteArray(const unsigned char* c, size_t n) { - return SafeByteArray(c, c + n); - } + inline SafeByteArray createSafeByteArray(const unsigned char* c, size_t n) { + return SafeByteArray(c, c + n); + } - inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const unsigned char* c, size_t n) { - return boost::make_shared<SafeByteArray>(c, c + n); - } + inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const unsigned char* c, size_t n) { + return boost::make_shared<SafeByteArray>(c, c + n); + } - /* WARNING! This breaks the safety of the data in the safe byte array. - * Do not use in modes that require data safety. */ - inline std::string safeByteArrayToString(const SafeByteArray& b) { - return byteArrayToString(ByteArray(b.begin(), b.end())); - } + /* WARNING! This breaks the safety of the data in the safe byte array. + * Do not use in modes that require data safety. */ + inline std::string safeByteArrayToString(const SafeByteArray& b) { + return byteArrayToString(ByteArray(b.begin(), b.end())); + } } diff --git a/Swiften/Base/SafeString.h b/Swiften/Base/SafeString.h index bb5f64f..5e54537 100644 --- a/Swiften/Base/SafeString.h +++ b/Swiften/Base/SafeString.h @@ -10,24 +10,24 @@ #include <Swiften/Base/SafeByteArray.h> namespace Swift { - class SWIFTEN_API SafeString { - public: - SafeString(const SafeByteArray& data) : data(data) { - } + class SWIFTEN_API SafeString { + public: + SafeString(const SafeByteArray& data) : data(data) { + } - SafeString(const std::string& s) { - data = createSafeByteArray(s); - } + SafeString(const std::string& s) { + data = createSafeByteArray(s); + } - SafeString(const char* s) { - data = createSafeByteArray(s); - } + SafeString(const char* s) { + data = createSafeByteArray(s); + } - operator SafeByteArray () const { - return data; - } + operator SafeByteArray () const { + return data; + } - private: - SafeByteArray data; - }; + private: + SafeByteArray data; + }; } diff --git a/Swiften/Base/SimpleIDGenerator.cpp b/Swiften/Base/SimpleIDGenerator.cpp index 97d59f9..072dd39 100644 --- a/Swiften/Base/SimpleIDGenerator.cpp +++ b/Swiften/Base/SimpleIDGenerator.cpp @@ -12,23 +12,23 @@ SimpleIDGenerator::SimpleIDGenerator() { } std::string SimpleIDGenerator::generateID() { - bool carry = true; - size_t i = 0; - while (carry && i < currentID.size()) { - char c = currentID[i]; - if (c >= 'z') { - currentID[i] = 'a'; - } - else { - currentID[i] = c+1; - carry = false; - } - ++i; - } - if (carry) { - currentID += 'a'; - } - return currentID; + bool carry = true; + size_t i = 0; + while (carry && i < currentID.size()) { + char c = currentID[i]; + if (c >= 'z') { + currentID[i] = 'a'; + } + else { + currentID[i] = c+1; + carry = false; + } + ++i; + } + if (carry) { + currentID += 'a'; + } + return currentID; } } diff --git a/Swiften/Base/SimpleIDGenerator.h b/Swiften/Base/SimpleIDGenerator.h index e4fa3f5..49ba59e 100644 --- a/Swiften/Base/SimpleIDGenerator.h +++ b/Swiften/Base/SimpleIDGenerator.h @@ -13,18 +13,18 @@ namespace Swift { - /** - * @brief The SimpleIDGenerator class implements a IDGenerator generating consecutive ID strings from - * the lower case latin alphabet. - */ + /** + * @brief The SimpleIDGenerator class implements a IDGenerator generating consecutive ID strings from + * the lower case latin alphabet. + */ - class SWIFTEN_API SimpleIDGenerator : public IDGenerator { - public: - SimpleIDGenerator(); + class SWIFTEN_API SimpleIDGenerator : public IDGenerator { + public: + SimpleIDGenerator(); - std::string generateID(); + std::string generateID(); - private: - std::string currentID; - }; + private: + std::string currentID; + }; } diff --git a/Swiften/Base/StartStopper.h b/Swiften/Base/StartStopper.h index 1808861..af1a72d 100644 --- a/Swiften/Base/StartStopper.h +++ b/Swiften/Base/StartStopper.h @@ -7,17 +7,17 @@ #pragma once namespace Swift { - template<typename T> class StartStopper { - public: - StartStopper(T* target) : target(target) { - target->start(); - } + template<typename T> class StartStopper { + public: + StartStopper(T* target) : target(target) { + target->start(); + } - ~StartStopper() { - target->stop(); - } - - private: - T* target; - }; + ~StartStopper() { + target->stop(); + } + + private: + T* target; + }; } diff --git a/Swiften/Base/String.cpp b/Swiften/Base/String.cpp index 5807957..91128ff 100644 --- a/Swiften/Base/String.cpp +++ b/Swiften/Base/String.cpp @@ -20,133 +20,133 @@ namespace Swift { static inline size_t sequenceLength(char firstByte) { - if ((firstByte & 0x80) == 0) { - return 1; - } - if ((firstByte & 0xE0) == 0xC0) { - return 2; - } - if ((firstByte & 0xF0) == 0xE0) { - return 3; - } - if ((firstByte & 0xF8) == 0xF0) { - return 4; - } - if ((firstByte & 0xFC) == 0xF8) { - return 5; - } - if ((firstByte & 0xFE) == 0xFC) { - return 6; - } - assert(false); - return 1; + if ((firstByte & 0x80) == 0) { + return 1; + } + if ((firstByte & 0xE0) == 0xC0) { + return 2; + } + if ((firstByte & 0xF0) == 0xE0) { + return 3; + } + if ((firstByte & 0xF8) == 0xF0) { + return 4; + } + if ((firstByte & 0xFC) == 0xF8) { + return 5; + } + if ((firstByte & 0xFE) == 0xFC) { + return 6; + } + assert(false); + return 1; } std::vector<unsigned int> String::getUnicodeCodePoints(const std::string& s) { - std::vector<unsigned int> result; - for (size_t i = 0; i < s.size();) { - unsigned int codePoint = 0; - char firstChar = s[i]; - size_t length = sequenceLength(firstChar); - - // First character is special - size_t firstCharBitSize = 7 - length; - if (length == 1) { - firstCharBitSize = 7; - } - codePoint = firstChar & ((1<<(firstCharBitSize+1)) - 1); - - for (size_t j = 1; j < length; ++j) { - codePoint = (codePoint<<6) | (s[i+j] & 0x3F); - } - result.push_back(codePoint); - i += length; - } - return result; + std::vector<unsigned int> result; + for (size_t i = 0; i < s.size();) { + unsigned int codePoint = 0; + char firstChar = s[i]; + size_t length = sequenceLength(firstChar); + + // First character is special + size_t firstCharBitSize = 7 - length; + if (length == 1) { + firstCharBitSize = 7; + } + codePoint = firstChar & ((1<<(firstCharBitSize+1)) - 1); + + for (size_t j = 1; j < length; ++j) { + codePoint = (codePoint<<6) | (s[i+j] & 0x3F); + } + result.push_back(codePoint); + i += length; + } + return result; } std::pair<std::string,std::string> String::getSplittedAtFirst(const std::string& s, char c) { - assert((c & 0x80) == 0); - size_t firstMatch = s.find(c); - if (firstMatch != s.npos) { - return std::make_pair(s.substr(0,firstMatch),s.substr(firstMatch+1,s.npos)); - } - else { - return std::make_pair(s, ""); - } + assert((c & 0x80) == 0); + size_t firstMatch = s.find(c); + if (firstMatch != s.npos) { + return std::make_pair(s.substr(0,firstMatch),s.substr(firstMatch+1,s.npos)); + } + else { + return std::make_pair(s, ""); + } } void String::replaceAll(std::string& src, char c, const std::string& s) { - size_t lastPos = 0; - size_t matchingIndex = 0; - while ((matchingIndex = src.find(c, lastPos)) != src.npos) { - src.replace(matchingIndex, 1, s); - lastPos = matchingIndex + s.size(); - } + size_t lastPos = 0; + size_t matchingIndex = 0; + while ((matchingIndex = src.find(c, lastPos)) != src.npos) { + src.replace(matchingIndex, 1, s); + lastPos = matchingIndex + s.size(); + } } std::vector<std::string> String::split(const std::string& s, char c) { - assert((c & 0x80) == 0); - std::vector<std::string> result; - std::string accumulator; - for (size_t i = 0; i < s.size(); ++i) { - if (s[i] == c) { - result.push_back(accumulator); - accumulator = ""; - } - else { - accumulator += s[i]; - } - } - result.push_back(accumulator); - return result; + assert((c & 0x80) == 0); + std::vector<std::string> result; + std::string accumulator; + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == c) { + result.push_back(accumulator); + accumulator = ""; + } + else { + accumulator += s[i]; + } + } + result.push_back(accumulator); + return result; } std::string String::convertIntToHexString(int h) { - std::stringstream ss; - ss << std::setbase(16); - ss << h; - return ss.str(); + std::stringstream ss; + ss << std::setbase(16); + ss << h; + return ss.str(); } int String::convertHexStringToInt(const std::string& s) { - std::stringstream ss; - int h; - ss << std::setbase(16); - ss << s; - ss >> h; - return h; + std::stringstream ss; + int h; + ss << std::setbase(16); + ss << s; + ss >> h; + return h; } #ifdef SWIFTEN_PLATFORM_WINDOWS std::string convertWStringToString(const std::wstring& s) { - int utf8Size = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, NULL, 0, NULL, NULL); - if (utf8Size < 0) { - throw std::runtime_error("Conversion error"); - } - std::vector<char> utf8Data(utf8Size); - int result = WideCharToMultiByte( - CP_UTF8, 0, s.c_str(), -1, vecptr(utf8Data), utf8Data.size(), NULL, NULL); - if (result < 0) { - throw std::runtime_error("Conversion error"); - } - return std::string(vecptr(utf8Data), utf8Size-1 /* trailing 0 character */); + int utf8Size = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, NULL, 0, NULL, NULL); + if (utf8Size < 0) { + throw std::runtime_error("Conversion error"); + } + std::vector<char> utf8Data(utf8Size); + int result = WideCharToMultiByte( + CP_UTF8, 0, s.c_str(), -1, vecptr(utf8Data), utf8Data.size(), NULL, NULL); + if (result < 0) { + throw std::runtime_error("Conversion error"); + } + return std::string(vecptr(utf8Data), utf8Size-1 /* trailing 0 character */); } std::wstring convertStringToWString(const std::string& s) { - int utf16Size = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); - if (utf16Size < 0) { - throw std::runtime_error("Conversion error"); - } - std::vector<wchar_t> utf16Data(utf16Size); - int result = MultiByteToWideChar( - CP_UTF8, 0, s.c_str(), -1, vecptr(utf16Data), utf16Data.size()); - if (result < 0) { - throw std::runtime_error("Conversion error"); - } - return std::wstring(vecptr(utf16Data), utf16Size-1 /* trailing 0 character */); + int utf16Size = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); + if (utf16Size < 0) { + throw std::runtime_error("Conversion error"); + } + std::vector<wchar_t> utf16Data(utf16Size); + int result = MultiByteToWideChar( + CP_UTF8, 0, s.c_str(), -1, vecptr(utf16Data), utf16Data.size()); + if (result < 0) { + throw std::runtime_error("Conversion error"); + } + return std::wstring(vecptr(utf16Data), utf16Size-1 /* trailing 0 character */); } #endif diff --git a/Swiften/Base/String.h b/Swiften/Base/String.h index a82df63..f19dca5 100644 --- a/Swiften/Base/String.h +++ b/Swiften/Base/String.h @@ -13,45 +13,45 @@ #include <Swiften/Base/API.h> #include <Swiften/Base/Platform.h> #define SWIFTEN_STRING_TO_CFSTRING(a) \ - CFStringCreateWithBytes(NULL, reinterpret_cast<const UInt8*>(a.c_str()), a.size(), kCFStringEncodingUTF8, false) + CFStringCreateWithBytes(NULL, reinterpret_cast<const UInt8*>(a.c_str()), a.size(), kCFStringEncodingUTF8, false) namespace Swift { - namespace String { - SWIFTEN_API std::vector<unsigned int> getUnicodeCodePoints(const std::string&); - SWIFTEN_API std::pair<std::string, std::string> getSplittedAtFirst(const std::string&, char c); - SWIFTEN_API std::vector<std::string> split(const std::string&, char c); - SWIFTEN_API void replaceAll(std::string&, char c, const std::string& s); + namespace String { + SWIFTEN_API std::vector<unsigned int> getUnicodeCodePoints(const std::string&); + SWIFTEN_API std::pair<std::string, std::string> getSplittedAtFirst(const std::string&, char c); + SWIFTEN_API std::vector<std::string> split(const std::string&, char c); + SWIFTEN_API void replaceAll(std::string&, char c, const std::string& s); - inline bool beginsWith(const std::string& s, char c) { - return s.size() > 0 && s[0] == c; - } + inline bool beginsWith(const std::string& s, char c) { + return s.size() > 0 && s[0] == c; + } - inline bool endsWith(const std::string& s, char c) { - return s.size() > 0 && s[s.size()-1] == c; - } + inline bool endsWith(const std::string& s, char c) { + return s.size() > 0 && s[s.size()-1] == c; + } - std::string convertIntToHexString(int h); - int convertHexStringToInt(const std::string& s); + std::string convertIntToHexString(int h); + int convertHexStringToInt(const std::string& s); - } + } #ifdef SWIFTEN_PLATFORM_WINDOWS - SWIFTEN_API std::string convertWStringToString(const std::wstring& s); - SWIFTEN_API std::wstring convertStringToWString(const std::string& s); + SWIFTEN_API std::string convertWStringToString(const std::wstring& s); + SWIFTEN_API std::wstring convertStringToWString(const std::string& s); #endif - class SWIFTEN_API makeString { - public: - template <typename T> makeString& operator<<(T const& v) { - stream << v; - return *this; - } + class SWIFTEN_API makeString { + public: + template <typename T> makeString& operator<<(T const& v) { + stream << v; + return *this; + } - operator std::string() const { - return stream.str(); - } + operator std::string() const { + return stream.str(); + } - private: - std::ostringstream stream; - }; + private: + std::ostringstream stream; + }; } diff --git a/Swiften/Base/URL.cpp b/Swiften/Base/URL.cpp index 28eba1e..a9a1140 100644 --- a/Swiften/Base/URL.cpp +++ b/Swiften/Base/URL.cpp @@ -11,104 +11,104 @@ namespace Swift { int URL::getPortOrDefaultPort(const URL& url) { - if (url.getPort()) { - return *url.getPort(); - } - else if (url.getScheme() == "http") { - return 80; - } - else if (url.getScheme() == "https") { - return 443; - } - else { - std::cerr << "Unknown scheme: " + url.getScheme() << std::endl; - return 80; - } + if (url.getPort()) { + return *url.getPort(); + } + else if (url.getScheme() == "http") { + return 80; + } + else if (url.getScheme() == "https") { + return 443; + } + else { + std::cerr << "Unknown scheme: " + url.getScheme() << std::endl; + return 80; + } } URL URL::fromString(const std::string& urlString) { - size_t colonIndex = urlString.find(':'); - if (colonIndex == std::string::npos) { - return URL(); - } - std::string scheme = urlString.substr(0, colonIndex); + size_t colonIndex = urlString.find(':'); + if (colonIndex == std::string::npos) { + return URL(); + } + std::string scheme = urlString.substr(0, colonIndex); - // Authority - if (urlString.size() > colonIndex + 2 && urlString[colonIndex+1] == '/' && urlString[colonIndex+2] == '/') { - size_t authorityIndex = colonIndex + 3; - size_t slashIndex = urlString.find('/', authorityIndex); - std::string authority; - std::string path; - if (slashIndex == std::string::npos) { - authority = urlString.substr(authorityIndex); - path = ""; - } - else { - authority = urlString.substr(authorityIndex, slashIndex - authorityIndex); - path = unescape(urlString.substr(slashIndex)); - } + // Authority + if (urlString.size() > colonIndex + 2 && urlString[colonIndex+1] == '/' && urlString[colonIndex+2] == '/') { + size_t authorityIndex = colonIndex + 3; + size_t slashIndex = urlString.find('/', authorityIndex); + std::string authority; + std::string path; + if (slashIndex == std::string::npos) { + authority = urlString.substr(authorityIndex); + path = ""; + } + else { + authority = urlString.substr(authorityIndex, slashIndex - authorityIndex); + path = unescape(urlString.substr(slashIndex)); + } - size_t atIndex = authority.find('@'); - std::string userInfo; - std::string hostAndPort; - if (atIndex != std::string::npos) { - userInfo = authority.substr(0, atIndex); - hostAndPort = authority.substr(atIndex + 1); - } - else { - userInfo = ""; - hostAndPort = authority; - } + size_t atIndex = authority.find('@'); + std::string userInfo; + std::string hostAndPort; + if (atIndex != std::string::npos) { + userInfo = authority.substr(0, atIndex); + hostAndPort = authority.substr(atIndex + 1); + } + else { + userInfo = ""; + hostAndPort = authority; + } - std::string host; - boost::optional<int> port; - colonIndex = hostAndPort.find(':'); - if (colonIndex != std::string::npos) { - host = unescape(hostAndPort.substr(0, colonIndex)); - try { - port = boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1)); - } - catch (const boost::bad_lexical_cast&) { - return URL(); - } - } - else { - host = unescape(hostAndPort); - } + std::string host; + boost::optional<int> port; + colonIndex = hostAndPort.find(':'); + if (colonIndex != std::string::npos) { + host = unescape(hostAndPort.substr(0, colonIndex)); + try { + port = boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1)); + } + catch (const boost::bad_lexical_cast&) { + return URL(); + } + } + else { + host = unescape(hostAndPort); + } - if (port) { - return URL(scheme, host, *port, path); - } - else { - return URL(scheme, host, path); - } - } - else { - // We don't support URLs without authorities yet - return URL(); - } + if (port) { + return URL(scheme, host, *port, path); + } + else { + return URL(scheme, host, path); + } + } + else { + // We don't support URLs without authorities yet + return URL(); + } } // FIXME: Escape non-ascii characters std::string URL::toString() const { - if (empty) { - return ""; - } - std::string result = scheme + "://"; - if (!user.empty()) { - result += user; - if (!password.empty()) { - result += ":" + password; - } - result += "@"; - } - result += host; - if (port) { - result += ":"; - result += boost::lexical_cast<std::string>(*port); - } - result += path; - return result; + if (empty) { + return ""; + } + std::string result = scheme + "://"; + if (!user.empty()) { + result += user; + if (!password.empty()) { + result += ":" + password; + } + result += "@"; + } + result += host; + if (port) { + result += ":"; + result += boost::lexical_cast<std::string>(*port); + } + result += path; + return result; } // Disabling this code for now, since GCC4.5+boost1.42 (on ubuntu) seems to @@ -118,72 +118,72 @@ std::string URL::toString() const { struct PercentEncodedCharacterFinder { template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) { - boost::iterator_range<Iterator> r = boost::first_finder("%")(begin, end); - if (r.end() == end) { - return r; - } - else { - if (r.end() + 1 == end || r.end() + 2 == end) { - throw std::runtime_error("Incomplete escape character"); - } - else { - r.advance_end(2); - return r; - } - } + boost::iterator_range<Iterator> r = boost::first_finder("%")(begin, end); + if (r.end() == end) { + return r; + } + else { + if (r.end() + 1 == end || r.end() + 2 == end) { + throw std::runtime_error("Incomplete escape character"); + } + else { + r.advance_end(2); + return r; + } + } } }; struct PercentUnencodeFormatter { template<typename FindResult> std::string operator()(const FindResult& match) const { - std::stringstream s; - s << std::hex << std::string(match.begin() + 1, match.end()); - unsigned int value; - s >> value; - if (s.fail() || s.bad()) { - throw std::runtime_error("Invalid escape character"); - } - unsigned char charValue = static_cast<unsigned char>(value); - return std::string(reinterpret_cast<const char*>(&charValue), 1); + std::stringstream s; + s << std::hex << std::string(match.begin() + 1, match.end()); + unsigned int value; + s >> value; + if (s.fail() || s.bad()) { + throw std::runtime_error("Invalid escape character"); + } + unsigned char charValue = static_cast<unsigned char>(value); + return std::string(reinterpret_cast<const char*>(&charValue), 1); } }; std::string unescape(const std::string& s) { - try { - return boost::find_format_all_copy(s, PercentEncodedCharacterFinder(), PercentUnencodeFormatter()); - } - catch (const std::exception&) { - return ""; - } + try { + return boost::find_format_all_copy(s, PercentEncodedCharacterFinder(), PercentUnencodeFormatter()); + } + catch (const std::exception&) { + return ""; + } } #endif std::string URL::unescape(const std::string& str) { - std::string result; - for (size_t i = 0; i < str.size(); ++i) { - if (str[i] == '%') { - if (i + 3 < str.size()) { - std::stringstream s; - s << std::hex << str.substr(i+1, 2); - unsigned int value; - s >> value; - if (s.fail() || s.bad()) { - return ""; - } - unsigned char charValue = static_cast<unsigned char>(value); - result += std::string(reinterpret_cast<const char*>(&charValue), 1); - i += 2; - } - else { - return ""; - } - } - else { - result += str[i]; - } - } - return result; + std::string result; + for (size_t i = 0; i < str.size(); ++i) { + if (str[i] == '%') { + if (i + 3 < str.size()) { + std::stringstream s; + s << std::hex << str.substr(i+1, 2); + unsigned int value; + s >> value; + if (s.fail() || s.bad()) { + return ""; + } + unsigned char charValue = static_cast<unsigned char>(value); + result += std::string(reinterpret_cast<const char*>(&charValue), 1); + i += 2; + } + else { + return ""; + } + } + else { + result += str[i]; + } + } + return result; } } diff --git a/Swiften/Base/URL.h b/Swiften/Base/URL.h index e172682..1a03efe 100644 --- a/Swiften/Base/URL.h +++ b/Swiften/Base/URL.h @@ -16,66 +16,66 @@ namespace Swift { class SWIFTEN_API URL { - public: - - URL() : scheme(""), user(""), password(""), host(""), path(""), empty(true) { - } - - URL(const std::string& scheme, const std::string& host, int port, const std::string& path) : scheme(scheme), user(), password(), host(host), port(port), path(path), empty(false) { - } - - URL(const std::string& scheme, const std::string& host, const std::string& path) : scheme(scheme), user(), password(), host(host), path(path), empty(false) { - } - - /** - * Whether the URL is empty. - */ - bool isEmpty() const { - return empty; - } - - /** - * Scheme used for the URL (http, https etc.) - */ - const std::string& getScheme() const { - return scheme; - } - - /** - * Hostname - */ - const std::string& getHost() const { - return host; - } - - /** - * Port number - */ - boost::optional<int> getPort() const { - return port; - } - - /** - * Path - */ - const std::string& getPath() const { - return path; - } - - std::string toString() const; - - static int getPortOrDefaultPort(const URL& url); - static URL fromString(const std::string&); - static std::string unescape(const std::string&); - - - private: - std::string scheme; - std::string user; - std::string password; - std::string host; - boost::optional<int> port; - std::string path; - bool empty; - }; + public: + + URL() : scheme(""), user(""), password(""), host(""), path(""), empty(true) { + } + + URL(const std::string& scheme, const std::string& host, int port, const std::string& path) : scheme(scheme), user(), password(), host(host), port(port), path(path), empty(false) { + } + + URL(const std::string& scheme, const std::string& host, const std::string& path) : scheme(scheme), user(), password(), host(host), path(path), empty(false) { + } + + /** + * Whether the URL is empty. + */ + bool isEmpty() const { + return empty; + } + + /** + * Scheme used for the URL (http, https etc.) + */ + const std::string& getScheme() const { + return scheme; + } + + /** + * Hostname + */ + const std::string& getHost() const { + return host; + } + + /** + * Port number + */ + boost::optional<int> getPort() const { + return port; + } + + /** + * Path + */ + const std::string& getPath() const { + return path; + } + + std::string toString() const; + + static int getPortOrDefaultPort(const URL& url); + static URL fromString(const std::string&); + static std::string unescape(const std::string&); + + + private: + std::string scheme; + std::string user; + std::string password; + std::string host; + boost::optional<int> port; + std::string path; + bool empty; + }; } diff --git a/Swiften/Base/UnitTest/ByteArrayTest.cpp b/Swiften/Base/UnitTest/ByteArrayTest.cpp index ce6b9db..2eb601b 100644 --- a/Swiften/Base/UnitTest/ByteArrayTest.cpp +++ b/Swiften/Base/UnitTest/ByteArrayTest.cpp @@ -14,44 +14,44 @@ using namespace Swift; class ByteArrayTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ByteArrayTest); - CPPUNIT_TEST(testGetData_NoData); - CPPUNIT_TEST(testToString); - CPPUNIT_TEST(testToString_NullTerminated); - CPPUNIT_TEST(testToString_TwoNullTerminated); - CPPUNIT_TEST(testToString_AllNull); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(ByteArrayTest); + CPPUNIT_TEST(testGetData_NoData); + CPPUNIT_TEST(testToString); + CPPUNIT_TEST(testToString_NullTerminated); + CPPUNIT_TEST(testToString_TwoNullTerminated); + CPPUNIT_TEST(testToString_AllNull); + CPPUNIT_TEST_SUITE_END(); - public: - void testGetData_NoData() { - ByteArray testling; + public: + void testGetData_NoData() { + ByteArray testling; - CPPUNIT_ASSERT_EQUAL(reinterpret_cast<const char*>(NULL), reinterpret_cast<const char*>(vecptr(testling))); - } + CPPUNIT_ASSERT_EQUAL(reinterpret_cast<const char*>(NULL), reinterpret_cast<const char*>(vecptr(testling))); + } - void testToString() { - ByteArray testling(createByteArray("abcde")); + void testToString() { + ByteArray testling(createByteArray("abcde")); - CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling)); - } + CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling)); + } - void testToString_NullTerminated() { - ByteArray testling(createByteArray("abcde\0", 6)); + void testToString_NullTerminated() { + ByteArray testling(createByteArray("abcde\0", 6)); - CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling)); - } + CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling)); + } - void testToString_TwoNullTerminated() { - ByteArray testling(createByteArray("abcde\0\0", 7)); + void testToString_TwoNullTerminated() { + ByteArray testling(createByteArray("abcde\0\0", 7)); - CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling)); - } + CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling)); + } - void testToString_AllNull() { - ByteArray testling(createByteArray("\0\0", 2)); + void testToString_AllNull() { + ByteArray testling(createByteArray("\0\0", 2)); - CPPUNIT_ASSERT_EQUAL(std::string(""), byteArrayToString(testling)); - } + CPPUNIT_ASSERT_EQUAL(std::string(""), byteArrayToString(testling)); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(ByteArrayTest); diff --git a/Swiften/Base/UnitTest/DateTimeTest.cpp b/Swiften/Base/UnitTest/DateTimeTest.cpp index 527e251..6a82d96 100644 --- a/Swiften/Base/UnitTest/DateTimeTest.cpp +++ b/Swiften/Base/UnitTest/DateTimeTest.cpp @@ -16,37 +16,37 @@ using namespace Swift; class DateTimeTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(DateTimeTest); - CPPUNIT_TEST(testStringToDateTime_UTC); - CPPUNIT_TEST(testStringToDateTime_WithTimezone); - CPPUNIT_TEST(testDateTimeToString); - CPPUNIT_TEST(testDateTimeToLocalStringNotThrowingException); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(DateTimeTest); + CPPUNIT_TEST(testStringToDateTime_UTC); + CPPUNIT_TEST(testStringToDateTime_WithTimezone); + CPPUNIT_TEST(testDateTimeToString); + CPPUNIT_TEST(testDateTimeToLocalStringNotThrowingException); + CPPUNIT_TEST_SUITE_END(); - public: - void testStringToDateTime_UTC() { - boost::posix_time::ptime time = stringToDateTime("1969-07-21T02:56:15Z"); + public: + void testStringToDateTime_UTC() { + boost::posix_time::ptime time = stringToDateTime("1969-07-21T02:56:15Z"); - CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time)); - } + CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time)); + } - void testStringToDateTime_WithTimezone() { - boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00"); + void testStringToDateTime_WithTimezone() { + boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00"); - CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time)); - } + CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time)); + } - void testDateTimeToString() { - boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00"); + void testDateTimeToString() { + boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00"); - CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15Z"), dateTimeToString(time)); - } + CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15Z"), dateTimeToString(time)); + } - void testDateTimeToLocalStringNotThrowingException() { - boost::posix_time::ptime time = stringToDateTime("1954-07-20T21:56:15-05:00"); + void testDateTimeToLocalStringNotThrowingException() { + boost::posix_time::ptime time = stringToDateTime("1954-07-20T21:56:15-05:00"); - CPPUNIT_ASSERT_EQUAL(std::string(""), dateTimeToLocalString(time)); - } + CPPUNIT_ASSERT_EQUAL(std::string(""), dateTimeToLocalString(time)); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(DateTimeTest); diff --git a/Swiften/Base/UnitTest/IDGeneratorTest.cpp b/Swiften/Base/UnitTest/IDGeneratorTest.cpp index d03969b..08bd48b 100644 --- a/Swiften/Base/UnitTest/IDGeneratorTest.cpp +++ b/Swiften/Base/UnitTest/IDGeneratorTest.cpp @@ -15,27 +15,27 @@ using namespace Swift; class IDGeneratorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(IDGeneratorTest); - CPPUNIT_TEST(testGenerate); - CPPUNIT_TEST_SUITE_END(); - - public: - IDGeneratorTest() {} - - void setUp() { - generatedIDs_.clear(); - } - - void testGenerate() { - IDGenerator testling; - for (unsigned int i = 0; i < 26*4; ++i) { - std::string id = testling.generateID(); - CPPUNIT_ASSERT(generatedIDs_.insert(id).second); - } - } - - private: - std::set<std::string> generatedIDs_; + CPPUNIT_TEST_SUITE(IDGeneratorTest); + CPPUNIT_TEST(testGenerate); + CPPUNIT_TEST_SUITE_END(); + + public: + IDGeneratorTest() {} + + void setUp() { + generatedIDs_.clear(); + } + + void testGenerate() { + IDGenerator testling; + for (unsigned int i = 0; i < 26*4; ++i) { + std::string id = testling.generateID(); + CPPUNIT_ASSERT(generatedIDs_.insert(id).second); + } + } + + private: + std::set<std::string> generatedIDs_; }; CPPUNIT_TEST_SUITE_REGISTRATION(IDGeneratorTest); diff --git a/Swiften/Base/UnitTest/PathTest.cpp b/Swiften/Base/UnitTest/PathTest.cpp index b22b570..dd2233b 100644 --- a/Swiften/Base/UnitTest/PathTest.cpp +++ b/Swiften/Base/UnitTest/PathTest.cpp @@ -13,23 +13,23 @@ using namespace Swift; class PathTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(PathTest); - CPPUNIT_TEST(testStringToPath); - CPPUNIT_TEST(testPathToString); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(PathTest); + CPPUNIT_TEST(testStringToPath); + CPPUNIT_TEST(testPathToString); + CPPUNIT_TEST_SUITE_END(); - public: - void testStringToPath() { + public: + void testStringToPath() { #ifdef SWIFTEN_PLATFORM_WINDOWS - CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == stringToPath("tron\xc3\xa7on").native()); + CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == stringToPath("tron\xc3\xa7on").native()); #else - CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), stringToPath("tron\xc3\xa7on").native()); + CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), stringToPath("tron\xc3\xa7on").native()); #endif - } + } - void testPathToString() { - CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), pathToString(stringToPath("tron\xc3\xa7on"))); - } + void testPathToString() { + CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), pathToString(stringToPath("tron\xc3\xa7on"))); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(PathTest); diff --git a/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp b/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp index 1c5fb2b..9b49c0a 100644 --- a/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp +++ b/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp @@ -15,27 +15,27 @@ using namespace Swift; class SimpleIDGeneratorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SimpleIDGeneratorTest); - CPPUNIT_TEST(testGenerate); - CPPUNIT_TEST_SUITE_END(); - - public: - SimpleIDGeneratorTest() {} - - void setUp() { - generatedIDs_.clear(); - } - - void testGenerate() { - SimpleIDGenerator testling; - for (unsigned int i = 0; i < 26*4; ++i) { - std::string id = testling.generateID(); - CPPUNIT_ASSERT(generatedIDs_.insert(id).second); - } - } - - private: - std::set<std::string> generatedIDs_; + CPPUNIT_TEST_SUITE(SimpleIDGeneratorTest); + CPPUNIT_TEST(testGenerate); + CPPUNIT_TEST_SUITE_END(); + + public: + SimpleIDGeneratorTest() {} + + void setUp() { + generatedIDs_.clear(); + } + + void testGenerate() { + SimpleIDGenerator testling; + for (unsigned int i = 0; i < 26*4; ++i) { + std::string id = testling.generateID(); + CPPUNIT_ASSERT(generatedIDs_.insert(id).second); + } + } + + private: + std::set<std::string> generatedIDs_; }; CPPUNIT_TEST_SUITE_REGISTRATION(SimpleIDGeneratorTest); diff --git a/Swiften/Base/UnitTest/StringTest.cpp b/Swiften/Base/UnitTest/StringTest.cpp index a17a253..e2e1665 100644 --- a/Swiften/Base/UnitTest/StringTest.cpp +++ b/Swiften/Base/UnitTest/StringTest.cpp @@ -15,115 +15,115 @@ using namespace Swift; class StringTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(StringTest); - CPPUNIT_TEST(testGetUnicodeCodePoints); - CPPUNIT_TEST(testGetSplittedAtFirst); - CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtBegin); - CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtEnd); - CPPUNIT_TEST(testGetSplittedAtFirst_NoSuchCharacter); - CPPUNIT_TEST(testReplaceAll); - CPPUNIT_TEST(testReplaceAll_LastChar); - CPPUNIT_TEST(testReplaceAll_ConsecutiveChars); - CPPUNIT_TEST(testReplaceAll_MatchingReplace); - CPPUNIT_TEST(testSplit); + CPPUNIT_TEST_SUITE(StringTest); + CPPUNIT_TEST(testGetUnicodeCodePoints); + CPPUNIT_TEST(testGetSplittedAtFirst); + CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtBegin); + CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtEnd); + CPPUNIT_TEST(testGetSplittedAtFirst_NoSuchCharacter); + CPPUNIT_TEST(testReplaceAll); + CPPUNIT_TEST(testReplaceAll_LastChar); + CPPUNIT_TEST(testReplaceAll_ConsecutiveChars); + CPPUNIT_TEST(testReplaceAll_MatchingReplace); + CPPUNIT_TEST(testSplit); #ifdef SWIFTEN_PLATFORM_WINDOWS - CPPUNIT_TEST(testConvertWStringToString); - CPPUNIT_TEST(testConvertStringToWString); + CPPUNIT_TEST(testConvertWStringToString); + CPPUNIT_TEST(testConvertStringToWString); #endif - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE_END(); - public: - void testGetUnicodeCodePoints() { - std::string testling("$\xc2\xa2\xe2\x82\xac\xf4\x8a\xaf\x8d"); - std::vector<unsigned int> points = String::getUnicodeCodePoints(testling); + public: + void testGetUnicodeCodePoints() { + std::string testling("$\xc2\xa2\xe2\x82\xac\xf4\x8a\xaf\x8d"); + std::vector<unsigned int> points = String::getUnicodeCodePoints(testling); - CPPUNIT_ASSERT_EQUAL(0x24U, points[0]); - CPPUNIT_ASSERT_EQUAL(0xA2U, points[1]); - CPPUNIT_ASSERT_EQUAL(0x20ACU, points[2]); - CPPUNIT_ASSERT_EQUAL(0x10ABCDU, points[3]); - } + CPPUNIT_ASSERT_EQUAL(0x24U, points[0]); + CPPUNIT_ASSERT_EQUAL(0xA2U, points[1]); + CPPUNIT_ASSERT_EQUAL(0x20ACU, points[2]); + CPPUNIT_ASSERT_EQUAL(0x10ABCDU, points[3]); + } - void testGetSplittedAtFirst() { - std::string testling("ab@cd@ef"); + void testGetSplittedAtFirst() { + std::string testling("ab@cd@ef"); - std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@'); - CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first); - CPPUNIT_ASSERT_EQUAL(std::string("cd@ef"), result.second); - } + std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@'); + CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first); + CPPUNIT_ASSERT_EQUAL(std::string("cd@ef"), result.second); + } - void testGetSplittedAtFirst_CharacterAtBegin() { - std::string testling(" ab"); + void testGetSplittedAtFirst_CharacterAtBegin() { + std::string testling(" ab"); - std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, ' '); - CPPUNIT_ASSERT(result.first.empty()); - CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.second); - } + std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, ' '); + CPPUNIT_ASSERT(result.first.empty()); + CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.second); + } - void testGetSplittedAtFirst_CharacterAtEnd() { - std::string testling("ab@"); + void testGetSplittedAtFirst_CharacterAtEnd() { + std::string testling("ab@"); - std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@'); - CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first); - CPPUNIT_ASSERT(result.second.empty()); - } + std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@'); + CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first); + CPPUNIT_ASSERT(result.second.empty()); + } - void testGetSplittedAtFirst_NoSuchCharacter() { - std::string testling("ab"); + void testGetSplittedAtFirst_NoSuchCharacter() { + std::string testling("ab"); - std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@'); - CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first); - CPPUNIT_ASSERT(result.second.empty()); - } + std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@'); + CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first); + CPPUNIT_ASSERT(result.second.empty()); + } - void testReplaceAll() { - std::string testling("abcbd"); + void testReplaceAll() { + std::string testling("abcbd"); - String::replaceAll(testling, 'b', "xyz"); - - CPPUNIT_ASSERT_EQUAL(std::string("axyzcxyzd"), testling); - } + String::replaceAll(testling, 'b', "xyz"); - void testReplaceAll_LastChar() { - std::string testling("abc"); + CPPUNIT_ASSERT_EQUAL(std::string("axyzcxyzd"), testling); + } - String::replaceAll(testling, 'c', "xyz"); - - CPPUNIT_ASSERT_EQUAL(std::string("abxyz"), testling); - } + void testReplaceAll_LastChar() { + std::string testling("abc"); - void testReplaceAll_ConsecutiveChars() { - std::string testling("abbc"); + String::replaceAll(testling, 'c', "xyz"); - String::replaceAll(testling, 'b',"xyz"); - - CPPUNIT_ASSERT_EQUAL(std::string("axyzxyzc"), testling); - } + CPPUNIT_ASSERT_EQUAL(std::string("abxyz"), testling); + } - void testReplaceAll_MatchingReplace() { - std::string testling("abc"); + void testReplaceAll_ConsecutiveChars() { + std::string testling("abbc"); - String::replaceAll(testling, 'b',"bbb"); - - CPPUNIT_ASSERT_EQUAL(std::string("abbbc"), testling); - } + String::replaceAll(testling, 'b',"xyz"); - void testSplit() { - std::vector<std::string> result = String::split("abc def ghi", ' '); + CPPUNIT_ASSERT_EQUAL(std::string("axyzxyzc"), testling); + } - CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(result.size())); - CPPUNIT_ASSERT_EQUAL(std::string("abc"), result[0]); - CPPUNIT_ASSERT_EQUAL(std::string("def"), result[1]); - CPPUNIT_ASSERT_EQUAL(std::string("ghi"), result[2]); - } + void testReplaceAll_MatchingReplace() { + std::string testling("abc"); + + String::replaceAll(testling, 'b',"bbb"); + + CPPUNIT_ASSERT_EQUAL(std::string("abbbc"), testling); + } + + void testSplit() { + std::vector<std::string> result = String::split("abc def ghi", ' '); + + CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(result.size())); + CPPUNIT_ASSERT_EQUAL(std::string("abc"), result[0]); + CPPUNIT_ASSERT_EQUAL(std::string("def"), result[1]); + CPPUNIT_ASSERT_EQUAL(std::string("ghi"), result[2]); + } #ifdef SWIFTEN_PLATFORM_WINDOWS - void testConvertWStringToString() { - CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), convertWStringToString(std::wstring(L"tron\xe7on"))); - } + void testConvertWStringToString() { + CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), convertWStringToString(std::wstring(L"tron\xe7on"))); + } - void testConvertStringToWString() { - CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == convertStringToWString(std::string("tron\xc3\xa7on"))); - } + void testConvertStringToWString() { + CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == convertStringToWString(std::string("tron\xc3\xa7on"))); + } #endif }; diff --git a/Swiften/Base/UnitTest/URLTest.cpp b/Swiften/Base/UnitTest/URLTest.cpp index d88269a..2d2ceba 100644 --- a/Swiften/Base/UnitTest/URLTest.cpp +++ b/Swiften/Base/UnitTest/URLTest.cpp @@ -14,102 +14,102 @@ using namespace Swift; class URLTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(URLTest); - CPPUNIT_TEST(testFromString); - CPPUNIT_TEST(testFromString_WithoutPath); - CPPUNIT_TEST(testFromString_WithRootPath); - CPPUNIT_TEST(testFromString_WithPort); - CPPUNIT_TEST(testFromString_WithPortOnePartPath); - CPPUNIT_TEST(testFromString_WithPortWithoutPath); - CPPUNIT_TEST(testFromString_WithUserInfo); - CPPUNIT_TEST(testFromString_NonASCIIHost); - CPPUNIT_TEST(testFromString_NonASCIIPath); - CPPUNIT_TEST(testToString); - CPPUNIT_TEST(testToString_WithPort); - CPPUNIT_TEST_SUITE_END(); - - public: - void testFromString() { - URL url = URL::fromString("http://foo.bar/baz/bam"); - - CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); - CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT(!url.getPort()); - CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); - } - - void testFromString_WithoutPath() { - URL url = URL::fromString("http://foo.bar"); - - CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); - CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT(!url.getPort()); - CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath()); - } - - void testFromString_WithRootPath() { - URL url = URL::fromString("http://foo.bar/"); - - CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); - CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT(!url.getPort()); - CPPUNIT_ASSERT_EQUAL(std::string("/"), url.getPath()); - } - - void testFromString_WithPort() { - URL url = URL::fromString("http://foo.bar:1234/baz/bam"); - - CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); - CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(1234, *url.getPort()); - CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); - } - - void testFromString_WithPortOnePartPath() { - URL url = URL::fromString("http://foo.bar:11440/http-bind/"); - - CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); - CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(11440, *url.getPort()); - CPPUNIT_ASSERT_EQUAL(std::string("/http-bind/"), url.getPath()); - } - - void testFromString_WithPortWithoutPath() { - URL url = URL::fromString("http://foo.bar:1234"); - - CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); - CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(1234, *url.getPort()); - CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath()); - } - - void testFromString_WithUserInfo() { - URL url = URL::fromString("http://user:pass@foo.bar/baz/bam"); - - CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); - CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); - } - - void testFromString_NonASCIIHost() { - URL url = URL::fromString("http://www.tron%C3%A7on.be/baz/bam"); - - CPPUNIT_ASSERT_EQUAL(std::string("www.tron\xc3\xa7on.be"), url.getHost()); - } - - void testFromString_NonASCIIPath() { - URL url = URL::fromString("http://foo.bar/baz/tron%C3%A7on/bam"); - - CPPUNIT_ASSERT_EQUAL(std::string("/baz/tron\xc3\xa7on/bam"), url.getPath()); - } - - void testToString() { - CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar/baz/bam"), URL("http", "foo.bar", "/baz/bam").toString()); - } - - void testToString_WithPort() { - CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar:1234/baz/bam"), URL("http", "foo.bar", 1234, "/baz/bam").toString()); - } + CPPUNIT_TEST_SUITE(URLTest); + CPPUNIT_TEST(testFromString); + CPPUNIT_TEST(testFromString_WithoutPath); + CPPUNIT_TEST(testFromString_WithRootPath); + CPPUNIT_TEST(testFromString_WithPort); + CPPUNIT_TEST(testFromString_WithPortOnePartPath); + CPPUNIT_TEST(testFromString_WithPortWithoutPath); + CPPUNIT_TEST(testFromString_WithUserInfo); + CPPUNIT_TEST(testFromString_NonASCIIHost); + CPPUNIT_TEST(testFromString_NonASCIIPath); + CPPUNIT_TEST(testToString); + CPPUNIT_TEST(testToString_WithPort); + CPPUNIT_TEST_SUITE_END(); + + public: + void testFromString() { + URL url = URL::fromString("http://foo.bar/baz/bam"); + + CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); + CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); + CPPUNIT_ASSERT(!url.getPort()); + CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); + } + + void testFromString_WithoutPath() { + URL url = URL::fromString("http://foo.bar"); + + CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); + CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); + CPPUNIT_ASSERT(!url.getPort()); + CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath()); + } + + void testFromString_WithRootPath() { + URL url = URL::fromString("http://foo.bar/"); + + CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); + CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); + CPPUNIT_ASSERT(!url.getPort()); + CPPUNIT_ASSERT_EQUAL(std::string("/"), url.getPath()); + } + + void testFromString_WithPort() { + URL url = URL::fromString("http://foo.bar:1234/baz/bam"); + + CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); + CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); + CPPUNIT_ASSERT_EQUAL(1234, *url.getPort()); + CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); + } + + void testFromString_WithPortOnePartPath() { + URL url = URL::fromString("http://foo.bar:11440/http-bind/"); + + CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); + CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); + CPPUNIT_ASSERT_EQUAL(11440, *url.getPort()); + CPPUNIT_ASSERT_EQUAL(std::string("/http-bind/"), url.getPath()); + } + + void testFromString_WithPortWithoutPath() { + URL url = URL::fromString("http://foo.bar:1234"); + + CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); + CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); + CPPUNIT_ASSERT_EQUAL(1234, *url.getPort()); + CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath()); + } + + void testFromString_WithUserInfo() { + URL url = URL::fromString("http://user:pass@foo.bar/baz/bam"); + + CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); + CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); + CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); + } + + void testFromString_NonASCIIHost() { + URL url = URL::fromString("http://www.tron%C3%A7on.be/baz/bam"); + + CPPUNIT_ASSERT_EQUAL(std::string("www.tron\xc3\xa7on.be"), url.getHost()); + } + + void testFromString_NonASCIIPath() { + URL url = URL::fromString("http://foo.bar/baz/tron%C3%A7on/bam"); + + CPPUNIT_ASSERT_EQUAL(std::string("/baz/tron\xc3\xa7on/bam"), url.getPath()); + } + + void testToString() { + CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar/baz/bam"), URL("http", "foo.bar", "/baz/bam").toString()); + } + + void testToString_WithPort() { + CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar:1234/baz/bam"), URL("http", "foo.bar", 1234, "/baz/bam").toString()); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(URLTest); diff --git a/Swiften/Base/WindowsRegistry.h b/Swiften/Base/WindowsRegistry.h index 31ece7a..6243dd2 100644 --- a/Swiften/Base/WindowsRegistry.h +++ b/Swiften/Base/WindowsRegistry.h @@ -9,49 +9,49 @@ #include <windows.h> namespace Swift { - class WindowsRegistry { - public: - static bool isFIPSEnabled() { - char* pathForXP = "System\\CurrentControlSet\\Control\\Lsa"; - char* pathSinceVista = "System\\CurrentControlSet\\Control\\Lsa\\FIPSAlgorithmPolicy"; - char* keyForXP = "FIPSAlgorithmPolicy"; - char* keySinceVista = "Enabled"; - - OSVERSIONINFO osvi; - ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - GetVersionEx(&osvi); - - char* keyForOS = osvi.dwMajorVersion < 6 ? keyForXP : keySinceVista; - char* pathForOS = osvi.dwMajorVersion < 6 ? pathForXP : pathSinceVista; - - /* http://support.microsoft.com/kb/811833 */ - /* http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx */ - HKEY key; - bool result = false; - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, - pathForOS, - 0, - KEY_READ, - &key) != ERROR_SUCCESS) { - /* If we can't find the key that says we're FIPS, we're not FIPS */ - return result; - } - DWORD keyType = REG_DWORD; - DWORD data; - DWORD length = sizeof(data); - - if (RegQueryValueEx(key, - keyForOS, - NULL, - &keyType, - (LPBYTE)&data, - &length) == ERROR_SUCCESS) { - result = data != 0; - } - - RegCloseKey(key); - return result; - } - }; + class WindowsRegistry { + public: + static bool isFIPSEnabled() { + char* pathForXP = "System\\CurrentControlSet\\Control\\Lsa"; + char* pathSinceVista = "System\\CurrentControlSet\\Control\\Lsa\\FIPSAlgorithmPolicy"; + char* keyForXP = "FIPSAlgorithmPolicy"; + char* keySinceVista = "Enabled"; + + OSVERSIONINFO osvi; + ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); + osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&osvi); + + char* keyForOS = osvi.dwMajorVersion < 6 ? keyForXP : keySinceVista; + char* pathForOS = osvi.dwMajorVersion < 6 ? pathForXP : pathSinceVista; + + /* http://support.microsoft.com/kb/811833 */ + /* http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx */ + HKEY key; + bool result = false; + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, + pathForOS, + 0, + KEY_READ, + &key) != ERROR_SUCCESS) { + /* If we can't find the key that says we're FIPS, we're not FIPS */ + return result; + } + DWORD keyType = REG_DWORD; + DWORD data; + DWORD length = sizeof(data); + + if (RegQueryValueEx(key, + keyForOS, + NULL, + &keyType, + (LPBYTE)&data, + &length) == ERROR_SUCCESS) { + result = data != 0; + } + + RegCloseKey(key); + return result; + } + }; } diff --git a/Swiften/Base/boost_bsignals.h b/Swiften/Base/boost_bsignals.h index 005c7dc..62f7cb3 100644 --- a/Swiften/Base/boost_bsignals.h +++ b/Swiften/Base/boost_bsignals.h @@ -17,7 +17,7 @@ #include <boost/signal.hpp> namespace boost { - namespace bsignals = signals; + namespace bsignals = signals; } #if defined(signals) && defined(Q_SIGNALS) && !defined(QT_MOC_CPP) diff --git a/Swiften/Base/format.h b/Swiften/Base/format.h index 07fcd88..e5696b0 100644 --- a/Swiften/Base/format.h +++ b/Swiften/Base/format.h @@ -11,16 +11,16 @@ #include <boost/format.hpp> namespace Swift { - inline boost::format format(const std::string& s) { - using namespace boost::io; - try { - boost::format fmter(s); - fmter.exceptions(no_error_bits); - return fmter; - } - catch (...) { - std::cerr << "Error: Invalid translation: " << s << std::endl; - throw; - } - } + inline boost::format format(const std::string& s) { + using namespace boost::io; + try { + boost::format fmter(s); + fmter.exceptions(no_error_bits); + return fmter; + } + catch (...) { + std::cerr << "Error: Invalid translation: " << s << std::endl; + throw; + } + } } diff --git a/Swiften/Base/sleep.cpp b/Swiften/Base/sleep.cpp index 0c450c3..5a0d729 100644 --- a/Swiften/Base/sleep.cpp +++ b/Swiften/Base/sleep.cpp @@ -12,14 +12,14 @@ namespace Swift { void sleep(unsigned int msecs) { - boost::xtime xt; + boost::xtime xt; #if BOOST_VERSION >= 105000 - boost::xtime_get(&xt, boost::TIME_UTC_); + boost::xtime_get(&xt, boost::TIME_UTC_); #else - boost::xtime_get(&xt, boost::TIME_UTC); + boost::xtime_get(&xt, boost::TIME_UTC); #endif - xt.nsec += msecs*1000000; - boost::thread::sleep(xt); + xt.nsec += msecs*1000000; + boost::thread::sleep(xt); } } diff --git a/Swiften/Base/sleep.h b/Swiften/Base/sleep.h index d2bec72..744e19f 100644 --- a/Swiften/Base/sleep.h +++ b/Swiften/Base/sleep.h @@ -9,5 +9,5 @@ #include <Swiften/Base/API.h> namespace Swift { - SWIFTEN_API void sleep(unsigned int msecs); + SWIFTEN_API void sleep(unsigned int msecs); } diff --git a/Swiften/Chat/ChatStateNotifier.cpp b/Swiften/Chat/ChatStateNotifier.cpp index b2b7f4b..c623ce1 100644 --- a/Swiften/Chat/ChatStateNotifier.cpp +++ b/Swiften/Chat/ChatStateNotifier.cpp @@ -17,77 +17,77 @@ namespace Swift { ChatStateNotifier::ChatStateNotifier(StanzaChannel* stanzaChannel, const JID& contact, EntityCapsProvider* entityCapsManager) : stanzaChannel_(stanzaChannel), entityCapsManager_(entityCapsManager), contact_(contact) { - setContact(contact); - entityCapsManager_->onCapsChanged.connect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1)); + setContact(contact); + entityCapsManager_->onCapsChanged.connect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1)); } ChatStateNotifier::~ChatStateNotifier() { - entityCapsManager_->onCapsChanged.disconnect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1)); + entityCapsManager_->onCapsChanged.disconnect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1)); } void ChatStateNotifier::setContact(const JID& contact) { - contactHasSentActive_ = false; - userIsTyping_ = false; - contactIsOnline_ = false; - contact_ = contact; - handleCapsChanged(contact_); + contactHasSentActive_ = false; + userIsTyping_ = false; + contactIsOnline_ = false; + contact_ = contact; + handleCapsChanged(contact_); } void ChatStateNotifier::setContactIsOnline(bool online) { - contactIsOnline_ = online; + contactIsOnline_ = online; } void ChatStateNotifier::setUserIsTyping() { - bool should = contactShouldReceiveStates(); - if (should && !userIsTyping_) { - userIsTyping_ = true; - changeState(ChatState::Composing); - } + bool should = contactShouldReceiveStates(); + if (should && !userIsTyping_) { + userIsTyping_ = true; + changeState(ChatState::Composing); + } } void ChatStateNotifier::userSentMessage() { - userIsTyping_ = false; + userIsTyping_ = false; } void ChatStateNotifier::userCancelledNewMessage() { - if (userIsTyping_) { - userIsTyping_ = false; - changeState(ChatState::Active); - } + if (userIsTyping_) { + userIsTyping_ = false; + changeState(ChatState::Active); + } } void ChatStateNotifier::receivedMessageFromContact(bool hasActiveElement) { - contactHasSentActive_ = hasActiveElement; + contactHasSentActive_ = hasActiveElement; } bool ChatStateNotifier::contactShouldReceiveStates() { - /* So, yes, the XEP says to look at caps, but it also says that once you've - heard from the contact, the active state overrides this. - *HOWEVER* it says that the MUST NOT send csn if you haven't received - active is OPTIONAL behaviour for if you haven't got caps.*/ - return contactIsOnline_ && (contactHasSentActive_ || contactHas85Caps_); + /* So, yes, the XEP says to look at caps, but it also says that once you've + heard from the contact, the active state overrides this. + *HOWEVER* it says that the MUST NOT send csn if you haven't received + active is OPTIONAL behaviour for if you haven't got caps.*/ + return contactIsOnline_ && (contactHasSentActive_ || contactHas85Caps_); } void ChatStateNotifier::changeState(ChatState::ChatStateType state) { - boost::shared_ptr<Message> message(boost::make_shared<Message>()); - message->setTo(contact_); - message->addPayload(boost::make_shared<ChatState>(state)); - stanzaChannel_->sendMessage(message); + boost::shared_ptr<Message> message(boost::make_shared<Message>()); + message->setTo(contact_); + message->addPayload(boost::make_shared<ChatState>(state)); + stanzaChannel_->sendMessage(message); } void ChatStateNotifier::addChatStateRequest(Message::ref message) { - if (contactShouldReceiveStates()) { - message->addPayload(boost::make_shared<ChatState>(ChatState::Active)); - } + if (contactShouldReceiveStates()) { + message->addPayload(boost::make_shared<ChatState>(ChatState::Active)); + } } void ChatStateNotifier::handleCapsChanged(const JID& jid) { - if (jid == contact_) { - DiscoInfo::ref caps = entityCapsManager_->getCaps(contact_); - bool hasCSN = caps && caps->hasFeature(DiscoInfo::ChatStatesFeature); - contactHas85Caps_ = hasCSN; - } + if (jid == contact_) { + DiscoInfo::ref caps = entityCapsManager_->getCaps(contact_); + bool hasCSN = caps && caps->hasFeature(DiscoInfo::ChatStatesFeature); + contactHas85Caps_ = hasCSN; + } } } diff --git a/Swiften/Chat/ChatStateNotifier.h b/Swiften/Chat/ChatStateNotifier.h index 609fed4..a53fad8 100644 --- a/Swiften/Chat/ChatStateNotifier.h +++ b/Swiften/Chat/ChatStateNotifier.h @@ -15,37 +15,37 @@ #include <Swiften/JID/JID.h> namespace Swift { - class StanzaChannel; - class EntityCapsProvider; - - class SWIFTEN_API ChatStateNotifier { - public: - ChatStateNotifier(StanzaChannel* stanzaChannel, const JID& contact, EntityCapsProvider* entityCapsManager); - ~ChatStateNotifier(); - - void setContact(const JID& contact); - - void addChatStateRequest(Message::ref message); - - void setUserIsTyping(); - void userSentMessage(); - void userCancelledNewMessage(); - - void receivedMessageFromContact(bool hasActiveElement); - void setContactIsOnline(bool online); - - private: - bool contactShouldReceiveStates(); - void changeState(ChatState::ChatStateType type); - void handleCapsChanged(const JID& contact); - - private: - StanzaChannel* stanzaChannel_; - EntityCapsProvider* entityCapsManager_; - JID contact_; - bool contactHas85Caps_; - bool contactHasSentActive_; - bool userIsTyping_; - bool contactIsOnline_; - }; + class StanzaChannel; + class EntityCapsProvider; + + class SWIFTEN_API ChatStateNotifier { + public: + ChatStateNotifier(StanzaChannel* stanzaChannel, const JID& contact, EntityCapsProvider* entityCapsManager); + ~ChatStateNotifier(); + + void setContact(const JID& contact); + + void addChatStateRequest(Message::ref message); + + void setUserIsTyping(); + void userSentMessage(); + void userCancelledNewMessage(); + + void receivedMessageFromContact(bool hasActiveElement); + void setContactIsOnline(bool online); + + private: + bool contactShouldReceiveStates(); + void changeState(ChatState::ChatStateType type); + void handleCapsChanged(const JID& contact); + + private: + StanzaChannel* stanzaChannel_; + EntityCapsProvider* entityCapsManager_; + JID contact_; + bool contactHas85Caps_; + bool contactHasSentActive_; + bool userIsTyping_; + bool contactIsOnline_; + }; } diff --git a/Swiften/Chat/ChatStateTracker.cpp b/Swiften/Chat/ChatStateTracker.cpp index 34b7a04..5141872 100644 --- a/Swiften/Chat/ChatStateTracker.cpp +++ b/Swiften/Chat/ChatStateTracker.cpp @@ -8,30 +8,30 @@ namespace Swift { ChatStateTracker::ChatStateTracker() { - currentState_ = ChatState::Gone; + currentState_ = ChatState::Gone; } void ChatStateTracker::handleMessageReceived(boost::shared_ptr<Message> message) { - if (message->getType() == Message::Error) { - return; - } - boost::shared_ptr<ChatState> statePayload = message->getPayload<ChatState>(); - if (statePayload) { - changeState(statePayload->getChatState());; - } + if (message->getType() == Message::Error) { + return; + } + boost::shared_ptr<ChatState> statePayload = message->getPayload<ChatState>(); + if (statePayload) { + changeState(statePayload->getChatState());; + } } void ChatStateTracker::handlePresenceChange(boost::shared_ptr<Presence> newPresence) { - if (newPresence->getType() == Presence::Unavailable) { - onChatStateChange(ChatState::Gone); - } + if (newPresence->getType() == Presence::Unavailable) { + onChatStateChange(ChatState::Gone); + } } void ChatStateTracker::changeState(ChatState::ChatStateType state) { - if (state != currentState_) { - currentState_ = state; - onChatStateChange(state); - } + if (state != currentState_) { + currentState_ = state; + onChatStateChange(state); + } } } diff --git a/Swiften/Chat/ChatStateTracker.h b/Swiften/Chat/ChatStateTracker.h index b756b98..f31da0b 100644 --- a/Swiften/Chat/ChatStateTracker.h +++ b/Swiften/Chat/ChatStateTracker.h @@ -15,14 +15,14 @@ #include <Swiften/Elements/Presence.h> namespace Swift { - class SWIFTEN_API ChatStateTracker { - public: - ChatStateTracker(); - void handleMessageReceived(boost::shared_ptr<Message> message); - void handlePresenceChange(boost::shared_ptr<Presence> newPresence); - boost::signal<void (ChatState::ChatStateType)> onChatStateChange; - private: - void changeState(ChatState::ChatStateType state); - ChatState::ChatStateType currentState_; - }; + class SWIFTEN_API ChatStateTracker { + public: + ChatStateTracker(); + void handleMessageReceived(boost::shared_ptr<Message> message); + void handlePresenceChange(boost::shared_ptr<Presence> newPresence); + boost::signal<void (ChatState::ChatStateType)> onChatStateChange; + private: + void changeState(ChatState::ChatStateType state); + ChatState::ChatStateType currentState_; + }; } diff --git a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp index b293f9d..af43ced 100644 --- a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp +++ b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp @@ -17,153 +17,153 @@ using namespace Swift; class ChatStateNotifierTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ChatStateNotifierTest); - CPPUNIT_TEST(testStartTypingReply_CapsNotIncluded); - CPPUNIT_TEST(testStartTypingReply_CapsIncluded); - CPPUNIT_TEST(testCancelledNewMessage); - CPPUNIT_TEST(testContinueTypingReply_CapsIncluded); - CPPUNIT_TEST(testTypeReplies_WentOffline); - CPPUNIT_TEST(testContactShouldReceiveStates_CapsOnly); - CPPUNIT_TEST(testContactShouldReceiveStates_CapsNorActive); - CPPUNIT_TEST(testContactShouldReceiveStates_ActiveOverrideOn); - CPPUNIT_TEST(testContactShouldReceiveStates_ActiveOverrideOff); - CPPUNIT_TEST_SUITE_END(); - + CPPUNIT_TEST_SUITE(ChatStateNotifierTest); + CPPUNIT_TEST(testStartTypingReply_CapsNotIncluded); + CPPUNIT_TEST(testStartTypingReply_CapsIncluded); + CPPUNIT_TEST(testCancelledNewMessage); + CPPUNIT_TEST(testContinueTypingReply_CapsIncluded); + CPPUNIT_TEST(testTypeReplies_WentOffline); + CPPUNIT_TEST(testContactShouldReceiveStates_CapsOnly); + CPPUNIT_TEST(testContactShouldReceiveStates_CapsNorActive); + CPPUNIT_TEST(testContactShouldReceiveStates_ActiveOverrideOn); + CPPUNIT_TEST(testContactShouldReceiveStates_ActiveOverrideOff); + CPPUNIT_TEST_SUITE_END(); + public: - void setUp() { - stanzaChannel = new DummyStanzaChannel(); - stanzaChannel->setAvailable(true); - entityCapsProvider = new DummyEntityCapsProvider(); - notifier_ = new ChatStateNotifier(stanzaChannel, JID("foo@bar.com/baz"), entityCapsProvider); - notifier_->setContactIsOnline(true); - } - - void tearDown() { - delete notifier_; - delete entityCapsProvider; - delete stanzaChannel; - } - - void testStartTypingReply_CapsNotIncluded() { - notifier_->setUserIsTyping(); - CPPUNIT_ASSERT_EQUAL(0, getComposingCount()); - } - - void testSendTwoMessages() { - setContactHas85Caps(); - notifier_->setUserIsTyping(); - notifier_->userSentMessage(); - notifier_->setUserIsTyping(); - notifier_->userSentMessage(); - CPPUNIT_ASSERT_EQUAL(2, getComposingCount()); - } - - void testCancelledNewMessage() { - setContactHas85Caps(); - notifier_->setUserIsTyping(); - notifier_->userCancelledNewMessage(); - CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); - CPPUNIT_ASSERT_EQUAL(1, getActiveCount()); - CPPUNIT_ASSERT_EQUAL(ChatState::Active, stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getPayload<ChatState>()->getChatState()); - } - - - void testContactShouldReceiveStates_CapsOnly() { - setContactHas85Caps(); - boost::shared_ptr<Message> message(new Message()); - notifier_->addChatStateRequest(message); - CPPUNIT_ASSERT(message->getPayload<ChatState>()); - CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState()); - } - - void testContactShouldReceiveStates_CapsNorActive() { - boost::shared_ptr<Message> message(new Message()); - notifier_->addChatStateRequest(message); - CPPUNIT_ASSERT(!message->getPayload<ChatState>()); - } - - void testContactShouldReceiveStates_ActiveOverrideOn() { - notifier_->receivedMessageFromContact(true); - boost::shared_ptr<Message> message(new Message()); - notifier_->addChatStateRequest(message); - CPPUNIT_ASSERT(message->getPayload<ChatState>()); - CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState()); - } - - void testContactShouldReceiveStates_ActiveOverrideOff() { - setContactHas85Caps(); - notifier_->receivedMessageFromContact(false); - /* I originally read the MUST NOT send after receiving without Active and - * thought this should check for false, but I later found it was OPTIONAL - * (MAY) behaviour only for if you didn't receive caps. - */ - boost::shared_ptr<Message> message(new Message()); - notifier_->addChatStateRequest(message); - CPPUNIT_ASSERT(message->getPayload<ChatState>()); - CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState()); - } - - - void testStartTypingReply_CapsIncluded() { - setContactHas85Caps(); - notifier_->setUserIsTyping(); - CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); - } - - void testContinueTypingReply_CapsIncluded() { - setContactHas85Caps(); - notifier_->setUserIsTyping(); - notifier_->setUserIsTyping(); - notifier_->setUserIsTyping(); - CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); - notifier_->userSentMessage(); - notifier_->setUserIsTyping(); - CPPUNIT_ASSERT_EQUAL(2, getComposingCount()); - - } - - void testTypeReplies_WentOffline() { - setContactHas85Caps(); - notifier_->setUserIsTyping(); - CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); - notifier_->setContactIsOnline(false); - notifier_->userSentMessage(); - notifier_->setUserIsTyping(); - CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); - } - - private: - void setContactHas85Caps() { - DiscoInfo::ref caps(new DiscoInfo()); - caps->addFeature(DiscoInfo::ChatStatesFeature); - entityCapsProvider->caps[JID("foo@bar.com/baz")] = caps; - entityCapsProvider->onCapsChanged(JID("foo@bar.com/baz")); - } - - int getComposingCount() const { - int result = 0; - foreach(boost::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) { - if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Composing) { - result++; - } - } - return result; - } - - int getActiveCount() const { - int result = 0; - foreach(boost::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) { - if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Active) { - result++; - } - } - return result; - } - - private: - DummyStanzaChannel* stanzaChannel; - DummyEntityCapsProvider* entityCapsProvider; - ChatStateNotifier* notifier_; + void setUp() { + stanzaChannel = new DummyStanzaChannel(); + stanzaChannel->setAvailable(true); + entityCapsProvider = new DummyEntityCapsProvider(); + notifier_ = new ChatStateNotifier(stanzaChannel, JID("foo@bar.com/baz"), entityCapsProvider); + notifier_->setContactIsOnline(true); + } + + void tearDown() { + delete notifier_; + delete entityCapsProvider; + delete stanzaChannel; + } + + void testStartTypingReply_CapsNotIncluded() { + notifier_->setUserIsTyping(); + CPPUNIT_ASSERT_EQUAL(0, getComposingCount()); + } + + void testSendTwoMessages() { + setContactHas85Caps(); + notifier_->setUserIsTyping(); + notifier_->userSentMessage(); + notifier_->setUserIsTyping(); + notifier_->userSentMessage(); + CPPUNIT_ASSERT_EQUAL(2, getComposingCount()); + } + + void testCancelledNewMessage() { + setContactHas85Caps(); + notifier_->setUserIsTyping(); + notifier_->userCancelledNewMessage(); + CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); + CPPUNIT_ASSERT_EQUAL(1, getActiveCount()); + CPPUNIT_ASSERT_EQUAL(ChatState::Active, stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getPayload<ChatState>()->getChatState()); + } + + + void testContactShouldReceiveStates_CapsOnly() { + setContactHas85Caps(); + boost::shared_ptr<Message> message(new Message()); + notifier_->addChatStateRequest(message); + CPPUNIT_ASSERT(message->getPayload<ChatState>()); + CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState()); + } + + void testContactShouldReceiveStates_CapsNorActive() { + boost::shared_ptr<Message> message(new Message()); + notifier_->addChatStateRequest(message); + CPPUNIT_ASSERT(!message->getPayload<ChatState>()); + } + + void testContactShouldReceiveStates_ActiveOverrideOn() { + notifier_->receivedMessageFromContact(true); + boost::shared_ptr<Message> message(new Message()); + notifier_->addChatStateRequest(message); + CPPUNIT_ASSERT(message->getPayload<ChatState>()); + CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState()); + } + + void testContactShouldReceiveStates_ActiveOverrideOff() { + setContactHas85Caps(); + notifier_->receivedMessageFromContact(false); + /* I originally read the MUST NOT send after receiving without Active and + * thought this should check for false, but I later found it was OPTIONAL + * (MAY) behaviour only for if you didn't receive caps. + */ + boost::shared_ptr<Message> message(new Message()); + notifier_->addChatStateRequest(message); + CPPUNIT_ASSERT(message->getPayload<ChatState>()); + CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState()); + } + + + void testStartTypingReply_CapsIncluded() { + setContactHas85Caps(); + notifier_->setUserIsTyping(); + CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); + } + + void testContinueTypingReply_CapsIncluded() { + setContactHas85Caps(); + notifier_->setUserIsTyping(); + notifier_->setUserIsTyping(); + notifier_->setUserIsTyping(); + CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); + notifier_->userSentMessage(); + notifier_->setUserIsTyping(); + CPPUNIT_ASSERT_EQUAL(2, getComposingCount()); + + } + + void testTypeReplies_WentOffline() { + setContactHas85Caps(); + notifier_->setUserIsTyping(); + CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); + notifier_->setContactIsOnline(false); + notifier_->userSentMessage(); + notifier_->setUserIsTyping(); + CPPUNIT_ASSERT_EQUAL(1, getComposingCount()); + } + + private: + void setContactHas85Caps() { + DiscoInfo::ref caps(new DiscoInfo()); + caps->addFeature(DiscoInfo::ChatStatesFeature); + entityCapsProvider->caps[JID("foo@bar.com/baz")] = caps; + entityCapsProvider->onCapsChanged(JID("foo@bar.com/baz")); + } + + int getComposingCount() const { + int result = 0; + foreach(boost::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) { + if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Composing) { + result++; + } + } + return result; + } + + int getActiveCount() const { + int result = 0; + foreach(boost::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) { + if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Active) { + result++; + } + } + return result; + } + + private: + DummyStanzaChannel* stanzaChannel; + DummyEntityCapsProvider* entityCapsProvider; + ChatStateNotifier* notifier_; }; CPPUNIT_TEST_SUITE_REGISTRATION(ChatStateNotifierTest); diff --git a/Swiften/Client/BlockList.cpp b/Swiften/Client/BlockList.cpp index abf9412..cb77080 100644 --- a/Swiften/Client/BlockList.cpp +++ b/Swiften/Client/BlockList.cpp @@ -15,8 +15,8 @@ BlockList::~BlockList() { } bool BlockList::isBlocked(const JID& jid) const { - const std::vector<JID>& items = getItems(); - return (std::find(items.begin(), items.end(), jid.toBare()) != items.end()) || - (std::find(items.begin(), items.end(), JID(jid.getDomain())) != items.end()) || - (std::find(items.begin(), items.end(), jid) != items.end()); + const std::vector<JID>& items = getItems(); + return (std::find(items.begin(), items.end(), jid.toBare()) != items.end()) || + (std::find(items.begin(), items.end(), JID(jid.getDomain())) != items.end()) || + (std::find(items.begin(), items.end(), jid) != items.end()); } diff --git a/Swiften/Client/BlockList.h b/Swiften/Client/BlockList.h index 1ee1ad9..c200f20 100644 --- a/Swiften/Client/BlockList.h +++ b/Swiften/Client/BlockList.h @@ -13,25 +13,25 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API BlockList { - public: - enum State { - Init, - Requesting, - Available, - Error - }; - virtual ~BlockList(); - - virtual State getState() const = 0; - - virtual const std::vector<JID>& getItems() const = 0; - - bool isBlocked(const JID& jid) const; - - public: - boost::signal<void ()> onStateChanged; - boost::signal<void (const JID&)> onItemAdded; - boost::signal<void (const JID&)> onItemRemoved; - }; + class SWIFTEN_API BlockList { + public: + enum State { + Init, + Requesting, + Available, + Error + }; + virtual ~BlockList(); + + virtual State getState() const = 0; + + virtual const std::vector<JID>& getItems() const = 0; + + bool isBlocked(const JID& jid) const; + + public: + boost::signal<void ()> onStateChanged; + boost::signal<void (const JID&)> onItemAdded; + boost::signal<void (const JID&)> onItemRemoved; + }; } diff --git a/Swiften/Client/BlockListImpl.cpp b/Swiften/Client/BlockListImpl.cpp index 4abaa37..ebffff8 100644 --- a/Swiften/Client/BlockListImpl.cpp +++ b/Swiften/Client/BlockListImpl.cpp @@ -17,58 +17,58 @@ BlockListImpl::BlockListImpl() : state(Init) { } void BlockListImpl::setItems(const std::vector<JID>& newItems) { - // JIDs which are in the current list but not in the new list, are removed. - foreach (const JID& jid, items) { - if (std::find(newItems.begin(), newItems.end(), jid) == newItems.end()) { - onItemRemoved(jid); - } - } + // JIDs which are in the current list but not in the new list, are removed. + foreach (const JID& jid, items) { + if (std::find(newItems.begin(), newItems.end(), jid) == newItems.end()) { + onItemRemoved(jid); + } + } - // JIDs which are in the new list but not in the current list, are added. - foreach (const JID& jid, newItems) { - if (std::find(items.begin(), items.end(), jid) == items.end()) { - onItemAdded(jid); - } - } - items = newItems; + // JIDs which are in the new list but not in the current list, are added. + foreach (const JID& jid, newItems) { + if (std::find(items.begin(), items.end(), jid) == items.end()) { + onItemAdded(jid); + } + } + items = newItems; } void BlockListImpl::addItem(const JID& item) { - if (std::find(items.begin(), items.end(), item) == items.end()) { - items.push_back(item); - onItemAdded(item); - } + if (std::find(items.begin(), items.end(), item) == items.end()) { + items.push_back(item); + onItemAdded(item); + } } void BlockListImpl::removeItem(const JID& item) { - size_t oldSize = items.size(); - items.erase(std::remove(items.begin(), items.end(), item), items.end()); - if (items.size() != oldSize) { - onItemRemoved(item); - } + size_t oldSize = items.size(); + items.erase(std::remove(items.begin(), items.end(), item), items.end()); + if (items.size() != oldSize) { + onItemRemoved(item); + } } void BlockListImpl::setState(State state) { - if (this->state != state) { - this->state = state; - onStateChanged(); - } + if (this->state != state) { + this->state = state; + onStateChanged(); + } } void BlockListImpl::addItems(const std::vector<JID>& items) { - foreach (const JID& item, items) { - addItem(item); - } + foreach (const JID& item, items) { + addItem(item); + } } void BlockListImpl::removeItems(const std::vector<JID>& items) { - std::vector<JID> itemsToRemove = items; - foreach (const JID& item, itemsToRemove) { - removeItem(item); - } + std::vector<JID> itemsToRemove = items; + foreach (const JID& item, itemsToRemove) { + removeItem(item); + } } void BlockListImpl::removeAllItems() { - removeItems(items); + removeItems(items); } diff --git a/Swiften/Client/BlockListImpl.h b/Swiften/Client/BlockListImpl.h index e203d68..edf459a 100644 --- a/Swiften/Client/BlockListImpl.h +++ b/Swiften/Client/BlockListImpl.h @@ -9,29 +9,29 @@ #include <Swiften/Client/BlockList.h> namespace Swift { - class BlockListImpl : public BlockList { - public: - BlockListImpl(); - - virtual State getState() const { - return state; - } - - void setState(State state); - - virtual const std::vector<JID>& getItems() const { - return items; - } - - void setItems(const std::vector<JID>& newItems); - void addItem(const JID& item); - void removeItem(const JID& item); - void addItems(const std::vector<JID>& items); - void removeItems(const std::vector<JID>& items); - void removeAllItems(); - - private: - State state; - std::vector<JID> items; - }; + class BlockListImpl : public BlockList { + public: + BlockListImpl(); + + virtual State getState() const { + return state; + } + + void setState(State state); + + virtual const std::vector<JID>& getItems() const { + return items; + } + + void setItems(const std::vector<JID>& newItems); + void addItem(const JID& item); + void removeItem(const JID& item); + void addItems(const std::vector<JID>& items); + void removeItems(const std::vector<JID>& items); + void removeAllItems(); + + private: + State state; + std::vector<JID> items; + }; } diff --git a/Swiften/Client/Client.cpp b/Swiften/Client/Client.cpp index f1266e9..89b66b8 100644 --- a/Swiften/Client/Client.cpp +++ b/Swiften/Client/Client.cpp @@ -39,160 +39,160 @@ namespace Swift { Client::Client(const JID& jid, const SafeString& password, NetworkFactories* networkFactories, Storages* storages) : CoreClient(jid, password, networkFactories), storages(storages) { - memoryStorages = new MemoryStorages(networkFactories->getCryptoProvider()); + memoryStorages = new MemoryStorages(networkFactories->getCryptoProvider()); - softwareVersionResponder = new SoftwareVersionResponder(getIQRouter()); - softwareVersionResponder->start(); + softwareVersionResponder = new SoftwareVersionResponder(getIQRouter()); + softwareVersionResponder->start(); - roster = new XMPPRosterImpl(); - rosterController = new XMPPRosterController(getIQRouter(), roster, getStorages()->getRosterStorage()); + roster = new XMPPRosterImpl(); + rosterController = new XMPPRosterController(getIQRouter(), roster, getStorages()->getRosterStorage()); - subscriptionManager = new SubscriptionManager(getStanzaChannel()); + subscriptionManager = new SubscriptionManager(getStanzaChannel()); - presenceOracle = new PresenceOracle(getStanzaChannel(), roster); - presenceOracle->onPresenceChange.connect(boost::ref(onPresenceChange)); + presenceOracle = new PresenceOracle(getStanzaChannel(), roster); + presenceOracle->onPresenceChange.connect(boost::ref(onPresenceChange)); - stanzaChannelPresenceSender = new StanzaChannelPresenceSender(getStanzaChannel()); - directedPresenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender); - discoManager = new ClientDiscoManager(getIQRouter(), directedPresenceSender, networkFactories->getCryptoProvider()); + stanzaChannelPresenceSender = new StanzaChannelPresenceSender(getStanzaChannel()); + directedPresenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender); + discoManager = new ClientDiscoManager(getIQRouter(), directedPresenceSender, networkFactories->getCryptoProvider()); - mucRegistry = new MUCRegistry(); - mucManager = new MUCManager(getStanzaChannel(), getIQRouter(), directedPresenceSender, mucRegistry); + mucRegistry = new MUCRegistry(); + mucManager = new MUCManager(getStanzaChannel(), getIQRouter(), directedPresenceSender, mucRegistry); - vcardManager = new VCardManager(jid, getIQRouter(), getStorages()->getVCardStorage()); - avatarManager = new AvatarManagerImpl(vcardManager, getStanzaChannel(), getStorages()->getAvatarStorage(), networkFactories->getCryptoProvider(), mucRegistry); - capsManager = new CapsManager(getStorages()->getCapsStorage(), getStanzaChannel(), getIQRouter(), networkFactories->getCryptoProvider()); - entityCapsManager = new EntityCapsManager(capsManager, getStanzaChannel()); + vcardManager = new VCardManager(jid, getIQRouter(), getStorages()->getVCardStorage()); + avatarManager = new AvatarManagerImpl(vcardManager, getStanzaChannel(), getStorages()->getAvatarStorage(), networkFactories->getCryptoProvider(), mucRegistry); + capsManager = new CapsManager(getStorages()->getCapsStorage(), getStanzaChannel(), getIQRouter(), networkFactories->getCryptoProvider()); + entityCapsManager = new EntityCapsManager(capsManager, getStanzaChannel()); - nickManager = new NickManagerImpl(jid.toBare(), vcardManager); - nickResolver = new NickResolver(jid.toBare(), roster, vcardManager, mucRegistry); + nickManager = new NickManagerImpl(jid.toBare(), vcardManager); + nickResolver = new NickResolver(jid.toBare(), roster, vcardManager, mucRegistry); - blindCertificateTrustChecker = new BlindCertificateTrustChecker(); - - jingleSessionManager = new JingleSessionManager(getIQRouter()); - blockListManager = new ClientBlockListManager(getIQRouter()); + blindCertificateTrustChecker = new BlindCertificateTrustChecker(); - whiteboardSessionManager = NULL; + jingleSessionManager = new JingleSessionManager(getIQRouter()); + blockListManager = new ClientBlockListManager(getIQRouter()); + + whiteboardSessionManager = NULL; #ifdef SWIFT_EXPERIMENTAL_WB - whiteboardSessionManager = new WhiteboardSessionManager(getIQRouter(), getStanzaChannel(), presenceOracle, getEntityCapsProvider()); + whiteboardSessionManager = new WhiteboardSessionManager(getIQRouter(), getStanzaChannel(), presenceOracle, getEntityCapsProvider()); #endif - pubsubManager = new PubSubManagerImpl(getStanzaChannel(), getIQRouter()); + pubsubManager = new PubSubManagerImpl(getStanzaChannel(), getIQRouter()); #ifdef SWIFT_EXPERIMENTAL_FT - fileTransferManager = new FileTransferManagerImpl( - getJID(), - jingleSessionManager, - getIQRouter(), - getEntityCapsProvider(), - presenceOracle, - getNetworkFactories()->getConnectionFactory(), - getNetworkFactories()->getConnectionServerFactory(), - getNetworkFactories()->getTimerFactory(), - getNetworkFactories()->getDomainNameResolver(), - getNetworkFactories()->getNetworkEnvironment(), - getNetworkFactories()->getNATTraverser(), - getNetworkFactories()->getCryptoProvider()); + fileTransferManager = new FileTransferManagerImpl( + getJID(), + jingleSessionManager, + getIQRouter(), + getEntityCapsProvider(), + presenceOracle, + getNetworkFactories()->getConnectionFactory(), + getNetworkFactories()->getConnectionServerFactory(), + getNetworkFactories()->getTimerFactory(), + getNetworkFactories()->getDomainNameResolver(), + getNetworkFactories()->getNetworkEnvironment(), + getNetworkFactories()->getNATTraverser(), + getNetworkFactories()->getCryptoProvider()); #else - fileTransferManager = new DummyFileTransferManager(); + fileTransferManager = new DummyFileTransferManager(); #endif } Client::~Client() { - delete pubsubManager; - delete whiteboardSessionManager; + delete pubsubManager; + delete whiteboardSessionManager; + + delete fileTransferManager; + delete blockListManager; + delete jingleSessionManager; - delete fileTransferManager; - delete blockListManager; - delete jingleSessionManager; - - delete blindCertificateTrustChecker; + delete blindCertificateTrustChecker; - delete nickResolver; - delete nickManager; + delete nickResolver; + delete nickManager; - delete entityCapsManager; - delete capsManager; - delete avatarManager; - delete vcardManager; + delete entityCapsManager; + delete capsManager; + delete avatarManager; + delete vcardManager; - delete mucManager; - delete mucRegistry; + delete mucManager; + delete mucRegistry; - delete discoManager; - delete directedPresenceSender; - delete stanzaChannelPresenceSender; + delete discoManager; + delete directedPresenceSender; + delete stanzaChannelPresenceSender; - delete presenceOracle; - delete subscriptionManager; - delete rosterController; - delete roster; + delete presenceOracle; + delete subscriptionManager; + delete rosterController; + delete roster; - softwareVersionResponder->stop(); - delete softwareVersionResponder; + softwareVersionResponder->stop(); + delete softwareVersionResponder; - delete memoryStorages; + delete memoryStorages; } XMPPRoster* Client::getRoster() const { - return roster; + return roster; } void Client::setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os) { - softwareVersionResponder->setVersion(name, version, os); + softwareVersionResponder->setVersion(name, version, os); } void Client::handleConnected() { - discoManager->handleConnected(); + discoManager->handleConnected(); } void Client::requestRoster() { - // FIXME: We should set this once when the session is finished, but there - // is currently no callback for this - if (getSession()) { - rosterController->setUseVersioning(getSession()->getRosterVersioningSupported()); - } - rosterController->requestRoster(); + // FIXME: We should set this once when the session is finished, but there + // is currently no callback for this + if (getSession()) { + rosterController->setUseVersioning(getSession()->getRosterVersioningSupported()); + } + rosterController->requestRoster(); } Presence::ref Client::getLastPresence(const JID& jid) const { - return presenceOracle->getLastPresence(jid); + return presenceOracle->getLastPresence(jid); } Presence::ref Client::getHighestPriorityPresence(const JID& bareJID) const { - return presenceOracle->getHighestPriorityPresence(bareJID); + return presenceOracle->getHighestPriorityPresence(bareJID); } Storages* Client::getStorages() const { - if (storages) { - return storages; - } - return memoryStorages; + if (storages) { + return storages; + } + return memoryStorages; } PresenceSender* Client::getPresenceSender() const { - return discoManager->getPresenceSender(); + return discoManager->getPresenceSender(); } EntityCapsProvider* Client::getEntityCapsProvider() const { - return entityCapsManager; + return entityCapsManager; } void Client::setAlwaysTrustCertificates() { - setCertificateTrustChecker(blindCertificateTrustChecker); + setCertificateTrustChecker(blindCertificateTrustChecker); } NickManager* Client::getNickManager() const { - return nickManager; + return nickManager; } FileTransferManager* Client::getFileTransferManager() const { - return fileTransferManager; + return fileTransferManager; } WhiteboardSessionManager* Client::getWhiteboardSessionManager() const { - return whiteboardSessionManager; + return whiteboardSessionManager; } } diff --git a/Swiften/Client/Client.h b/Swiften/Client/Client.h index f7a372e..a3d11a1 100644 --- a/Swiften/Client/Client.h +++ b/Swiften/Client/Client.h @@ -11,196 +11,196 @@ #include <Swiften/Client/CoreClient.h> namespace Swift { - class SoftwareVersionResponder; - class BlindCertificateTrustChecker; - class XMPPRoster; - class XMPPRosterImpl; - class MUCManager; - class XMPPRosterController; - class PresenceOracle; - class PresenceSender; - class DirectedPresenceSender; - class StanzaChannelPresenceSender; - class MUCRegistry; - class Storages; - class MemoryStorages; - class VCardManager; - class AvatarManager; - class CapsManager; - class EntityCapsManager; - class EntityCapsProvider; - class NickResolver; - class SubscriptionManager; - class ClientDiscoManager; - class NickManager; - class FileTransferManager; - class JingleSessionManager; - class FileTransferManager; - class WhiteboardSessionManager; - class ClientBlockListManager; - class PubSubManager; - - /** - * Provides the core functionality for writing XMPP client software. - * - * Besides connecting to an XMPP server, this class also provides interfaces for - * performing most tasks on the XMPP network. - */ - class SWIFTEN_API Client : public CoreClient { - public: - /** - * Constructs a client for the given JID with the given password. - * - * \param storages The interfaces for storing cache information etc. If - * this is NULL, - * all data will be stored in memory (and be lost on shutdown) - */ - Client(const JID& jid, const SafeString& password, NetworkFactories* networkFactories, Storages* storages = NULL); - virtual ~Client(); - - - /** - * Sets the software version of the client. - * - * This will be used to respond to version queries from other entities. - */ - void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os = ""); - - /** - * Returns a representation of the roster. - * - * The roster is initially empty. To populate it, call requestRoster(), - * which will request the roster from the server. When the roster has - * been requested, it will also be kept up to date when it is updated on - * the server side. - * - * This pointer remains the same across the lifetime of Client. All - * changes to the roster (e.g. after the initial roster request, or after - * subsequent roster updates) are notified through the XMPPRoster's - * signals. - * - * \see requestRoster() - */ - XMPPRoster* getRoster() const; - - /** - * Requests the roster from the server. - * - * \see getRoster() - */ - void requestRoster(); - - /** - * Returns the last received presence for the given (full) JID. - */ - boost::shared_ptr<Presence> getLastPresence(const JID& jid) const; - - /** - * Returns the presence with the highest priority received for the given JID. - */ - boost::shared_ptr<Presence> getHighestPriorityPresence(const JID& bareJID) const; - - PresenceOracle* getPresenceOracle() const { - return presenceOracle; - } - - PresenceSender* getPresenceSender() const; - - MUCManager* getMUCManager() const { - return mucManager; - } - - MUCRegistry* getMUCRegistry() const { - return mucRegistry; - } - - VCardManager* getVCardManager() const { - return vcardManager; - } - - AvatarManager* getAvatarManager() const { - return avatarManager; - } - - EntityCapsProvider* getEntityCapsProvider() const; - - NickManager* getNickManager() const; - - NickResolver* getNickResolver() const { - return nickResolver; - } - - SubscriptionManager* getSubscriptionManager() const { - return subscriptionManager; - } - - ClientDiscoManager* getDiscoManager() const { - return discoManager; - } - - ClientBlockListManager* getClientBlockListManager() const { - return blockListManager; - } - - /** - * Returns a FileTransferManager for the client. This is only available after the onConnected - * signal has been fired. - * - * WARNING: File transfer will only work if Swiften is built in 'experimental' mode. - */ - FileTransferManager* getFileTransferManager() const; - - /** - * Configures the client to always trust a non-validating - * TLS certificate from the server. - * This is equivalent to setting a BlindCertificateTrustChecker - * using setCertificateTrustChecker(). - */ - void setAlwaysTrustCertificates(); - - WhiteboardSessionManager* getWhiteboardSessionManager() const; - - PubSubManager* getPubSubManager() const { - return pubsubManager; - } - - - public: - /** - * This signal is emitted when a JID changes presence. - */ - boost::signal<void (boost::shared_ptr<Presence>)> onPresenceChange; - - private: - Storages* getStorages() const; - - protected: - void handleConnected(); - - private: - Storages* storages; - MemoryStorages* memoryStorages; - SoftwareVersionResponder* softwareVersionResponder; - XMPPRosterImpl* roster; - XMPPRosterController* rosterController; - PresenceOracle* presenceOracle; - DirectedPresenceSender* directedPresenceSender; - StanzaChannelPresenceSender* stanzaChannelPresenceSender; - MUCRegistry* mucRegistry; - VCardManager* vcardManager; - AvatarManager* avatarManager; - CapsManager* capsManager; - EntityCapsManager* entityCapsManager; - NickManager* nickManager; - NickResolver* nickResolver; - SubscriptionManager* subscriptionManager; - MUCManager* mucManager; - ClientDiscoManager* discoManager; - JingleSessionManager* jingleSessionManager; - FileTransferManager* fileTransferManager; - BlindCertificateTrustChecker* blindCertificateTrustChecker; - WhiteboardSessionManager* whiteboardSessionManager; - ClientBlockListManager* blockListManager; - PubSubManager* pubsubManager; - }; + class SoftwareVersionResponder; + class BlindCertificateTrustChecker; + class XMPPRoster; + class XMPPRosterImpl; + class MUCManager; + class XMPPRosterController; + class PresenceOracle; + class PresenceSender; + class DirectedPresenceSender; + class StanzaChannelPresenceSender; + class MUCRegistry; + class Storages; + class MemoryStorages; + class VCardManager; + class AvatarManager; + class CapsManager; + class EntityCapsManager; + class EntityCapsProvider; + class NickResolver; + class SubscriptionManager; + class ClientDiscoManager; + class NickManager; + class FileTransferManager; + class JingleSessionManager; + class FileTransferManager; + class WhiteboardSessionManager; + class ClientBlockListManager; + class PubSubManager; + + /** + * Provides the core functionality for writing XMPP client software. + * + * Besides connecting to an XMPP server, this class also provides interfaces for + * performing most tasks on the XMPP network. + */ + class SWIFTEN_API Client : public CoreClient { + public: + /** + * Constructs a client for the given JID with the given password. + * + * \param storages The interfaces for storing cache information etc. If + * this is NULL, + * all data will be stored in memory (and be lost on shutdown) + */ + Client(const JID& jid, const SafeString& password, NetworkFactories* networkFactories, Storages* storages = NULL); + virtual ~Client(); + + + /** + * Sets the software version of the client. + * + * This will be used to respond to version queries from other entities. + */ + void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os = ""); + + /** + * Returns a representation of the roster. + * + * The roster is initially empty. To populate it, call requestRoster(), + * which will request the roster from the server. When the roster has + * been requested, it will also be kept up to date when it is updated on + * the server side. + * + * This pointer remains the same across the lifetime of Client. All + * changes to the roster (e.g. after the initial roster request, or after + * subsequent roster updates) are notified through the XMPPRoster's + * signals. + * + * \see requestRoster() + */ + XMPPRoster* getRoster() const; + + /** + * Requests the roster from the server. + * + * \see getRoster() + */ + void requestRoster(); + + /** + * Returns the last received presence for the given (full) JID. + */ + boost::shared_ptr<Presence> getLastPresence(const JID& jid) const; + + /** + * Returns the presence with the highest priority received for the given JID. + */ + boost::shared_ptr<Presence> getHighestPriorityPresence(const JID& bareJID) const; + + PresenceOracle* getPresenceOracle() const { + return presenceOracle; + } + + PresenceSender* getPresenceSender() const; + + MUCManager* getMUCManager() const { + return mucManager; + } + + MUCRegistry* getMUCRegistry() const { + return mucRegistry; + } + + VCardManager* getVCardManager() const { + return vcardManager; + } + + AvatarManager* getAvatarManager() const { + return avatarManager; + } + + EntityCapsProvider* getEntityCapsProvider() const; + + NickManager* getNickManager() const; + + NickResolver* getNickResolver() const { + return nickResolver; + } + + SubscriptionManager* getSubscriptionManager() const { + return subscriptionManager; + } + + ClientDiscoManager* getDiscoManager() const { + return discoManager; + } + + ClientBlockListManager* getClientBlockListManager() const { + return blockListManager; + } + + /** + * Returns a FileTransferManager for the client. This is only available after the onConnected + * signal has been fired. + * + * WARNING: File transfer will only work if Swiften is built in 'experimental' mode. + */ + FileTransferManager* getFileTransferManager() const; + + /** + * Configures the client to always trust a non-validating + * TLS certificate from the server. + * This is equivalent to setting a BlindCertificateTrustChecker + * using setCertificateTrustChecker(). + */ + void setAlwaysTrustCertificates(); + + WhiteboardSessionManager* getWhiteboardSessionManager() const; + + PubSubManager* getPubSubManager() const { + return pubsubManager; + } + + + public: + /** + * This signal is emitted when a JID changes presence. + */ + boost::signal<void (boost::shared_ptr<Presence>)> onPresenceChange; + + private: + Storages* getStorages() const; + + protected: + void handleConnected(); + + private: + Storages* storages; + MemoryStorages* memoryStorages; + SoftwareVersionResponder* softwareVersionResponder; + XMPPRosterImpl* roster; + XMPPRosterController* rosterController; + PresenceOracle* presenceOracle; + DirectedPresenceSender* directedPresenceSender; + StanzaChannelPresenceSender* stanzaChannelPresenceSender; + MUCRegistry* mucRegistry; + VCardManager* vcardManager; + AvatarManager* avatarManager; + CapsManager* capsManager; + EntityCapsManager* entityCapsManager; + NickManager* nickManager; + NickResolver* nickResolver; + SubscriptionManager* subscriptionManager; + MUCManager* mucManager; + ClientDiscoManager* discoManager; + JingleSessionManager* jingleSessionManager; + FileTransferManager* fileTransferManager; + BlindCertificateTrustChecker* blindCertificateTrustChecker; + WhiteboardSessionManager* whiteboardSessionManager; + ClientBlockListManager* blockListManager; + PubSubManager* pubsubManager; + }; } diff --git a/Swiften/Client/ClientBlockListManager.cpp b/Swiften/Client/ClientBlockListManager.cpp index fa7cd42..84a5639 100644 --- a/Swiften/Client/ClientBlockListManager.cpp +++ b/Swiften/Client/ClientBlockListManager.cpp @@ -16,54 +16,54 @@ using namespace Swift; namespace { - class BlockResponder : public SetResponder<BlockPayload> { - public: - BlockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<BlockPayload>(iqRouter), blockList(blockList) { - } - - virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<BlockPayload> payload) { - if (getIQRouter()->isAccountJID(from)) { - if (payload) { - blockList->addItems(payload->getItems()); - } - sendResponse(from, id, boost::shared_ptr<BlockPayload>()); - } - else { - sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel); - } - return true; - } - - private: - boost::shared_ptr<BlockListImpl> blockList; - }; - - class UnblockResponder : public SetResponder<UnblockPayload> { - public: - UnblockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<UnblockPayload>(iqRouter), blockList(blockList) { - } - - virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<UnblockPayload> payload) { - if (getIQRouter()->isAccountJID(from)) { - if (payload) { - if (payload->getItems().empty()) { - blockList->removeAllItems(); - } - else { - blockList->removeItems(payload->getItems()); - } - } - sendResponse(from, id, boost::shared_ptr<UnblockPayload>()); - } - else { - sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel); - } - return true; - } - - private: - boost::shared_ptr<BlockListImpl> blockList; - }; + class BlockResponder : public SetResponder<BlockPayload> { + public: + BlockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<BlockPayload>(iqRouter), blockList(blockList) { + } + + virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<BlockPayload> payload) { + if (getIQRouter()->isAccountJID(from)) { + if (payload) { + blockList->addItems(payload->getItems()); + } + sendResponse(from, id, boost::shared_ptr<BlockPayload>()); + } + else { + sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel); + } + return true; + } + + private: + boost::shared_ptr<BlockListImpl> blockList; + }; + + class UnblockResponder : public SetResponder<UnblockPayload> { + public: + UnblockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<UnblockPayload>(iqRouter), blockList(blockList) { + } + + virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<UnblockPayload> payload) { + if (getIQRouter()->isAccountJID(from)) { + if (payload) { + if (payload->getItems().empty()) { + blockList->removeAllItems(); + } + else { + blockList->removeItems(payload->getItems()); + } + } + sendResponse(from, id, boost::shared_ptr<UnblockPayload>()); + } + else { + sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel); + } + return true; + } + + private: + boost::shared_ptr<BlockListImpl> blockList; + }; } ClientBlockListManager::ClientBlockListManager(IQRouter* iqRouter) : iqRouter(iqRouter) { @@ -71,69 +71,69 @@ ClientBlockListManager::ClientBlockListManager(IQRouter* iqRouter) : iqRouter(iq } ClientBlockListManager::~ClientBlockListManager() { - if (blockList && blockList->getState() == BlockList::Available) { - unblockResponder->stop(); - blockResponder->stop(); - } + if (blockList && blockList->getState() == BlockList::Available) { + unblockResponder->stop(); + blockResponder->stop(); + } } boost::shared_ptr<BlockList> ClientBlockListManager::getBlockList() { - if (!blockList) { - blockList = boost::make_shared<BlockListImpl>(); - blockList->setState(BlockList::Init); - } - return blockList; + if (!blockList) { + blockList = boost::make_shared<BlockListImpl>(); + blockList->setState(BlockList::Init); + } + return blockList; } boost::shared_ptr<BlockList> ClientBlockListManager::requestBlockList() { - if (!blockList) { - blockList = boost::make_shared<BlockListImpl>(); - } - blockList->setState(BlockList::Requesting); - boost::shared_ptr<GenericRequest<BlockListPayload> > getRequest = boost::make_shared< GenericRequest<BlockListPayload> >(IQ::Get, JID(), boost::make_shared<BlockListPayload>(), iqRouter); - getRequest->onResponse.connect(boost::bind(&ClientBlockListManager::handleBlockListReceived, this, _1, _2)); - getRequest->send(); - return blockList; + if (!blockList) { + blockList = boost::make_shared<BlockListImpl>(); + } + blockList->setState(BlockList::Requesting); + boost::shared_ptr<GenericRequest<BlockListPayload> > getRequest = boost::make_shared< GenericRequest<BlockListPayload> >(IQ::Get, JID(), boost::make_shared<BlockListPayload>(), iqRouter); + getRequest->onResponse.connect(boost::bind(&ClientBlockListManager::handleBlockListReceived, this, _1, _2)); + getRequest->send(); + return blockList; } GenericRequest<BlockPayload>::ref ClientBlockListManager::createBlockJIDRequest(const JID& jid) { - return createBlockJIDsRequest(std::vector<JID>(1, jid)); + return createBlockJIDsRequest(std::vector<JID>(1, jid)); } GenericRequest<BlockPayload>::ref ClientBlockListManager::createBlockJIDsRequest(const std::vector<JID>& jids) { - boost::shared_ptr<BlockPayload> payload = boost::make_shared<BlockPayload>(jids); - return boost::make_shared< GenericRequest<BlockPayload> >(IQ::Set, JID(), payload, iqRouter); + boost::shared_ptr<BlockPayload> payload = boost::make_shared<BlockPayload>(jids); + return boost::make_shared< GenericRequest<BlockPayload> >(IQ::Set, JID(), payload, iqRouter); } GenericRequest<UnblockPayload>::ref ClientBlockListManager::createUnblockJIDRequest(const JID& jid) { - return createUnblockJIDsRequest(std::vector<JID>(1, jid)); + return createUnblockJIDsRequest(std::vector<JID>(1, jid)); } GenericRequest<UnblockPayload>::ref ClientBlockListManager::createUnblockJIDsRequest(const std::vector<JID>& jids) { - boost::shared_ptr<UnblockPayload> payload = boost::make_shared<UnblockPayload>(jids); - return boost::make_shared< GenericRequest<UnblockPayload> >(IQ::Set, JID(), payload, iqRouter); + boost::shared_ptr<UnblockPayload> payload = boost::make_shared<UnblockPayload>(jids); + return boost::make_shared< GenericRequest<UnblockPayload> >(IQ::Set, JID(), payload, iqRouter); } GenericRequest<UnblockPayload>::ref ClientBlockListManager::createUnblockAllRequest() { - return createUnblockJIDsRequest(std::vector<JID>()); + return createUnblockJIDsRequest(std::vector<JID>()); } void ClientBlockListManager::handleBlockListReceived(boost::shared_ptr<BlockListPayload> payload, ErrorPayload::ref error) { - if (error || !payload) { - blockList->setState(BlockList::Error); - } - else { - blockList->setItems(payload->getItems()); - blockList->setState(BlockList::Available); - if (!blockResponder) { - blockResponder = boost::make_shared<BlockResponder>(blockList, iqRouter); - blockResponder->start(); - } - if (!unblockResponder) { - unblockResponder = boost::make_shared<UnblockResponder>(blockList, iqRouter); - unblockResponder->start(); - } - } + if (error || !payload) { + blockList->setState(BlockList::Error); + } + else { + blockList->setItems(payload->getItems()); + blockList->setState(BlockList::Available); + if (!blockResponder) { + blockResponder = boost::make_shared<BlockResponder>(blockList, iqRouter); + blockResponder->start(); + } + if (!unblockResponder) { + unblockResponder = boost::make_shared<UnblockResponder>(blockList, iqRouter); + unblockResponder->start(); + } + } } diff --git a/Swiften/Client/ClientBlockListManager.h b/Swiften/Client/ClientBlockListManager.h index 1aafdc6..63ff1cd 100644 --- a/Swiften/Client/ClientBlockListManager.h +++ b/Swiften/Client/ClientBlockListManager.h @@ -20,38 +20,38 @@ #include <Swiften/Queries/SetResponder.h> namespace Swift { - class IQRouter; - - class SWIFTEN_API ClientBlockListManager { - public: - ClientBlockListManager(IQRouter *iqRouter); - ~ClientBlockListManager(); - - /** - * Returns the blocklist. - */ - boost::shared_ptr<BlockList> getBlockList(); - - /** - * Get the blocklist from the server. - */ - boost::shared_ptr<BlockList> requestBlockList(); - - GenericRequest<BlockPayload>::ref createBlockJIDRequest(const JID& jid); - GenericRequest<BlockPayload>::ref createBlockJIDsRequest(const std::vector<JID>& jids); - - GenericRequest<UnblockPayload>::ref createUnblockJIDRequest(const JID& jid); - GenericRequest<UnblockPayload>::ref createUnblockJIDsRequest(const std::vector<JID>& jids); - GenericRequest<UnblockPayload>::ref createUnblockAllRequest(); - - private: - void handleBlockListReceived(boost::shared_ptr<BlockListPayload> payload, ErrorPayload::ref); - - private: - IQRouter* iqRouter; - boost::shared_ptr<SetResponder<BlockPayload> > blockResponder; - boost::shared_ptr<SetResponder<UnblockPayload> > unblockResponder; - boost::shared_ptr<BlockListImpl> blockList; - }; + class IQRouter; + + class SWIFTEN_API ClientBlockListManager { + public: + ClientBlockListManager(IQRouter *iqRouter); + ~ClientBlockListManager(); + + /** + * Returns the blocklist. + */ + boost::shared_ptr<BlockList> getBlockList(); + + /** + * Get the blocklist from the server. + */ + boost::shared_ptr<BlockList> requestBlockList(); + + GenericRequest<BlockPayload>::ref createBlockJIDRequest(const JID& jid); + GenericRequest<BlockPayload>::ref createBlockJIDsRequest(const std::vector<JID>& jids); + + GenericRequest<UnblockPayload>::ref createUnblockJIDRequest(const JID& jid); + GenericRequest<UnblockPayload>::ref createUnblockJIDsRequest(const std::vector<JID>& jids); + GenericRequest<UnblockPayload>::ref createUnblockAllRequest(); + + private: + void handleBlockListReceived(boost::shared_ptr<BlockListPayload> payload, ErrorPayload::ref); + + private: + IQRouter* iqRouter; + boost::shared_ptr<SetResponder<BlockPayload> > blockResponder; + boost::shared_ptr<SetResponder<UnblockPayload> > unblockResponder; + boost::shared_ptr<BlockListImpl> blockList; + }; } diff --git a/Swiften/Client/ClientError.h b/Swiften/Client/ClientError.h index 19de42b..5ae1086 100644 --- a/Swiften/Client/ClientError.h +++ b/Swiften/Client/ClientError.h @@ -10,56 +10,56 @@ #include <boost/system/system_error.hpp> namespace Swift { - class ClientError { - public: - enum Type { - UnknownError, - DomainNameResolveError, - ConnectionError, - ConnectionReadError, - ConnectionWriteError, - XMLError, - AuthenticationFailedError, - CompressionFailedError, - ServerVerificationFailedError, - NoSupportedAuthMechanismsError, - UnexpectedElementError, - ResourceBindError, - SessionStartError, - StreamError, - TLSError, - ClientCertificateLoadError, - ClientCertificateError, + class ClientError { + public: + enum Type { + UnknownError, + DomainNameResolveError, + ConnectionError, + ConnectionReadError, + ConnectionWriteError, + XMLError, + AuthenticationFailedError, + CompressionFailedError, + ServerVerificationFailedError, + NoSupportedAuthMechanismsError, + UnexpectedElementError, + ResourceBindError, + SessionStartError, + StreamError, + TLSError, + ClientCertificateLoadError, + ClientCertificateError, - // Certifate on smartcard was removed - CertificateCardRemoved, + // Certifate on smartcard was removed + CertificateCardRemoved, - // Certificate verification errors - UnknownCertificateError, - CertificateExpiredError, - CertificateNotYetValidError, - CertificateSelfSignedError, - CertificateRejectedError, - CertificateUntrustedError, - InvalidCertificatePurposeError, - CertificatePathLengthExceededError, - InvalidCertificateSignatureError, - InvalidCAError, - InvalidServerIdentityError, - RevokedError, - RevocationCheckFailedError - }; + // Certificate verification errors + UnknownCertificateError, + CertificateExpiredError, + CertificateNotYetValidError, + CertificateSelfSignedError, + CertificateRejectedError, + CertificateUntrustedError, + InvalidCertificatePurposeError, + CertificatePathLengthExceededError, + InvalidCertificateSignatureError, + InvalidCAError, + InvalidServerIdentityError, + RevokedError, + RevocationCheckFailedError + }; - ClientError(Type type = UnknownError) : type_(type) {} + ClientError(Type type = UnknownError) : type_(type) {} - Type getType() const { return type_; } + Type getType() const { return type_; } - void setErrorCode(boost::shared_ptr<boost::system::error_code> errorCode) { errorCode_ = errorCode; } + void setErrorCode(boost::shared_ptr<boost::system::error_code> errorCode) { errorCode_ = errorCode; } - boost::shared_ptr<boost::system::error_code> getErrorCode() const { return errorCode_; } + boost::shared_ptr<boost::system::error_code> getErrorCode() const { return errorCode_; } - private: - Type type_; - boost::shared_ptr<boost::system::error_code> errorCode_; - }; + private: + Type type_; + boost::shared_ptr<boost::system::error_code> errorCode_; + }; } diff --git a/Swiften/Client/ClientOptions.h b/Swiften/Client/ClientOptions.h index bef5833..c902388 100644 --- a/Swiften/Client/ClientOptions.h +++ b/Swiften/Client/ClientOptions.h @@ -14,149 +14,149 @@ #include <Swiften/TLS/TLSOptions.h> namespace Swift { - class HTTPTrafficFilter; - - struct SWIFTEN_API ClientOptions { - enum UseTLS { - NeverUseTLS, - UseTLSWhenAvailable, - RequireTLS - }; - - enum ProxyType { - NoProxy, - SystemConfiguredProxy, - SOCKS5Proxy, - HTTPConnectProxy - }; - - ClientOptions() : - useStreamCompression(true), - useTLS(UseTLSWhenAvailable), - allowPLAINWithoutTLS(false), - useStreamResumption(false), - forgetPassword(false), - useAcks(true), - singleSignOn(false), - manualHostname(""), - manualPort(-1), - proxyType(SystemConfiguredProxy), - manualProxyHostname(""), - manualProxyPort(-1), - boshHTTPConnectProxyAuthID(""), - boshHTTPConnectProxyAuthPassword("") { - } - - /** - * Whether ZLib stream compression should be used when available. - * - * Default: true - */ - bool useStreamCompression; - - /** - * Sets whether TLS encryption should be used. - * - * Default: UseTLSWhenAvailable - */ - UseTLS useTLS; - - /** - * Sets whether plaintext authentication is - * allowed over non-TLS-encrypted connections. - * - * Default: false - */ - bool allowPLAINWithoutTLS; - - /** - * Use XEP-196 stream resumption when available. - * - * Default: false - */ - bool useStreamResumption; - - /** - * Forget the password once it's used. - * This makes the Client useless after the first login attempt. - * - * FIXME: This is a temporary workaround. - * - * Default: false - */ - bool forgetPassword; - - /** - * Use XEP-0198 acks in the stream when available. - * Default: true - */ - bool useAcks; - - /** - * Use Single Sign On. - * Default: false - */ - bool singleSignOn; - - /** - * The hostname to connect to. - * Leave this empty for standard XMPP connection, based on the JID domain. - */ - std::string manualHostname; - - /** - * The port to connect to. - * Leave this to -1 to use the port discovered by SRV lookups, and 5222 as a - * fallback. - */ - int manualPort; - - /** - * The type of proxy to use for connecting to the XMPP - * server. - */ - ProxyType proxyType; - - /** - * Override the system-configured proxy hostname. - */ - std::string manualProxyHostname; - - /** - * Override the system-configured proxy port. - */ - int manualProxyPort; - - /** - * If non-empty, use BOSH instead of direct TCP, with the given URL. - * Default: empty (no BOSH) - */ - URL boshURL; - - /** - * If non-empty, BOSH connections will try to connect over this HTTP CONNECT - * proxy instead of directly. - * Default: empty (no proxy) - */ - URL boshHTTPConnectProxyURL; - - /** - * If this and matching Password are non-empty, BOSH connections over - * HTTP CONNECT proxies will use these credentials for proxy access. - * Default: empty (no authentication needed by the proxy) - */ - SafeString boshHTTPConnectProxyAuthID; - SafeString boshHTTPConnectProxyAuthPassword; - - /** - * This can be initialized with a custom HTTPTrafficFilter, which allows HTTP CONNECT - * proxy initialization to be customized. - */ - boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter; - - /** - * Options passed to the TLS stack - */ - TLSOptions tlsOptions; - }; + class HTTPTrafficFilter; + + struct SWIFTEN_API ClientOptions { + enum UseTLS { + NeverUseTLS, + UseTLSWhenAvailable, + RequireTLS + }; + + enum ProxyType { + NoProxy, + SystemConfiguredProxy, + SOCKS5Proxy, + HTTPConnectProxy + }; + + ClientOptions() : + useStreamCompression(true), + useTLS(UseTLSWhenAvailable), + allowPLAINWithoutTLS(false), + useStreamResumption(false), + forgetPassword(false), + useAcks(true), + singleSignOn(false), + manualHostname(""), + manualPort(-1), + proxyType(SystemConfiguredProxy), + manualProxyHostname(""), + manualProxyPort(-1), + boshHTTPConnectProxyAuthID(""), + boshHTTPConnectProxyAuthPassword("") { + } + + /** + * Whether ZLib stream compression should be used when available. + * + * Default: true + */ + bool useStreamCompression; + + /** + * Sets whether TLS encryption should be used. + * + * Default: UseTLSWhenAvailable + */ + UseTLS useTLS; + + /** + * Sets whether plaintext authentication is + * allowed over non-TLS-encrypted connections. + * + * Default: false + */ + bool allowPLAINWithoutTLS; + + /** + * Use XEP-196 stream resumption when available. + * + * Default: false + */ + bool useStreamResumption; + + /** + * Forget the password once it's used. + * This makes the Client useless after the first login attempt. + * + * FIXME: This is a temporary workaround. + * + * Default: false + */ + bool forgetPassword; + + /** + * Use XEP-0198 acks in the stream when available. + * Default: true + */ + bool useAcks; + + /** + * Use Single Sign On. + * Default: false + */ + bool singleSignOn; + + /** + * The hostname to connect to. + * Leave this empty for standard XMPP connection, based on the JID domain. + */ + std::string manualHostname; + + /** + * The port to connect to. + * Leave this to -1 to use the port discovered by SRV lookups, and 5222 as a + * fallback. + */ + int manualPort; + + /** + * The type of proxy to use for connecting to the XMPP + * server. + */ + ProxyType proxyType; + + /** + * Override the system-configured proxy hostname. + */ + std::string manualProxyHostname; + + /** + * Override the system-configured proxy port. + */ + int manualProxyPort; + + /** + * If non-empty, use BOSH instead of direct TCP, with the given URL. + * Default: empty (no BOSH) + */ + URL boshURL; + + /** + * If non-empty, BOSH connections will try to connect over this HTTP CONNECT + * proxy instead of directly. + * Default: empty (no proxy) + */ + URL boshHTTPConnectProxyURL; + + /** + * If this and matching Password are non-empty, BOSH connections over + * HTTP CONNECT proxies will use these credentials for proxy access. + * Default: empty (no authentication needed by the proxy) + */ + SafeString boshHTTPConnectProxyAuthID; + SafeString boshHTTPConnectProxyAuthPassword; + + /** + * This can be initialized with a custom HTTPTrafficFilter, which allows HTTP CONNECT + * proxy initialization to be customized. + */ + boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter; + + /** + * Options passed to the TLS stack + */ + TLSOptions tlsOptions; + }; } diff --git a/Swiften/Client/ClientSession.cpp b/Swiften/Client/ClientSession.cpp index 52b8cfb..e38dde8 100644 --- a/Swiften/Client/ClientSession.cpp +++ b/Swiften/Client/ClientSession.cpp @@ -51,35 +51,35 @@ #endif #define CHECK_STATE_OR_RETURN(a) \ - if (!checkState(a)) { return; } + if (!checkState(a)) { return; } namespace Swift { ClientSession::ClientSession( - const JID& jid, - boost::shared_ptr<SessionStream> stream, - IDNConverter* idnConverter, - CryptoProvider* crypto) : - localJID(jid), - state(Initial), - stream(stream), - idnConverter(idnConverter), - crypto(crypto), - allowPLAINOverNonTLS(false), - useStreamCompression(true), - useTLS(UseTLSWhenAvailable), - useAcks(true), - needSessionStart(false), - needResourceBind(false), - needAcking(false), - rosterVersioningSupported(false), - authenticator(NULL), - certificateTrustChecker(NULL), - singleSignOn(false), - authenticationPort(-1) { + const JID& jid, + boost::shared_ptr<SessionStream> stream, + IDNConverter* idnConverter, + CryptoProvider* crypto) : + localJID(jid), + state(Initial), + stream(stream), + idnConverter(idnConverter), + crypto(crypto), + allowPLAINOverNonTLS(false), + useStreamCompression(true), + useTLS(UseTLSWhenAvailable), + useAcks(true), + needSessionStart(false), + needResourceBind(false), + needAcking(false), + rosterVersioningSupported(false), + authenticator(NULL), + certificateTrustChecker(NULL), + singleSignOn(false), + authenticationPort(-1) { #ifdef SWIFTEN_PLATFORM_WIN32 if (WindowsRegistry::isFIPSEnabled()) { - SWIFT_LOG(info) << "Windows is running in FIPS-140 mode. Some authentication methods will be unavailable." << std::endl; + SWIFT_LOG(info) << "Windows is running in FIPS-140 mode. Some authentication methods will be unavailable." << std::endl; } #endif } @@ -88,427 +88,427 @@ ClientSession::~ClientSession() { } void ClientSession::start() { - stream->onStreamStartReceived.connect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1)); - stream->onElementReceived.connect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1)); - stream->onClosed.connect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1)); - stream->onTLSEncrypted.connect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this())); - - assert(state == Initial); - state = WaitingForStreamStart; - sendStreamHeader(); + stream->onStreamStartReceived.connect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1)); + stream->onElementReceived.connect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1)); + stream->onClosed.connect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1)); + stream->onTLSEncrypted.connect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this())); + + assert(state == Initial); + state = WaitingForStreamStart; + sendStreamHeader(); } void ClientSession::sendStreamHeader() { - ProtocolHeader header; - header.setTo(getRemoteJID()); - stream->writeHeader(header); + ProtocolHeader header; + header.setTo(getRemoteJID()); + stream->writeHeader(header); } void ClientSession::sendStanza(boost::shared_ptr<Stanza> stanza) { - stream->writeElement(stanza); - if (stanzaAckRequester_) { - stanzaAckRequester_->handleStanzaSent(stanza); - } + stream->writeElement(stanza); + if (stanzaAckRequester_) { + stanzaAckRequester_->handleStanzaSent(stanza); + } } void ClientSession::handleStreamStart(const ProtocolHeader&) { - CHECK_STATE_OR_RETURN(WaitingForStreamStart); - state = Negotiating; + CHECK_STATE_OR_RETURN(WaitingForStreamStart); + state = Negotiating; } void ClientSession::handleElement(boost::shared_ptr<ToplevelElement> element) { - if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) { - if (stanzaAckResponder_) { - stanzaAckResponder_->handleStanzaReceived(); - } - if (getState() == Initialized) { - onStanzaReceived(stanza); - } - else if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(element)) { - if (state == BindingResource) { - boost::shared_ptr<ResourceBind> resourceBind(iq->getPayload<ResourceBind>()); - if (iq->getType() == IQ::Error && iq->getID() == "session-bind") { - finishSession(Error::ResourceBindError); - } - else if (!resourceBind) { - finishSession(Error::UnexpectedElementError); - } - else if (iq->getType() == IQ::Result) { - localJID = resourceBind->getJID(); - if (!localJID.isValid()) { - finishSession(Error::ResourceBindError); - } - needResourceBind = false; - continueSessionInitialization(); - } - else { - finishSession(Error::UnexpectedElementError); - } - } - else if (state == StartingSession) { - if (iq->getType() == IQ::Result) { - needSessionStart = false; - continueSessionInitialization(); - } - else if (iq->getType() == IQ::Error) { - finishSession(Error::SessionStartError); - } - else { - finishSession(Error::UnexpectedElementError); - } - } - else { - finishSession(Error::UnexpectedElementError); - } - } - } - else if (boost::dynamic_pointer_cast<StanzaAckRequest>(element)) { - if (stanzaAckResponder_) { - stanzaAckResponder_->handleAckRequestReceived(); - } - } - else if (boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(element)) { - if (stanzaAckRequester_) { - if (ack->isValid()) { - stanzaAckRequester_->handleAckReceived(ack->getHandledStanzasCount()); - } - else { - SWIFT_LOG(warning) << "Got invalid ack from server"; - } - } - else { - SWIFT_LOG(warning) << "Ignoring ack"; - } - } - else if (StreamError::ref streamError = boost::dynamic_pointer_cast<StreamError>(element)) { - finishSession(Error::StreamError); - } - else if (getState() == Initialized) { - boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element); - if (stanza) { - if (stanzaAckResponder_) { - stanzaAckResponder_->handleStanzaReceived(); - } - onStanzaReceived(stanza); - } - } - else if (StreamFeatures* streamFeatures = dynamic_cast<StreamFeatures*>(element.get())) { - CHECK_STATE_OR_RETURN(Negotiating); - - if (streamFeatures->hasStartTLS() && stream->supportsTLSEncryption() && useTLS != NeverUseTLS) { - state = WaitingForEncrypt; - stream->writeElement(boost::make_shared<StartTLSRequest>()); - } - else if (useTLS == RequireTLS && !stream->isTLSEncrypted()) { - finishSession(Error::NoSupportedAuthMechanismsError); - } - else if (useStreamCompression && stream->supportsZLibCompression() && streamFeatures->hasCompressionMethod("zlib")) { - state = Compressing; - stream->writeElement(boost::make_shared<CompressRequest>("zlib")); - } - else if (streamFeatures->hasAuthenticationMechanisms()) { + if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) { + if (stanzaAckResponder_) { + stanzaAckResponder_->handleStanzaReceived(); + } + if (getState() == Initialized) { + onStanzaReceived(stanza); + } + else if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(element)) { + if (state == BindingResource) { + boost::shared_ptr<ResourceBind> resourceBind(iq->getPayload<ResourceBind>()); + if (iq->getType() == IQ::Error && iq->getID() == "session-bind") { + finishSession(Error::ResourceBindError); + } + else if (!resourceBind) { + finishSession(Error::UnexpectedElementError); + } + else if (iq->getType() == IQ::Result) { + localJID = resourceBind->getJID(); + if (!localJID.isValid()) { + finishSession(Error::ResourceBindError); + } + needResourceBind = false; + continueSessionInitialization(); + } + else { + finishSession(Error::UnexpectedElementError); + } + } + else if (state == StartingSession) { + if (iq->getType() == IQ::Result) { + needSessionStart = false; + continueSessionInitialization(); + } + else if (iq->getType() == IQ::Error) { + finishSession(Error::SessionStartError); + } + else { + finishSession(Error::UnexpectedElementError); + } + } + else { + finishSession(Error::UnexpectedElementError); + } + } + } + else if (boost::dynamic_pointer_cast<StanzaAckRequest>(element)) { + if (stanzaAckResponder_) { + stanzaAckResponder_->handleAckRequestReceived(); + } + } + else if (boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(element)) { + if (stanzaAckRequester_) { + if (ack->isValid()) { + stanzaAckRequester_->handleAckReceived(ack->getHandledStanzasCount()); + } + else { + SWIFT_LOG(warning) << "Got invalid ack from server"; + } + } + else { + SWIFT_LOG(warning) << "Ignoring ack"; + } + } + else if (StreamError::ref streamError = boost::dynamic_pointer_cast<StreamError>(element)) { + finishSession(Error::StreamError); + } + else if (getState() == Initialized) { + boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element); + if (stanza) { + if (stanzaAckResponder_) { + stanzaAckResponder_->handleStanzaReceived(); + } + onStanzaReceived(stanza); + } + } + else if (StreamFeatures* streamFeatures = dynamic_cast<StreamFeatures*>(element.get())) { + CHECK_STATE_OR_RETURN(Negotiating); + + if (streamFeatures->hasStartTLS() && stream->supportsTLSEncryption() && useTLS != NeverUseTLS) { + state = WaitingForEncrypt; + stream->writeElement(boost::make_shared<StartTLSRequest>()); + } + else if (useTLS == RequireTLS && !stream->isTLSEncrypted()) { + finishSession(Error::NoSupportedAuthMechanismsError); + } + else if (useStreamCompression && stream->supportsZLibCompression() && streamFeatures->hasCompressionMethod("zlib")) { + state = Compressing; + stream->writeElement(boost::make_shared<CompressRequest>("zlib")); + } + else if (streamFeatures->hasAuthenticationMechanisms()) { #ifdef SWIFTEN_PLATFORM_WIN32 - if (singleSignOn) { - const boost::optional<std::string> authenticationHostname = streamFeatures->getAuthenticationHostname(); - bool gssapiSupported = streamFeatures->hasAuthenticationMechanism("GSSAPI") && authenticationHostname && !authenticationHostname->empty(); - - if (!gssapiSupported) { - finishSession(Error::NoSupportedAuthMechanismsError); - } - else { - WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = new WindowsGSSAPIClientAuthenticator(*authenticationHostname, localJID.getDomain(), authenticationPort); - boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError); - - authenticator = gssapiAuthenticator; - - if (!gssapiAuthenticator->isError()) { - state = Authenticating; - stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse())); - } - else { - error->errorCode = gssapiAuthenticator->getErrorCode(); - finishSession(error); - } - } - } - else + if (singleSignOn) { + const boost::optional<std::string> authenticationHostname = streamFeatures->getAuthenticationHostname(); + bool gssapiSupported = streamFeatures->hasAuthenticationMechanism("GSSAPI") && authenticationHostname && !authenticationHostname->empty(); + + if (!gssapiSupported) { + finishSession(Error::NoSupportedAuthMechanismsError); + } + else { + WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = new WindowsGSSAPIClientAuthenticator(*authenticationHostname, localJID.getDomain(), authenticationPort); + boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError); + + authenticator = gssapiAuthenticator; + + if (!gssapiAuthenticator->isError()) { + state = Authenticating; + stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse())); + } + else { + error->errorCode = gssapiAuthenticator->getErrorCode(); + finishSession(error); + } + } + } + else #endif - if (stream->hasTLSCertificate()) { - if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) { - authenticator = new EXTERNALClientAuthenticator(); - state = Authenticating; - stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray(""))); - } - else { - finishSession(Error::TLSClientCertificateError); - } - } - else if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) { - authenticator = new EXTERNALClientAuthenticator(); - state = Authenticating; - stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray(""))); - } - else if (streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1") || streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS")) { - std::ostringstream s; - ByteArray finishMessage; - bool plus = streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS"); - if (stream->isTLSEncrypted()) { - finishMessage = stream->getTLSFinishMessage(); - plus &= !finishMessage.empty(); - } - s << boost::uuids::random_generator()(); - SCRAMSHA1ClientAuthenticator* scramAuthenticator = new SCRAMSHA1ClientAuthenticator(s.str(), plus, idnConverter, crypto); - if (!finishMessage.empty()) { - scramAuthenticator->setTLSChannelBindingData(finishMessage); - } - authenticator = scramAuthenticator; - state = WaitingForCredentials; - onNeedCredentials(); - } - else if ((stream->isTLSEncrypted() || allowPLAINOverNonTLS) && streamFeatures->hasAuthenticationMechanism("PLAIN")) { - authenticator = new PLAINClientAuthenticator(); - state = WaitingForCredentials; - onNeedCredentials(); - } - else if (streamFeatures->hasAuthenticationMechanism("DIGEST-MD5") && crypto->isMD5AllowedForCrypto()) { - std::ostringstream s; - s << boost::uuids::random_generator()(); - // FIXME: Host should probably be the actual host - authenticator = new DIGESTMD5ClientAuthenticator(localJID.getDomain(), s.str(), crypto); - state = WaitingForCredentials; - onNeedCredentials(); - } - else { - finishSession(Error::NoSupportedAuthMechanismsError); - } - } - else { - // Start the session - rosterVersioningSupported = streamFeatures->hasRosterVersioning(); - stream->setWhitespacePingEnabled(true); - needSessionStart = streamFeatures->hasSession(); - needResourceBind = streamFeatures->hasResourceBind(); - needAcking = streamFeatures->hasStreamManagement() && useAcks; - if (!needResourceBind) { - // Resource binding is a MUST - finishSession(Error::ResourceBindError); - } - else { - continueSessionInitialization(); - } - } - } - else if (boost::dynamic_pointer_cast<Compressed>(element)) { - CHECK_STATE_OR_RETURN(Compressing); - state = WaitingForStreamStart; - stream->addZLibCompression(); - stream->resetXMPPParser(); - sendStreamHeader(); - } - else if (boost::dynamic_pointer_cast<CompressFailure>(element)) { - finishSession(Error::CompressionFailedError); - } - else if (boost::dynamic_pointer_cast<StreamManagementEnabled>(element)) { - stanzaAckRequester_ = boost::make_shared<StanzaAckRequester>(); - stanzaAckRequester_->onRequestAck.connect(boost::bind(&ClientSession::requestAck, shared_from_this())); - stanzaAckRequester_->onStanzaAcked.connect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1)); - stanzaAckResponder_ = boost::make_shared<StanzaAckResponder>(); - stanzaAckResponder_->onAck.connect(boost::bind(&ClientSession::ack, shared_from_this(), _1)); - needAcking = false; - continueSessionInitialization(); - } - else if (boost::dynamic_pointer_cast<StreamManagementFailed>(element)) { - needAcking = false; - continueSessionInitialization(); - } - else if (AuthChallenge* challenge = dynamic_cast<AuthChallenge*>(element.get())) { - CHECK_STATE_OR_RETURN(Authenticating); - assert(authenticator); - if (authenticator->setChallenge(challenge->getValue())) { - stream->writeElement(boost::make_shared<AuthResponse>(authenticator->getResponse())); - } + if (stream->hasTLSCertificate()) { + if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) { + authenticator = new EXTERNALClientAuthenticator(); + state = Authenticating; + stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray(""))); + } + else { + finishSession(Error::TLSClientCertificateError); + } + } + else if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) { + authenticator = new EXTERNALClientAuthenticator(); + state = Authenticating; + stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray(""))); + } + else if (streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1") || streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS")) { + std::ostringstream s; + ByteArray finishMessage; + bool plus = streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS"); + if (stream->isTLSEncrypted()) { + finishMessage = stream->getTLSFinishMessage(); + plus &= !finishMessage.empty(); + } + s << boost::uuids::random_generator()(); + SCRAMSHA1ClientAuthenticator* scramAuthenticator = new SCRAMSHA1ClientAuthenticator(s.str(), plus, idnConverter, crypto); + if (!finishMessage.empty()) { + scramAuthenticator->setTLSChannelBindingData(finishMessage); + } + authenticator = scramAuthenticator; + state = WaitingForCredentials; + onNeedCredentials(); + } + else if ((stream->isTLSEncrypted() || allowPLAINOverNonTLS) && streamFeatures->hasAuthenticationMechanism("PLAIN")) { + authenticator = new PLAINClientAuthenticator(); + state = WaitingForCredentials; + onNeedCredentials(); + } + else if (streamFeatures->hasAuthenticationMechanism("DIGEST-MD5") && crypto->isMD5AllowedForCrypto()) { + std::ostringstream s; + s << boost::uuids::random_generator()(); + // FIXME: Host should probably be the actual host + authenticator = new DIGESTMD5ClientAuthenticator(localJID.getDomain(), s.str(), crypto); + state = WaitingForCredentials; + onNeedCredentials(); + } + else { + finishSession(Error::NoSupportedAuthMechanismsError); + } + } + else { + // Start the session + rosterVersioningSupported = streamFeatures->hasRosterVersioning(); + stream->setWhitespacePingEnabled(true); + needSessionStart = streamFeatures->hasSession(); + needResourceBind = streamFeatures->hasResourceBind(); + needAcking = streamFeatures->hasStreamManagement() && useAcks; + if (!needResourceBind) { + // Resource binding is a MUST + finishSession(Error::ResourceBindError); + } + else { + continueSessionInitialization(); + } + } + } + else if (boost::dynamic_pointer_cast<Compressed>(element)) { + CHECK_STATE_OR_RETURN(Compressing); + state = WaitingForStreamStart; + stream->addZLibCompression(); + stream->resetXMPPParser(); + sendStreamHeader(); + } + else if (boost::dynamic_pointer_cast<CompressFailure>(element)) { + finishSession(Error::CompressionFailedError); + } + else if (boost::dynamic_pointer_cast<StreamManagementEnabled>(element)) { + stanzaAckRequester_ = boost::make_shared<StanzaAckRequester>(); + stanzaAckRequester_->onRequestAck.connect(boost::bind(&ClientSession::requestAck, shared_from_this())); + stanzaAckRequester_->onStanzaAcked.connect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1)); + stanzaAckResponder_ = boost::make_shared<StanzaAckResponder>(); + stanzaAckResponder_->onAck.connect(boost::bind(&ClientSession::ack, shared_from_this(), _1)); + needAcking = false; + continueSessionInitialization(); + } + else if (boost::dynamic_pointer_cast<StreamManagementFailed>(element)) { + needAcking = false; + continueSessionInitialization(); + } + else if (AuthChallenge* challenge = dynamic_cast<AuthChallenge*>(element.get())) { + CHECK_STATE_OR_RETURN(Authenticating); + assert(authenticator); + if (authenticator->setChallenge(challenge->getValue())) { + stream->writeElement(boost::make_shared<AuthResponse>(authenticator->getResponse())); + } #ifdef SWIFTEN_PLATFORM_WIN32 - else if (WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = dynamic_cast<WindowsGSSAPIClientAuthenticator*>(authenticator)) { - boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError); + else if (WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = dynamic_cast<WindowsGSSAPIClientAuthenticator*>(authenticator)) { + boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError); - error->errorCode = gssapiAuthenticator->getErrorCode(); - finishSession(error); - } + error->errorCode = gssapiAuthenticator->getErrorCode(); + finishSession(error); + } #endif - else { - finishSession(Error::AuthenticationFailedError); - } - } - else if (AuthSuccess* authSuccess = dynamic_cast<AuthSuccess*>(element.get())) { - CHECK_STATE_OR_RETURN(Authenticating); - assert(authenticator); - if (!authenticator->setChallenge(authSuccess->getValue())) { - finishSession(Error::ServerVerificationFailedError); - } - else { - state = WaitingForStreamStart; - delete authenticator; - authenticator = NULL; - stream->resetXMPPParser(); - sendStreamHeader(); - } - } - else if (dynamic_cast<AuthFailure*>(element.get())) { - finishSession(Error::AuthenticationFailedError); - } - else if (dynamic_cast<TLSProceed*>(element.get())) { - CHECK_STATE_OR_RETURN(WaitingForEncrypt); - state = Encrypting; - stream->addTLSEncryption(); - } - else if (dynamic_cast<StartTLSFailure*>(element.get())) { - finishSession(Error::TLSError); - } - else { - // FIXME Not correct? - state = Initialized; - onInitialized(); - } + else { + finishSession(Error::AuthenticationFailedError); + } + } + else if (AuthSuccess* authSuccess = dynamic_cast<AuthSuccess*>(element.get())) { + CHECK_STATE_OR_RETURN(Authenticating); + assert(authenticator); + if (!authenticator->setChallenge(authSuccess->getValue())) { + finishSession(Error::ServerVerificationFailedError); + } + else { + state = WaitingForStreamStart; + delete authenticator; + authenticator = NULL; + stream->resetXMPPParser(); + sendStreamHeader(); + } + } + else if (dynamic_cast<AuthFailure*>(element.get())) { + finishSession(Error::AuthenticationFailedError); + } + else if (dynamic_cast<TLSProceed*>(element.get())) { + CHECK_STATE_OR_RETURN(WaitingForEncrypt); + state = Encrypting; + stream->addTLSEncryption(); + } + else if (dynamic_cast<StartTLSFailure*>(element.get())) { + finishSession(Error::TLSError); + } + else { + // FIXME Not correct? + state = Initialized; + onInitialized(); + } } void ClientSession::continueSessionInitialization() { - if (needResourceBind) { - state = BindingResource; - boost::shared_ptr<ResourceBind> resourceBind(boost::make_shared<ResourceBind>()); - if (!localJID.getResource().empty()) { - resourceBind->setResource(localJID.getResource()); - } - sendStanza(IQ::createRequest(IQ::Set, JID(), "session-bind", resourceBind)); - } - else if (needAcking) { - state = EnablingSessionManagement; - stream->writeElement(boost::make_shared<EnableStreamManagement>()); - } - else if (needSessionStart) { - state = StartingSession; - sendStanza(IQ::createRequest(IQ::Set, JID(), "session-start", boost::make_shared<StartSession>())); - } - else { - state = Initialized; - onInitialized(); - } + if (needResourceBind) { + state = BindingResource; + boost::shared_ptr<ResourceBind> resourceBind(boost::make_shared<ResourceBind>()); + if (!localJID.getResource().empty()) { + resourceBind->setResource(localJID.getResource()); + } + sendStanza(IQ::createRequest(IQ::Set, JID(), "session-bind", resourceBind)); + } + else if (needAcking) { + state = EnablingSessionManagement; + stream->writeElement(boost::make_shared<EnableStreamManagement>()); + } + else if (needSessionStart) { + state = StartingSession; + sendStanza(IQ::createRequest(IQ::Set, JID(), "session-start", boost::make_shared<StartSession>())); + } + else { + state = Initialized; + onInitialized(); + } } bool ClientSession::checkState(State state) { - if (this->state != state) { - finishSession(Error::UnexpectedElementError); - return false; - } - return true; + if (this->state != state) { + finishSession(Error::UnexpectedElementError); + return false; + } + return true; } void ClientSession::sendCredentials(const SafeByteArray& password) { - assert(WaitingForCredentials); - assert(authenticator); - state = Authenticating; - authenticator->setCredentials(localJID.getNode(), password); - stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse())); + assert(WaitingForCredentials); + assert(authenticator); + state = Authenticating; + authenticator->setCredentials(localJID.getNode(), password); + stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse())); } void ClientSession::handleTLSEncrypted() { - CHECK_STATE_OR_RETURN(Encrypting); - - std::vector<Certificate::ref> certificateChain = stream->getPeerCertificateChain(); - boost::shared_ptr<CertificateVerificationError> verificationError = stream->getPeerCertificateVerificationError(); - if (verificationError) { - checkTrustOrFinish(certificateChain, verificationError); - } - else { - ServerIdentityVerifier identityVerifier(localJID, idnConverter); - if (!certificateChain.empty() && identityVerifier.certificateVerifies(certificateChain[0])) { - continueAfterTLSEncrypted(); - } - else { - checkTrustOrFinish(certificateChain, boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidServerIdentity)); - } - } + CHECK_STATE_OR_RETURN(Encrypting); + + std::vector<Certificate::ref> certificateChain = stream->getPeerCertificateChain(); + boost::shared_ptr<CertificateVerificationError> verificationError = stream->getPeerCertificateVerificationError(); + if (verificationError) { + checkTrustOrFinish(certificateChain, verificationError); + } + else { + ServerIdentityVerifier identityVerifier(localJID, idnConverter); + if (!certificateChain.empty() && identityVerifier.certificateVerifies(certificateChain[0])) { + continueAfterTLSEncrypted(); + } + else { + checkTrustOrFinish(certificateChain, boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidServerIdentity)); + } + } } void ClientSession::checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error) { - if (certificateTrustChecker && certificateTrustChecker->isCertificateTrusted(certificateChain)) { - continueAfterTLSEncrypted(); - } - else { - finishSession(error); - } + if (certificateTrustChecker && certificateTrustChecker->isCertificateTrusted(certificateChain)) { + continueAfterTLSEncrypted(); + } + else { + finishSession(error); + } } void ClientSession::continueAfterTLSEncrypted() { - state = WaitingForStreamStart; - stream->resetXMPPParser(); - sendStreamHeader(); + state = WaitingForStreamStart; + stream->resetXMPPParser(); + sendStreamHeader(); } void ClientSession::handleStreamClosed(boost::shared_ptr<Swift::Error> streamError) { - State previousState = state; - state = Finished; - - if (stanzaAckRequester_) { - stanzaAckRequester_->onRequestAck.disconnect(boost::bind(&ClientSession::requestAck, shared_from_this())); - stanzaAckRequester_->onStanzaAcked.disconnect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1)); - stanzaAckRequester_.reset(); - } - if (stanzaAckResponder_) { - stanzaAckResponder_->onAck.disconnect(boost::bind(&ClientSession::ack, shared_from_this(), _1)); - stanzaAckResponder_.reset(); - } - stream->setWhitespacePingEnabled(false); - stream->onStreamStartReceived.disconnect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1)); - stream->onElementReceived.disconnect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1)); - stream->onClosed.disconnect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1)); - stream->onTLSEncrypted.disconnect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this())); - - if (previousState == Finishing) { - onFinished(error_); - } - else { - onFinished(streamError); - } + State previousState = state; + state = Finished; + + if (stanzaAckRequester_) { + stanzaAckRequester_->onRequestAck.disconnect(boost::bind(&ClientSession::requestAck, shared_from_this())); + stanzaAckRequester_->onStanzaAcked.disconnect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1)); + stanzaAckRequester_.reset(); + } + if (stanzaAckResponder_) { + stanzaAckResponder_->onAck.disconnect(boost::bind(&ClientSession::ack, shared_from_this(), _1)); + stanzaAckResponder_.reset(); + } + stream->setWhitespacePingEnabled(false); + stream->onStreamStartReceived.disconnect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1)); + stream->onElementReceived.disconnect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1)); + stream->onClosed.disconnect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1)); + stream->onTLSEncrypted.disconnect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this())); + + if (previousState == Finishing) { + onFinished(error_); + } + else { + onFinished(streamError); + } } void ClientSession::finish() { - finishSession(boost::shared_ptr<Error>()); + finishSession(boost::shared_ptr<Error>()); } void ClientSession::finishSession(Error::Type error) { - finishSession(boost::make_shared<Swift::ClientSession::Error>(error)); + finishSession(boost::make_shared<Swift::ClientSession::Error>(error)); } void ClientSession::finishSession(boost::shared_ptr<Swift::Error> error) { - state = Finishing; - if (!error_) { - error_ = error; - } - else { - SWIFT_LOG(warning) << "Session finished twice"; - } - assert(stream->isOpen()); - if (stanzaAckResponder_) { - stanzaAckResponder_->handleAckRequestReceived(); - } - if (authenticator) { - delete authenticator; - authenticator = NULL; - } - stream->writeFooter(); - stream->close(); + state = Finishing; + if (!error_) { + error_ = error; + } + else { + SWIFT_LOG(warning) << "Session finished twice"; + } + assert(stream->isOpen()); + if (stanzaAckResponder_) { + stanzaAckResponder_->handleAckRequestReceived(); + } + if (authenticator) { + delete authenticator; + authenticator = NULL; + } + stream->writeFooter(); + stream->close(); } void ClientSession::requestAck() { - stream->writeElement(boost::make_shared<StanzaAckRequest>()); + stream->writeElement(boost::make_shared<StanzaAckRequest>()); } void ClientSession::handleStanzaAcked(boost::shared_ptr<Stanza> stanza) { - onStanzaAcked(stanza); + onStanzaAcked(stanza); } void ClientSession::ack(unsigned int handledStanzasCount) { - stream->writeElement(boost::make_shared<StanzaAck>(handledStanzasCount)); + stream->writeElement(boost::make_shared<StanzaAck>(handledStanzasCount)); } } diff --git a/Swiften/Client/ClientSession.h b/Swiften/Client/ClientSession.h index a125c71..b1b6755 100644 --- a/Swiften/Client/ClientSession.h +++ b/Swiften/Client/ClientSession.h @@ -21,182 +21,182 @@ #include <Swiften/StreamManagement/StanzaAckResponder.h> namespace Swift { - class ClientAuthenticator; - class CertificateTrustChecker; - class IDNConverter; - class CryptoProvider; - - class SWIFTEN_API ClientSession : public boost::enable_shared_from_this<ClientSession> { - public: - enum State { - Initial, - WaitingForStreamStart, - Negotiating, - Compressing, - WaitingForEncrypt, - Encrypting, - WaitingForCredentials, - Authenticating, - EnablingSessionManagement, - BindingResource, - StartingSession, - Initialized, - Finishing, - Finished - }; - - struct Error : public Swift::Error { - enum Type { - AuthenticationFailedError, - CompressionFailedError, - ServerVerificationFailedError, - NoSupportedAuthMechanismsError, - UnexpectedElementError, - ResourceBindError, - SessionStartError, - TLSClientCertificateError, - TLSError, - StreamError - } type; - boost::shared_ptr<boost::system::error_code> errorCode; - Error(Type type) : type(type) {} - }; - - enum UseTLS { - NeverUseTLS, - UseTLSWhenAvailable, - RequireTLS - }; - - ~ClientSession(); - - static boost::shared_ptr<ClientSession> create(const JID& jid, boost::shared_ptr<SessionStream> stream, IDNConverter* idnConverter, CryptoProvider* crypto) { - return boost::shared_ptr<ClientSession>(new ClientSession(jid, stream, idnConverter, crypto)); - } - - State getState() const { - return state; - } - - void setAllowPLAINOverNonTLS(bool b) { - allowPLAINOverNonTLS = b; - } - - void setUseStreamCompression(bool b) { - useStreamCompression = b; - } - - void setUseTLS(UseTLS b) { - useTLS = b; - } - - void setUseAcks(bool b) { - useAcks = b; - } - - - bool getStreamManagementEnabled() const { - // Explicitly convert to bool. In C++11, it would be cleaner to - // compare to nullptr. - return static_cast<bool>(stanzaAckRequester_); - } - - bool getRosterVersioningSupported() const { - return rosterVersioningSupported; - } - - std::vector<Certificate::ref> getPeerCertificateChain() const { - return stream->getPeerCertificateChain(); - } - - const JID& getLocalJID() const { - return localJID; - } - - void start(); - void finish(); - - bool isFinished() const { - return getState() == Finished; - } - - void sendCredentials(const SafeByteArray& password); - void sendStanza(boost::shared_ptr<Stanza>); - - void setCertificateTrustChecker(CertificateTrustChecker* checker) { - certificateTrustChecker = checker; - } - - void setSingleSignOn(bool b) { - singleSignOn = b; - } - - /** - * Sets the port number used in Kerberos authentication - * Does not affect network connectivity. - */ - void setAuthenticationPort(int i) { - authenticationPort = i; - } - - public: - boost::signal<void ()> onNeedCredentials; - boost::signal<void ()> onInitialized; - boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished; - boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived; - boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked; - - private: - ClientSession( - const JID& jid, - boost::shared_ptr<SessionStream>, - IDNConverter* idnConverter, - CryptoProvider* crypto); - - void finishSession(Error::Type error); - void finishSession(boost::shared_ptr<Swift::Error> error); - - JID getRemoteJID() const { - return JID("", localJID.getDomain()); - } - - void sendStreamHeader(); - - void handleElement(boost::shared_ptr<ToplevelElement>); - void handleStreamStart(const ProtocolHeader&); - void handleStreamClosed(boost::shared_ptr<Swift::Error>); - - void handleTLSEncrypted(); - - bool checkState(State); - void continueSessionInitialization(); - - void requestAck(); - void handleStanzaAcked(boost::shared_ptr<Stanza> stanza); - void ack(unsigned int handledStanzasCount); - void continueAfterTLSEncrypted(); - void checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error); - - private: - JID localJID; - State state; - boost::shared_ptr<SessionStream> stream; - IDNConverter* idnConverter; - CryptoProvider* crypto; - bool allowPLAINOverNonTLS; - bool useStreamCompression; - UseTLS useTLS; - bool useAcks; - bool needSessionStart; - bool needResourceBind; - bool needAcking; - bool rosterVersioningSupported; - ClientAuthenticator* authenticator; - boost::shared_ptr<StanzaAckRequester> stanzaAckRequester_; - boost::shared_ptr<StanzaAckResponder> stanzaAckResponder_; - boost::shared_ptr<Swift::Error> error_; - CertificateTrustChecker* certificateTrustChecker; - bool singleSignOn; - int authenticationPort; - }; + class ClientAuthenticator; + class CertificateTrustChecker; + class IDNConverter; + class CryptoProvider; + + class SWIFTEN_API ClientSession : public boost::enable_shared_from_this<ClientSession> { + public: + enum State { + Initial, + WaitingForStreamStart, + Negotiating, + Compressing, + WaitingForEncrypt, + Encrypting, + WaitingForCredentials, + Authenticating, + EnablingSessionManagement, + BindingResource, + StartingSession, + Initialized, + Finishing, + Finished + }; + + struct Error : public Swift::Error { + enum Type { + AuthenticationFailedError, + CompressionFailedError, + ServerVerificationFailedError, + NoSupportedAuthMechanismsError, + UnexpectedElementError, + ResourceBindError, + SessionStartError, + TLSClientCertificateError, + TLSError, + StreamError + } type; + boost::shared_ptr<boost::system::error_code> errorCode; + Error(Type type) : type(type) {} + }; + + enum UseTLS { + NeverUseTLS, + UseTLSWhenAvailable, + RequireTLS + }; + + ~ClientSession(); + + static boost::shared_ptr<ClientSession> create(const JID& jid, boost::shared_ptr<SessionStream> stream, IDNConverter* idnConverter, CryptoProvider* crypto) { + return boost::shared_ptr<ClientSession>(new ClientSession(jid, stream, idnConverter, crypto)); + } + + State getState() const { + return state; + } + + void setAllowPLAINOverNonTLS(bool b) { + allowPLAINOverNonTLS = b; + } + + void setUseStreamCompression(bool b) { + useStreamCompression = b; + } + + void setUseTLS(UseTLS b) { + useTLS = b; + } + + void setUseAcks(bool b) { + useAcks = b; + } + + + bool getStreamManagementEnabled() const { + // Explicitly convert to bool. In C++11, it would be cleaner to + // compare to nullptr. + return static_cast<bool>(stanzaAckRequester_); + } + + bool getRosterVersioningSupported() const { + return rosterVersioningSupported; + } + + std::vector<Certificate::ref> getPeerCertificateChain() const { + return stream->getPeerCertificateChain(); + } + + const JID& getLocalJID() const { + return localJID; + } + + void start(); + void finish(); + + bool isFinished() const { + return getState() == Finished; + } + + void sendCredentials(const SafeByteArray& password); + void sendStanza(boost::shared_ptr<Stanza>); + + void setCertificateTrustChecker(CertificateTrustChecker* checker) { + certificateTrustChecker = checker; + } + + void setSingleSignOn(bool b) { + singleSignOn = b; + } + + /** + * Sets the port number used in Kerberos authentication + * Does not affect network connectivity. + */ + void setAuthenticationPort(int i) { + authenticationPort = i; + } + + public: + boost::signal<void ()> onNeedCredentials; + boost::signal<void ()> onInitialized; + boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished; + boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived; + boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked; + + private: + ClientSession( + const JID& jid, + boost::shared_ptr<SessionStream>, + IDNConverter* idnConverter, + CryptoProvider* crypto); + + void finishSession(Error::Type error); + void finishSession(boost::shared_ptr<Swift::Error> error); + + JID getRemoteJID() const { + return JID("", localJID.getDomain()); + } + + void sendStreamHeader(); + + void handleElement(boost::shared_ptr<ToplevelElement>); + void handleStreamStart(const ProtocolHeader&); + void handleStreamClosed(boost::shared_ptr<Swift::Error>); + + void handleTLSEncrypted(); + + bool checkState(State); + void continueSessionInitialization(); + + void requestAck(); + void handleStanzaAcked(boost::shared_ptr<Stanza> stanza); + void ack(unsigned int handledStanzasCount); + void continueAfterTLSEncrypted(); + void checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error); + + private: + JID localJID; + State state; + boost::shared_ptr<SessionStream> stream; + IDNConverter* idnConverter; + CryptoProvider* crypto; + bool allowPLAINOverNonTLS; + bool useStreamCompression; + UseTLS useTLS; + bool useAcks; + bool needSessionStart; + bool needResourceBind; + bool needAcking; + bool rosterVersioningSupported; + ClientAuthenticator* authenticator; + boost::shared_ptr<StanzaAckRequester> stanzaAckRequester_; + boost::shared_ptr<StanzaAckResponder> stanzaAckResponder_; + boost::shared_ptr<Swift::Error> error_; + CertificateTrustChecker* certificateTrustChecker; + bool singleSignOn; + int authenticationPort; + }; } diff --git a/Swiften/Client/ClientSessionStanzaChannel.cpp b/Swiften/Client/ClientSessionStanzaChannel.cpp index 3dc8c59..1340b7c 100644 --- a/Swiften/Client/ClientSessionStanzaChannel.cpp +++ b/Swiften/Client/ClientSessionStanzaChannel.cpp @@ -13,100 +13,100 @@ namespace Swift { ClientSessionStanzaChannel::~ClientSessionStanzaChannel() { - if (session) { - session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1)); - session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1)); - session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1)); - session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this)); - session.reset(); - } + if (session) { + session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1)); + session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1)); + session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1)); + session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this)); + session.reset(); + } } void ClientSessionStanzaChannel::setSession(boost::shared_ptr<ClientSession> session) { - assert(!this->session); - this->session = session; - session->onInitialized.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this)); - session->onFinished.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1)); - session->onStanzaReceived.connect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1)); - session->onStanzaAcked.connect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1)); + assert(!this->session); + this->session = session; + session->onInitialized.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this)); + session->onFinished.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1)); + session->onStanzaReceived.connect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1)); + session->onStanzaAcked.connect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1)); } void ClientSessionStanzaChannel::sendIQ(boost::shared_ptr<IQ> iq) { - send(iq); + send(iq); } void ClientSessionStanzaChannel::sendMessage(boost::shared_ptr<Message> message) { - send(message); + send(message); } void ClientSessionStanzaChannel::sendPresence(boost::shared_ptr<Presence> presence) { - send(presence); + send(presence); } std::string ClientSessionStanzaChannel::getNewIQID() { - return idGenerator.generateID(); + return idGenerator.generateID(); } void ClientSessionStanzaChannel::send(boost::shared_ptr<Stanza> stanza) { - if (!isAvailable()) { - std::cerr << "Warning: Client: Trying to send a stanza while disconnected." << std::endl; - return; - } - session->sendStanza(stanza); + if (!isAvailable()) { + std::cerr << "Warning: Client: Trying to send a stanza while disconnected." << std::endl; + return; + } + session->sendStanza(stanza); } void ClientSessionStanzaChannel::handleSessionFinished(boost::shared_ptr<Error>) { - session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1)); - session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1)); - session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1)); - session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this)); - session.reset(); + session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1)); + session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1)); + session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1)); + session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this)); + session.reset(); - onAvailableChanged(false); + onAvailableChanged(false); } void ClientSessionStanzaChannel::handleStanza(boost::shared_ptr<Stanza> stanza) { - boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza); - if (message) { - onMessageReceived(message); - return; - } - - boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza); - if (presence) { - onPresenceReceived(presence); - return; - } - - boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza); - if (iq) { - onIQReceived(iq); - return; - } + boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza); + if (message) { + onMessageReceived(message); + return; + } + + boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza); + if (presence) { + onPresenceReceived(presence); + return; + } + + boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza); + if (iq) { + onIQReceived(iq); + return; + } } bool ClientSessionStanzaChannel::getStreamManagementEnabled() const { - if (session) { - return session->getStreamManagementEnabled(); - } - return false; + if (session) { + return session->getStreamManagementEnabled(); + } + return false; } std::vector<Certificate::ref> ClientSessionStanzaChannel::getPeerCertificateChain() const { - if (session) { - return session->getPeerCertificateChain(); - } - return std::vector<Certificate::ref>(); + if (session) { + return session->getPeerCertificateChain(); + } + return std::vector<Certificate::ref>(); } void ClientSessionStanzaChannel::handleStanzaAcked(boost::shared_ptr<Stanza> stanza) { - onStanzaAcked(stanza); + onStanzaAcked(stanza); } void ClientSessionStanzaChannel::handleSessionInitialized() { - onAvailableChanged(true); + onAvailableChanged(true); } } diff --git a/Swiften/Client/ClientSessionStanzaChannel.h b/Swiften/Client/ClientSessionStanzaChannel.h index 0ffcd9d..d3b302b 100644 --- a/Swiften/Client/ClientSessionStanzaChannel.h +++ b/Swiften/Client/ClientSessionStanzaChannel.h @@ -17,36 +17,36 @@ #include <Swiften/Elements/Presence.h> namespace Swift { - /** - * StanzaChannel implementation around a ClientSession. - */ - class SWIFTEN_API ClientSessionStanzaChannel : public StanzaChannel { - public: - virtual ~ClientSessionStanzaChannel(); - - void setSession(boost::shared_ptr<ClientSession> session); - - void sendIQ(boost::shared_ptr<IQ> iq); - void sendMessage(boost::shared_ptr<Message> message); - void sendPresence(boost::shared_ptr<Presence> presence); - bool getStreamManagementEnabled() const; - virtual std::vector<Certificate::ref> getPeerCertificateChain() const; - - bool isAvailable() const { - return session && session->getState() == ClientSession::Initialized; - } - - private: - std::string getNewIQID(); - void send(boost::shared_ptr<Stanza> stanza); - void handleSessionFinished(boost::shared_ptr<Error> error); - void handleStanza(boost::shared_ptr<Stanza> stanza); - void handleStanzaAcked(boost::shared_ptr<Stanza> stanza); - void handleSessionInitialized(); - - private: - IDGenerator idGenerator; - boost::shared_ptr<ClientSession> session; - }; + /** + * StanzaChannel implementation around a ClientSession. + */ + class SWIFTEN_API ClientSessionStanzaChannel : public StanzaChannel { + public: + virtual ~ClientSessionStanzaChannel(); + + void setSession(boost::shared_ptr<ClientSession> session); + + void sendIQ(boost::shared_ptr<IQ> iq); + void sendMessage(boost::shared_ptr<Message> message); + void sendPresence(boost::shared_ptr<Presence> presence); + bool getStreamManagementEnabled() const; + virtual std::vector<Certificate::ref> getPeerCertificateChain() const; + + bool isAvailable() const { + return session && session->getState() == ClientSession::Initialized; + } + + private: + std::string getNewIQID(); + void send(boost::shared_ptr<Stanza> stanza); + void handleSessionFinished(boost::shared_ptr<Error> error); + void handleStanza(boost::shared_ptr<Stanza> stanza); + void handleStanzaAcked(boost::shared_ptr<Stanza> stanza); + void handleSessionInitialized(); + + private: + IDGenerator idGenerator; + boost::shared_ptr<ClientSession> session; + }; } diff --git a/Swiften/Client/ClientXMLTracer.cpp b/Swiften/Client/ClientXMLTracer.cpp index a34aecc..4852aa1 100644 --- a/Swiften/Client/ClientXMLTracer.cpp +++ b/Swiften/Client/ClientXMLTracer.cpp @@ -16,41 +16,41 @@ namespace Swift { ClientXMLTracer::ClientXMLTracer(CoreClient* client, bool bosh) : bosh(bosh) { #ifdef SWIFTEN_PLATFORM_WIN32 - beautifier = new XMLBeautifier(true, false); + beautifier = new XMLBeautifier(true, false); #else - beautifier = new XMLBeautifier(true, true); + beautifier = new XMLBeautifier(true, true); #endif - onDataReadConnection = client->onDataRead.connect(boost::bind(&ClientXMLTracer::printData, this, '<', _1)); - onDataWrittenConnection = client->onDataWritten.connect(boost::bind(&ClientXMLTracer::printData, this, '>', _1)); + onDataReadConnection = client->onDataRead.connect(boost::bind(&ClientXMLTracer::printData, this, '<', _1)); + onDataWrittenConnection = client->onDataWritten.connect(boost::bind(&ClientXMLTracer::printData, this, '>', _1)); } ClientXMLTracer::~ClientXMLTracer() { - delete beautifier; + delete beautifier; } void ClientXMLTracer::printData(char direction, const SafeByteArray& data) { - printLine(direction); - if (bosh) { - std::string line = byteArrayToString(ByteArray(data.begin(), data.end())); + printLine(direction); + if (bosh) { + std::string line = byteArrayToString(ByteArray(data.begin(), data.end())); // Disabled because it swallows bits of XML (namespaces, if I recall) -// size_t endOfHTTP = line.find("\r\n\r\n"); -// if (false && endOfHTTP != std::string::npos) { -// std::cerr << line.substr(0, endOfHTTP) << std::endl << beautifier->beautify(line.substr(endOfHTTP)) << std::endl; -// } -// else { - std::cerr << line << std::endl; -// } - } - else { - std::cerr << beautifier->beautify(byteArrayToString(ByteArray(data.begin(), data.end()))) << std::endl; - } +// size_t endOfHTTP = line.find("\r\n\r\n"); +// if (false && endOfHTTP != std::string::npos) { +// std::cerr << line.substr(0, endOfHTTP) << std::endl << beautifier->beautify(line.substr(endOfHTTP)) << std::endl; +// } +// else { + std::cerr << line << std::endl; +// } + } + else { + std::cerr << beautifier->beautify(byteArrayToString(ByteArray(data.begin(), data.end()))) << std::endl; + } } void ClientXMLTracer::printLine(char c) { - for (unsigned int i = 0; i < 80; ++i) { - std::cerr << c; - } - std::cerr << std::endl; + for (unsigned int i = 0; i < 80; ++i) { + std::cerr << c; + } + std::cerr << std::endl; } } diff --git a/Swiften/Client/ClientXMLTracer.h b/Swiften/Client/ClientXMLTracer.h index bbaced9..ccecb41 100644 --- a/Swiften/Client/ClientXMLTracer.h +++ b/Swiften/Client/ClientXMLTracer.h @@ -12,19 +12,19 @@ #include <Swiften/Client/XMLBeautifier.h> namespace Swift { - class SWIFTEN_API ClientXMLTracer { - public: - ClientXMLTracer(CoreClient* client, bool bosh = false); - ~ClientXMLTracer(); + class SWIFTEN_API ClientXMLTracer { + public: + ClientXMLTracer(CoreClient* client, bool bosh = false); + ~ClientXMLTracer(); - private: - void printData(char direction, const SafeByteArray& data); - void printLine(char c); + private: + void printData(char direction, const SafeByteArray& data); + void printLine(char c); - private: - XMLBeautifier *beautifier; - bool bosh; - boost::bsignals::scoped_connection onDataReadConnection; - boost::bsignals::scoped_connection onDataWrittenConnection; - }; + private: + XMLBeautifier *beautifier; + bool bosh; + boost::bsignals::scoped_connection onDataReadConnection; + boost::bsignals::scoped_connection onDataWrittenConnection; + }; } diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp index 6fc491c..fd7f894 100644 --- a/Swiften/Client/CoreClient.cpp +++ b/Swiften/Client/CoreClient.cpp @@ -32,448 +32,448 @@ namespace Swift { CoreClient::CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories) : jid_(jid), password_(password), networkFactories(networkFactories), disconnectRequested_(false), certificateTrustChecker(NULL) { - stanzaChannel_ = new ClientSessionStanzaChannel(); - stanzaChannel_->onMessageReceived.connect(boost::bind(&CoreClient::handleMessageReceived, this, _1)); - stanzaChannel_->onPresenceReceived.connect(boost::bind(&CoreClient::handlePresenceReceived, this, _1)); - stanzaChannel_->onStanzaAcked.connect(boost::bind(&CoreClient::handleStanzaAcked, this, _1)); - stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1)); - - iqRouter_ = new IQRouter(stanzaChannel_); - iqRouter_->setJID(jid); + stanzaChannel_ = new ClientSessionStanzaChannel(); + stanzaChannel_->onMessageReceived.connect(boost::bind(&CoreClient::handleMessageReceived, this, _1)); + stanzaChannel_->onPresenceReceived.connect(boost::bind(&CoreClient::handlePresenceReceived, this, _1)); + stanzaChannel_->onStanzaAcked.connect(boost::bind(&CoreClient::handleStanzaAcked, this, _1)); + stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1)); + + iqRouter_ = new IQRouter(stanzaChannel_); + iqRouter_->setJID(jid); } CoreClient::~CoreClient() { - forceReset(); - delete iqRouter_; - - stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1)); - stanzaChannel_->onMessageReceived.disconnect(boost::bind(&CoreClient::handleMessageReceived, this, _1)); - stanzaChannel_->onPresenceReceived.disconnect(boost::bind(&CoreClient::handlePresenceReceived, this, _1)); - stanzaChannel_->onStanzaAcked.disconnect(boost::bind(&CoreClient::handleStanzaAcked, this, _1)); - delete stanzaChannel_; + forceReset(); + delete iqRouter_; + + stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1)); + stanzaChannel_->onMessageReceived.disconnect(boost::bind(&CoreClient::handleMessageReceived, this, _1)); + stanzaChannel_->onPresenceReceived.disconnect(boost::bind(&CoreClient::handlePresenceReceived, this, _1)); + stanzaChannel_->onStanzaAcked.disconnect(boost::bind(&CoreClient::handleStanzaAcked, this, _1)); + delete stanzaChannel_; } void CoreClient::connect(const ClientOptions& o) { - SWIFT_LOG(debug) << "Connecting "; - - forceReset(); - disconnectRequested_ = false; - - options = o; - - - // Determine connection types to use - assert(proxyConnectionFactories.empty()); - bool useDirectConnection = true; - HostAddressPort systemSOCKS5Proxy = networkFactories->getProxyProvider()->getSOCKS5Proxy(); - HostAddressPort systemHTTPConnectProxy = networkFactories->getProxyProvider()->getHTTPConnectProxy(); - switch (o.proxyType) { - case ClientOptions::NoProxy: - SWIFT_LOG(debug) << " without a proxy" << std::endl; - break; - case ClientOptions::SystemConfiguredProxy: - SWIFT_LOG(debug) << " with a system configured proxy" << std::endl; - if (systemSOCKS5Proxy.isValid()) { - SWIFT_LOG(debug) << "Found SOCK5 Proxy: " << systemSOCKS5Proxy.getAddress().toString() << ":" << systemSOCKS5Proxy.getPort() << std::endl; - proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemSOCKS5Proxy.getAddress().toString(), systemSOCKS5Proxy.getPort())); - } - if (systemHTTPConnectProxy.isValid()) { - SWIFT_LOG(debug) << "Found HTTPConnect Proxy: " << systemHTTPConnectProxy.getAddress().toString() << ":" << systemHTTPConnectProxy.getPort() << std::endl; - proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemHTTPConnectProxy.getAddress().toString(), systemHTTPConnectProxy.getPort())); - } - break; - case ClientOptions::SOCKS5Proxy: { - SWIFT_LOG(debug) << " with manual configured SOCKS5 proxy" << std::endl; - std::string proxyHostname = o.manualProxyHostname.empty() ? systemSOCKS5Proxy.getAddress().toString() : o.manualProxyHostname; - int proxyPort = o.manualProxyPort == -1 ? systemSOCKS5Proxy.getPort() : o.manualProxyPort; - SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl; - proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort)); - useDirectConnection = false; - break; - } - case ClientOptions::HTTPConnectProxy: { - SWIFT_LOG(debug) << " with manual configured HTTPConnect proxy" << std::endl; - std::string proxyHostname = o.manualProxyHostname.empty() ? systemHTTPConnectProxy.getAddress().toString() : o.manualProxyHostname; - int proxyPort = o.manualProxyPort == -1 ? systemHTTPConnectProxy.getPort() : o.manualProxyPort; - SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl; - proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort, o.httpTrafficFilter)); - useDirectConnection = false; - break; - } - } - std::vector<ConnectionFactory*> connectionFactories(proxyConnectionFactories); - if (useDirectConnection) { - connectionFactories.push_back(networkFactories->getConnectionFactory()); - } - - // Create connector - std::string host = o.manualHostname.empty() ? jid_.getDomain() : o.manualHostname; - int port = o.manualPort; - boost::optional<std::string> serviceLookupPrefix; - if (o.manualHostname.empty()) { - serviceLookupPrefix = "_xmpp-client._tcp."; - } - assert(!connector_); - if (options.boshURL.isEmpty()) { - connector_ = boost::make_shared<ChainedConnector>(host, port, serviceLookupPrefix, networkFactories->getDomainNameResolver(), connectionFactories, networkFactories->getTimerFactory()); - connector_->onConnectFinished.connect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2)); - connector_->setTimeoutMilliseconds(2*60*1000); - connector_->start(); - } - else { - /* Autodiscovery of which proxy works is largely ok with a TCP session, because this is a one-off. With BOSH - * it would be quite painful given that potentially every stanza could be sent on a new connection. - */ - boost::shared_ptr<BOSHSessionStream> boshSessionStream_ = boost::shared_ptr<BOSHSessionStream>(new BOSHSessionStream( - options.boshURL, - getPayloadParserFactories(), - getPayloadSerializers(), - networkFactories->getConnectionFactory(), - networkFactories->getTLSContextFactory(), - networkFactories->getTimerFactory(), - networkFactories->getXMLParserFactory(), - networkFactories->getEventLoop(), - networkFactories->getDomainNameResolver(), - host, - options.boshHTTPConnectProxyURL, - options.boshHTTPConnectProxyAuthID, - options.boshHTTPConnectProxyAuthPassword, - options.tlsOptions, - options.httpTrafficFilter)); - sessionStream_ = boshSessionStream_; - sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1)); - sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1)); - if (certificate_ && !certificate_->isNull()) { - SWIFT_LOG(debug) << "set certificate" << std::endl; - sessionStream_->setTLSCertificate(certificate_); - } - boshSessionStream_->open(); - bindSessionToStream(); - } + SWIFT_LOG(debug) << "Connecting "; + + forceReset(); + disconnectRequested_ = false; + + options = o; + + + // Determine connection types to use + assert(proxyConnectionFactories.empty()); + bool useDirectConnection = true; + HostAddressPort systemSOCKS5Proxy = networkFactories->getProxyProvider()->getSOCKS5Proxy(); + HostAddressPort systemHTTPConnectProxy = networkFactories->getProxyProvider()->getHTTPConnectProxy(); + switch (o.proxyType) { + case ClientOptions::NoProxy: + SWIFT_LOG(debug) << " without a proxy" << std::endl; + break; + case ClientOptions::SystemConfiguredProxy: + SWIFT_LOG(debug) << " with a system configured proxy" << std::endl; + if (systemSOCKS5Proxy.isValid()) { + SWIFT_LOG(debug) << "Found SOCK5 Proxy: " << systemSOCKS5Proxy.getAddress().toString() << ":" << systemSOCKS5Proxy.getPort() << std::endl; + proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemSOCKS5Proxy.getAddress().toString(), systemSOCKS5Proxy.getPort())); + } + if (systemHTTPConnectProxy.isValid()) { + SWIFT_LOG(debug) << "Found HTTPConnect Proxy: " << systemHTTPConnectProxy.getAddress().toString() << ":" << systemHTTPConnectProxy.getPort() << std::endl; + proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemHTTPConnectProxy.getAddress().toString(), systemHTTPConnectProxy.getPort())); + } + break; + case ClientOptions::SOCKS5Proxy: { + SWIFT_LOG(debug) << " with manual configured SOCKS5 proxy" << std::endl; + std::string proxyHostname = o.manualProxyHostname.empty() ? systemSOCKS5Proxy.getAddress().toString() : o.manualProxyHostname; + int proxyPort = o.manualProxyPort == -1 ? systemSOCKS5Proxy.getPort() : o.manualProxyPort; + SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl; + proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort)); + useDirectConnection = false; + break; + } + case ClientOptions::HTTPConnectProxy: { + SWIFT_LOG(debug) << " with manual configured HTTPConnect proxy" << std::endl; + std::string proxyHostname = o.manualProxyHostname.empty() ? systemHTTPConnectProxy.getAddress().toString() : o.manualProxyHostname; + int proxyPort = o.manualProxyPort == -1 ? systemHTTPConnectProxy.getPort() : o.manualProxyPort; + SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl; + proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort, o.httpTrafficFilter)); + useDirectConnection = false; + break; + } + } + std::vector<ConnectionFactory*> connectionFactories(proxyConnectionFactories); + if (useDirectConnection) { + connectionFactories.push_back(networkFactories->getConnectionFactory()); + } + + // Create connector + std::string host = o.manualHostname.empty() ? jid_.getDomain() : o.manualHostname; + int port = o.manualPort; + boost::optional<std::string> serviceLookupPrefix; + if (o.manualHostname.empty()) { + serviceLookupPrefix = "_xmpp-client._tcp."; + } + assert(!connector_); + if (options.boshURL.isEmpty()) { + connector_ = boost::make_shared<ChainedConnector>(host, port, serviceLookupPrefix, networkFactories->getDomainNameResolver(), connectionFactories, networkFactories->getTimerFactory()); + connector_->onConnectFinished.connect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2)); + connector_->setTimeoutMilliseconds(2*60*1000); + connector_->start(); + } + else { + /* Autodiscovery of which proxy works is largely ok with a TCP session, because this is a one-off. With BOSH + * it would be quite painful given that potentially every stanza could be sent on a new connection. + */ + boost::shared_ptr<BOSHSessionStream> boshSessionStream_ = boost::shared_ptr<BOSHSessionStream>(new BOSHSessionStream( + options.boshURL, + getPayloadParserFactories(), + getPayloadSerializers(), + networkFactories->getConnectionFactory(), + networkFactories->getTLSContextFactory(), + networkFactories->getTimerFactory(), + networkFactories->getXMLParserFactory(), + networkFactories->getEventLoop(), + networkFactories->getDomainNameResolver(), + host, + options.boshHTTPConnectProxyURL, + options.boshHTTPConnectProxyAuthID, + options.boshHTTPConnectProxyAuthPassword, + options.tlsOptions, + options.httpTrafficFilter)); + sessionStream_ = boshSessionStream_; + sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1)); + sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1)); + if (certificate_ && !certificate_->isNull()) { + SWIFT_LOG(debug) << "set certificate" << std::endl; + sessionStream_->setTLSCertificate(certificate_); + } + boshSessionStream_->open(); + bindSessionToStream(); + } } void CoreClient::bindSessionToStream() { - session_ = ClientSession::create(jid_, sessionStream_, networkFactories->getIDNConverter(), networkFactories->getCryptoProvider()); - session_->setCertificateTrustChecker(certificateTrustChecker); - session_->setUseStreamCompression(options.useStreamCompression); - session_->setAllowPLAINOverNonTLS(options.allowPLAINWithoutTLS); - session_->setSingleSignOn(options.singleSignOn); - session_->setAuthenticationPort(options.manualPort); - switch(options.useTLS) { - case ClientOptions::UseTLSWhenAvailable: - session_->setUseTLS(ClientSession::UseTLSWhenAvailable); - break; - case ClientOptions::NeverUseTLS: - session_->setUseTLS(ClientSession::NeverUseTLS); - break; - case ClientOptions::RequireTLS: - session_->setUseTLS(ClientSession::RequireTLS); - break; - } - session_->setUseAcks(options.useAcks); - stanzaChannel_->setSession(session_); - session_->onFinished.connect(boost::bind(&CoreClient::handleSessionFinished, this, _1)); - session_->onNeedCredentials.connect(boost::bind(&CoreClient::handleNeedCredentials, this)); - session_->start(); + session_ = ClientSession::create(jid_, sessionStream_, networkFactories->getIDNConverter(), networkFactories->getCryptoProvider()); + session_->setCertificateTrustChecker(certificateTrustChecker); + session_->setUseStreamCompression(options.useStreamCompression); + session_->setAllowPLAINOverNonTLS(options.allowPLAINWithoutTLS); + session_->setSingleSignOn(options.singleSignOn); + session_->setAuthenticationPort(options.manualPort); + switch(options.useTLS) { + case ClientOptions::UseTLSWhenAvailable: + session_->setUseTLS(ClientSession::UseTLSWhenAvailable); + break; + case ClientOptions::NeverUseTLS: + session_->setUseTLS(ClientSession::NeverUseTLS); + break; + case ClientOptions::RequireTLS: + session_->setUseTLS(ClientSession::RequireTLS); + break; + } + session_->setUseAcks(options.useAcks); + stanzaChannel_->setSession(session_); + session_->onFinished.connect(boost::bind(&CoreClient::handleSessionFinished, this, _1)); + session_->onNeedCredentials.connect(boost::bind(&CoreClient::handleNeedCredentials, this)); + session_->start(); } /** * Only called for TCP sessions. BOSH is handled inside the BOSHSessionStream. */ void CoreClient::handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> error) { - resetConnector(); - if (!connection) { - if (options.forgetPassword) { - purgePassword(); - } - boost::optional<ClientError> clientError; - if (!disconnectRequested_) { - clientError = boost::dynamic_pointer_cast<DomainNameResolveError>(error) ? boost::optional<ClientError>(ClientError::DomainNameResolveError) : boost::optional<ClientError>(ClientError::ConnectionError); - } - onDisconnected(clientError); - } - else { - assert(!connection_); - assert(!sessionStream_); - - if (certificate_ && certificate_->isNull()) { - //certificate cannot be read so do not initailise session - onDisconnected(boost::optional<ClientError>(ClientError::ClientCertificateLoadError)); - return; - } - - connection_ = connection; - - sessionStream_ = boost::make_shared<BasicSessionStream>(ClientStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), networkFactories->getTLSContextFactory(), networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), options.tlsOptions); - if (certificate_) { - sessionStream_->setTLSCertificate(certificate_); - } - sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1)); - sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1)); - - bindSessionToStream(); - } + resetConnector(); + if (!connection) { + if (options.forgetPassword) { + purgePassword(); + } + boost::optional<ClientError> clientError; + if (!disconnectRequested_) { + clientError = boost::dynamic_pointer_cast<DomainNameResolveError>(error) ? boost::optional<ClientError>(ClientError::DomainNameResolveError) : boost::optional<ClientError>(ClientError::ConnectionError); + } + onDisconnected(clientError); + } + else { + assert(!connection_); + assert(!sessionStream_); + + if (certificate_ && certificate_->isNull()) { + //certificate cannot be read so do not initailise session + onDisconnected(boost::optional<ClientError>(ClientError::ClientCertificateLoadError)); + return; + } + + connection_ = connection; + + sessionStream_ = boost::make_shared<BasicSessionStream>(ClientStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), networkFactories->getTLSContextFactory(), networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), options.tlsOptions); + if (certificate_) { + sessionStream_->setTLSCertificate(certificate_); + } + sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1)); + sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1)); + + bindSessionToStream(); + } } void CoreClient::disconnect() { - // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between - // connector finishing without a connection due to an error or because of a disconnect. - disconnectRequested_ = true; - if (session_ && !session_->isFinished()) { - session_->finish(); - } - else if (connector_) { - connector_->stop(); - } + // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between + // connector finishing without a connection due to an error or because of a disconnect. + disconnectRequested_ = true; + if (session_ && !session_->isFinished()) { + session_->finish(); + } + else if (connector_) { + connector_->stop(); + } } void CoreClient::setCertificate(CertificateWithKey::ref certificate) { - certificate_ = certificate; + certificate_ = certificate; } void CoreClient::handleSessionFinished(boost::shared_ptr<Error> error) { - if (options.forgetPassword) { - purgePassword(); - } - resetSession(); - - boost::optional<ClientError> actualError; - if (error) { - ClientError clientError; - if (boost::shared_ptr<ClientSession::Error> actualError = boost::dynamic_pointer_cast<ClientSession::Error>(error)) { - switch(actualError->type) { - case ClientSession::Error::AuthenticationFailedError: - clientError = ClientError(ClientError::AuthenticationFailedError); - break; - case ClientSession::Error::CompressionFailedError: - clientError = ClientError(ClientError::CompressionFailedError); - break; - case ClientSession::Error::ServerVerificationFailedError: - clientError = ClientError(ClientError::ServerVerificationFailedError); - break; - case ClientSession::Error::NoSupportedAuthMechanismsError: - clientError = ClientError(ClientError::NoSupportedAuthMechanismsError); - break; - case ClientSession::Error::UnexpectedElementError: - clientError = ClientError(ClientError::UnexpectedElementError); - break; - case ClientSession::Error::ResourceBindError: - clientError = ClientError(ClientError::ResourceBindError); - break; - case ClientSession::Error::SessionStartError: - clientError = ClientError(ClientError::SessionStartError); - break; - case ClientSession::Error::TLSError: - clientError = ClientError(ClientError::TLSError); - break; - case ClientSession::Error::TLSClientCertificateError: - clientError = ClientError(ClientError::ClientCertificateError); - break; - case ClientSession::Error::StreamError: - clientError = ClientError(ClientError::StreamError); - break; - } - clientError.setErrorCode(actualError->errorCode); - } - else if (boost::shared_ptr<TLSError> actualError = boost::dynamic_pointer_cast<TLSError>(error)) { - switch(actualError->getType()) { - case TLSError::CertificateCardRemoved: - clientError = ClientError(ClientError::CertificateCardRemoved); - break; - case TLSError::UnknownError: - clientError = ClientError(ClientError::TLSError); - break; - } - } - else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) { - switch(actualError->type) { - case SessionStream::SessionStreamError::ParseError: - clientError = ClientError(ClientError::XMLError); - break; - case SessionStream::SessionStreamError::TLSError: - clientError = ClientError(ClientError::TLSError); - break; - case SessionStream::SessionStreamError::InvalidTLSCertificateError: - clientError = ClientError(ClientError::ClientCertificateLoadError); - break; - case SessionStream::SessionStreamError::ConnectionReadError: - clientError = ClientError(ClientError::ConnectionReadError); - break; - case SessionStream::SessionStreamError::ConnectionWriteError: - clientError = ClientError(ClientError::ConnectionWriteError); - break; - } - } - else if (boost::shared_ptr<CertificateVerificationError> verificationError = boost::dynamic_pointer_cast<CertificateVerificationError>(error)) { - switch(verificationError->getType()) { - case CertificateVerificationError::UnknownError: - clientError = ClientError(ClientError::UnknownCertificateError); - break; - case CertificateVerificationError::Expired: - clientError = ClientError(ClientError::CertificateExpiredError); - break; - case CertificateVerificationError::NotYetValid: - clientError = ClientError(ClientError::CertificateNotYetValidError); - break; - case CertificateVerificationError::SelfSigned: - clientError = ClientError(ClientError::CertificateSelfSignedError); - break; - case CertificateVerificationError::Rejected: - clientError = ClientError(ClientError::CertificateRejectedError); - break; - case CertificateVerificationError::Untrusted: - clientError = ClientError(ClientError::CertificateUntrustedError); - break; - case CertificateVerificationError::InvalidPurpose: - clientError = ClientError(ClientError::InvalidCertificatePurposeError); - break; - case CertificateVerificationError::PathLengthExceeded: - clientError = ClientError(ClientError::CertificatePathLengthExceededError); - break; - case CertificateVerificationError::InvalidSignature: - clientError = ClientError(ClientError::InvalidCertificateSignatureError); - break; - case CertificateVerificationError::InvalidCA: - clientError = ClientError(ClientError::InvalidCAError); - break; - case CertificateVerificationError::InvalidServerIdentity: - clientError = ClientError(ClientError::InvalidServerIdentityError); - break; - case CertificateVerificationError::Revoked: - clientError = ClientError(ClientError::RevokedError); - break; - case CertificateVerificationError::RevocationCheckFailed: - clientError = ClientError(ClientError::RevocationCheckFailedError); - break; - } - } - actualError = boost::optional<ClientError>(clientError); - } - onDisconnected(actualError); + if (options.forgetPassword) { + purgePassword(); + } + resetSession(); + + boost::optional<ClientError> actualError; + if (error) { + ClientError clientError; + if (boost::shared_ptr<ClientSession::Error> actualError = boost::dynamic_pointer_cast<ClientSession::Error>(error)) { + switch(actualError->type) { + case ClientSession::Error::AuthenticationFailedError: + clientError = ClientError(ClientError::AuthenticationFailedError); + break; + case ClientSession::Error::CompressionFailedError: + clientError = ClientError(ClientError::CompressionFailedError); + break; + case ClientSession::Error::ServerVerificationFailedError: + clientError = ClientError(ClientError::ServerVerificationFailedError); + break; + case ClientSession::Error::NoSupportedAuthMechanismsError: + clientError = ClientError(ClientError::NoSupportedAuthMechanismsError); + break; + case ClientSession::Error::UnexpectedElementError: + clientError = ClientError(ClientError::UnexpectedElementError); + break; + case ClientSession::Error::ResourceBindError: + clientError = ClientError(ClientError::ResourceBindError); + break; + case ClientSession::Error::SessionStartError: + clientError = ClientError(ClientError::SessionStartError); + break; + case ClientSession::Error::TLSError: + clientError = ClientError(ClientError::TLSError); + break; + case ClientSession::Error::TLSClientCertificateError: + clientError = ClientError(ClientError::ClientCertificateError); + break; + case ClientSession::Error::StreamError: + clientError = ClientError(ClientError::StreamError); + break; + } + clientError.setErrorCode(actualError->errorCode); + } + else if (boost::shared_ptr<TLSError> actualError = boost::dynamic_pointer_cast<TLSError>(error)) { + switch(actualError->getType()) { + case TLSError::CertificateCardRemoved: + clientError = ClientError(ClientError::CertificateCardRemoved); + break; + case TLSError::UnknownError: + clientError = ClientError(ClientError::TLSError); + break; + } + } + else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) { + switch(actualError->type) { + case SessionStream::SessionStreamError::ParseError: + clientError = ClientError(ClientError::XMLError); + break; + case SessionStream::SessionStreamError::TLSError: + clientError = ClientError(ClientError::TLSError); + break; + case SessionStream::SessionStreamError::InvalidTLSCertificateError: + clientError = ClientError(ClientError::ClientCertificateLoadError); + break; + case SessionStream::SessionStreamError::ConnectionReadError: + clientError = ClientError(ClientError::ConnectionReadError); + break; + case SessionStream::SessionStreamError::ConnectionWriteError: + clientError = ClientError(ClientError::ConnectionWriteError); + break; + } + } + else if (boost::shared_ptr<CertificateVerificationError> verificationError = boost::dynamic_pointer_cast<CertificateVerificationError>(error)) { + switch(verificationError->getType()) { + case CertificateVerificationError::UnknownError: + clientError = ClientError(ClientError::UnknownCertificateError); + break; + case CertificateVerificationError::Expired: + clientError = ClientError(ClientError::CertificateExpiredError); + break; + case CertificateVerificationError::NotYetValid: + clientError = ClientError(ClientError::CertificateNotYetValidError); + break; + case CertificateVerificationError::SelfSigned: + clientError = ClientError(ClientError::CertificateSelfSignedError); + break; + case CertificateVerificationError::Rejected: + clientError = ClientError(ClientError::CertificateRejectedError); + break; + case CertificateVerificationError::Untrusted: + clientError = ClientError(ClientError::CertificateUntrustedError); + break; + case CertificateVerificationError::InvalidPurpose: + clientError = ClientError(ClientError::InvalidCertificatePurposeError); + break; + case CertificateVerificationError::PathLengthExceeded: + clientError = ClientError(ClientError::CertificatePathLengthExceededError); + break; + case CertificateVerificationError::InvalidSignature: + clientError = ClientError(ClientError::InvalidCertificateSignatureError); + break; + case CertificateVerificationError::InvalidCA: + clientError = ClientError(ClientError::InvalidCAError); + break; + case CertificateVerificationError::InvalidServerIdentity: + clientError = ClientError(ClientError::InvalidServerIdentityError); + break; + case CertificateVerificationError::Revoked: + clientError = ClientError(ClientError::RevokedError); + break; + case CertificateVerificationError::RevocationCheckFailed: + clientError = ClientError(ClientError::RevocationCheckFailedError); + break; + } + } + actualError = boost::optional<ClientError>(clientError); + } + onDisconnected(actualError); } void CoreClient::handleNeedCredentials() { - assert(session_); - session_->sendCredentials(password_); - if (options.forgetPassword) { - purgePassword(); - } + assert(session_); + session_->sendCredentials(password_); + if (options.forgetPassword) { + purgePassword(); + } } void CoreClient::handleDataRead(const SafeByteArray& data) { - onDataRead(data); + onDataRead(data); } void CoreClient::handleDataWritten(const SafeByteArray& data) { - onDataWritten(data); + onDataWritten(data); } void CoreClient::handleStanzaChannelAvailableChanged(bool available) { - if (available) { - iqRouter_->setJID(session_->getLocalJID()); - handleConnected(); - onConnected(); - } + if (available) { + iqRouter_->setJID(session_->getLocalJID()); + handleConnected(); + onConnected(); + } } void CoreClient::sendMessage(boost::shared_ptr<Message> message) { - stanzaChannel_->sendMessage(message); + stanzaChannel_->sendMessage(message); } void CoreClient::sendPresence(boost::shared_ptr<Presence> presence) { - stanzaChannel_->sendPresence(presence); + stanzaChannel_->sendPresence(presence); } void CoreClient::sendData(const std::string& data) { - sessionStream_->writeData(data); + sessionStream_->writeData(data); } bool CoreClient::isActive() const { - return (session_ && !session_->isFinished()) || connector_; + return (session_ && !session_->isFinished()) || connector_; } void CoreClient::setCertificateTrustChecker(CertificateTrustChecker* checker) { - certificateTrustChecker = checker; + certificateTrustChecker = checker; } void CoreClient::handlePresenceReceived(Presence::ref presence) { - onPresenceReceived(presence); + onPresenceReceived(presence); } void CoreClient::handleMessageReceived(Message::ref message) { - onMessageReceived(message); + onMessageReceived(message); } void CoreClient::handleStanzaAcked(Stanza::ref stanza) { - onStanzaAcked(stanza); + onStanzaAcked(stanza); } bool CoreClient::isAvailable() const { - return stanzaChannel_->isAvailable(); + return stanzaChannel_->isAvailable(); } bool CoreClient::getStreamManagementEnabled() const { - return stanzaChannel_->getStreamManagementEnabled(); + return stanzaChannel_->getStreamManagementEnabled(); } bool CoreClient::isStreamEncrypted() const { - return sessionStream_->isTLSEncrypted(); + return sessionStream_->isTLSEncrypted(); } StanzaChannel* CoreClient::getStanzaChannel() const { - return stanzaChannel_; + return stanzaChannel_; } const JID& CoreClient::getJID() const { - if (session_) { - return session_->getLocalJID(); - } - else { - return jid_; - } + if (session_) { + return session_->getLocalJID(); + } + else { + return jid_; + } } void CoreClient::purgePassword() { - safeClear(password_); + safeClear(password_); } void CoreClient::resetConnector() { - connector_->onConnectFinished.disconnect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2)); - connector_.reset(); - foreach(ConnectionFactory* f, proxyConnectionFactories) { - delete f; - } - proxyConnectionFactories.clear(); + connector_->onConnectFinished.disconnect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2)); + connector_.reset(); + foreach(ConnectionFactory* f, proxyConnectionFactories) { + delete f; + } + proxyConnectionFactories.clear(); } void CoreClient::resetSession() { - session_->onFinished.disconnect(boost::bind(&CoreClient::handleSessionFinished, this, _1)); - session_->onNeedCredentials.disconnect(boost::bind(&CoreClient::handleNeedCredentials, this)); - - sessionStream_->onDataRead.disconnect(boost::bind(&CoreClient::handleDataRead, this, _1)); - sessionStream_->onDataWritten.disconnect(boost::bind(&CoreClient::handleDataWritten, this, _1)); - - if (connection_) { - connection_->disconnect(); - } - else if (boost::dynamic_pointer_cast<BOSHSessionStream>(sessionStream_)) { - sessionStream_->close(); - } - sessionStream_.reset(); - connection_.reset(); + session_->onFinished.disconnect(boost::bind(&CoreClient::handleSessionFinished, this, _1)); + session_->onNeedCredentials.disconnect(boost::bind(&CoreClient::handleNeedCredentials, this)); + + sessionStream_->onDataRead.disconnect(boost::bind(&CoreClient::handleDataRead, this, _1)); + sessionStream_->onDataWritten.disconnect(boost::bind(&CoreClient::handleDataWritten, this, _1)); + + if (connection_) { + connection_->disconnect(); + } + else if (boost::dynamic_pointer_cast<BOSHSessionStream>(sessionStream_)) { + sessionStream_->close(); + } + sessionStream_.reset(); + connection_.reset(); } void CoreClient::forceReset() { - if (connector_) { - SWIFT_LOG(warning) << "Client not disconnected properly: Connector still active" << std::endl; - resetConnector(); - } - if (sessionStream_ || connection_) { - SWIFT_LOG(warning) << "Client not disconnected properly: Session still active" << std::endl; - resetSession(); - } + if (connector_) { + SWIFT_LOG(warning) << "Client not disconnected properly: Connector still active" << std::endl; + resetConnector(); + } + if (sessionStream_ || connection_) { + SWIFT_LOG(warning) << "Client not disconnected properly: Session still active" << std::endl; + resetSession(); + } } } diff --git a/Swiften/Client/CoreClient.h b/Swiften/Client/CoreClient.h index 002a704..3efc38f 100644 --- a/Swiften/Client/CoreClient.h +++ b/Swiften/Client/CoreClient.h @@ -20,223 +20,223 @@ #include <Swiften/TLS/CertificateWithKey.h> namespace Swift { - class ChainedConnector; - class Message; - class Presence; - class Error; - class IQRouter; - class TLSContextFactory; - class ConnectionFactory; - class Connection; - class TimerFactory; - class ClientSession; - class StanzaChannel; - class Stanza; - class SessionStream; - class CertificateTrustChecker; - class NetworkFactories; - class ClientSessionStanzaChannel; - - /** - * The central class for communicating with an XMPP server. - * - * This class is responsible for setting up the connection with the XMPP - * server, authenticating, and initializing the session. - * - * This class can be used directly in your application, although the Client - * subclass provides more functionality and interfaces, and is better suited - * for most needs. - */ - class SWIFTEN_API CoreClient : public Entity { - public: - /** - * Constructs a client for the given JID with the given password. - */ - CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories); - virtual ~CoreClient(); - - /** - * Set a client certificate to use for strong authentication with the server. - * Ensure that it is of the correct type for the TLS engine in use. - * This means, largely, PKCS12Certificate for OpenSSL and CAPICertificate for CAPI. - */ - void setCertificate(CertificateWithKey::ref certificate); - - /** - * Connects the client to the server. - * - * After the connection is established, the client will set - * initialize the stream and authenticate. - */ - void connect(const ClientOptions& = ClientOptions()); - - /** - * Disconnects the client from the server. - */ - void disconnect(); - - /** - * Sends a message. - */ - void sendMessage(boost::shared_ptr<Message>); - - /** - * Sends a presence stanza. - */ - void sendPresence(boost::shared_ptr<Presence>); - - /** - * Sends raw, unchecked data. - */ - void sendData(const std::string& data); - - /** - * Returns the IQ router for this client. - */ - IQRouter* getIQRouter() const { - return iqRouter_; - } - - /** - * Checks whether the client is connected to the server, - * and stanzas can be sent. - */ - bool isAvailable() const; - - /** - * Checks whether the client is active. - * - * A client is active when it is connected or connecting to the server. - */ - bool isActive() const; - - /** - * Returns the JID of the client. - * After the session was initialized, this returns the bound JID. - */ - const JID& getJID() const; - - /** - * Checks whether stream management is enabled. - * - * If stream management is enabled, onStanzaAcked will be - * emitted when a stanza is received by the server. - * - * \see onStanzaAcked - */ - bool getStreamManagementEnabled() const; - - /** - * Checks whether stream encryption (TLS) is currently active. - */ - bool isStreamEncrypted() const; - - StanzaChannel* getStanzaChannel() const; - - /** - * Sets the certificate trust checker. - * - * This checker will be called when the server sends a - * TLS certificate that does not validate. If the trust checker - * says the certificate is trusted, then connecting will proceed; - * if not, the connection will end with an error. - */ - void setCertificateTrustChecker(CertificateTrustChecker*); - - public: - /** - * Emitted when the client was disconnected from the network. - * - * If the connection was due to a non-recoverable error, the type - * of error will be passed as a parameter. - */ - boost::signal<void (const boost::optional<ClientError>&)> onDisconnected; - - /** - * Emitted when the client is connected and authenticated, - * and stanzas can be sent. - */ - boost::signal<void ()> onConnected; - - /** - * Emitted when the client receives data. - * - * This signal is emitted before the XML data is parsed, - * so this data is unformatted. - */ - boost::signal<void (const SafeByteArray&)> onDataRead; - - /** - * Emitted when the client sends data. - * - * This signal is emitted after the XML was serialized, and - * is unformatted. - */ - boost::signal<void (const SafeByteArray&)> onDataWritten; - - /** - * Emitted when a message is received. - */ - boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived; - - /** - * Emitted when a presence stanza is received. - */ - boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived; - - /** - * Emitted when the server acknowledges receipt of a - * stanza (if acknowledgements are available). - * - * \see getStreamManagementEnabled() - */ - boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked; - - protected: - boost::shared_ptr<ClientSession> getSession() const { - return session_; - } - - NetworkFactories* getNetworkFactories() const { - return networkFactories; - } - - /** - * Called before onConnected signal is emmitted. - */ - virtual void handleConnected() {} - - private: - void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error> error); - void handleStanzaChannelAvailableChanged(bool available); - void handleSessionFinished(boost::shared_ptr<Error>); - void handleNeedCredentials(); - void handleDataRead(const SafeByteArray&); - void handleDataWritten(const SafeByteArray&); - void handlePresenceReceived(boost::shared_ptr<Presence>); - void handleMessageReceived(boost::shared_ptr<Message>); - void handleStanzaAcked(boost::shared_ptr<Stanza>); - void purgePassword(); - void bindSessionToStream(); - - void resetConnector(); - void resetSession(); - void forceReset(); - - private: - JID jid_; - SafeByteArray password_; - NetworkFactories* networkFactories; - ClientSessionStanzaChannel* stanzaChannel_; - IQRouter* iqRouter_; - ClientOptions options; - boost::shared_ptr<ChainedConnector> connector_; - std::vector<ConnectionFactory*> proxyConnectionFactories; - boost::shared_ptr<Connection> connection_; - boost::shared_ptr<SessionStream> sessionStream_; - boost::shared_ptr<ClientSession> session_; - CertificateWithKey::ref certificate_; - bool disconnectRequested_; - CertificateTrustChecker* certificateTrustChecker; - }; + class ChainedConnector; + class Message; + class Presence; + class Error; + class IQRouter; + class TLSContextFactory; + class ConnectionFactory; + class Connection; + class TimerFactory; + class ClientSession; + class StanzaChannel; + class Stanza; + class SessionStream; + class CertificateTrustChecker; + class NetworkFactories; + class ClientSessionStanzaChannel; + + /** + * The central class for communicating with an XMPP server. + * + * This class is responsible for setting up the connection with the XMPP + * server, authenticating, and initializing the session. + * + * This class can be used directly in your application, although the Client + * subclass provides more functionality and interfaces, and is better suited + * for most needs. + */ + class SWIFTEN_API CoreClient : public Entity { + public: + /** + * Constructs a client for the given JID with the given password. + */ + CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories); + virtual ~CoreClient(); + + /** + * Set a client certificate to use for strong authentication with the server. + * Ensure that it is of the correct type for the TLS engine in use. + * This means, largely, PKCS12Certificate for OpenSSL and CAPICertificate for CAPI. + */ + void setCertificate(CertificateWithKey::ref certificate); + + /** + * Connects the client to the server. + * + * After the connection is established, the client will set + * initialize the stream and authenticate. + */ + void connect(const ClientOptions& = ClientOptions()); + + /** + * Disconnects the client from the server. + */ + void disconnect(); + + /** + * Sends a message. + */ + void sendMessage(boost::shared_ptr<Message>); + + /** + * Sends a presence stanza. + */ + void sendPresence(boost::shared_ptr<Presence>); + + /** + * Sends raw, unchecked data. + */ + void sendData(const std::string& data); + + /** + * Returns the IQ router for this client. + */ + IQRouter* getIQRouter() const { + return iqRouter_; + } + + /** + * Checks whether the client is connected to the server, + * and stanzas can be sent. + */ + bool isAvailable() const; + + /** + * Checks whether the client is active. + * + * A client is active when it is connected or connecting to the server. + */ + bool isActive() const; + + /** + * Returns the JID of the client. + * After the session was initialized, this returns the bound JID. + */ + const JID& getJID() const; + + /** + * Checks whether stream management is enabled. + * + * If stream management is enabled, onStanzaAcked will be + * emitted when a stanza is received by the server. + * + * \see onStanzaAcked + */ + bool getStreamManagementEnabled() const; + + /** + * Checks whether stream encryption (TLS) is currently active. + */ + bool isStreamEncrypted() const; + + StanzaChannel* getStanzaChannel() const; + + /** + * Sets the certificate trust checker. + * + * This checker will be called when the server sends a + * TLS certificate that does not validate. If the trust checker + * says the certificate is trusted, then connecting will proceed; + * if not, the connection will end with an error. + */ + void setCertificateTrustChecker(CertificateTrustChecker*); + + public: + /** + * Emitted when the client was disconnected from the network. + * + * If the connection was due to a non-recoverable error, the type + * of error will be passed as a parameter. + */ + boost::signal<void (const boost::optional<ClientError>&)> onDisconnected; + + /** + * Emitted when the client is connected and authenticated, + * and stanzas can be sent. + */ + boost::signal<void ()> onConnected; + + /** + * Emitted when the client receives data. + * + * This signal is emitted before the XML data is parsed, + * so this data is unformatted. + */ + boost::signal<void (const SafeByteArray&)> onDataRead; + + /** + * Emitted when the client sends data. + * + * This signal is emitted after the XML was serialized, and + * is unformatted. + */ + boost::signal<void (const SafeByteArray&)> onDataWritten; + + /** + * Emitted when a message is received. + */ + boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived; + + /** + * Emitted when a presence stanza is received. + */ + boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived; + + /** + * Emitted when the server acknowledges receipt of a + * stanza (if acknowledgements are available). + * + * \see getStreamManagementEnabled() + */ + boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked; + + protected: + boost::shared_ptr<ClientSession> getSession() const { + return session_; + } + + NetworkFactories* getNetworkFactories() const { + return networkFactories; + } + + /** + * Called before onConnected signal is emmitted. + */ + virtual void handleConnected() {} + + private: + void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error> error); + void handleStanzaChannelAvailableChanged(bool available); + void handleSessionFinished(boost::shared_ptr<Error>); + void handleNeedCredentials(); + void handleDataRead(const SafeByteArray&); + void handleDataWritten(const SafeByteArray&); + void handlePresenceReceived(boost::shared_ptr<Presence>); + void handleMessageReceived(boost::shared_ptr<Message>); + void handleStanzaAcked(boost::shared_ptr<Stanza>); + void purgePassword(); + void bindSessionToStream(); + + void resetConnector(); + void resetSession(); + void forceReset(); + + private: + JID jid_; + SafeByteArray password_; + NetworkFactories* networkFactories; + ClientSessionStanzaChannel* stanzaChannel_; + IQRouter* iqRouter_; + ClientOptions options; + boost::shared_ptr<ChainedConnector> connector_; + std::vector<ConnectionFactory*> proxyConnectionFactories; + boost::shared_ptr<Connection> connection_; + boost::shared_ptr<SessionStream> sessionStream_; + boost::shared_ptr<ClientSession> session_; + CertificateWithKey::ref certificate_; + bool disconnectRequested_; + CertificateTrustChecker* certificateTrustChecker; + }; } diff --git a/Swiften/Client/DummyNickManager.h b/Swiften/Client/DummyNickManager.h index 2f5f13f..52a8401 100644 --- a/Swiften/Client/DummyNickManager.h +++ b/Swiften/Client/DummyNickManager.h @@ -9,15 +9,15 @@ #include <Swiften/Client/NickManager.h> namespace Swift { - class VCardManager; + class VCardManager; - class DummyNickManager : public NickManager { - public: - std::string getOwnNick() const { - return ""; - } + class DummyNickManager : public NickManager { + public: + std::string getOwnNick() const { + return ""; + } - void setOwnNick(const std::string&) { - } - }; + void setOwnNick(const std::string&) { + } + }; } diff --git a/Swiften/Client/DummyStanzaChannel.h b/Swiften/Client/DummyStanzaChannel.h index 0373cc4..0e52f62 100644 --- a/Swiften/Client/DummyStanzaChannel.h +++ b/Swiften/Client/DummyStanzaChannel.h @@ -11,79 +11,79 @@ #include <Swiften/Client/StanzaChannel.h> namespace Swift { - class DummyStanzaChannel : public StanzaChannel { - public: - DummyStanzaChannel() : available_(true) {} - - virtual void sendStanza(boost::shared_ptr<Stanza> stanza) { - sentStanzas.push_back(stanza); - } - - void setAvailable(bool available) { - available_ = available; - onAvailableChanged(available); - } - - virtual void sendIQ(boost::shared_ptr<IQ> iq) { - sentStanzas.push_back(iq); - } - - virtual void sendMessage(boost::shared_ptr<Message> message) { - sentStanzas.push_back(message); - } - - virtual void sendPresence(boost::shared_ptr<Presence> presence) { - sentStanzas.push_back(presence); - } - - virtual std::string getNewIQID() { - return "test-id"; - } - - virtual bool isAvailable() const { - return available_; - } - - virtual bool getStreamManagementEnabled() const { - return false; - } - - template<typename T> bool isRequestAtIndex(size_t index, const JID& jid, IQ::Type type) { - if (index >= sentStanzas.size()) { - return false; - } - boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]); - return iqStanza && iqStanza->getType() == type && iqStanza->getTo() == jid && iqStanza->getPayload<T>(); - } - - bool isResultAtIndex(size_t index, const std::string& id) { - if (index >= sentStanzas.size()) { - return false; - } - boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]); - return iqStanza && iqStanza->getType() == IQ::Result && iqStanza->getID() == id; - } - - bool isErrorAtIndex(size_t index, const std::string& id) { - if (index >= sentStanzas.size()) { - return false; - } - boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]); - return iqStanza && iqStanza->getType() == IQ::Error && iqStanza->getID() == id; - } - - template<typename T> boost::shared_ptr<T> getStanzaAtIndex(size_t index) { - if (sentStanzas.size() <= index) { - return boost::shared_ptr<T>(); - } - return boost::dynamic_pointer_cast<T>(sentStanzas[index]); - } - - std::vector<Certificate::ref> getPeerCertificateChain() const { - return std::vector<Certificate::ref>(); - } - - std::vector<boost::shared_ptr<Stanza> > sentStanzas; - bool available_; - }; + class DummyStanzaChannel : public StanzaChannel { + public: + DummyStanzaChannel() : available_(true) {} + + virtual void sendStanza(boost::shared_ptr<Stanza> stanza) { + sentStanzas.push_back(stanza); + } + + void setAvailable(bool available) { + available_ = available; + onAvailableChanged(available); + } + + virtual void sendIQ(boost::shared_ptr<IQ> iq) { + sentStanzas.push_back(iq); + } + + virtual void sendMessage(boost::shared_ptr<Message> message) { + sentStanzas.push_back(message); + } + + virtual void sendPresence(boost::shared_ptr<Presence> presence) { + sentStanzas.push_back(presence); + } + + virtual std::string getNewIQID() { + return "test-id"; + } + + virtual bool isAvailable() const { + return available_; + } + + virtual bool getStreamManagementEnabled() const { + return false; + } + + template<typename T> bool isRequestAtIndex(size_t index, const JID& jid, IQ::Type type) { + if (index >= sentStanzas.size()) { + return false; + } + boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]); + return iqStanza && iqStanza->getType() == type && iqStanza->getTo() == jid && iqStanza->getPayload<T>(); + } + + bool isResultAtIndex(size_t index, const std::string& id) { + if (index >= sentStanzas.size()) { + return false; + } + boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]); + return iqStanza && iqStanza->getType() == IQ::Result && iqStanza->getID() == id; + } + + bool isErrorAtIndex(size_t index, const std::string& id) { + if (index >= sentStanzas.size()) { + return false; + } + boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]); + return iqStanza && iqStanza->getType() == IQ::Error && iqStanza->getID() == id; + } + + template<typename T> boost::shared_ptr<T> getStanzaAtIndex(size_t index) { + if (sentStanzas.size() <= index) { + return boost::shared_ptr<T>(); + } + return boost::dynamic_pointer_cast<T>(sentStanzas[index]); + } + + std::vector<Certificate::ref> getPeerCertificateChain() const { + return std::vector<Certificate::ref>(); + } + + std::vector<boost::shared_ptr<Stanza> > sentStanzas; + bool available_; + }; } diff --git a/Swiften/Client/MemoryStorages.cpp b/Swiften/Client/MemoryStorages.cpp index 8825fa2..14aa63a 100644 --- a/Swiften/Client/MemoryStorages.cpp +++ b/Swiften/Client/MemoryStorages.cpp @@ -16,48 +16,48 @@ namespace Swift { MemoryStorages::MemoryStorages(CryptoProvider* crypto) { - vcardStorage = new VCardMemoryStorage(crypto); - capsStorage = new CapsMemoryStorage(); - avatarStorage = new AvatarMemoryStorage(); - rosterStorage = new RosterMemoryStorage(); + vcardStorage = new VCardMemoryStorage(crypto); + capsStorage = new CapsMemoryStorage(); + avatarStorage = new AvatarMemoryStorage(); + rosterStorage = new RosterMemoryStorage(); #ifdef SWIFT_EXPERIMENTAL_HISTORY - historyStorage = new SQLiteHistoryStorage(":memory:"); + historyStorage = new SQLiteHistoryStorage(":memory:"); #else - historyStorage = NULL; + historyStorage = NULL; #endif } MemoryStorages::~MemoryStorages() { - delete rosterStorage; - delete avatarStorage; - delete capsStorage; - delete vcardStorage; + delete rosterStorage; + delete avatarStorage; + delete capsStorage; + delete vcardStorage; #ifdef SWIFT_EXPERIMENTAL_HISTORY - delete historyStorage; + delete historyStorage; #endif } VCardStorage* MemoryStorages::getVCardStorage() const { - return vcardStorage; + return vcardStorage; } CapsStorage* MemoryStorages::getCapsStorage() const { - return capsStorage; + return capsStorage; } AvatarStorage* MemoryStorages::getAvatarStorage() const { - return avatarStorage; + return avatarStorage; } RosterStorage* MemoryStorages::getRosterStorage() const { - return rosterStorage; + return rosterStorage; } HistoryStorage* MemoryStorages::getHistoryStorage() const { #ifdef SWIFT_EXPERIMENTAL_HISTORY - return historyStorage; + return historyStorage; #else - return NULL; + return NULL; #endif } diff --git a/Swiften/Client/MemoryStorages.h b/Swiften/Client/MemoryStorages.h index 49f18f5..b905ed9 100644 --- a/Swiften/Client/MemoryStorages.h +++ b/Swiften/Client/MemoryStorages.h @@ -10,29 +10,29 @@ #include <Swiften/Client/Storages.h> namespace Swift { - class VCardMemoryStorage; - class CryptoProvider; + class VCardMemoryStorage; + class CryptoProvider; - /** - * An implementation of Storages for storing all - * controller data in memory. - */ - class SWIFTEN_API MemoryStorages : public Storages { - public: - MemoryStorages(CryptoProvider*); - virtual ~MemoryStorages(); + /** + * An implementation of Storages for storing all + * controller data in memory. + */ + class SWIFTEN_API MemoryStorages : public Storages { + public: + MemoryStorages(CryptoProvider*); + virtual ~MemoryStorages(); - virtual VCardStorage* getVCardStorage() const; - virtual AvatarStorage* getAvatarStorage() const; - virtual CapsStorage* getCapsStorage() const; - virtual RosterStorage* getRosterStorage() const; - virtual HistoryStorage* getHistoryStorage() const; + virtual VCardStorage* getVCardStorage() const; + virtual AvatarStorage* getAvatarStorage() const; + virtual CapsStorage* getCapsStorage() const; + virtual RosterStorage* getRosterStorage() const; + virtual HistoryStorage* getHistoryStorage() const; - private: - VCardMemoryStorage* vcardStorage; - AvatarStorage* avatarStorage; - CapsStorage* capsStorage; - RosterStorage* rosterStorage; - HistoryStorage* historyStorage; - }; + private: + VCardMemoryStorage* vcardStorage; + AvatarStorage* avatarStorage; + CapsStorage* capsStorage; + RosterStorage* rosterStorage; + HistoryStorage* historyStorage; + }; } diff --git a/Swiften/Client/NickManager.h b/Swiften/Client/NickManager.h index f05c122..4769bad 100644 --- a/Swiften/Client/NickManager.h +++ b/Swiften/Client/NickManager.h @@ -12,13 +12,13 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - class SWIFTEN_API NickManager { - public: - virtual ~NickManager(); + class SWIFTEN_API NickManager { + public: + virtual ~NickManager(); - virtual std::string getOwnNick() const = 0; - virtual void setOwnNick(const std::string& nick) = 0; + virtual std::string getOwnNick() const = 0; + virtual void setOwnNick(const std::string& nick) = 0; - boost::signal<void (const std::string&)> onOwnNickChanged; - }; + boost::signal<void (const std::string&)> onOwnNickChanged; + }; } diff --git a/Swiften/Client/NickManagerImpl.cpp b/Swiften/Client/NickManagerImpl.cpp index f755424..f8fef39 100644 --- a/Swiften/Client/NickManagerImpl.cpp +++ b/Swiften/Client/NickManagerImpl.cpp @@ -13,38 +13,38 @@ namespace Swift { NickManagerImpl::NickManagerImpl(const JID& ownJID, VCardManager* vcardManager) : ownJID(ownJID), vcardManager(vcardManager) { - vcardManager->onVCardChanged.connect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2)); + vcardManager->onVCardChanged.connect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2)); - updateOwnNickFromVCard(vcardManager->getVCard(ownJID.toBare())); + updateOwnNickFromVCard(vcardManager->getVCard(ownJID.toBare())); } NickManagerImpl::~NickManagerImpl() { - vcardManager->onVCardChanged.disconnect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2)); + vcardManager->onVCardChanged.disconnect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2)); } std::string NickManagerImpl::getOwnNick() const { - return ownNick; + return ownNick; } void NickManagerImpl::setOwnNick(const std::string&) { } void NickManagerImpl::handleVCardReceived(const JID& jid, VCard::ref vcard) { - if (!jid.equals(ownJID, JID::WithoutResource)) { - return; - } - updateOwnNickFromVCard(vcard); + if (!jid.equals(ownJID, JID::WithoutResource)) { + return; + } + updateOwnNickFromVCard(vcard); } void NickManagerImpl::updateOwnNickFromVCard(VCard::ref vcard) { - std::string nick; - if (vcard && !vcard->getNickname().empty()) { - nick = vcard->getNickname(); - } - if (ownNick != nick) { - ownNick = nick; - onOwnNickChanged(ownNick); - } + std::string nick; + if (vcard && !vcard->getNickname().empty()) { + nick = vcard->getNickname(); + } + if (ownNick != nick) { + ownNick = nick; + onOwnNickChanged(ownNick); + } } } diff --git a/Swiften/Client/NickManagerImpl.h b/Swiften/Client/NickManagerImpl.h index 51a8624..a413378 100644 --- a/Swiften/Client/NickManagerImpl.h +++ b/Swiften/Client/NickManagerImpl.h @@ -13,23 +13,23 @@ #include <Swiften/JID/JID.h> namespace Swift { - class VCardManager; + class VCardManager; - class NickManagerImpl : public NickManager { - public: - NickManagerImpl(const JID& ownJID, VCardManager* vcardManager); - virtual ~NickManagerImpl(); + class NickManagerImpl : public NickManager { + public: + NickManagerImpl(const JID& ownJID, VCardManager* vcardManager); + virtual ~NickManagerImpl(); - std::string getOwnNick() const; - void setOwnNick(const std::string& nick); + std::string getOwnNick() const; + void setOwnNick(const std::string& nick); - private: - void handleVCardReceived(const JID& jid, VCard::ref vCard); - void updateOwnNickFromVCard(VCard::ref vcard); + private: + void handleVCardReceived(const JID& jid, VCard::ref vCard); + void updateOwnNickFromVCard(VCard::ref vcard); - private: - JID ownJID; - VCardManager* vcardManager; - std::string ownNick; - }; + private: + JID ownJID; + VCardManager* vcardManager; + std::string ownNick; + }; } diff --git a/Swiften/Client/NickResolver.cpp b/Swiften/Client/NickResolver.cpp index 4136a42..c424447 100644 --- a/Swiften/Client/NickResolver.cpp +++ b/Swiften/Client/NickResolver.cpp @@ -21,59 +21,59 @@ namespace Swift { NickResolver::NickResolver(const JID& ownJID, XMPPRoster* xmppRoster, VCardManager* vcardManager, MUCRegistry* mucRegistry) : ownJID_(ownJID) { - xmppRoster_ = xmppRoster; - vcardManager_ = vcardManager; - if (vcardManager_) { - vcardManager_->onVCardChanged.connect(boost::bind(&NickResolver::handleVCardReceived, this, _1, _2)); - } - mucRegistry_ = mucRegistry; - xmppRoster_->onJIDUpdated.connect(boost::bind(&NickResolver::handleJIDUpdated, this, _1, _2, _3)); - xmppRoster_->onJIDAdded.connect(boost::bind(&NickResolver::handleJIDAdded, this, _1)); + xmppRoster_ = xmppRoster; + vcardManager_ = vcardManager; + if (vcardManager_) { + vcardManager_->onVCardChanged.connect(boost::bind(&NickResolver::handleVCardReceived, this, _1, _2)); + } + mucRegistry_ = mucRegistry; + xmppRoster_->onJIDUpdated.connect(boost::bind(&NickResolver::handleJIDUpdated, this, _1, _2, _3)); + xmppRoster_->onJIDAdded.connect(boost::bind(&NickResolver::handleJIDAdded, this, _1)); } void NickResolver::handleJIDUpdated(const JID& jid, const std::string& previousNick, const std::vector<std::string>& /*groups*/) { - onNickChanged(jid, previousNick); + onNickChanged(jid, previousNick); } void NickResolver::handleJIDAdded(const JID& jid) { - std::string oldNick(jidToNick(jid)); - onNickChanged(jid, oldNick); + std::string oldNick(jidToNick(jid)); + onNickChanged(jid, oldNick); } std::string NickResolver::jidToNick(const JID& jid) { - if (jid.toBare() == ownJID_) { - if (!ownNick_.empty()) { - return ownNick_; - } - } - std::string nick; + if (jid.toBare() == ownJID_) { + if (!ownNick_.empty()) { + return ownNick_; + } + } + std::string nick; - if (mucRegistry_ && mucRegistry_->isMUC(jid.toBare()) ) { - return jid.getResource().empty() ? jid.toBare().toString() : jid.getResource(); - } + if (mucRegistry_ && mucRegistry_->isMUC(jid.toBare()) ) { + return jid.getResource().empty() ? jid.toBare().toString() : jid.getResource(); + } - if (xmppRoster_->containsJID(jid) && !xmppRoster_->getNameForJID(jid).empty()) { - return xmppRoster_->getNameForJID(jid); - } + if (xmppRoster_->containsJID(jid) && !xmppRoster_->getNameForJID(jid).empty()) { + return xmppRoster_->getNameForJID(jid); + } - return jid.toBare(); + return jid.toBare(); } void NickResolver::handleVCardReceived(const JID& jid, VCard::ref ownVCard) { - if (!jid.equals(ownJID_, JID::WithoutResource)) { - return; - } - std::string initialNick = ownNick_; - ownNick_ = ownJID_.toString(); - if (ownVCard) { - if (!ownVCard->getNickname().empty()) { - ownNick_ = ownVCard->getNickname(); - } else if (!ownVCard->getGivenName().empty()) { - ownNick_ = ownVCard->getGivenName(); - } else if (!ownVCard->getFullName().empty()) { - ownNick_ = ownVCard->getFullName(); - } - } + if (!jid.equals(ownJID_, JID::WithoutResource)) { + return; + } + std::string initialNick = ownNick_; + ownNick_ = ownJID_.toString(); + if (ownVCard) { + if (!ownVCard->getNickname().empty()) { + ownNick_ = ownVCard->getNickname(); + } else if (!ownVCard->getGivenName().empty()) { + ownNick_ = ownVCard->getGivenName(); + } else if (!ownVCard->getFullName().empty()) { + ownNick_ = ownVCard->getFullName(); + } + } } } diff --git a/Swiften/Client/NickResolver.h b/Swiften/Client/NickResolver.h index c3e6f05..b187796 100644 --- a/Swiften/Client/NickResolver.h +++ b/Swiften/Client/NickResolver.h @@ -17,28 +17,28 @@ #include <Swiften/JID/JID.h> namespace Swift { - class XMPPRoster; - class MUCRegistry; - class VCardManager; - - class SWIFTEN_API NickResolver { - public: - NickResolver(const JID& ownJID, XMPPRoster* xmppRoster, VCardManager* vcardManager, MUCRegistry* mucRegistry); - - std::string jidToNick(const JID& jid); - - boost::signal<void (const JID&, const std::string& /*previousNick*/)> onNickChanged; - - private: - void handleVCardReceived(const JID& jid, VCard::ref vCard); - void handleJIDUpdated(const JID& jid, const std::string& previousNick, const std::vector<std::string>& groups); - void handleJIDAdded(const JID& jid); - - private: - JID ownJID_; - std::string ownNick_; - XMPPRoster* xmppRoster_; - MUCRegistry* mucRegistry_; - VCardManager* vcardManager_; - }; + class XMPPRoster; + class MUCRegistry; + class VCardManager; + + class SWIFTEN_API NickResolver { + public: + NickResolver(const JID& ownJID, XMPPRoster* xmppRoster, VCardManager* vcardManager, MUCRegistry* mucRegistry); + + std::string jidToNick(const JID& jid); + + boost::signal<void (const JID&, const std::string& /*previousNick*/)> onNickChanged; + + private: + void handleVCardReceived(const JID& jid, VCard::ref vCard); + void handleJIDUpdated(const JID& jid, const std::string& previousNick, const std::vector<std::string>& groups); + void handleJIDAdded(const JID& jid); + + private: + JID ownJID_; + std::string ownNick_; + XMPPRoster* xmppRoster_; + MUCRegistry* mucRegistry_; + VCardManager* vcardManager_; + }; } diff --git a/Swiften/Client/StanzaChannel.h b/Swiften/Client/StanzaChannel.h index bf81c6a..ec36634 100644 --- a/Swiften/Client/StanzaChannel.h +++ b/Swiften/Client/StanzaChannel.h @@ -16,17 +16,17 @@ #include <Swiften/TLS/Certificate.h> namespace Swift { - class SWIFTEN_API StanzaChannel : public IQChannel { - public: - virtual void sendMessage(boost::shared_ptr<Message>) = 0; - virtual void sendPresence(boost::shared_ptr<Presence>) = 0; - virtual bool isAvailable() const = 0; - virtual bool getStreamManagementEnabled() const = 0; - virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0; + class SWIFTEN_API StanzaChannel : public IQChannel { + public: + virtual void sendMessage(boost::shared_ptr<Message>) = 0; + virtual void sendPresence(boost::shared_ptr<Presence>) = 0; + virtual bool isAvailable() const = 0; + virtual bool getStreamManagementEnabled() const = 0; + virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0; - boost::signal<void (bool /* isAvailable */)> onAvailableChanged; - boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived; - boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived; - boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked; - }; + boost::signal<void (bool /* isAvailable */)> onAvailableChanged; + boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived; + boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived; + boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked; + }; } diff --git a/Swiften/Client/Storages.h b/Swiften/Client/Storages.h index 3187cf7..9485831 100644 --- a/Swiften/Client/Storages.h +++ b/Swiften/Client/Storages.h @@ -9,24 +9,24 @@ #include <Swiften/Base/API.h> namespace Swift { - class VCardStorage; - class AvatarStorage; - class CapsStorage; - class RosterStorage; - class HistoryStorage; + class VCardStorage; + class AvatarStorage; + class CapsStorage; + class RosterStorage; + class HistoryStorage; - /** - * An interface to hold storage classes for different - * controllers. - */ - class SWIFTEN_API Storages { - public: - virtual ~Storages(); + /** + * An interface to hold storage classes for different + * controllers. + */ + class SWIFTEN_API Storages { + public: + virtual ~Storages(); - virtual VCardStorage* getVCardStorage() const = 0; - virtual AvatarStorage* getAvatarStorage() const = 0; - virtual CapsStorage* getCapsStorage() const = 0; - virtual RosterStorage* getRosterStorage() const = 0; - virtual HistoryStorage* getHistoryStorage() const = 0; - }; + virtual VCardStorage* getVCardStorage() const = 0; + virtual AvatarStorage* getAvatarStorage() const = 0; + virtual CapsStorage* getCapsStorage() const = 0; + virtual RosterStorage* getRosterStorage() const = 0; + virtual HistoryStorage* getHistoryStorage() const = 0; + }; } diff --git a/Swiften/Client/UnitTest/BlockListImplTest.cpp b/Swiften/Client/UnitTest/BlockListImplTest.cpp index 9e5bc1a..0502f46 100644 --- a/Swiften/Client/UnitTest/BlockListImplTest.cpp +++ b/Swiften/Client/UnitTest/BlockListImplTest.cpp @@ -17,75 +17,75 @@ using namespace Swift; class BlockListImplTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(BlockListImplTest); - CPPUNIT_TEST(testSetItemsToSubset); - CPPUNIT_TEST(testSetItemsToSuperset); - CPPUNIT_TEST(testSetItemsAllDifferent); - CPPUNIT_TEST_SUITE_END(); - - public: - - void testSetItemsToSubset() { - std::vector<JID> subset; - subset.push_back(JID("a@example.com")); - - blockList_->setItems(subset); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), addedJIDs_.size()); - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), removedJIDs_.size()); - } - - void testSetItemsToSuperset() { - std::vector<JID> superset; - superset.push_back(JID("a@example.com")); - superset.push_back(JID("b@example.com")); - superset.push_back(JID("c@example.com")); - - blockList_->setItems(superset); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), addedJIDs_.size()); - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), removedJIDs_.size()); - } - - void testSetItemsAllDifferent() { - std::vector<JID> newBlockList; - newBlockList.push_back(JID("x@example.com")); - newBlockList.push_back(JID("y@example.com")); - newBlockList.push_back(JID("z@example.com")); - - blockList_->setItems(newBlockList); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), addedJIDs_.size()); - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), removedJIDs_.size()); - } - - void setUp() { - blockList_ = boost::make_shared<BlockListImpl>(); - addedJIDs_.clear(); - removedJIDs_.clear(); - blockList_->addItem(JID("a@example.com")); - blockList_->addItem(JID("b@example.com")); - - blockList_->onItemAdded.connect(boost::bind(&BlockListImplTest::handleBlockListItemAdded, this, _1)); - blockList_->onItemRemoved.connect(boost::bind(&BlockListImplTest::handleBlockListItemRemoved, this, _1)); - } - - void tearDown() { - blockList_.reset(); - } - - void handleBlockListItemAdded(const JID& jid) { - addedJIDs_.push_back(jid); - } - - void handleBlockListItemRemoved(const JID& jid) { - removedJIDs_.push_back(jid); - } - - private: - boost::shared_ptr<BlockListImpl> blockList_; - std::vector<JID> addedJIDs_; - std::vector<JID> removedJIDs_; + CPPUNIT_TEST_SUITE(BlockListImplTest); + CPPUNIT_TEST(testSetItemsToSubset); + CPPUNIT_TEST(testSetItemsToSuperset); + CPPUNIT_TEST(testSetItemsAllDifferent); + CPPUNIT_TEST_SUITE_END(); + + public: + + void testSetItemsToSubset() { + std::vector<JID> subset; + subset.push_back(JID("a@example.com")); + + blockList_->setItems(subset); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), addedJIDs_.size()); + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), removedJIDs_.size()); + } + + void testSetItemsToSuperset() { + std::vector<JID> superset; + superset.push_back(JID("a@example.com")); + superset.push_back(JID("b@example.com")); + superset.push_back(JID("c@example.com")); + + blockList_->setItems(superset); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), addedJIDs_.size()); + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), removedJIDs_.size()); + } + + void testSetItemsAllDifferent() { + std::vector<JID> newBlockList; + newBlockList.push_back(JID("x@example.com")); + newBlockList.push_back(JID("y@example.com")); + newBlockList.push_back(JID("z@example.com")); + + blockList_->setItems(newBlockList); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), addedJIDs_.size()); + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), removedJIDs_.size()); + } + + void setUp() { + blockList_ = boost::make_shared<BlockListImpl>(); + addedJIDs_.clear(); + removedJIDs_.clear(); + blockList_->addItem(JID("a@example.com")); + blockList_->addItem(JID("b@example.com")); + + blockList_->onItemAdded.connect(boost::bind(&BlockListImplTest::handleBlockListItemAdded, this, _1)); + blockList_->onItemRemoved.connect(boost::bind(&BlockListImplTest::handleBlockListItemRemoved, this, _1)); + } + + void tearDown() { + blockList_.reset(); + } + + void handleBlockListItemAdded(const JID& jid) { + addedJIDs_.push_back(jid); + } + + void handleBlockListItemRemoved(const JID& jid) { + removedJIDs_.push_back(jid); + } + + private: + boost::shared_ptr<BlockListImpl> blockList_; + std::vector<JID> addedJIDs_; + std::vector<JID> removedJIDs_; }; CPPUNIT_TEST_SUITE_REGISTRATION(BlockListImplTest); diff --git a/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp b/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp index 53c39b5..ef2f537 100644 --- a/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp +++ b/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp @@ -25,170 +25,170 @@ using namespace Swift; class ClientBlockListManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ClientBlockListManagerTest); - CPPUNIT_TEST(testFetchBlockList); - CPPUNIT_TEST(testBlockCommand); - CPPUNIT_TEST(testUnblockCommand); - CPPUNIT_TEST(testUnblockAllCommand); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - ownJID_ = JID("kev@wonderland.lit"); - stanzaChannel_ = new DummyStanzaChannel(); - iqRouter_ = new IQRouter(stanzaChannel_); - iqRouter_->setJID(ownJID_); - clientBlockListManager_ = new ClientBlockListManager(iqRouter_); - } - - void testFetchBlockList() { - std::vector<JID> blockJids; - blockJids.push_back(JID("romeo@montague.net")); - blockJids.push_back(JID("iago@shakespeare.lit")); - helperInitialBlockListFetch(blockJids); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size()); - } - - void testBlockCommand() { - // start with an already fetched block list - helperInitialBlockListFetch(std::vector<JID>(1, JID("iago@shakespeare.lit"))); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size()); - CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); - - GenericRequest<BlockPayload>::ref blockRequest = clientBlockListManager_->createBlockJIDRequest(JID("romeo@montague.net")); - blockRequest->send(); - IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2); - CPPUNIT_ASSERT(request.get() != NULL); - boost::shared_ptr<BlockPayload> blockPayload = request->getPayload<BlockPayload>(); - CPPUNIT_ASSERT(blockPayload.get() != NULL); - CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), blockPayload->getItems().at(0)); - - IQ::ref blockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID()); - stanzaChannel_->sendIQ(blockRequestResponse); - stanzaChannel_->onIQReceived(blockRequestResponse); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size()); - - // send block push - boost::shared_ptr<BlockPayload> pushPayload = boost::make_shared<BlockPayload>(); - pushPayload->addItem(JID("romeo@montague.net")); - IQ::ref blockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload); - stanzaChannel_->sendIQ(blockPush); - stanzaChannel_->onIQReceived(blockPush); - - std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems(); - CPPUNIT_ASSERT(blockedJIDs.end() != std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net"))); - } - - void testUnblockCommand() { - // start with an already fetched block list - std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit")); - initialBlockList.push_back(JID("romeo@montague.net")); - helperInitialBlockListFetch(initialBlockList); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size()); - CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); - - GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockJIDRequest(JID("romeo@montague.net")); - unblockRequest->send(); - IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2); - CPPUNIT_ASSERT(request.get() != NULL); - boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>(); - CPPUNIT_ASSERT(unblockPayload.get() != NULL); - CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), unblockPayload->getItems().at(0)); - - IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID()); - stanzaChannel_->sendIQ(unblockRequestResponse); - stanzaChannel_->onIQReceived(unblockRequestResponse); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size()); - - // send block push - boost::shared_ptr<UnblockPayload> pushPayload = boost::make_shared<UnblockPayload>(); - pushPayload->addItem(JID("romeo@montague.net")); - IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload); - stanzaChannel_->sendIQ(unblockPush); - stanzaChannel_->onIQReceived(unblockPush); - - std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems(); - CPPUNIT_ASSERT(blockedJIDs.end() == std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net"))); - } - - void testUnblockAllCommand() { - // start with an already fetched block list - std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit")); - initialBlockList.push_back(JID("romeo@montague.net")); - initialBlockList.push_back(JID("benvolio@montague.net")); - helperInitialBlockListFetch(initialBlockList); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size()); - CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); - - GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockAllRequest(); - unblockRequest->send(); - IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2); - CPPUNIT_ASSERT(request.get() != NULL); - boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>(); - CPPUNIT_ASSERT(unblockPayload.get() != NULL); - CPPUNIT_ASSERT_EQUAL(true, unblockPayload->getItems().empty()); - - IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID()); - stanzaChannel_->sendIQ(unblockRequestResponse); - stanzaChannel_->onIQReceived(unblockRequestResponse); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size()); - - // send block push - boost::shared_ptr<UnblockPayload> pushPayload = boost::make_shared<UnblockPayload>(); - IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload); - stanzaChannel_->sendIQ(unblockPush); - stanzaChannel_->onIQReceived(unblockPush); - - CPPUNIT_ASSERT_EQUAL(true, clientBlockListManager_->getBlockList()->getItems().empty()); - } - - void tearDown() { - delete clientBlockListManager_; - delete iqRouter_; - delete stanzaChannel_; - } - - private: - void helperInitialBlockListFetch(const std::vector<JID>& blockedJids) { - boost::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList(); - CPPUNIT_ASSERT(blockList); - - // check for IQ request - IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(0); - CPPUNIT_ASSERT(request.get() != NULL); - boost::shared_ptr<BlockListPayload> requestPayload = request->getPayload<BlockListPayload>(); - CPPUNIT_ASSERT(requestPayload.get() != NULL); - - CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, blockList->getState()); - CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, clientBlockListManager_->getBlockList()->getState()); - - // build IQ response - boost::shared_ptr<BlockListPayload> responsePayload = boost::make_shared<BlockListPayload>(); - foreach(const JID& jid, blockedJids) { - responsePayload->addItem(jid); - } - - IQ::ref response = IQ::createResult(ownJID_, JID(), request->getID(), responsePayload); - stanzaChannel_->sendIQ(response); - stanzaChannel_->onIQReceived(response); - - CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); - CPPUNIT_ASSERT(responsePayload->getItems() == clientBlockListManager_->getBlockList()->getItems()); - } - - - private: - JID ownJID_; - IQRouter* iqRouter_; - DummyStanzaChannel* stanzaChannel_; - ClientBlockListManager* clientBlockListManager_; + CPPUNIT_TEST_SUITE(ClientBlockListManagerTest); + CPPUNIT_TEST(testFetchBlockList); + CPPUNIT_TEST(testBlockCommand); + CPPUNIT_TEST(testUnblockCommand); + CPPUNIT_TEST(testUnblockAllCommand); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + ownJID_ = JID("kev@wonderland.lit"); + stanzaChannel_ = new DummyStanzaChannel(); + iqRouter_ = new IQRouter(stanzaChannel_); + iqRouter_->setJID(ownJID_); + clientBlockListManager_ = new ClientBlockListManager(iqRouter_); + } + + void testFetchBlockList() { + std::vector<JID> blockJids; + blockJids.push_back(JID("romeo@montague.net")); + blockJids.push_back(JID("iago@shakespeare.lit")); + helperInitialBlockListFetch(blockJids); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size()); + } + + void testBlockCommand() { + // start with an already fetched block list + helperInitialBlockListFetch(std::vector<JID>(1, JID("iago@shakespeare.lit"))); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size()); + CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); + + GenericRequest<BlockPayload>::ref blockRequest = clientBlockListManager_->createBlockJIDRequest(JID("romeo@montague.net")); + blockRequest->send(); + IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2); + CPPUNIT_ASSERT(request.get() != NULL); + boost::shared_ptr<BlockPayload> blockPayload = request->getPayload<BlockPayload>(); + CPPUNIT_ASSERT(blockPayload.get() != NULL); + CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), blockPayload->getItems().at(0)); + + IQ::ref blockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID()); + stanzaChannel_->sendIQ(blockRequestResponse); + stanzaChannel_->onIQReceived(blockRequestResponse); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size()); + + // send block push + boost::shared_ptr<BlockPayload> pushPayload = boost::make_shared<BlockPayload>(); + pushPayload->addItem(JID("romeo@montague.net")); + IQ::ref blockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload); + stanzaChannel_->sendIQ(blockPush); + stanzaChannel_->onIQReceived(blockPush); + + std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems(); + CPPUNIT_ASSERT(blockedJIDs.end() != std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net"))); + } + + void testUnblockCommand() { + // start with an already fetched block list + std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit")); + initialBlockList.push_back(JID("romeo@montague.net")); + helperInitialBlockListFetch(initialBlockList); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size()); + CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); + + GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockJIDRequest(JID("romeo@montague.net")); + unblockRequest->send(); + IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2); + CPPUNIT_ASSERT(request.get() != NULL); + boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>(); + CPPUNIT_ASSERT(unblockPayload.get() != NULL); + CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), unblockPayload->getItems().at(0)); + + IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID()); + stanzaChannel_->sendIQ(unblockRequestResponse); + stanzaChannel_->onIQReceived(unblockRequestResponse); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size()); + + // send block push + boost::shared_ptr<UnblockPayload> pushPayload = boost::make_shared<UnblockPayload>(); + pushPayload->addItem(JID("romeo@montague.net")); + IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload); + stanzaChannel_->sendIQ(unblockPush); + stanzaChannel_->onIQReceived(unblockPush); + + std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems(); + CPPUNIT_ASSERT(blockedJIDs.end() == std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net"))); + } + + void testUnblockAllCommand() { + // start with an already fetched block list + std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit")); + initialBlockList.push_back(JID("romeo@montague.net")); + initialBlockList.push_back(JID("benvolio@montague.net")); + helperInitialBlockListFetch(initialBlockList); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size()); + CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); + + GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockAllRequest(); + unblockRequest->send(); + IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2); + CPPUNIT_ASSERT(request.get() != NULL); + boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>(); + CPPUNIT_ASSERT(unblockPayload.get() != NULL); + CPPUNIT_ASSERT_EQUAL(true, unblockPayload->getItems().empty()); + + IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID()); + stanzaChannel_->sendIQ(unblockRequestResponse); + stanzaChannel_->onIQReceived(unblockRequestResponse); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size()); + + // send block push + boost::shared_ptr<UnblockPayload> pushPayload = boost::make_shared<UnblockPayload>(); + IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload); + stanzaChannel_->sendIQ(unblockPush); + stanzaChannel_->onIQReceived(unblockPush); + + CPPUNIT_ASSERT_EQUAL(true, clientBlockListManager_->getBlockList()->getItems().empty()); + } + + void tearDown() { + delete clientBlockListManager_; + delete iqRouter_; + delete stanzaChannel_; + } + + private: + void helperInitialBlockListFetch(const std::vector<JID>& blockedJids) { + boost::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList(); + CPPUNIT_ASSERT(blockList); + + // check for IQ request + IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(0); + CPPUNIT_ASSERT(request.get() != NULL); + boost::shared_ptr<BlockListPayload> requestPayload = request->getPayload<BlockListPayload>(); + CPPUNIT_ASSERT(requestPayload.get() != NULL); + + CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, blockList->getState()); + CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, clientBlockListManager_->getBlockList()->getState()); + + // build IQ response + boost::shared_ptr<BlockListPayload> responsePayload = boost::make_shared<BlockListPayload>(); + foreach(const JID& jid, blockedJids) { + responsePayload->addItem(jid); + } + + IQ::ref response = IQ::createResult(ownJID_, JID(), request->getID(), responsePayload); + stanzaChannel_->sendIQ(response); + stanzaChannel_->onIQReceived(response); + + CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState()); + CPPUNIT_ASSERT(responsePayload->getItems() == clientBlockListManager_->getBlockList()->getItems()); + } + + + private: + JID ownJID_; + IQRouter* iqRouter_; + DummyStanzaChannel* stanzaChannel_; + ClientBlockListManager* clientBlockListManager_; }; CPPUNIT_TEST_SUITE_REGISTRATION(ClientBlockListManagerTest); diff --git a/Swiften/Client/UnitTest/ClientSessionTest.cpp b/Swiften/Client/UnitTest/ClientSessionTest.cpp index 396edf6..335b537 100644 --- a/Swiften/Client/UnitTest/ClientSessionTest.cpp +++ b/Swiften/Client/UnitTest/ClientSessionTest.cpp @@ -41,789 +41,789 @@ using namespace Swift; class ClientSessionTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ClientSessionTest); - CPPUNIT_TEST(testStart_Error); - CPPUNIT_TEST(testStart_StreamError); - CPPUNIT_TEST(testStartTLS); - CPPUNIT_TEST(testStartTLS_ServerError); - CPPUNIT_TEST(testStartTLS_ConnectError); - CPPUNIT_TEST(testStartTLS_InvalidIdentity); - CPPUNIT_TEST(testStart_StreamFeaturesWithoutResourceBindingFails); - CPPUNIT_TEST(testAuthenticate); - CPPUNIT_TEST(testAuthenticate_Unauthorized); - CPPUNIT_TEST(testAuthenticate_NoValidAuthMechanisms); - CPPUNIT_TEST(testAuthenticate_PLAINOverNonTLS); - CPPUNIT_TEST(testAuthenticate_RequireTLS); - CPPUNIT_TEST(testAuthenticate_EXTERNAL); - CPPUNIT_TEST(testStreamManagement); - CPPUNIT_TEST(testStreamManagement_Failed); - CPPUNIT_TEST(testUnexpectedChallenge); - CPPUNIT_TEST(testFinishAcksStanzas); - /* - CPPUNIT_TEST(testResourceBind); - CPPUNIT_TEST(testResourceBind_ChangeResource); - CPPUNIT_TEST(testResourceBind_EmptyResource); - CPPUNIT_TEST(testResourceBind_Error); - CPPUNIT_TEST(testSessionStart); - CPPUNIT_TEST(testSessionStart_Error); - CPPUNIT_TEST(testSessionStart_AfterResourceBind); - CPPUNIT_TEST(testWhitespacePing); - CPPUNIT_TEST(testReceiveElementAfterSessionStarted); - CPPUNIT_TEST(testSendElement); - */ - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create()); - server = boost::make_shared<MockSessionStream>(); - sessionFinishedReceived = false; - needCredentials = false; - blindCertificateTrustChecker = new BlindCertificateTrustChecker(); - } - - void tearDown() { - delete blindCertificateTrustChecker; - } - - void testStart_Error() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->breakConnection(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testStart_StreamError() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->sendStreamStart(); - server->sendStreamError(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testStartTLS() { - boost::shared_ptr<ClientSession> session(createSession()); - session->setCertificateTrustChecker(blindCertificateTrustChecker); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithStartTLS(); - server->receiveStartTLS(); - CPPUNIT_ASSERT(!server->tlsEncrypted); - server->sendTLSProceed(); - CPPUNIT_ASSERT(server->tlsEncrypted); - server->onTLSEncrypted(); - server->receiveStreamStart(); - server->sendStreamStart(); - - session->finish(); - } - - void testStartTLS_ServerError() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithStartTLS(); - server->receiveStartTLS(); - server->sendTLSFailure(); - - CPPUNIT_ASSERT(!server->tlsEncrypted); - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testStartTLS_ConnectError() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithStartTLS(); - server->receiveStartTLS(); - server->sendTLSProceed(); - server->breakTLS(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testStartTLS_InvalidIdentity() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithStartTLS(); - server->receiveStartTLS(); - CPPUNIT_ASSERT(!server->tlsEncrypted); - server->sendTLSProceed(); - CPPUNIT_ASSERT(server->tlsEncrypted); - server->onTLSEncrypted(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::InvalidServerIdentity, boost::dynamic_pointer_cast<CertificateVerificationError>(sessionFinishedError)->getType()); - } - - void testStart_StreamFeaturesWithoutResourceBindingFails() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendEmptyStreamFeatures(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testAuthenticate() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithPLAINAuthentication(); - CPPUNIT_ASSERT(needCredentials); - CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState()); - session->sendCredentials(createSafeByteArray("mypass")); - server->receiveAuthRequest("PLAIN"); - server->sendAuthSuccess(); - server->receiveStreamStart(); - - session->finish(); - } - - void testAuthenticate_Unauthorized() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithPLAINAuthentication(); - CPPUNIT_ASSERT(needCredentials); - CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState()); - session->sendCredentials(createSafeByteArray("mypass")); - server->receiveAuthRequest("PLAIN"); - server->sendAuthFailure(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testAuthenticate_PLAINOverNonTLS() { - boost::shared_ptr<ClientSession> session(createSession()); - session->setAllowPLAINOverNonTLS(false); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithPLAINAuthentication(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testAuthenticate_RequireTLS() { - boost::shared_ptr<ClientSession> session(createSession()); - session->setUseTLS(ClientSession::RequireTLS); - session->setAllowPLAINOverNonTLS(true); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithMultipleAuthentication(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testAuthenticate_NoValidAuthMechanisms() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithUnknownAuthentication(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testAuthenticate_EXTERNAL() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithEXTERNALAuthentication(); - server->receiveAuthRequest("EXTERNAL"); - server->sendAuthSuccess(); - server->receiveStreamStart(); - - session->finish(); - } - - void testUnexpectedChallenge() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithEXTERNALAuthentication(); - server->receiveAuthRequest("EXTERNAL"); - server->sendChallenge(); - server->sendChallenge(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testStreamManagement() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithPLAINAuthentication(); - session->sendCredentials(createSafeByteArray("mypass")); - server->receiveAuthRequest("PLAIN"); - server->sendAuthSuccess(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithBindAndStreamManagement(); - server->receiveBind(); - server->sendBindResult(); - server->receiveStreamManagementEnable(); - server->sendStreamManagementEnabled(); - - CPPUNIT_ASSERT(session->getStreamManagementEnabled()); - // TODO: Test if the requesters & responders do their work - CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState()); - - session->finish(); - } - - void testStreamManagement_Failed() { - boost::shared_ptr<ClientSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithPLAINAuthentication(); - session->sendCredentials(createSafeByteArray("mypass")); - server->receiveAuthRequest("PLAIN"); - server->sendAuthSuccess(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithBindAndStreamManagement(); - server->receiveBind(); - server->sendBindResult(); - server->receiveStreamManagementEnable(); - server->sendStreamManagementFailed(); - - CPPUNIT_ASSERT(!session->getStreamManagementEnabled()); - CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState()); - - session->finish(); - } - - void testFinishAcksStanzas() { - boost::shared_ptr<ClientSession> session(createSession()); - initializeSession(session); - server->sendMessage(); - server->sendMessage(); - server->sendMessage(); - - session->finish(); - - server->receiveAck(3); - } - - private: - boost::shared_ptr<ClientSession> createSession() { - boost::shared_ptr<ClientSession> session = ClientSession::create(JID("me@foo.com"), server, idnConverter.get(), crypto.get()); - session->onFinished.connect(boost::bind(&ClientSessionTest::handleSessionFinished, this, _1)); - session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::handleSessionNeedCredentials, this)); - session->setAllowPLAINOverNonTLS(true); - return session; - } - - void initializeSession(boost::shared_ptr<ClientSession> session) { - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithPLAINAuthentication(); - session->sendCredentials(createSafeByteArray("mypass")); - server->receiveAuthRequest("PLAIN"); - server->sendAuthSuccess(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->sendStreamFeaturesWithBindAndStreamManagement(); - server->receiveBind(); - server->sendBindResult(); - server->receiveStreamManagementEnable(); - server->sendStreamManagementEnabled(); - } - - void handleSessionFinished(boost::shared_ptr<Error> error) { - sessionFinishedReceived = true; - sessionFinishedError = error; - } - - void handleSessionNeedCredentials() { - needCredentials = true; - } - - class MockSessionStream : public SessionStream { - public: - struct Event { - Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {} - Event(const ProtocolHeader& header) : header(header), footer(false) {} - Event() : footer(true) {} - - boost::shared_ptr<ToplevelElement> element; - boost::optional<ProtocolHeader> header; - bool footer; - }; - - MockSessionStream() : available(true), canTLSEncrypt(true), tlsEncrypted(false), compressed(false), whitespacePingEnabled(false), resetCount(0) { - } - - virtual void close() { - onClosed(boost::shared_ptr<Error>()); - } - - virtual bool isOpen() { - return available; - } - - virtual void writeHeader(const ProtocolHeader& header) { - receivedEvents.push_back(Event(header)); - } - - virtual void writeFooter() { - receivedEvents.push_back(Event()); - } - - virtual void writeElement(boost::shared_ptr<ToplevelElement> element) { - receivedEvents.push_back(Event(element)); - } - - virtual void writeData(const std::string&) { - } - - virtual bool supportsTLSEncryption() { - return canTLSEncrypt; - } - - virtual void addTLSEncryption() { - tlsEncrypted = true; - } - - virtual bool isTLSEncrypted() { - return tlsEncrypted; - } - - virtual ByteArray getTLSFinishMessage() const { - return ByteArray(); - } - - virtual Certificate::ref getPeerCertificate() const { - return Certificate::ref(new SimpleCertificate()); - } - - virtual std::vector<Certificate::ref> getPeerCertificateChain() const { - return std::vector<Certificate::ref>(); - } - - virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const { - return boost::shared_ptr<CertificateVerificationError>(); - } - - virtual bool supportsZLibCompression() { - return true; - } - - virtual void addZLibCompression() { - compressed = true; - } - - virtual void setWhitespacePingEnabled(bool enabled) { - whitespacePingEnabled = enabled; - } - - virtual void resetXMPPParser() { - resetCount++; - } - - void breakConnection() { - onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError)); - } - - void breakTLS() { - onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::TLSError)); - } - - - void sendStreamStart() { - ProtocolHeader header; - header.setTo("foo.com"); - return onStreamStartReceived(header); - } - - void sendStreamFeaturesWithStartTLS() { - boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); - streamFeatures->setHasStartTLS(); - onElementReceived(streamFeatures); - } - - void sendChallenge() { - onElementReceived(boost::make_shared<AuthChallenge>()); - } - - void sendStreamError() { - onElementReceived(boost::make_shared<StreamError>()); - } - - void sendTLSProceed() { - onElementReceived(boost::make_shared<TLSProceed>()); - } - - void sendTLSFailure() { - onElementReceived(boost::make_shared<StartTLSFailure>()); - } - - void sendStreamFeaturesWithMultipleAuthentication() { - boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); - streamFeatures->addAuthenticationMechanism("PLAIN"); - streamFeatures->addAuthenticationMechanism("DIGEST-MD5"); - streamFeatures->addAuthenticationMechanism("SCRAM-SHA1"); - onElementReceived(streamFeatures); - } - - void sendStreamFeaturesWithPLAINAuthentication() { - boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); - streamFeatures->addAuthenticationMechanism("PLAIN"); - onElementReceived(streamFeatures); - } - - void sendStreamFeaturesWithEXTERNALAuthentication() { - boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); - streamFeatures->addAuthenticationMechanism("EXTERNAL"); - onElementReceived(streamFeatures); - } - - void sendStreamFeaturesWithUnknownAuthentication() { - boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); - streamFeatures->addAuthenticationMechanism("UNKNOWN"); - onElementReceived(streamFeatures); - } - - void sendStreamFeaturesWithBindAndStreamManagement() { - boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); - streamFeatures->setHasResourceBind(); - streamFeatures->setHasStreamManagement(); - onElementReceived(streamFeatures); - } - - void sendEmptyStreamFeatures() { - onElementReceived(boost::make_shared<StreamFeatures>()); - } - - void sendAuthSuccess() { - onElementReceived(boost::make_shared<AuthSuccess>()); - } - - void sendAuthFailure() { - onElementReceived(boost::make_shared<AuthFailure>()); - } - - void sendStreamManagementEnabled() { - onElementReceived(boost::make_shared<StreamManagementEnabled>()); - } - - void sendStreamManagementFailed() { - onElementReceived(boost::make_shared<StreamManagementFailed>()); - } - - void sendBindResult() { - boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind()); - resourceBind->setJID(JID("foo@bar.com/bla")); - boost::shared_ptr<IQ> iq = IQ::createResult(JID("foo@bar.com"), bindID, resourceBind); - onElementReceived(iq); - } - - void sendMessage() { - boost::shared_ptr<Message> message = boost::make_shared<Message>(); - message->setTo(JID("foo@bar.com/bla")); - onElementReceived(message); - } - - void receiveStreamStart() { - Event event = popEvent(); - CPPUNIT_ASSERT(event.header); - } - - void receiveStartTLS() { - Event event = popEvent(); - CPPUNIT_ASSERT(event.element); - CPPUNIT_ASSERT(boost::dynamic_pointer_cast<StartTLSRequest>(event.element)); - } - - void receiveAuthRequest(const std::string& mech) { - Event event = popEvent(); - CPPUNIT_ASSERT(event.element); - boost::shared_ptr<AuthRequest> request(boost::dynamic_pointer_cast<AuthRequest>(event.element)); - CPPUNIT_ASSERT(request); - CPPUNIT_ASSERT_EQUAL(mech, request->getMechanism()); - } - - void receiveStreamManagementEnable() { - Event event = popEvent(); - CPPUNIT_ASSERT(event.element); - CPPUNIT_ASSERT(boost::dynamic_pointer_cast<EnableStreamManagement>(event.element)); - } - - void receiveBind() { - Event event = popEvent(); - CPPUNIT_ASSERT(event.element); - boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(event.element); - CPPUNIT_ASSERT(iq); - CPPUNIT_ASSERT(iq->getPayload<ResourceBind>()); - bindID = iq->getID(); - } - - void receiveAck(unsigned int n) { - Event event = popEvent(); - CPPUNIT_ASSERT(event.element); - boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(event.element); - CPPUNIT_ASSERT(ack); - CPPUNIT_ASSERT_EQUAL(n, ack->getHandledStanzasCount()); - } - - Event popEvent() { - CPPUNIT_ASSERT(!receivedEvents.empty()); - Event event = receivedEvents.front(); - receivedEvents.pop_front(); - return event; - } - - bool available; - bool canTLSEncrypt; - bool tlsEncrypted; - bool compressed; - bool whitespacePingEnabled; - std::string bindID; - int resetCount; - std::deque<Event> receivedEvents; - }; - - boost::shared_ptr<IDNConverter> idnConverter; - boost::shared_ptr<MockSessionStream> server; - bool sessionFinishedReceived; - bool needCredentials; - boost::shared_ptr<Error> sessionFinishedError; - BlindCertificateTrustChecker* blindCertificateTrustChecker; - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(ClientSessionTest); + CPPUNIT_TEST(testStart_Error); + CPPUNIT_TEST(testStart_StreamError); + CPPUNIT_TEST(testStartTLS); + CPPUNIT_TEST(testStartTLS_ServerError); + CPPUNIT_TEST(testStartTLS_ConnectError); + CPPUNIT_TEST(testStartTLS_InvalidIdentity); + CPPUNIT_TEST(testStart_StreamFeaturesWithoutResourceBindingFails); + CPPUNIT_TEST(testAuthenticate); + CPPUNIT_TEST(testAuthenticate_Unauthorized); + CPPUNIT_TEST(testAuthenticate_NoValidAuthMechanisms); + CPPUNIT_TEST(testAuthenticate_PLAINOverNonTLS); + CPPUNIT_TEST(testAuthenticate_RequireTLS); + CPPUNIT_TEST(testAuthenticate_EXTERNAL); + CPPUNIT_TEST(testStreamManagement); + CPPUNIT_TEST(testStreamManagement_Failed); + CPPUNIT_TEST(testUnexpectedChallenge); + CPPUNIT_TEST(testFinishAcksStanzas); + /* + CPPUNIT_TEST(testResourceBind); + CPPUNIT_TEST(testResourceBind_ChangeResource); + CPPUNIT_TEST(testResourceBind_EmptyResource); + CPPUNIT_TEST(testResourceBind_Error); + CPPUNIT_TEST(testSessionStart); + CPPUNIT_TEST(testSessionStart_Error); + CPPUNIT_TEST(testSessionStart_AfterResourceBind); + CPPUNIT_TEST(testWhitespacePing); + CPPUNIT_TEST(testReceiveElementAfterSessionStarted); + CPPUNIT_TEST(testSendElement); + */ + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create()); + server = boost::make_shared<MockSessionStream>(); + sessionFinishedReceived = false; + needCredentials = false; + blindCertificateTrustChecker = new BlindCertificateTrustChecker(); + } + + void tearDown() { + delete blindCertificateTrustChecker; + } + + void testStart_Error() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->breakConnection(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testStart_StreamError() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->sendStreamStart(); + server->sendStreamError(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testStartTLS() { + boost::shared_ptr<ClientSession> session(createSession()); + session->setCertificateTrustChecker(blindCertificateTrustChecker); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithStartTLS(); + server->receiveStartTLS(); + CPPUNIT_ASSERT(!server->tlsEncrypted); + server->sendTLSProceed(); + CPPUNIT_ASSERT(server->tlsEncrypted); + server->onTLSEncrypted(); + server->receiveStreamStart(); + server->sendStreamStart(); + + session->finish(); + } + + void testStartTLS_ServerError() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithStartTLS(); + server->receiveStartTLS(); + server->sendTLSFailure(); + + CPPUNIT_ASSERT(!server->tlsEncrypted); + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testStartTLS_ConnectError() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithStartTLS(); + server->receiveStartTLS(); + server->sendTLSProceed(); + server->breakTLS(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testStartTLS_InvalidIdentity() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithStartTLS(); + server->receiveStartTLS(); + CPPUNIT_ASSERT(!server->tlsEncrypted); + server->sendTLSProceed(); + CPPUNIT_ASSERT(server->tlsEncrypted); + server->onTLSEncrypted(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::InvalidServerIdentity, boost::dynamic_pointer_cast<CertificateVerificationError>(sessionFinishedError)->getType()); + } + + void testStart_StreamFeaturesWithoutResourceBindingFails() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendEmptyStreamFeatures(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testAuthenticate() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithPLAINAuthentication(); + CPPUNIT_ASSERT(needCredentials); + CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState()); + session->sendCredentials(createSafeByteArray("mypass")); + server->receiveAuthRequest("PLAIN"); + server->sendAuthSuccess(); + server->receiveStreamStart(); + + session->finish(); + } + + void testAuthenticate_Unauthorized() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithPLAINAuthentication(); + CPPUNIT_ASSERT(needCredentials); + CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState()); + session->sendCredentials(createSafeByteArray("mypass")); + server->receiveAuthRequest("PLAIN"); + server->sendAuthFailure(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testAuthenticate_PLAINOverNonTLS() { + boost::shared_ptr<ClientSession> session(createSession()); + session->setAllowPLAINOverNonTLS(false); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithPLAINAuthentication(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testAuthenticate_RequireTLS() { + boost::shared_ptr<ClientSession> session(createSession()); + session->setUseTLS(ClientSession::RequireTLS); + session->setAllowPLAINOverNonTLS(true); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithMultipleAuthentication(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testAuthenticate_NoValidAuthMechanisms() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithUnknownAuthentication(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testAuthenticate_EXTERNAL() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithEXTERNALAuthentication(); + server->receiveAuthRequest("EXTERNAL"); + server->sendAuthSuccess(); + server->receiveStreamStart(); + + session->finish(); + } + + void testUnexpectedChallenge() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithEXTERNALAuthentication(); + server->receiveAuthRequest("EXTERNAL"); + server->sendChallenge(); + server->sendChallenge(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testStreamManagement() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithPLAINAuthentication(); + session->sendCredentials(createSafeByteArray("mypass")); + server->receiveAuthRequest("PLAIN"); + server->sendAuthSuccess(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithBindAndStreamManagement(); + server->receiveBind(); + server->sendBindResult(); + server->receiveStreamManagementEnable(); + server->sendStreamManagementEnabled(); + + CPPUNIT_ASSERT(session->getStreamManagementEnabled()); + // TODO: Test if the requesters & responders do their work + CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState()); + + session->finish(); + } + + void testStreamManagement_Failed() { + boost::shared_ptr<ClientSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithPLAINAuthentication(); + session->sendCredentials(createSafeByteArray("mypass")); + server->receiveAuthRequest("PLAIN"); + server->sendAuthSuccess(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithBindAndStreamManagement(); + server->receiveBind(); + server->sendBindResult(); + server->receiveStreamManagementEnable(); + server->sendStreamManagementFailed(); + + CPPUNIT_ASSERT(!session->getStreamManagementEnabled()); + CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState()); + + session->finish(); + } + + void testFinishAcksStanzas() { + boost::shared_ptr<ClientSession> session(createSession()); + initializeSession(session); + server->sendMessage(); + server->sendMessage(); + server->sendMessage(); + + session->finish(); + + server->receiveAck(3); + } + + private: + boost::shared_ptr<ClientSession> createSession() { + boost::shared_ptr<ClientSession> session = ClientSession::create(JID("me@foo.com"), server, idnConverter.get(), crypto.get()); + session->onFinished.connect(boost::bind(&ClientSessionTest::handleSessionFinished, this, _1)); + session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::handleSessionNeedCredentials, this)); + session->setAllowPLAINOverNonTLS(true); + return session; + } + + void initializeSession(boost::shared_ptr<ClientSession> session) { + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithPLAINAuthentication(); + session->sendCredentials(createSafeByteArray("mypass")); + server->receiveAuthRequest("PLAIN"); + server->sendAuthSuccess(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->sendStreamFeaturesWithBindAndStreamManagement(); + server->receiveBind(); + server->sendBindResult(); + server->receiveStreamManagementEnable(); + server->sendStreamManagementEnabled(); + } + + void handleSessionFinished(boost::shared_ptr<Error> error) { + sessionFinishedReceived = true; + sessionFinishedError = error; + } + + void handleSessionNeedCredentials() { + needCredentials = true; + } + + class MockSessionStream : public SessionStream { + public: + struct Event { + Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {} + Event(const ProtocolHeader& header) : header(header), footer(false) {} + Event() : footer(true) {} + + boost::shared_ptr<ToplevelElement> element; + boost::optional<ProtocolHeader> header; + bool footer; + }; + + MockSessionStream() : available(true), canTLSEncrypt(true), tlsEncrypted(false), compressed(false), whitespacePingEnabled(false), resetCount(0) { + } + + virtual void close() { + onClosed(boost::shared_ptr<Error>()); + } + + virtual bool isOpen() { + return available; + } + + virtual void writeHeader(const ProtocolHeader& header) { + receivedEvents.push_back(Event(header)); + } + + virtual void writeFooter() { + receivedEvents.push_back(Event()); + } + + virtual void writeElement(boost::shared_ptr<ToplevelElement> element) { + receivedEvents.push_back(Event(element)); + } + + virtual void writeData(const std::string&) { + } + + virtual bool supportsTLSEncryption() { + return canTLSEncrypt; + } + + virtual void addTLSEncryption() { + tlsEncrypted = true; + } + + virtual bool isTLSEncrypted() { + return tlsEncrypted; + } + + virtual ByteArray getTLSFinishMessage() const { + return ByteArray(); + } + + virtual Certificate::ref getPeerCertificate() const { + return Certificate::ref(new SimpleCertificate()); + } + + virtual std::vector<Certificate::ref> getPeerCertificateChain() const { + return std::vector<Certificate::ref>(); + } + + virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const { + return boost::shared_ptr<CertificateVerificationError>(); + } + + virtual bool supportsZLibCompression() { + return true; + } + + virtual void addZLibCompression() { + compressed = true; + } + + virtual void setWhitespacePingEnabled(bool enabled) { + whitespacePingEnabled = enabled; + } + + virtual void resetXMPPParser() { + resetCount++; + } + + void breakConnection() { + onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError)); + } + + void breakTLS() { + onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::TLSError)); + } + + + void sendStreamStart() { + ProtocolHeader header; + header.setTo("foo.com"); + return onStreamStartReceived(header); + } + + void sendStreamFeaturesWithStartTLS() { + boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); + streamFeatures->setHasStartTLS(); + onElementReceived(streamFeatures); + } + + void sendChallenge() { + onElementReceived(boost::make_shared<AuthChallenge>()); + } + + void sendStreamError() { + onElementReceived(boost::make_shared<StreamError>()); + } + + void sendTLSProceed() { + onElementReceived(boost::make_shared<TLSProceed>()); + } + + void sendTLSFailure() { + onElementReceived(boost::make_shared<StartTLSFailure>()); + } + + void sendStreamFeaturesWithMultipleAuthentication() { + boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); + streamFeatures->addAuthenticationMechanism("PLAIN"); + streamFeatures->addAuthenticationMechanism("DIGEST-MD5"); + streamFeatures->addAuthenticationMechanism("SCRAM-SHA1"); + onElementReceived(streamFeatures); + } + + void sendStreamFeaturesWithPLAINAuthentication() { + boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); + streamFeatures->addAuthenticationMechanism("PLAIN"); + onElementReceived(streamFeatures); + } + + void sendStreamFeaturesWithEXTERNALAuthentication() { + boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); + streamFeatures->addAuthenticationMechanism("EXTERNAL"); + onElementReceived(streamFeatures); + } + + void sendStreamFeaturesWithUnknownAuthentication() { + boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); + streamFeatures->addAuthenticationMechanism("UNKNOWN"); + onElementReceived(streamFeatures); + } + + void sendStreamFeaturesWithBindAndStreamManagement() { + boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures()); + streamFeatures->setHasResourceBind(); + streamFeatures->setHasStreamManagement(); + onElementReceived(streamFeatures); + } + + void sendEmptyStreamFeatures() { + onElementReceived(boost::make_shared<StreamFeatures>()); + } + + void sendAuthSuccess() { + onElementReceived(boost::make_shared<AuthSuccess>()); + } + + void sendAuthFailure() { + onElementReceived(boost::make_shared<AuthFailure>()); + } + + void sendStreamManagementEnabled() { + onElementReceived(boost::make_shared<StreamManagementEnabled>()); + } + + void sendStreamManagementFailed() { + onElementReceived(boost::make_shared<StreamManagementFailed>()); + } + + void sendBindResult() { + boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind()); + resourceBind->setJID(JID("foo@bar.com/bla")); + boost::shared_ptr<IQ> iq = IQ::createResult(JID("foo@bar.com"), bindID, resourceBind); + onElementReceived(iq); + } + + void sendMessage() { + boost::shared_ptr<Message> message = boost::make_shared<Message>(); + message->setTo(JID("foo@bar.com/bla")); + onElementReceived(message); + } + + void receiveStreamStart() { + Event event = popEvent(); + CPPUNIT_ASSERT(event.header); + } + + void receiveStartTLS() { + Event event = popEvent(); + CPPUNIT_ASSERT(event.element); + CPPUNIT_ASSERT(boost::dynamic_pointer_cast<StartTLSRequest>(event.element)); + } + + void receiveAuthRequest(const std::string& mech) { + Event event = popEvent(); + CPPUNIT_ASSERT(event.element); + boost::shared_ptr<AuthRequest> request(boost::dynamic_pointer_cast<AuthRequest>(event.element)); + CPPUNIT_ASSERT(request); + CPPUNIT_ASSERT_EQUAL(mech, request->getMechanism()); + } + + void receiveStreamManagementEnable() { + Event event = popEvent(); + CPPUNIT_ASSERT(event.element); + CPPUNIT_ASSERT(boost::dynamic_pointer_cast<EnableStreamManagement>(event.element)); + } + + void receiveBind() { + Event event = popEvent(); + CPPUNIT_ASSERT(event.element); + boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(event.element); + CPPUNIT_ASSERT(iq); + CPPUNIT_ASSERT(iq->getPayload<ResourceBind>()); + bindID = iq->getID(); + } + + void receiveAck(unsigned int n) { + Event event = popEvent(); + CPPUNIT_ASSERT(event.element); + boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(event.element); + CPPUNIT_ASSERT(ack); + CPPUNIT_ASSERT_EQUAL(n, ack->getHandledStanzasCount()); + } + + Event popEvent() { + CPPUNIT_ASSERT(!receivedEvents.empty()); + Event event = receivedEvents.front(); + receivedEvents.pop_front(); + return event; + } + + bool available; + bool canTLSEncrypt; + bool tlsEncrypted; + bool compressed; + bool whitespacePingEnabled; + std::string bindID; + int resetCount; + std::deque<Event> receivedEvents; + }; + + boost::shared_ptr<IDNConverter> idnConverter; + boost::shared_ptr<MockSessionStream> server; + bool sessionFinishedReceived; + bool needCredentials; + boost::shared_ptr<Error> sessionFinishedError; + BlindCertificateTrustChecker* blindCertificateTrustChecker; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(ClientSessionTest); #if 0 - void testAuthenticate() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::setNeedCredentials, this)); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithAuthentication(); - session->startSession(); - processEvents(); - CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState()); - CPPUNIT_ASSERT(needCredentials_); - - getMockServer()->expectAuth("me", "mypass"); - getMockServer()->sendAuthSuccess(); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - session->sendCredentials("mypass"); - CPPUNIT_ASSERT_EQUAL(ClientSession::Authenticating, session->getState()); - processEvents(); - CPPUNIT_ASSERT_EQUAL(ClientSession::Negotiating, session->getState()); - } - - void testAuthenticate_Unauthorized() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithAuthentication(); - session->startSession(); - processEvents(); - - getMockServer()->expectAuth("me", "mypass"); - getMockServer()->sendAuthFailure(); - session->sendCredentials("mypass"); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); - CPPUNIT_ASSERT_EQUAL(ClientSession::AuthenticationFailedError, *session->getError()); - } - - void testAuthenticate_NoValidAuthMechanisms() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithUnsupportedAuthentication(); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); - CPPUNIT_ASSERT_EQUAL(ClientSession::NoSupportedAuthMechanismsError, *session->getError()); - } - - void testResourceBind() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithResourceBind(); - getMockServer()->expectResourceBind("Bar", "session-bind"); - // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::BindingResource, session->getState()); - getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind"); - session->startSession(); - - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); - CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar"), session->getLocalJID()); - } - - void testResourceBind_ChangeResource() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithResourceBind(); - getMockServer()->expectResourceBind("Bar", "session-bind"); - getMockServer()->sendResourceBindResponse("me@foo.com/Bar123", "session-bind"); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); - CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar123"), session->getLocalJID()); - } - - void testResourceBind_EmptyResource() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithResourceBind(); - getMockServer()->expectResourceBind("", "session-bind"); - getMockServer()->sendResourceBindResponse("me@foo.com/NewResource", "session-bind"); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); - CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/NewResource"), session->getLocalJID()); - } - - void testResourceBind_Error() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithResourceBind(); - getMockServer()->expectResourceBind("", "session-bind"); - getMockServer()->sendError("session-bind"); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); - CPPUNIT_ASSERT_EQUAL(ClientSession::ResourceBindError, *session->getError()); - } - - void testSessionStart() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this)); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithSession(); - getMockServer()->expectSessionStart("session-start"); - // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::StartingSession, session->getState()); - getMockServer()->sendSessionStartResponse("session-start"); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); - CPPUNIT_ASSERT(sessionStarted_); - } - - void testSessionStart_Error() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithSession(); - getMockServer()->expectSessionStart("session-start"); - getMockServer()->sendError("session-start"); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); - CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStartError, *session->getError()); - } - - void testSessionStart_AfterResourceBind() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this)); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeaturesWithResourceBindAndSession(); - getMockServer()->expectResourceBind("Bar", "session-bind"); - getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind"); - getMockServer()->expectSessionStart("session-start"); - getMockServer()->sendSessionStartResponse("session-start"); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); - CPPUNIT_ASSERT(sessionStarted_); - } - - void testWhitespacePing() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeatures(); - session->startSession(); - processEvents(); - CPPUNIT_ASSERT(session->getWhitespacePingLayer()); - } - - void testReceiveElementAfterSessionStarted() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeatures(); - session->startSession(); - processEvents(); - - getMockServer()->expectMessage(); - session->sendElement(boost::make_shared<Message>())); - } - - void testSendElement() { - boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); - session->onElementReceived.connect(boost::bind(&ClientSessionTest::addReceivedElement, this, _1)); - getMockServer()->expectStreamStart(); - getMockServer()->sendStreamStart(); - getMockServer()->sendStreamFeatures(); - getMockServer()->sendMessage(); - session->startSession(); - processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedElements_.size())); - CPPUNIT_ASSERT(boost::dynamic_pointer_cast<Message>(receivedElements_[0])); - } + void testAuthenticate() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::setNeedCredentials, this)); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithAuthentication(); + session->startSession(); + processEvents(); + CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState()); + CPPUNIT_ASSERT(needCredentials_); + + getMockServer()->expectAuth("me", "mypass"); + getMockServer()->sendAuthSuccess(); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + session->sendCredentials("mypass"); + CPPUNIT_ASSERT_EQUAL(ClientSession::Authenticating, session->getState()); + processEvents(); + CPPUNIT_ASSERT_EQUAL(ClientSession::Negotiating, session->getState()); + } + + void testAuthenticate_Unauthorized() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithAuthentication(); + session->startSession(); + processEvents(); + + getMockServer()->expectAuth("me", "mypass"); + getMockServer()->sendAuthFailure(); + session->sendCredentials("mypass"); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); + CPPUNIT_ASSERT_EQUAL(ClientSession::AuthenticationFailedError, *session->getError()); + } + + void testAuthenticate_NoValidAuthMechanisms() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithUnsupportedAuthentication(); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); + CPPUNIT_ASSERT_EQUAL(ClientSession::NoSupportedAuthMechanismsError, *session->getError()); + } + + void testResourceBind() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithResourceBind(); + getMockServer()->expectResourceBind("Bar", "session-bind"); + // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::BindingResource, session->getState()); + getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind"); + session->startSession(); + + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); + CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar"), session->getLocalJID()); + } + + void testResourceBind_ChangeResource() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithResourceBind(); + getMockServer()->expectResourceBind("Bar", "session-bind"); + getMockServer()->sendResourceBindResponse("me@foo.com/Bar123", "session-bind"); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); + CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar123"), session->getLocalJID()); + } + + void testResourceBind_EmptyResource() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithResourceBind(); + getMockServer()->expectResourceBind("", "session-bind"); + getMockServer()->sendResourceBindResponse("me@foo.com/NewResource", "session-bind"); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); + CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/NewResource"), session->getLocalJID()); + } + + void testResourceBind_Error() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithResourceBind(); + getMockServer()->expectResourceBind("", "session-bind"); + getMockServer()->sendError("session-bind"); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); + CPPUNIT_ASSERT_EQUAL(ClientSession::ResourceBindError, *session->getError()); + } + + void testSessionStart() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this)); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithSession(); + getMockServer()->expectSessionStart("session-start"); + // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::StartingSession, session->getState()); + getMockServer()->sendSessionStartResponse("session-start"); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); + CPPUNIT_ASSERT(sessionStarted_); + } + + void testSessionStart_Error() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithSession(); + getMockServer()->expectSessionStart("session-start"); + getMockServer()->sendError("session-start"); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState()); + CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStartError, *session->getError()); + } + + void testSessionStart_AfterResourceBind() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this)); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeaturesWithResourceBindAndSession(); + getMockServer()->expectResourceBind("Bar", "session-bind"); + getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind"); + getMockServer()->expectSessionStart("session-start"); + getMockServer()->sendSessionStartResponse("session-start"); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState()); + CPPUNIT_ASSERT(sessionStarted_); + } + + void testWhitespacePing() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeatures(); + session->startSession(); + processEvents(); + CPPUNIT_ASSERT(session->getWhitespacePingLayer()); + } + + void testReceiveElementAfterSessionStarted() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeatures(); + session->startSession(); + processEvents(); + + getMockServer()->expectMessage(); + session->sendElement(boost::make_shared<Message>())); + } + + void testSendElement() { + boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar")); + session->onElementReceived.connect(boost::bind(&ClientSessionTest::addReceivedElement, this, _1)); + getMockServer()->expectStreamStart(); + getMockServer()->sendStreamStart(); + getMockServer()->sendStreamFeatures(); + getMockServer()->sendMessage(); + session->startSession(); + processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedElements_.size())); + CPPUNIT_ASSERT(boost::dynamic_pointer_cast<Message>(receivedElements_[0])); + } #endif diff --git a/Swiften/Client/UnitTest/NickResolverTest.cpp b/Swiften/Client/UnitTest/NickResolverTest.cpp index c7d7a3a..855b15a 100644 --- a/Swiften/Client/UnitTest/NickResolverTest.cpp +++ b/Swiften/Client/UnitTest/NickResolverTest.cpp @@ -20,134 +20,134 @@ using namespace Swift; class NickResolverTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(NickResolverTest); - CPPUNIT_TEST(testNoMatch); - CPPUNIT_TEST(testZeroLengthMatch); - CPPUNIT_TEST(testMatch); - CPPUNIT_TEST(testOverwrittenMatch); - CPPUNIT_TEST(testRemovedMatch); - CPPUNIT_TEST(testMUCNick); - CPPUNIT_TEST(testMUCNoNick); - CPPUNIT_TEST(testRemovedMatch); - CPPUNIT_TEST(testOwnNickFullOnly); - CPPUNIT_TEST(testOwnNickGivenAndFull); - CPPUNIT_TEST(testOwnNickNickEtAl); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - ownJID_ = JID("kev@wonderland.lit"); - xmppRoster_ = new XMPPRosterImpl(); - stanzaChannel_ = new DummyStanzaChannel(); - iqRouter_ = new IQRouter(stanzaChannel_); - vCardStorage_ = new VCardMemoryStorage(crypto.get()); - vCardManager_ = new VCardManager(ownJID_, iqRouter_, vCardStorage_); - registry_ = new MUCRegistry(); - resolver_ = new NickResolver(ownJID_, xmppRoster_, vCardManager_, registry_); - } - - void tearDown() { - delete resolver_; - delete registry_; - delete vCardManager_; - delete iqRouter_; - delete stanzaChannel_; - delete vCardStorage_; - delete xmppRoster_; - } - - void testMUCNick() { - registry_->addMUC(JID("foo@bar")); - JID testJID("foo@bar/baz"); - - CPPUNIT_ASSERT_EQUAL(std::string("baz"), resolver_->jidToNick(testJID)); - } - - void testMUCNoNick() { - registry_->addMUC(JID("foo@bar")); - JID testJID("foo@bar"); - - CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); - } - - - void testNoMatch() { - JID testJID("foo@bar/baz"); - - CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); - } - - void testZeroLengthMatch() { - JID testJID("foo@bar/baz"); - xmppRoster_->addContact(testJID, "", groups_, RosterItemPayload::Both); - CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); - } - - void testMatch() { - JID testJID("foo@bar/baz"); - xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both); - - CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID)); - } - - void testOverwrittenMatch() { - JID testJID("foo@bar/baz"); - xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both); - xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both); - - CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID)); - } - - void testRemovedMatch() { - JID testJID("foo@bar/baz"); - xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both); - xmppRoster_->removeContact(testJID); - CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); - } - - void testOwnNickFullOnly() { - populateOwnVCard("", "", "Kevin Smith"); - CPPUNIT_ASSERT_EQUAL(std::string("Kevin Smith"), resolver_->jidToNick(ownJID_)); - } - - void testOwnNickGivenAndFull() { - populateOwnVCard("", "Kevin", "Kevin Smith"); - CPPUNIT_ASSERT_EQUAL(std::string("Kevin"), resolver_->jidToNick(ownJID_)); - } - - void testOwnNickNickEtAl() { - populateOwnVCard("Kev", "Kevin", "Kevin Smith"); - CPPUNIT_ASSERT_EQUAL(std::string("Kev"), resolver_->jidToNick(ownJID_)); - } - - void populateOwnVCard(const std::string& nick, const std::string& given, const std::string& full) { - VCard::ref vcard(new VCard()); - if (!nick.empty()) { - vcard->setNickname(nick); - } - if (!given.empty()) { - vcard->setGivenName(given); - } - if (!full.empty()) { - vcard->setFullName(full); - } - vCardManager_->requestVCard(ownJID_); - IQ::ref result(IQ::createResult(JID(), stanzaChannel_->sentStanzas[0]->getID(), vcard)); - stanzaChannel_->onIQReceived(result); - } - - private: - std::vector<std::string> groups_; - XMPPRosterImpl* xmppRoster_; - VCardStorage* vCardStorage_; - IQRouter* iqRouter_; - DummyStanzaChannel* stanzaChannel_; - VCardManager* vCardManager_; - MUCRegistry* registry_; - NickResolver* resolver_; - JID ownJID_; - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(NickResolverTest); + CPPUNIT_TEST(testNoMatch); + CPPUNIT_TEST(testZeroLengthMatch); + CPPUNIT_TEST(testMatch); + CPPUNIT_TEST(testOverwrittenMatch); + CPPUNIT_TEST(testRemovedMatch); + CPPUNIT_TEST(testMUCNick); + CPPUNIT_TEST(testMUCNoNick); + CPPUNIT_TEST(testRemovedMatch); + CPPUNIT_TEST(testOwnNickFullOnly); + CPPUNIT_TEST(testOwnNickGivenAndFull); + CPPUNIT_TEST(testOwnNickNickEtAl); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + ownJID_ = JID("kev@wonderland.lit"); + xmppRoster_ = new XMPPRosterImpl(); + stanzaChannel_ = new DummyStanzaChannel(); + iqRouter_ = new IQRouter(stanzaChannel_); + vCardStorage_ = new VCardMemoryStorage(crypto.get()); + vCardManager_ = new VCardManager(ownJID_, iqRouter_, vCardStorage_); + registry_ = new MUCRegistry(); + resolver_ = new NickResolver(ownJID_, xmppRoster_, vCardManager_, registry_); + } + + void tearDown() { + delete resolver_; + delete registry_; + delete vCardManager_; + delete iqRouter_; + delete stanzaChannel_; + delete vCardStorage_; + delete xmppRoster_; + } + + void testMUCNick() { + registry_->addMUC(JID("foo@bar")); + JID testJID("foo@bar/baz"); + + CPPUNIT_ASSERT_EQUAL(std::string("baz"), resolver_->jidToNick(testJID)); + } + + void testMUCNoNick() { + registry_->addMUC(JID("foo@bar")); + JID testJID("foo@bar"); + + CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); + } + + + void testNoMatch() { + JID testJID("foo@bar/baz"); + + CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); + } + + void testZeroLengthMatch() { + JID testJID("foo@bar/baz"); + xmppRoster_->addContact(testJID, "", groups_, RosterItemPayload::Both); + CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); + } + + void testMatch() { + JID testJID("foo@bar/baz"); + xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both); + + CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID)); + } + + void testOverwrittenMatch() { + JID testJID("foo@bar/baz"); + xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both); + xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both); + + CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID)); + } + + void testRemovedMatch() { + JID testJID("foo@bar/baz"); + xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both); + xmppRoster_->removeContact(testJID); + CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID)); + } + + void testOwnNickFullOnly() { + populateOwnVCard("", "", "Kevin Smith"); + CPPUNIT_ASSERT_EQUAL(std::string("Kevin Smith"), resolver_->jidToNick(ownJID_)); + } + + void testOwnNickGivenAndFull() { + populateOwnVCard("", "Kevin", "Kevin Smith"); + CPPUNIT_ASSERT_EQUAL(std::string("Kevin"), resolver_->jidToNick(ownJID_)); + } + + void testOwnNickNickEtAl() { + populateOwnVCard("Kev", "Kevin", "Kevin Smith"); + CPPUNIT_ASSERT_EQUAL(std::string("Kev"), resolver_->jidToNick(ownJID_)); + } + + void populateOwnVCard(const std::string& nick, const std::string& given, const std::string& full) { + VCard::ref vcard(new VCard()); + if (!nick.empty()) { + vcard->setNickname(nick); + } + if (!given.empty()) { + vcard->setGivenName(given); + } + if (!full.empty()) { + vcard->setFullName(full); + } + vCardManager_->requestVCard(ownJID_); + IQ::ref result(IQ::createResult(JID(), stanzaChannel_->sentStanzas[0]->getID(), vcard)); + stanzaChannel_->onIQReceived(result); + } + + private: + std::vector<std::string> groups_; + XMPPRosterImpl* xmppRoster_; + VCardStorage* vCardStorage_; + IQRouter* iqRouter_; + DummyStanzaChannel* stanzaChannel_; + VCardManager* vCardManager_; + MUCRegistry* registry_; + NickResolver* resolver_; + JID ownJID_; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(NickResolverTest); diff --git a/Swiften/Client/XMLBeautifier.cpp b/Swiften/Client/XMLBeautifier.cpp index 78a10ec..f084bb3 100644 --- a/Swiften/Client/XMLBeautifier.cpp +++ b/Swiften/Client/XMLBeautifier.cpp @@ -22,26 +22,26 @@ namespace Swift { XMLBeautifier::XMLBeautifier(bool indention, bool coloring) : doIndention(indention), doColoring(coloring), intLevel(0), parser(NULL), lastWasStepDown(false) { - factory = new PlatformXMLParserFactory(); + factory = new PlatformXMLParserFactory(); } XMLBeautifier::~XMLBeautifier() { - delete factory; + delete factory; } std::string XMLBeautifier::beautify(const std::string &text) { - parser = factory->createXMLParser(this); - intLevel = 0; - buffer.str(std::string()); - parser->parse(text); - delete parser; - return buffer.str(); + parser = factory->createXMLParser(this); + intLevel = 0; + buffer.str(std::string()); + parser->parse(text); + delete parser; + return buffer.str(); } void XMLBeautifier::indent() { - for (int i = 0; i < intLevel; ++i) { - buffer << " "; - } + for (int i = 0; i < intLevel; ++i) { + buffer << " "; + } } // all bold but reset @@ -56,78 +56,78 @@ static const char colorYellow[] = "\x1b[01;33m"; std::string XMLBeautifier::styleTag(const std::string& text) const { - std::string result; - result += colorYellow; - result += text; - result += colorReset; - return result; + std::string result; + result += colorYellow; + result += text; + result += colorReset; + return result; } std::string XMLBeautifier::styleNamespace(const std::string& text) const { - std::string result; - result += colorRed; - result += text; - result += colorReset; - return result; + std::string result; + result += colorRed; + result += text; + result += colorReset; + return result; } std::string XMLBeautifier::styleAttribute(const std::string& text) const { - std::string result; - result += colorGreen; - result += text; - result += colorReset; - return result; + std::string result; + result += colorGreen; + result += text; + result += colorReset; + return result; } std::string XMLBeautifier::styleValue(const std::string& text) const { - std::string result; - result += colorCyan; - result += text; - result += colorReset; - return result; + std::string result; + result += colorCyan; + result += text; + result += colorReset; + return result; } void XMLBeautifier::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) { - if (doIndention) { - if (intLevel) buffer << std::endl; - } - indent(); - buffer << "<" << (doColoring ? styleTag(element) : element); - if (!ns.empty() && (!parentNSs.empty() && parentNSs.top() != ns)) { - buffer << " "; - buffer << (doColoring ? styleAttribute("xmlns") : "xmlns"); - buffer << "="; - buffer << "\"" << (doColoring ? styleNamespace(ns) : ns) << "\""; - } - if (!attributes.getEntries().empty()) { - foreach(AttributeMap::Entry entry, attributes.getEntries()) { - buffer << " "; - buffer << (doColoring ? styleAttribute(entry.getAttribute().getName()) : entry.getAttribute().getName()); - buffer << "="; - buffer << "\"" << (doColoring ? styleValue(entry.getValue()) : entry.getValue()) << "\""; - } - } - buffer << ">"; - ++intLevel; - lastWasStepDown = false; - parentNSs.push(ns); + if (doIndention) { + if (intLevel) buffer << std::endl; + } + indent(); + buffer << "<" << (doColoring ? styleTag(element) : element); + if (!ns.empty() && (!parentNSs.empty() && parentNSs.top() != ns)) { + buffer << " "; + buffer << (doColoring ? styleAttribute("xmlns") : "xmlns"); + buffer << "="; + buffer << "\"" << (doColoring ? styleNamespace(ns) : ns) << "\""; + } + if (!attributes.getEntries().empty()) { + foreach(AttributeMap::Entry entry, attributes.getEntries()) { + buffer << " "; + buffer << (doColoring ? styleAttribute(entry.getAttribute().getName()) : entry.getAttribute().getName()); + buffer << "="; + buffer << "\"" << (doColoring ? styleValue(entry.getValue()) : entry.getValue()) << "\""; + } + } + buffer << ">"; + ++intLevel; + lastWasStepDown = false; + parentNSs.push(ns); } void XMLBeautifier::handleEndElement(const std::string& element, const std::string& /* ns */) { - --intLevel; - parentNSs.pop(); - if (/*hadCDATA.top() ||*/ lastWasStepDown) { - if (doIndention) { - buffer << std::endl; - } - indent(); - } - buffer << "</" << (doColoring ? styleTag(element) : element) << ">"; - lastWasStepDown = true; + --intLevel; + parentNSs.pop(); + if (/*hadCDATA.top() ||*/ lastWasStepDown) { + if (doIndention) { + buffer << std::endl; + } + indent(); + } + buffer << "</" << (doColoring ? styleTag(element) : element) << ">"; + lastWasStepDown = true; } void XMLBeautifier::handleCharacterData(const std::string& data) { - buffer << data; - lastWasStepDown = false; + buffer << data; + lastWasStepDown = false; } } diff --git a/Swiften/Client/XMLBeautifier.h b/Swiften/Client/XMLBeautifier.h index 233c68e..a765bc5 100644 --- a/Swiften/Client/XMLBeautifier.h +++ b/Swiften/Client/XMLBeautifier.h @@ -26,36 +26,36 @@ namespace Swift { class SWIFTEN_API XMLBeautifier : public XMLParserClient { public: - XMLBeautifier(bool indention, bool coloring); - virtual ~XMLBeautifier(); + XMLBeautifier(bool indention, bool coloring); + virtual ~XMLBeautifier(); - std::string beautify(const std::string&); + std::string beautify(const std::string&); private: - void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes); - void handleEndElement(const std::string& element, const std::string& ns); - void handleCharacterData(const std::string& data); + void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes); + void handleEndElement(const std::string& element, const std::string& ns); + void handleCharacterData(const std::string& data); private: - void indent(); + void indent(); private: - std::string styleTag(const std::string& text) const; - std::string styleNamespace(const std::string& text) const; - std::string styleAttribute(const std::string& text) const; - std::string styleValue(const std::string& text) const; + std::string styleTag(const std::string& text) const; + std::string styleNamespace(const std::string& text) const; + std::string styleAttribute(const std::string& text) const; + std::string styleValue(const std::string& text) const; private: - bool doIndention; - bool doColoring; + bool doIndention; + bool doColoring; - int intLevel; - std::string inputBuffer; - std::stringstream buffer; - XMLParserFactory* factory; - XMLParser* parser; + int intLevel; + std::string inputBuffer; + std::stringstream buffer; + XMLParserFactory* factory; + XMLParser* parser; - bool lastWasStepDown; - std::stack<std::string> parentNSs; + bool lastWasStepDown; + std::stack<std::string> parentNSs; }; } diff --git a/Swiften/Component/Component.cpp b/Swiften/Component/Component.cpp index 1340de2..e6835bd 100644 --- a/Swiften/Component/Component.cpp +++ b/Swiften/Component/Component.cpp @@ -11,17 +11,17 @@ namespace Swift { Component::Component(const JID& jid, const std::string& secret, NetworkFactories* networkFactories) : CoreComponent(jid, secret, networkFactories) { - softwareVersionResponder = new SoftwareVersionResponder(getIQRouter()); - softwareVersionResponder->start(); + softwareVersionResponder = new SoftwareVersionResponder(getIQRouter()); + softwareVersionResponder->start(); } Component::~Component() { - softwareVersionResponder->stop(); - delete softwareVersionResponder; + softwareVersionResponder->stop(); + delete softwareVersionResponder; } void Component::setSoftwareVersion(const std::string& name, const std::string& version) { - softwareVersionResponder->setVersion(name, version); + softwareVersionResponder->setVersion(name, version); } } diff --git a/Swiften/Component/Component.h b/Swiften/Component/Component.h index 63aa9f7..a7ef621 100644 --- a/Swiften/Component/Component.h +++ b/Swiften/Component/Component.h @@ -10,27 +10,27 @@ #include <Swiften/Component/CoreComponent.h> namespace Swift { - class SoftwareVersionResponder; + class SoftwareVersionResponder; - /** - * Provides the core functionality for writing XMPP component software. - * - * Besides connecting to an XMPP server, this class also provides interfaces for - * performing most component tasks on the XMPP network. - */ - class SWIFTEN_API Component : public CoreComponent { - public: - Component(const JID& jid, const std::string& secret, NetworkFactories* networkFactories); - virtual ~Component(); + /** + * Provides the core functionality for writing XMPP component software. + * + * Besides connecting to an XMPP server, this class also provides interfaces for + * performing most component tasks on the XMPP network. + */ + class SWIFTEN_API Component : public CoreComponent { + public: + Component(const JID& jid, const std::string& secret, NetworkFactories* networkFactories); + virtual ~Component(); - /** - * Sets the software version of the client. - * - * This will be used to respond to version queries from other entities. - */ - void setSoftwareVersion(const std::string& name, const std::string& version); + /** + * Sets the software version of the client. + * + * This will be used to respond to version queries from other entities. + */ + void setSoftwareVersion(const std::string& name, const std::string& version); - private: - SoftwareVersionResponder* softwareVersionResponder; - }; + private: + SoftwareVersionResponder* softwareVersionResponder; + }; } diff --git a/Swiften/Component/ComponentConnector.cpp b/Swiften/Component/ComponentConnector.cpp index 7a2121a..410c19e 100644 --- a/Swiften/Component/ComponentConnector.cpp +++ b/Swiften/Component/ComponentConnector.cpp @@ -21,88 +21,88 @@ ComponentConnector::ComponentConnector(const std::string& hostname, int port, Do } void ComponentConnector::setTimeoutMilliseconds(int milliseconds) { - timeoutMilliseconds = milliseconds; + timeoutMilliseconds = milliseconds; } void ComponentConnector::start() { - assert(!currentConnection); - assert(!timer); - assert(!addressQuery); - addressQuery = resolver->createAddressQuery(hostname); - addressQuery->onResult.connect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2)); - if (timeoutMilliseconds > 0) { - timer = timerFactory->createTimer(timeoutMilliseconds); - timer->onTick.connect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this())); - timer->start(); - } - addressQuery->run(); + assert(!currentConnection); + assert(!timer); + assert(!addressQuery); + addressQuery = resolver->createAddressQuery(hostname); + addressQuery->onResult.connect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2)); + if (timeoutMilliseconds > 0) { + timer = timerFactory->createTimer(timeoutMilliseconds); + timer->onTick.connect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this())); + timer->start(); + } + addressQuery->run(); } void ComponentConnector::stop() { - finish(boost::shared_ptr<Connection>()); + finish(boost::shared_ptr<Connection>()); } void ComponentConnector::handleAddressQueryResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error) { - addressQuery.reset(); - if (error || addresses.empty()) { - finish(boost::shared_ptr<Connection>()); - } - else { - addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end()); - tryNextAddress(); - } + addressQuery.reset(); + if (error || addresses.empty()) { + finish(boost::shared_ptr<Connection>()); + } + else { + addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end()); + tryNextAddress(); + } } void ComponentConnector::tryNextAddress() { - assert(!addressQueryResults.empty()); - HostAddress address = addressQueryResults.front(); - addressQueryResults.pop_front(); - tryConnect(HostAddressPort(address, port)); + assert(!addressQueryResults.empty()); + HostAddress address = addressQueryResults.front(); + addressQueryResults.pop_front(); + tryConnect(HostAddressPort(address, port)); } void ComponentConnector::tryConnect(const HostAddressPort& target) { - assert(!currentConnection); - currentConnection = connectionFactory->createConnection(); - currentConnection->onConnectFinished.connect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1)); - currentConnection->connect(target); + assert(!currentConnection); + currentConnection = connectionFactory->createConnection(); + currentConnection->onConnectFinished.connect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1)); + currentConnection->connect(target); } void ComponentConnector::handleConnectionConnectFinished(bool error) { - currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1)); - if (error) { - currentConnection.reset(); - if (!addressQueryResults.empty()) { - tryNextAddress(); - } - else { - finish(boost::shared_ptr<Connection>()); - } - } - else { - finish(currentConnection); - } + currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1)); + if (error) { + currentConnection.reset(); + if (!addressQueryResults.empty()) { + tryNextAddress(); + } + else { + finish(boost::shared_ptr<Connection>()); + } + } + else { + finish(currentConnection); + } } void ComponentConnector::finish(boost::shared_ptr<Connection> connection) { - if (timer) { - timer->stop(); - timer->onTick.disconnect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this())); - timer.reset(); - } - if (addressQuery) { - addressQuery->onResult.disconnect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2)); - addressQuery.reset(); - } - if (currentConnection) { - currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1)); - currentConnection.reset(); - } - onConnectFinished(connection); + if (timer) { + timer->stop(); + timer->onTick.disconnect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this())); + timer.reset(); + } + if (addressQuery) { + addressQuery->onResult.disconnect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2)); + addressQuery.reset(); + } + if (currentConnection) { + currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1)); + currentConnection.reset(); + } + onConnectFinished(connection); } void ComponentConnector::handleTimeout() { - finish(boost::shared_ptr<Connection>()); + finish(boost::shared_ptr<Connection>()); } } diff --git a/Swiften/Component/ComponentConnector.h b/Swiften/Component/ComponentConnector.h index 008236b..68cb0d7 100644 --- a/Swiften/Component/ComponentConnector.h +++ b/Swiften/Component/ComponentConnector.h @@ -19,48 +19,48 @@ #include <Swiften/Network/Timer.h> namespace Swift { - class DomainNameAddressQuery; - class DomainNameResolver; - class ConnectionFactory; - class TimerFactory; + class DomainNameAddressQuery; + class DomainNameResolver; + class ConnectionFactory; + class TimerFactory; - class SWIFTEN_API ComponentConnector : public boost::bsignals::trackable, public boost::enable_shared_from_this<ComponentConnector> { - public: - typedef boost::shared_ptr<ComponentConnector> ref; + class SWIFTEN_API ComponentConnector : public boost::bsignals::trackable, public boost::enable_shared_from_this<ComponentConnector> { + public: + typedef boost::shared_ptr<ComponentConnector> ref; - static ComponentConnector::ref create(const std::string& hostname, int port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { - return ref(new ComponentConnector(hostname, port, resolver, connectionFactory, timerFactory)); - } + static ComponentConnector::ref create(const std::string& hostname, int port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { + return ref(new ComponentConnector(hostname, port, resolver, connectionFactory, timerFactory)); + } - void setTimeoutMilliseconds(int milliseconds); + void setTimeoutMilliseconds(int milliseconds); - void start(); - void stop(); + void start(); + void stop(); - boost::signal<void (boost::shared_ptr<Connection>)> onConnectFinished; + boost::signal<void (boost::shared_ptr<Connection>)> onConnectFinished; - private: - ComponentConnector(const std::string& hostname, int port, DomainNameResolver*, ConnectionFactory*, TimerFactory*); + private: + ComponentConnector(const std::string& hostname, int port, DomainNameResolver*, ConnectionFactory*, TimerFactory*); - void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error); - void tryNextAddress(); - void tryConnect(const HostAddressPort& target); + void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error); + void tryNextAddress(); + void tryConnect(const HostAddressPort& target); - void handleConnectionConnectFinished(bool error); - void finish(boost::shared_ptr<Connection>); - void handleTimeout(); + void handleConnectionConnectFinished(bool error); + void finish(boost::shared_ptr<Connection>); + void handleTimeout(); - private: - std::string hostname; - int port; - DomainNameResolver* resolver; - ConnectionFactory* connectionFactory; - TimerFactory* timerFactory; - int timeoutMilliseconds; - boost::shared_ptr<Timer> timer; - boost::shared_ptr<DomainNameAddressQuery> addressQuery; - std::deque<HostAddress> addressQueryResults; - boost::shared_ptr<Connection> currentConnection; - }; + private: + std::string hostname; + int port; + DomainNameResolver* resolver; + ConnectionFactory* connectionFactory; + TimerFactory* timerFactory; + int timeoutMilliseconds; + boost::shared_ptr<Timer> timer; + boost::shared_ptr<DomainNameAddressQuery> addressQuery; + std::deque<HostAddress> addressQueryResults; + boost::shared_ptr<Connection> currentConnection; + }; } diff --git a/Swiften/Component/ComponentError.h b/Swiften/Component/ComponentError.h index 7609b9a..dca8c99 100644 --- a/Swiften/Component/ComponentError.h +++ b/Swiften/Component/ComponentError.h @@ -9,23 +9,23 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API ComponentError { - public: - enum Type { - UnknownError, - ConnectionError, - ConnectionReadError, - ConnectionWriteError, - XMLError, - AuthenticationFailedError, - UnexpectedElementError - }; + class SWIFTEN_API ComponentError { + public: + enum Type { + UnknownError, + ConnectionError, + ConnectionReadError, + ConnectionWriteError, + XMLError, + AuthenticationFailedError, + UnexpectedElementError + }; - ComponentError(Type type = UnknownError) : type_(type) {} + ComponentError(Type type = UnknownError) : type_(type) {} - Type getType() const { return type_; } + Type getType() const { return type_; } - private: - Type type_; - }; + private: + Type type_; + }; } diff --git a/Swiften/Component/ComponentHandshakeGenerator.cpp b/Swiften/Component/ComponentHandshakeGenerator.cpp index a0eacab..647b3da 100644 --- a/Swiften/Component/ComponentHandshakeGenerator.cpp +++ b/Swiften/Component/ComponentHandshakeGenerator.cpp @@ -13,13 +13,13 @@ namespace Swift { std::string ComponentHandshakeGenerator::getHandshake(const std::string& streamID, const std::string& secret, CryptoProvider* crypto) { - std::string concatenatedString = streamID + secret; - String::replaceAll(concatenatedString, '&', "&"); - String::replaceAll(concatenatedString, '<', "<"); - String::replaceAll(concatenatedString, '>', ">"); - String::replaceAll(concatenatedString, '\'', "'"); - String::replaceAll(concatenatedString, '"', """); - return Hexify::hexify(crypto->getSHA1Hash(createByteArray(concatenatedString))); + std::string concatenatedString = streamID + secret; + String::replaceAll(concatenatedString, '&', "&"); + String::replaceAll(concatenatedString, '<', "<"); + String::replaceAll(concatenatedString, '>', ">"); + String::replaceAll(concatenatedString, '\'', "'"); + String::replaceAll(concatenatedString, '"', """); + return Hexify::hexify(crypto->getSHA1Hash(createByteArray(concatenatedString))); } } diff --git a/Swiften/Component/ComponentHandshakeGenerator.h b/Swiften/Component/ComponentHandshakeGenerator.h index 7d9f60c..0aafb83 100644 --- a/Swiften/Component/ComponentHandshakeGenerator.h +++ b/Swiften/Component/ComponentHandshakeGenerator.h @@ -11,11 +11,11 @@ #include <Swiften/Base/API.h> namespace Swift { - class CryptoProvider; + class CryptoProvider; - class SWIFTEN_API ComponentHandshakeGenerator { - public: - static std::string getHandshake(const std::string& streamID, const std::string& secret, CryptoProvider* crypto); - }; + class SWIFTEN_API ComponentHandshakeGenerator { + public: + static std::string getHandshake(const std::string& streamID, const std::string& secret, CryptoProvider* crypto); + }; } diff --git a/Swiften/Component/ComponentSession.cpp b/Swiften/Component/ComponentSession.cpp index 79660de..46c88db 100644 --- a/Swiften/Component/ComponentSession.cpp +++ b/Swiften/Component/ComponentSession.cpp @@ -24,99 +24,99 @@ ComponentSession::~ComponentSession() { } void ComponentSession::start() { - stream->onStreamStartReceived.connect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1)); - stream->onElementReceived.connect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1)); - stream->onClosed.connect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1)); + stream->onStreamStartReceived.connect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1)); + stream->onElementReceived.connect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1)); + stream->onClosed.connect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1)); - assert(state == Initial); - state = WaitingForStreamStart; - sendStreamHeader(); + assert(state == Initial); + state = WaitingForStreamStart; + sendStreamHeader(); } void ComponentSession::sendStreamHeader() { - ProtocolHeader header; - header.setTo(jid); - stream->writeHeader(header); + ProtocolHeader header; + header.setTo(jid); + stream->writeHeader(header); } void ComponentSession::sendStanza(boost::shared_ptr<Stanza> stanza) { - stream->writeElement(stanza); + stream->writeElement(stanza); } void ComponentSession::handleStreamStart(const ProtocolHeader& header) { - checkState(WaitingForStreamStart); - state = Authenticating; - stream->writeElement(ComponentHandshake::ref(new ComponentHandshake(ComponentHandshakeGenerator::getHandshake(header.getID(), secret, crypto)))); + checkState(WaitingForStreamStart); + state = Authenticating; + stream->writeElement(ComponentHandshake::ref(new ComponentHandshake(ComponentHandshakeGenerator::getHandshake(header.getID(), secret, crypto)))); } void ComponentSession::handleElement(boost::shared_ptr<ToplevelElement> element) { - if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) { - if (getState() == Initialized) { - onStanzaReceived(stanza); - } - else { - finishSession(Error::UnexpectedElementError); - } - } - else if (boost::dynamic_pointer_cast<ComponentHandshake>(element)) { - if (!checkState(Authenticating)) { - return; - } - stream->setWhitespacePingEnabled(true); - state = Initialized; - onInitialized(); - } - else if (getState() == Authenticating) { - if (boost::dynamic_pointer_cast<StreamFeatures>(element)) { - // M-Link sends stream features, so swallow that. - } - else { - // FIXME: We should actually check the element received - finishSession(Error::AuthenticationFailedError); - } - } - else { - finishSession(Error::UnexpectedElementError); - } + if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) { + if (getState() == Initialized) { + onStanzaReceived(stanza); + } + else { + finishSession(Error::UnexpectedElementError); + } + } + else if (boost::dynamic_pointer_cast<ComponentHandshake>(element)) { + if (!checkState(Authenticating)) { + return; + } + stream->setWhitespacePingEnabled(true); + state = Initialized; + onInitialized(); + } + else if (getState() == Authenticating) { + if (boost::dynamic_pointer_cast<StreamFeatures>(element)) { + // M-Link sends stream features, so swallow that. + } + else { + // FIXME: We should actually check the element received + finishSession(Error::AuthenticationFailedError); + } + } + else { + finishSession(Error::UnexpectedElementError); + } } bool ComponentSession::checkState(State state) { - if (this->state != state) { - finishSession(Error::UnexpectedElementError); - return false; - } - return true; + if (this->state != state) { + finishSession(Error::UnexpectedElementError); + return false; + } + return true; } void ComponentSession::handleStreamClosed(boost::shared_ptr<Swift::Error> streamError) { - State oldState = state; - state = Finished; - stream->setWhitespacePingEnabled(false); - stream->onStreamStartReceived.disconnect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1)); - stream->onElementReceived.disconnect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1)); - stream->onClosed.disconnect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1)); - if (oldState == Finishing) { - onFinished(error); - } - else { - onFinished(streamError); - } + State oldState = state; + state = Finished; + stream->setWhitespacePingEnabled(false); + stream->onStreamStartReceived.disconnect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1)); + stream->onElementReceived.disconnect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1)); + stream->onClosed.disconnect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1)); + if (oldState == Finishing) { + onFinished(error); + } + else { + onFinished(streamError); + } } void ComponentSession::finish() { - finishSession(boost::shared_ptr<Error>()); + finishSession(boost::shared_ptr<Error>()); } void ComponentSession::finishSession(Error::Type error) { - finishSession(boost::make_shared<Swift::ComponentSession::Error>(error)); + finishSession(boost::make_shared<Swift::ComponentSession::Error>(error)); } void ComponentSession::finishSession(boost::shared_ptr<Swift::Error> finishError) { - state = Finishing; - error = finishError; - assert(stream->isOpen()); - stream->writeFooter(); - stream->close(); + state = Finishing; + error = finishError; + assert(stream->isOpen()); + stream->writeFooter(); + stream->close(); } } diff --git a/Swiften/Component/ComponentSession.h b/Swiften/Component/ComponentSession.h index 3a750cc..608bb79 100644 --- a/Swiften/Component/ComponentSession.h +++ b/Swiften/Component/ComponentSession.h @@ -20,68 +20,68 @@ #include <Swiften/Session/SessionStream.h> namespace Swift { - class ComponentAuthenticator; - class CryptoProvider; - - class SWIFTEN_API ComponentSession : public boost::enable_shared_from_this<ComponentSession> { - public: - enum State { - Initial, - WaitingForStreamStart, - Authenticating, - Initialized, - Finishing, - Finished - }; - - struct Error : public Swift::Error { - enum Type { - AuthenticationFailedError, - UnexpectedElementError - } type; - Error(Type type) : type(type) {} - }; - - ~ComponentSession(); - - static boost::shared_ptr<ComponentSession> create(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream> stream, CryptoProvider* crypto) { - return boost::shared_ptr<ComponentSession>(new ComponentSession(jid, secret, stream, crypto)); - } - - State getState() const { - return state; - } - - void start(); - void finish(); - - void sendStanza(boost::shared_ptr<Stanza>); - - public: - boost::signal<void ()> onInitialized; - boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished; - boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived; - - private: - ComponentSession(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream>, CryptoProvider*); - - void finishSession(Error::Type error); - void finishSession(boost::shared_ptr<Swift::Error> error); - - void sendStreamHeader(); - - void handleElement(boost::shared_ptr<ToplevelElement>); - void handleStreamStart(const ProtocolHeader&); - void handleStreamClosed(boost::shared_ptr<Swift::Error>); - - bool checkState(State); - - private: - JID jid; - std::string secret; - boost::shared_ptr<SessionStream> stream; - CryptoProvider* crypto; - boost::shared_ptr<Swift::Error> error; - State state; - }; + class ComponentAuthenticator; + class CryptoProvider; + + class SWIFTEN_API ComponentSession : public boost::enable_shared_from_this<ComponentSession> { + public: + enum State { + Initial, + WaitingForStreamStart, + Authenticating, + Initialized, + Finishing, + Finished + }; + + struct Error : public Swift::Error { + enum Type { + AuthenticationFailedError, + UnexpectedElementError + } type; + Error(Type type) : type(type) {} + }; + + ~ComponentSession(); + + static boost::shared_ptr<ComponentSession> create(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream> stream, CryptoProvider* crypto) { + return boost::shared_ptr<ComponentSession>(new ComponentSession(jid, secret, stream, crypto)); + } + + State getState() const { + return state; + } + + void start(); + void finish(); + + void sendStanza(boost::shared_ptr<Stanza>); + + public: + boost::signal<void ()> onInitialized; + boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished; + boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived; + + private: + ComponentSession(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream>, CryptoProvider*); + + void finishSession(Error::Type error); + void finishSession(boost::shared_ptr<Swift::Error> error); + + void sendStreamHeader(); + + void handleElement(boost::shared_ptr<ToplevelElement>); + void handleStreamStart(const ProtocolHeader&); + void handleStreamClosed(boost::shared_ptr<Swift::Error>); + + bool checkState(State); + + private: + JID jid; + std::string secret; + boost::shared_ptr<SessionStream> stream; + CryptoProvider* crypto; + boost::shared_ptr<Swift::Error> error; + State state; + }; } diff --git a/Swiften/Component/ComponentSessionStanzaChannel.cpp b/Swiften/Component/ComponentSessionStanzaChannel.cpp index 7ff374f..ffb1f13 100644 --- a/Swiften/Component/ComponentSessionStanzaChannel.cpp +++ b/Swiften/Component/ComponentSessionStanzaChannel.cpp @@ -13,68 +13,68 @@ namespace Swift { void ComponentSessionStanzaChannel::setSession(boost::shared_ptr<ComponentSession> session) { - assert(!this->session); - this->session = session; - session->onInitialized.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this)); - session->onFinished.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1)); - session->onStanzaReceived.connect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1)); + assert(!this->session); + this->session = session; + session->onInitialized.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this)); + session->onFinished.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1)); + session->onStanzaReceived.connect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1)); } void ComponentSessionStanzaChannel::sendIQ(boost::shared_ptr<IQ> iq) { - send(iq); + send(iq); } void ComponentSessionStanzaChannel::sendMessage(boost::shared_ptr<Message> message) { - send(message); + send(message); } void ComponentSessionStanzaChannel::sendPresence(boost::shared_ptr<Presence> presence) { - send(presence); + send(presence); } std::string ComponentSessionStanzaChannel::getNewIQID() { - return idGenerator.generateID(); + return idGenerator.generateID(); } void ComponentSessionStanzaChannel::send(boost::shared_ptr<Stanza> stanza) { - if (!isAvailable()) { - std::cerr << "Warning: Component: Trying to send a stanza while disconnected." << std::endl; - return; - } - session->sendStanza(stanza); + if (!isAvailable()) { + std::cerr << "Warning: Component: Trying to send a stanza while disconnected." << std::endl; + return; + } + session->sendStanza(stanza); } void ComponentSessionStanzaChannel::handleSessionFinished(boost::shared_ptr<Error>) { - session->onFinished.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1)); - session->onStanzaReceived.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1)); - session->onInitialized.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this)); - session.reset(); + session->onFinished.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1)); + session->onStanzaReceived.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1)); + session->onInitialized.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this)); + session.reset(); - onAvailableChanged(false); + onAvailableChanged(false); } void ComponentSessionStanzaChannel::handleStanza(boost::shared_ptr<Stanza> stanza) { - boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza); - if (message) { - onMessageReceived(message); - return; - } - - boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza); - if (presence) { - onPresenceReceived(presence); - return; - } - - boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza); - if (iq) { - onIQReceived(iq); - return; - } + boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza); + if (message) { + onMessageReceived(message); + return; + } + + boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza); + if (presence) { + onPresenceReceived(presence); + return; + } + + boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza); + if (iq) { + onIQReceived(iq); + return; + } } void ComponentSessionStanzaChannel::handleSessionInitialized() { - onAvailableChanged(true); + onAvailableChanged(true); } } diff --git a/Swiften/Component/ComponentSessionStanzaChannel.h b/Swiften/Component/ComponentSessionStanzaChannel.h index a507904..31931ea 100644 --- a/Swiften/Component/ComponentSessionStanzaChannel.h +++ b/Swiften/Component/ComponentSessionStanzaChannel.h @@ -17,40 +17,40 @@ #include <Swiften/Elements/Presence.h> namespace Swift { - /** - * StanzaChannel implementation around a ComponentSession. - */ - class SWIFTEN_API ComponentSessionStanzaChannel : public StanzaChannel { - public: - void setSession(boost::shared_ptr<ComponentSession> session); - - void sendIQ(boost::shared_ptr<IQ> iq); - void sendMessage(boost::shared_ptr<Message> message); - void sendPresence(boost::shared_ptr<Presence> presence); - - bool getStreamManagementEnabled() const { - return false; - } - - std::vector<Certificate::ref> getPeerCertificateChain() const { - // TODO: actually implement this method - return std::vector<Certificate::ref>(); - } - - bool isAvailable() const { - return session && session->getState() == ComponentSession::Initialized; - } - - private: - std::string getNewIQID(); - void send(boost::shared_ptr<Stanza> stanza); - void handleSessionFinished(boost::shared_ptr<Error> error); - void handleStanza(boost::shared_ptr<Stanza> stanza); - void handleSessionInitialized(); - - private: - IDGenerator idGenerator; - boost::shared_ptr<ComponentSession> session; - }; + /** + * StanzaChannel implementation around a ComponentSession. + */ + class SWIFTEN_API ComponentSessionStanzaChannel : public StanzaChannel { + public: + void setSession(boost::shared_ptr<ComponentSession> session); + + void sendIQ(boost::shared_ptr<IQ> iq); + void sendMessage(boost::shared_ptr<Message> message); + void sendPresence(boost::shared_ptr<Presence> presence); + + bool getStreamManagementEnabled() const { + return false; + } + + std::vector<Certificate::ref> getPeerCertificateChain() const { + // TODO: actually implement this method + return std::vector<Certificate::ref>(); + } + + bool isAvailable() const { + return session && session->getState() == ComponentSession::Initialized; + } + + private: + std::string getNewIQID(); + void send(boost::shared_ptr<Stanza> stanza); + void handleSessionFinished(boost::shared_ptr<Error> error); + void handleStanza(boost::shared_ptr<Stanza> stanza); + void handleSessionInitialized(); + + private: + IDGenerator idGenerator; + boost::shared_ptr<ComponentSession> session; + }; } diff --git a/Swiften/Component/ComponentXMLTracer.cpp b/Swiften/Component/ComponentXMLTracer.cpp index 49d948b..94d4ec2 100644 --- a/Swiften/Component/ComponentXMLTracer.cpp +++ b/Swiften/Component/ComponentXMLTracer.cpp @@ -13,20 +13,20 @@ namespace Swift { ComponentXMLTracer::ComponentXMLTracer(CoreComponent* client) { - client->onDataRead.connect(boost::bind(&ComponentXMLTracer::printData, '<', _1)); - client->onDataWritten.connect(boost::bind(&ComponentXMLTracer::printData, '>', _1)); + client->onDataRead.connect(boost::bind(&ComponentXMLTracer::printData, '<', _1)); + client->onDataWritten.connect(boost::bind(&ComponentXMLTracer::printData, '>', _1)); } void ComponentXMLTracer::printData(char direction, const SafeByteArray& data) { - printLine(direction); - std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl; + printLine(direction); + std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl; } void ComponentXMLTracer::printLine(char c) { - for (unsigned int i = 0; i < 80; ++i) { - std::cerr << c; - } - std::cerr << std::endl; + for (unsigned int i = 0; i < 80; ++i) { + std::cerr << c; + } + std::cerr << std::endl; } } diff --git a/Swiften/Component/ComponentXMLTracer.h b/Swiften/Component/ComponentXMLTracer.h index 2c07305..d34930b 100644 --- a/Swiften/Component/ComponentXMLTracer.h +++ b/Swiften/Component/ComponentXMLTracer.h @@ -10,12 +10,12 @@ #include <Swiften/Component/Component.h> namespace Swift { - class SWIFTEN_API ComponentXMLTracer { - public: - ComponentXMLTracer(CoreComponent* component); + class SWIFTEN_API ComponentXMLTracer { + public: + ComponentXMLTracer(CoreComponent* component); - private: - static void printData(char direction, const SafeByteArray& data); - static void printLine(char c); - }; + private: + static void printData(char direction, const SafeByteArray& data); + static void printLine(char c); + }; } diff --git a/Swiften/Component/CoreComponent.cpp b/Swiften/Component/CoreComponent.cpp index fbf59f3..0b8e01c 100644 --- a/Swiften/Component/CoreComponent.cpp +++ b/Swiften/Component/CoreComponent.cpp @@ -23,148 +23,148 @@ namespace Swift { CoreComponent::CoreComponent(const JID& jid, const std::string& secret, NetworkFactories* networkFactories) : networkFactories(networkFactories), jid_(jid), secret_(secret), disconnectRequested_(false) { - stanzaChannel_ = new ComponentSessionStanzaChannel(); - stanzaChannel_->onMessageReceived.connect(boost::ref(onMessageReceived)); - stanzaChannel_->onPresenceReceived.connect(boost::ref(onPresenceReceived)); - stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1)); + stanzaChannel_ = new ComponentSessionStanzaChannel(); + stanzaChannel_->onMessageReceived.connect(boost::ref(onMessageReceived)); + stanzaChannel_->onPresenceReceived.connect(boost::ref(onPresenceReceived)); + stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1)); - iqRouter_ = new IQRouter(stanzaChannel_); - iqRouter_->setFrom(jid); + iqRouter_ = new IQRouter(stanzaChannel_); + iqRouter_->setFrom(jid); } CoreComponent::~CoreComponent() { - if (session_ || connection_) { - std::cerr << "Warning: Component not disconnected properly" << std::endl; - } - delete iqRouter_; - - stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1)); - stanzaChannel_->onMessageReceived.disconnect(boost::ref(onMessageReceived)); - stanzaChannel_->onPresenceReceived.disconnect(boost::ref(onPresenceReceived)); - delete stanzaChannel_; + if (session_ || connection_) { + std::cerr << "Warning: Component not disconnected properly" << std::endl; + } + delete iqRouter_; + + stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1)); + stanzaChannel_->onMessageReceived.disconnect(boost::ref(onMessageReceived)); + stanzaChannel_->onPresenceReceived.disconnect(boost::ref(onPresenceReceived)); + delete stanzaChannel_; } void CoreComponent::connect(const std::string& host, int port) { - assert(!connector_); - connector_ = ComponentConnector::create(host, port, networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory()); - connector_->onConnectFinished.connect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1)); - connector_->setTimeoutMilliseconds(60*1000); - connector_->start(); + assert(!connector_); + connector_ = ComponentConnector::create(host, port, networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory()); + connector_->onConnectFinished.connect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1)); + connector_->setTimeoutMilliseconds(60*1000); + connector_->start(); } void CoreComponent::handleConnectorFinished(boost::shared_ptr<Connection> connection) { - connector_->onConnectFinished.disconnect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1)); - connector_.reset(); - if (!connection) { - if (!disconnectRequested_) { - onError(ComponentError::ConnectionError); - } - } - else { - assert(!connection_); - connection_ = connection; - - assert(!sessionStream_); - sessionStream_ = boost::shared_ptr<BasicSessionStream>(new BasicSessionStream(ComponentStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), NULL, networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), TLSOptions())); - sessionStream_->onDataRead.connect(boost::bind(&CoreComponent::handleDataRead, this, _1)); - sessionStream_->onDataWritten.connect(boost::bind(&CoreComponent::handleDataWritten, this, _1)); - - session_ = ComponentSession::create(jid_, secret_, sessionStream_, networkFactories->getCryptoProvider()); - stanzaChannel_->setSession(session_); - session_->onFinished.connect(boost::bind(&CoreComponent::handleSessionFinished, this, _1)); - session_->start(); - } + connector_->onConnectFinished.disconnect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1)); + connector_.reset(); + if (!connection) { + if (!disconnectRequested_) { + onError(ComponentError::ConnectionError); + } + } + else { + assert(!connection_); + connection_ = connection; + + assert(!sessionStream_); + sessionStream_ = boost::shared_ptr<BasicSessionStream>(new BasicSessionStream(ComponentStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), NULL, networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), TLSOptions())); + sessionStream_->onDataRead.connect(boost::bind(&CoreComponent::handleDataRead, this, _1)); + sessionStream_->onDataWritten.connect(boost::bind(&CoreComponent::handleDataWritten, this, _1)); + + session_ = ComponentSession::create(jid_, secret_, sessionStream_, networkFactories->getCryptoProvider()); + stanzaChannel_->setSession(session_); + session_->onFinished.connect(boost::bind(&CoreComponent::handleSessionFinished, this, _1)); + session_->start(); + } } void CoreComponent::disconnect() { - // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between - // connector finishing without a connection due to an error or because of a disconnect. - disconnectRequested_ = true; - if (session_) { - session_->finish(); - } - else if (connector_) { - connector_->stop(); - assert(!session_); - } - //assert(!session_); /* commenting out until we have time to refactor to be like CoreClient */ - //assert(!sessionStream_); - //assert(!connector_); - disconnectRequested_ = false; + // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between + // connector finishing without a connection due to an error or because of a disconnect. + disconnectRequested_ = true; + if (session_) { + session_->finish(); + } + else if (connector_) { + connector_->stop(); + assert(!session_); + } + //assert(!session_); /* commenting out until we have time to refactor to be like CoreClient */ + //assert(!sessionStream_); + //assert(!connector_); + disconnectRequested_ = false; } void CoreComponent::handleSessionFinished(boost::shared_ptr<Error> error) { - session_->onFinished.disconnect(boost::bind(&CoreComponent::handleSessionFinished, this, _1)); - session_.reset(); - - sessionStream_->onDataRead.disconnect(boost::bind(&CoreComponent::handleDataRead, this, _1)); - sessionStream_->onDataWritten.disconnect(boost::bind(&CoreComponent::handleDataWritten, this, _1)); - sessionStream_.reset(); - - connection_->disconnect(); - connection_.reset(); - - if (error) { - ComponentError componentError; - if (boost::shared_ptr<ComponentSession::Error> actualError = boost::dynamic_pointer_cast<ComponentSession::Error>(error)) { - switch(actualError->type) { - case ComponentSession::Error::AuthenticationFailedError: - componentError = ComponentError(ComponentError::AuthenticationFailedError); - break; - case ComponentSession::Error::UnexpectedElementError: - componentError = ComponentError(ComponentError::UnexpectedElementError); - break; - } - } - else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) { - switch(actualError->type) { - case SessionStream::SessionStreamError::ParseError: - componentError = ComponentError(ComponentError::XMLError); - break; - case SessionStream::SessionStreamError::TLSError: - assert(false); - componentError = ComponentError(ComponentError::UnknownError); - break; - case SessionStream::SessionStreamError::InvalidTLSCertificateError: - assert(false); - componentError = ComponentError(ComponentError::UnknownError); - break; - case SessionStream::SessionStreamError::ConnectionReadError: - componentError = ComponentError(ComponentError::ConnectionReadError); - break; - case SessionStream::SessionStreamError::ConnectionWriteError: - componentError = ComponentError(ComponentError::ConnectionWriteError); - break; - } - } - onError(componentError); - } + session_->onFinished.disconnect(boost::bind(&CoreComponent::handleSessionFinished, this, _1)); + session_.reset(); + + sessionStream_->onDataRead.disconnect(boost::bind(&CoreComponent::handleDataRead, this, _1)); + sessionStream_->onDataWritten.disconnect(boost::bind(&CoreComponent::handleDataWritten, this, _1)); + sessionStream_.reset(); + + connection_->disconnect(); + connection_.reset(); + + if (error) { + ComponentError componentError; + if (boost::shared_ptr<ComponentSession::Error> actualError = boost::dynamic_pointer_cast<ComponentSession::Error>(error)) { + switch(actualError->type) { + case ComponentSession::Error::AuthenticationFailedError: + componentError = ComponentError(ComponentError::AuthenticationFailedError); + break; + case ComponentSession::Error::UnexpectedElementError: + componentError = ComponentError(ComponentError::UnexpectedElementError); + break; + } + } + else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) { + switch(actualError->type) { + case SessionStream::SessionStreamError::ParseError: + componentError = ComponentError(ComponentError::XMLError); + break; + case SessionStream::SessionStreamError::TLSError: + assert(false); + componentError = ComponentError(ComponentError::UnknownError); + break; + case SessionStream::SessionStreamError::InvalidTLSCertificateError: + assert(false); + componentError = ComponentError(ComponentError::UnknownError); + break; + case SessionStream::SessionStreamError::ConnectionReadError: + componentError = ComponentError(ComponentError::ConnectionReadError); + break; + case SessionStream::SessionStreamError::ConnectionWriteError: + componentError = ComponentError(ComponentError::ConnectionWriteError); + break; + } + } + onError(componentError); + } } void CoreComponent::handleDataRead(const SafeByteArray& data) { - onDataRead(data); + onDataRead(data); } void CoreComponent::handleDataWritten(const SafeByteArray& data) { - onDataWritten(data); + onDataWritten(data); } void CoreComponent::handleStanzaChannelAvailableChanged(bool available) { - if (available) { - onConnected(); - } + if (available) { + onConnected(); + } } void CoreComponent::sendMessage(boost::shared_ptr<Message> message) { - stanzaChannel_->sendMessage(message); + stanzaChannel_->sendMessage(message); } void CoreComponent::sendPresence(boost::shared_ptr<Presence> presence) { - stanzaChannel_->sendPresence(presence); + stanzaChannel_->sendPresence(presence); } void CoreComponent::sendData(const std::string& data) { - sessionStream_->writeData(data); + sessionStream_->writeData(data); } } diff --git a/Swiften/Component/CoreComponent.h b/Swiften/Component/CoreComponent.h index 12b38eb..ff88173 100644 --- a/Swiften/Component/CoreComponent.h +++ b/Swiften/Component/CoreComponent.h @@ -26,79 +26,79 @@ #include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h> namespace Swift { - class EventLoop; - class IQRouter; - class NetworkFactories; - class ComponentSession; - class BasicSessionStream; - - /** - * The central class for communicating with an XMPP server as a component. - * - * This class is responsible for setting up the connection with the XMPP - * server and authenticating the component. - * - * This class can be used directly in your application, although the Component - * subclass provides more functionality and interfaces, and is better suited - * for most needs. - */ - class SWIFTEN_API CoreComponent : public Entity { - public: - CoreComponent(const JID& jid, const std::string& secret, NetworkFactories* networkFactories); - virtual ~CoreComponent(); - - void connect(const std::string& host, int port); - void disconnect(); - - void sendMessage(boost::shared_ptr<Message>); - void sendPresence(boost::shared_ptr<Presence>); - void sendData(const std::string& data); - - IQRouter* getIQRouter() const { - return iqRouter_; - } - - StanzaChannel* getStanzaChannel() const { - return stanzaChannel_; - } - - bool isAvailable() const { - return stanzaChannel_->isAvailable(); - } - - /** - * Returns the JID of the component - */ - const JID& getJID() const { - return jid_; - } - - public: - boost::signal<void (const ComponentError&)> onError; - boost::signal<void ()> onConnected; - boost::signal<void (const SafeByteArray&)> onDataRead; - boost::signal<void (const SafeByteArray&)> onDataWritten; - - boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived; - boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived; - - private: - void handleConnectorFinished(boost::shared_ptr<Connection>); - void handleStanzaChannelAvailableChanged(bool available); - void handleSessionFinished(boost::shared_ptr<Error>); - void handleDataRead(const SafeByteArray&); - void handleDataWritten(const SafeByteArray&); - - private: - NetworkFactories* networkFactories; - JID jid_; - std::string secret_; - ComponentSessionStanzaChannel* stanzaChannel_; - IQRouter* iqRouter_; - ComponentConnector::ref connector_; - boost::shared_ptr<Connection> connection_; - boost::shared_ptr<BasicSessionStream> sessionStream_; - boost::shared_ptr<ComponentSession> session_; - bool disconnectRequested_; - }; + class EventLoop; + class IQRouter; + class NetworkFactories; + class ComponentSession; + class BasicSessionStream; + + /** + * The central class for communicating with an XMPP server as a component. + * + * This class is responsible for setting up the connection with the XMPP + * server and authenticating the component. + * + * This class can be used directly in your application, although the Component + * subclass provides more functionality and interfaces, and is better suited + * for most needs. + */ + class SWIFTEN_API CoreComponent : public Entity { + public: + CoreComponent(const JID& jid, const std::string& secret, NetworkFactories* networkFactories); + virtual ~CoreComponent(); + + void connect(const std::string& host, int port); + void disconnect(); + + void sendMessage(boost::shared_ptr<Message>); + void sendPresence(boost::shared_ptr<Presence>); + void sendData(const std::string& data); + + IQRouter* getIQRouter() const { + return iqRouter_; + } + + StanzaChannel* getStanzaChannel() const { + return stanzaChannel_; + } + + bool isAvailable() const { + return stanzaChannel_->isAvailable(); + } + + /** + * Returns the JID of the component + */ + const JID& getJID() const { + return jid_; + } + + public: + boost::signal<void (const ComponentError&)> onError; + boost::signal<void ()> onConnected; + boost::signal<void (const SafeByteArray&)> onDataRead; + boost::signal<void (const SafeByteArray&)> onDataWritten; + + boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived; + boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived; + + private: + void handleConnectorFinished(boost::shared_ptr<Connection>); + void handleStanzaChannelAvailableChanged(bool available); + void handleSessionFinished(boost::shared_ptr<Error>); + void handleDataRead(const SafeByteArray&); + void handleDataWritten(const SafeByteArray&); + + private: + NetworkFactories* networkFactories; + JID jid_; + std::string secret_; + ComponentSessionStanzaChannel* stanzaChannel_; + IQRouter* iqRouter_; + ComponentConnector::ref connector_; + boost::shared_ptr<Connection> connection_; + boost::shared_ptr<BasicSessionStream> sessionStream_; + boost::shared_ptr<ComponentSession> session_; + bool disconnectRequested_; + }; } diff --git a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp index 3968c2c..04a6a9e 100644 --- a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp +++ b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp @@ -21,190 +21,190 @@ using namespace Swift; class ComponentConnectorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ComponentConnectorTest); - CPPUNIT_TEST(testConnect); - CPPUNIT_TEST(testConnect_FirstAddressHostFails); - CPPUNIT_TEST(testConnect_NoHosts); - CPPUNIT_TEST(testConnect_TimeoutDuringResolve); - CPPUNIT_TEST(testConnect_TimeoutDuringConnect); - CPPUNIT_TEST(testConnect_NoTimeout); - CPPUNIT_TEST(testStop_Timeout); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - host1 = HostAddress("1.1.1.1"); - host2 = HostAddress("2.2.2.2"); - eventLoop = new DummyEventLoop(); - resolver = new StaticDomainNameResolver(eventLoop); - connectionFactory = new MockConnectionFactory(eventLoop); - timerFactory = new DummyTimerFactory(); - } - - void tearDown() { - delete timerFactory; - delete connectionFactory; - delete resolver; - delete eventLoop; - } - - void testConnect() { - ComponentConnector::ref testling(createConnector("foo.com", 1234)); - resolver->addAddress("foo.com", host1); - - testling->start(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); - CPPUNIT_ASSERT(connections[0]); - CPPUNIT_ASSERT(HostAddressPort(host1, 1234) == *(connections[0]->hostAddressPort)); - } - - void testConnect_FirstAddressHostFails() { - ComponentConnector::ref testling(createConnector("foo.com", 1234)); - resolver->addAddress("foo.com", host1); - resolver->addAddress("foo.com", host2); - connectionFactory->failingPorts.push_back(HostAddressPort(host1, 1234)); - - testling->start(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); - CPPUNIT_ASSERT(connections[0]); - CPPUNIT_ASSERT(HostAddressPort(host2, 1234) == *(connections[0]->hostAddressPort)); - } - - void testConnect_NoHosts() { - ComponentConnector::ref testling(createConnector("foo.com", 1234)); - - testling->start(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); - CPPUNIT_ASSERT(!connections[0]); - } - - - void testConnect_TimeoutDuringResolve() { - ComponentConnector::ref testling(createConnector("foo.com", 1234)); - - testling->setTimeoutMilliseconds(10); - resolver->setIsResponsive(false); - - testling->start(); - eventLoop->processEvents(); - timerFactory->setTime(10); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); - CPPUNIT_ASSERT(!connections[0]); - } - - void testConnect_TimeoutDuringConnect() { - ComponentConnector::ref testling(createConnector("foo.com", 1234)); - testling->setTimeoutMilliseconds(10); - resolver->addAddress("foo.com", host1); - connectionFactory->isResponsive = false; - - testling->start(); - eventLoop->processEvents(); - timerFactory->setTime(10); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); - CPPUNIT_ASSERT(!connections[0]); - } - - void testConnect_NoTimeout() { - ComponentConnector::ref testling(createConnector("foo.com", 1234)); - testling->setTimeoutMilliseconds(10); - resolver->addAddress("foo.com", host1); - - testling->start(); - eventLoop->processEvents(); - timerFactory->setTime(10); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); - CPPUNIT_ASSERT(connections[0]); - } - - void testStop_Timeout() { - ComponentConnector::ref testling(createConnector("foo.com", 1234)); - testling->setTimeoutMilliseconds(10); - resolver->addAddress("foo.com", host1); - - testling->start(); - testling->stop(); - - eventLoop->processEvents(); - timerFactory->setTime(10); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); - CPPUNIT_ASSERT(!connections[0]); - } - - private: - ComponentConnector::ref createConnector(const std::string& hostname, int port) { - ComponentConnector::ref connector = ComponentConnector::create(hostname, port, resolver, connectionFactory, timerFactory); - connector->onConnectFinished.connect(boost::bind(&ComponentConnectorTest::handleConnectorFinished, this, _1)); - return connector; - } - - void handleConnectorFinished(boost::shared_ptr<Connection> connection) { - boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection)); - if (connection) { - assert(c); - } - connections.push_back(c); - } - - struct MockConnection : public Connection { - public: - MockConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive) {} - - void listen() { assert(false); } - void connect(const HostAddressPort& address) { - hostAddressPort = address; - if (isResponsive) { - bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end(); - eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail)); - } - } - - void disconnect() { assert(false); } - void write(const SafeByteArray&) { assert(false); } - HostAddressPort getLocalAddress() const { return HostAddressPort(); } - HostAddressPort getRemoteAddress() const { return HostAddressPort(); } - - EventLoop* eventLoop; - boost::optional<HostAddressPort> hostAddressPort; - std::vector<HostAddressPort> failingPorts; - bool isResponsive; - }; - - struct MockConnectionFactory : public ConnectionFactory { - MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop), isResponsive(true) { - } - - boost::shared_ptr<Connection> createConnection() { - return boost::shared_ptr<Connection>(new MockConnection(failingPorts, isResponsive, eventLoop)); - } - - EventLoop* eventLoop; - bool isResponsive; - std::vector<HostAddressPort> failingPorts; - }; - - private: - HostAddress host1; - HostAddress host2; - DummyEventLoop* eventLoop; - StaticDomainNameResolver* resolver; - MockConnectionFactory* connectionFactory; - DummyTimerFactory* timerFactory; - std::vector< boost::shared_ptr<MockConnection> > connections; + CPPUNIT_TEST_SUITE(ComponentConnectorTest); + CPPUNIT_TEST(testConnect); + CPPUNIT_TEST(testConnect_FirstAddressHostFails); + CPPUNIT_TEST(testConnect_NoHosts); + CPPUNIT_TEST(testConnect_TimeoutDuringResolve); + CPPUNIT_TEST(testConnect_TimeoutDuringConnect); + CPPUNIT_TEST(testConnect_NoTimeout); + CPPUNIT_TEST(testStop_Timeout); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + host1 = HostAddress("1.1.1.1"); + host2 = HostAddress("2.2.2.2"); + eventLoop = new DummyEventLoop(); + resolver = new StaticDomainNameResolver(eventLoop); + connectionFactory = new MockConnectionFactory(eventLoop); + timerFactory = new DummyTimerFactory(); + } + + void tearDown() { + delete timerFactory; + delete connectionFactory; + delete resolver; + delete eventLoop; + } + + void testConnect() { + ComponentConnector::ref testling(createConnector("foo.com", 1234)); + resolver->addAddress("foo.com", host1); + + testling->start(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(connections[0]); + CPPUNIT_ASSERT(HostAddressPort(host1, 1234) == *(connections[0]->hostAddressPort)); + } + + void testConnect_FirstAddressHostFails() { + ComponentConnector::ref testling(createConnector("foo.com", 1234)); + resolver->addAddress("foo.com", host1); + resolver->addAddress("foo.com", host2); + connectionFactory->failingPorts.push_back(HostAddressPort(host1, 1234)); + + testling->start(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(connections[0]); + CPPUNIT_ASSERT(HostAddressPort(host2, 1234) == *(connections[0]->hostAddressPort)); + } + + void testConnect_NoHosts() { + ComponentConnector::ref testling(createConnector("foo.com", 1234)); + + testling->start(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(!connections[0]); + } + + + void testConnect_TimeoutDuringResolve() { + ComponentConnector::ref testling(createConnector("foo.com", 1234)); + + testling->setTimeoutMilliseconds(10); + resolver->setIsResponsive(false); + + testling->start(); + eventLoop->processEvents(); + timerFactory->setTime(10); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(!connections[0]); + } + + void testConnect_TimeoutDuringConnect() { + ComponentConnector::ref testling(createConnector("foo.com", 1234)); + testling->setTimeoutMilliseconds(10); + resolver->addAddress("foo.com", host1); + connectionFactory->isResponsive = false; + + testling->start(); + eventLoop->processEvents(); + timerFactory->setTime(10); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(!connections[0]); + } + + void testConnect_NoTimeout() { + ComponentConnector::ref testling(createConnector("foo.com", 1234)); + testling->setTimeoutMilliseconds(10); + resolver->addAddress("foo.com", host1); + + testling->start(); + eventLoop->processEvents(); + timerFactory->setTime(10); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(connections[0]); + } + + void testStop_Timeout() { + ComponentConnector::ref testling(createConnector("foo.com", 1234)); + testling->setTimeoutMilliseconds(10); + resolver->addAddress("foo.com", host1); + + testling->start(); + testling->stop(); + + eventLoop->processEvents(); + timerFactory->setTime(10); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(!connections[0]); + } + + private: + ComponentConnector::ref createConnector(const std::string& hostname, int port) { + ComponentConnector::ref connector = ComponentConnector::create(hostname, port, resolver, connectionFactory, timerFactory); + connector->onConnectFinished.connect(boost::bind(&ComponentConnectorTest::handleConnectorFinished, this, _1)); + return connector; + } + + void handleConnectorFinished(boost::shared_ptr<Connection> connection) { + boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection)); + if (connection) { + assert(c); + } + connections.push_back(c); + } + + struct MockConnection : public Connection { + public: + MockConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive) {} + + void listen() { assert(false); } + void connect(const HostAddressPort& address) { + hostAddressPort = address; + if (isResponsive) { + bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end(); + eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail)); + } + } + + void disconnect() { assert(false); } + void write(const SafeByteArray&) { assert(false); } + HostAddressPort getLocalAddress() const { return HostAddressPort(); } + HostAddressPort getRemoteAddress() const { return HostAddressPort(); } + + EventLoop* eventLoop; + boost::optional<HostAddressPort> hostAddressPort; + std::vector<HostAddressPort> failingPorts; + bool isResponsive; + }; + + struct MockConnectionFactory : public ConnectionFactory { + MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop), isResponsive(true) { + } + + boost::shared_ptr<Connection> createConnection() { + return boost::shared_ptr<Connection>(new MockConnection(failingPorts, isResponsive, eventLoop)); + } + + EventLoop* eventLoop; + bool isResponsive; + std::vector<HostAddressPort> failingPorts; + }; + + private: + HostAddress host1; + HostAddress host2; + DummyEventLoop* eventLoop; + StaticDomainNameResolver* resolver; + MockConnectionFactory* connectionFactory; + DummyTimerFactory* timerFactory; + std::vector< boost::shared_ptr<MockConnection> > connections; }; CPPUNIT_TEST_SUITE_REGISTRATION(ComponentConnectorTest); diff --git a/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp b/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp index 570ccf1..82f43f6 100644 --- a/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp +++ b/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp @@ -14,28 +14,28 @@ using namespace Swift; class ComponentHandshakeGeneratorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ComponentHandshakeGeneratorTest); - CPPUNIT_TEST(testGetHandshake); - CPPUNIT_TEST(testGetHandshake_SpecialChars); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - } - - void testGetHandshake() { - std::string result = ComponentHandshakeGenerator::getHandshake("myid", "mysecret", crypto.get()); - CPPUNIT_ASSERT_EQUAL(std::string("4011cd31f9b99ac089a0cd7ce297da7323fa2525"), result); - } - - void testGetHandshake_SpecialChars() { - std::string result = ComponentHandshakeGenerator::getHandshake("&<", ">'\"", crypto.get()); - CPPUNIT_ASSERT_EQUAL(std::string("33631b3e0aaeb2a11c4994c917919324028873fe"), result); - } - - private: - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(ComponentHandshakeGeneratorTest); + CPPUNIT_TEST(testGetHandshake); + CPPUNIT_TEST(testGetHandshake_SpecialChars); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + } + + void testGetHandshake() { + std::string result = ComponentHandshakeGenerator::getHandshake("myid", "mysecret", crypto.get()); + CPPUNIT_ASSERT_EQUAL(std::string("4011cd31f9b99ac089a0cd7ce297da7323fa2525"), result); + } + + void testGetHandshake_SpecialChars() { + std::string result = ComponentHandshakeGenerator::getHandshake("&<", ">'\"", crypto.get()); + CPPUNIT_ASSERT_EQUAL(std::string("33631b3e0aaeb2a11c4994c917919324028873fe"), result); + } + + private: + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(ComponentHandshakeGeneratorTest); diff --git a/Swiften/Component/UnitTest/ComponentSessionTest.cpp b/Swiften/Component/UnitTest/ComponentSessionTest.cpp index 61c8ce9..1726794 100644 --- a/Swiften/Component/UnitTest/ComponentSessionTest.cpp +++ b/Swiften/Component/UnitTest/ComponentSessionTest.cpp @@ -22,201 +22,201 @@ using namespace Swift; class ComponentSessionTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ComponentSessionTest); - CPPUNIT_TEST(testStart); - CPPUNIT_TEST(testStart_Error); - CPPUNIT_TEST(testStart_Unauthorized); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - server = boost::make_shared<MockSessionStream>(); - sessionFinishedReceived = false; - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - } - - void testStart() { - boost::shared_ptr<ComponentSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->receiveHandshake(); - server->sendHandshakeResponse(); - - CPPUNIT_ASSERT(server->whitespacePingEnabled); - - session->finish(); - CPPUNIT_ASSERT(!server->whitespacePingEnabled); - - } - - void testStart_Error() { - boost::shared_ptr<ComponentSession> session(createSession()); - session->start(); - server->breakConnection(); - - CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - void testStart_Unauthorized() { - boost::shared_ptr<ComponentSession> session(createSession()); - session->start(); - server->receiveStreamStart(); - server->sendStreamStart(); - server->receiveHandshake(); - server->sendHandshakeError(); - - CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState()); - CPPUNIT_ASSERT(sessionFinishedReceived); - CPPUNIT_ASSERT(sessionFinishedError); - } - - private: - boost::shared_ptr<ComponentSession> createSession() { - boost::shared_ptr<ComponentSession> session = ComponentSession::create(JID("service.foo.com"), "servicesecret", server, crypto.get()); - session->onFinished.connect(boost::bind(&ComponentSessionTest::handleSessionFinished, this, _1)); - return session; - } - - void handleSessionFinished(boost::shared_ptr<Error> error) { - sessionFinishedReceived = true; - sessionFinishedError = error; - } - - class MockSessionStream : public SessionStream { - public: - struct Event { - Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {} - Event(const ProtocolHeader& header) : header(header), footer(false) {} - Event() : footer(true) {} - - boost::shared_ptr<ToplevelElement> element; - boost::optional<ProtocolHeader> header; - bool footer; - }; - - MockSessionStream() : available(true), whitespacePingEnabled(false), resetCount(0) { - } - - virtual void close() { - onClosed(boost::shared_ptr<Error>()); - } - - virtual bool isOpen() { - return available; - } - - virtual void writeHeader(const ProtocolHeader& header) { - receivedEvents.push_back(Event(header)); - } - - virtual void writeFooter() { - receivedEvents.push_back(Event()); - } - - virtual void writeElement(boost::shared_ptr<ToplevelElement> element) { - receivedEvents.push_back(Event(element)); - } - - virtual void writeData(const std::string&) { - } - - virtual bool supportsTLSEncryption() { - return false; - } - - virtual void addTLSEncryption() { - assert(false); - } - - virtual bool isTLSEncrypted() { - return false; - } - - virtual ByteArray getTLSFinishMessage() const { - return ByteArray(); - } - - virtual Certificate::ref getPeerCertificate() const { - return Certificate::ref(); - } - - virtual std::vector<Certificate::ref> getPeerCertificateChain() const { - return std::vector<Certificate::ref>(); - } - - virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const { - return boost::shared_ptr<CertificateVerificationError>(); - } - - virtual bool supportsZLibCompression() { - return true; - } - - virtual void addZLibCompression() { - assert(false); - } - - virtual void setWhitespacePingEnabled(bool enabled) { - whitespacePingEnabled = enabled; - } - - virtual void resetXMPPParser() { - resetCount++; - } - - void breakConnection() { - onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError)); - } - - void sendStreamStart() { - ProtocolHeader header; - header.setFrom("service.foo.com"); - return onStreamStartReceived(header); - } - - void sendHandshakeResponse() { - onElementReceived(ComponentHandshake::ref(new ComponentHandshake())); - } - - void sendHandshakeError() { - // FIXME: This isn't the correct element - onElementReceived(AuthFailure::ref(new AuthFailure())); - } - - void receiveStreamStart() { - Event event = popEvent(); - CPPUNIT_ASSERT(event.header); - } - - void receiveHandshake() { - Event event = popEvent(); - CPPUNIT_ASSERT(event.element); - ComponentHandshake::ref handshake(boost::dynamic_pointer_cast<ComponentHandshake>(event.element)); - CPPUNIT_ASSERT(handshake); - CPPUNIT_ASSERT_EQUAL(std::string("4c4f8a41141722c8bbfbdd92d827f7b2fc0a542b"), handshake->getData()); - } - - Event popEvent() { - CPPUNIT_ASSERT(!receivedEvents.empty()); - Event event = receivedEvents.front(); - receivedEvents.pop_front(); - return event; - } - - bool available; - bool whitespacePingEnabled; - std::string bindID; - int resetCount; - std::deque<Event> receivedEvents; - }; - - boost::shared_ptr<MockSessionStream> server; - bool sessionFinishedReceived; - boost::shared_ptr<Error> sessionFinishedError; - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(ComponentSessionTest); + CPPUNIT_TEST(testStart); + CPPUNIT_TEST(testStart_Error); + CPPUNIT_TEST(testStart_Unauthorized); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + server = boost::make_shared<MockSessionStream>(); + sessionFinishedReceived = false; + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + } + + void testStart() { + boost::shared_ptr<ComponentSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->receiveHandshake(); + server->sendHandshakeResponse(); + + CPPUNIT_ASSERT(server->whitespacePingEnabled); + + session->finish(); + CPPUNIT_ASSERT(!server->whitespacePingEnabled); + + } + + void testStart_Error() { + boost::shared_ptr<ComponentSession> session(createSession()); + session->start(); + server->breakConnection(); + + CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + void testStart_Unauthorized() { + boost::shared_ptr<ComponentSession> session(createSession()); + session->start(); + server->receiveStreamStart(); + server->sendStreamStart(); + server->receiveHandshake(); + server->sendHandshakeError(); + + CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState()); + CPPUNIT_ASSERT(sessionFinishedReceived); + CPPUNIT_ASSERT(sessionFinishedError); + } + + private: + boost::shared_ptr<ComponentSession> createSession() { + boost::shared_ptr<ComponentSession> session = ComponentSession::create(JID("service.foo.com"), "servicesecret", server, crypto.get()); + session->onFinished.connect(boost::bind(&ComponentSessionTest::handleSessionFinished, this, _1)); + return session; + } + + void handleSessionFinished(boost::shared_ptr<Error> error) { + sessionFinishedReceived = true; + sessionFinishedError = error; + } + + class MockSessionStream : public SessionStream { + public: + struct Event { + Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {} + Event(const ProtocolHeader& header) : header(header), footer(false) {} + Event() : footer(true) {} + + boost::shared_ptr<ToplevelElement> element; + boost::optional<ProtocolHeader> header; + bool footer; + }; + + MockSessionStream() : available(true), whitespacePingEnabled(false), resetCount(0) { + } + + virtual void close() { + onClosed(boost::shared_ptr<Error>()); + } + + virtual bool isOpen() { + return available; + } + + virtual void writeHeader(const ProtocolHeader& header) { + receivedEvents.push_back(Event(header)); + } + + virtual void writeFooter() { + receivedEvents.push_back(Event()); + } + + virtual void writeElement(boost::shared_ptr<ToplevelElement> element) { + receivedEvents.push_back(Event(element)); + } + + virtual void writeData(const std::string&) { + } + + virtual bool supportsTLSEncryption() { + return false; + } + + virtual void addTLSEncryption() { + assert(false); + } + + virtual bool isTLSEncrypted() { + return false; + } + + virtual ByteArray getTLSFinishMessage() const { + return ByteArray(); + } + + virtual Certificate::ref getPeerCertificate() const { + return Certificate::ref(); + } + + virtual std::vector<Certificate::ref> getPeerCertificateChain() const { + return std::vector<Certificate::ref>(); + } + + virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const { + return boost::shared_ptr<CertificateVerificationError>(); + } + + virtual bool supportsZLibCompression() { + return true; + } + + virtual void addZLibCompression() { + assert(false); + } + + virtual void setWhitespacePingEnabled(bool enabled) { + whitespacePingEnabled = enabled; + } + + virtual void resetXMPPParser() { + resetCount++; + } + + void breakConnection() { + onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError)); + } + + void sendStreamStart() { + ProtocolHeader header; + header.setFrom("service.foo.com"); + return onStreamStartReceived(header); + } + + void sendHandshakeResponse() { + onElementReceived(ComponentHandshake::ref(new ComponentHandshake())); + } + + void sendHandshakeError() { + // FIXME: This isn't the correct element + onElementReceived(AuthFailure::ref(new AuthFailure())); + } + + void receiveStreamStart() { + Event event = popEvent(); + CPPUNIT_ASSERT(event.header); + } + + void receiveHandshake() { + Event event = popEvent(); + CPPUNIT_ASSERT(event.element); + ComponentHandshake::ref handshake(boost::dynamic_pointer_cast<ComponentHandshake>(event.element)); + CPPUNIT_ASSERT(handshake); + CPPUNIT_ASSERT_EQUAL(std::string("4c4f8a41141722c8bbfbdd92d827f7b2fc0a542b"), handshake->getData()); + } + + Event popEvent() { + CPPUNIT_ASSERT(!receivedEvents.empty()); + Event event = receivedEvents.front(); + receivedEvents.pop_front(); + return event; + } + + bool available; + bool whitespacePingEnabled; + std::string bindID; + int resetCount; + std::deque<Event> receivedEvents; + }; + + boost::shared_ptr<MockSessionStream> server; + bool sessionFinishedReceived; + boost::shared_ptr<Error> sessionFinishedError; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(ComponentSessionTest); diff --git a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp index 584a4f7..ca99201 100644 --- a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp +++ b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp @@ -17,28 +17,28 @@ using namespace Swift; class ZLibCompressorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ZLibCompressorTest); - CPPUNIT_TEST(testProcess); - CPPUNIT_TEST(testProcess_Twice); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(ZLibCompressorTest); + CPPUNIT_TEST(testProcess); + CPPUNIT_TEST(testProcess_Twice); + CPPUNIT_TEST_SUITE_END(); - public: - ZLibCompressorTest() {} + public: + ZLibCompressorTest() {} - void testProcess() { - ZLibCompressor testling; - SafeByteArray result = testling.process(createSafeByteArray("foo")); + void testProcess() { + ZLibCompressor testling; + SafeByteArray result = testling.process(createSafeByteArray("foo")); - CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11), result); - } + CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11), result); + } - void testProcess_Twice() { - ZLibCompressor testling; - testling.process(createSafeByteArray("foo")); - SafeByteArray result = testling.process(createSafeByteArray("bar")); + void testProcess_Twice() { + ZLibCompressor testling; + testling.process(createSafeByteArray("foo")); + SafeByteArray result = testling.process(createSafeByteArray("bar")); - CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff",9), result); - } + CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff",9), result); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(ZLibCompressorTest); diff --git a/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp b/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp index 7e57676..5873c0e 100644 --- a/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp +++ b/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp @@ -19,62 +19,62 @@ using namespace Swift; class ZLibDecompressorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ZLibDecompressorTest); - CPPUNIT_TEST(testProcess); - CPPUNIT_TEST(testProcess_Twice); - CPPUNIT_TEST(testProcess_Invalid); - CPPUNIT_TEST(testProcess_Huge); - CPPUNIT_TEST(testProcess_ChunkSize); - CPPUNIT_TEST_SUITE_END(); - - public: - ZLibDecompressorTest() {} - - void testProcess() { - ZLibDecompressor testling; - SafeByteArray result = testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11)); - - CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), result); - } - - void testProcess_Twice() { - ZLibDecompressor testling; - testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11)); - SafeByteArray result = testling.process(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff", 9)); - - CPPUNIT_ASSERT_EQUAL(createSafeByteArray("bar"), result); - } - - void testProcess_Invalid() { - ZLibDecompressor testling; - CPPUNIT_ASSERT_THROW(testling.process(createSafeByteArray("invalid")), ZLibException); - } - - void testProcess_Huge() { - std::vector<char> data; - data.reserve(2048); - for (unsigned int i = 0; i < 2048; ++i) { - data.push_back(static_cast<char>(i)); - } - SafeByteArray original(createSafeByteArray(&data[0], data.size())); - SafeByteArray compressed = ZLibCompressor().process(original); - SafeByteArray decompressed = ZLibDecompressor().process(compressed); - - CPPUNIT_ASSERT_EQUAL(original, decompressed); - } - - void testProcess_ChunkSize() { - std::vector<char> data; - data.reserve(1024); - for (unsigned int i = 0; i < 1024; ++i) { - data.push_back(static_cast<char>(i)); - } - SafeByteArray original(createSafeByteArray(&data[0], data.size())); - SafeByteArray compressed = ZLibCompressor().process(original); - SafeByteArray decompressed = ZLibDecompressor().process(compressed); - - CPPUNIT_ASSERT_EQUAL(original, decompressed); - } + CPPUNIT_TEST_SUITE(ZLibDecompressorTest); + CPPUNIT_TEST(testProcess); + CPPUNIT_TEST(testProcess_Twice); + CPPUNIT_TEST(testProcess_Invalid); + CPPUNIT_TEST(testProcess_Huge); + CPPUNIT_TEST(testProcess_ChunkSize); + CPPUNIT_TEST_SUITE_END(); + + public: + ZLibDecompressorTest() {} + + void testProcess() { + ZLibDecompressor testling; + SafeByteArray result = testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11)); + + CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), result); + } + + void testProcess_Twice() { + ZLibDecompressor testling; + testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11)); + SafeByteArray result = testling.process(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff", 9)); + + CPPUNIT_ASSERT_EQUAL(createSafeByteArray("bar"), result); + } + + void testProcess_Invalid() { + ZLibDecompressor testling; + CPPUNIT_ASSERT_THROW(testling.process(createSafeByteArray("invalid")), ZLibException); + } + + void testProcess_Huge() { + std::vector<char> data; + data.reserve(2048); + for (unsigned int i = 0; i < 2048; ++i) { + data.push_back(static_cast<char>(i)); + } + SafeByteArray original(createSafeByteArray(&data[0], data.size())); + SafeByteArray compressed = ZLibCompressor().process(original); + SafeByteArray decompressed = ZLibDecompressor().process(compressed); + + CPPUNIT_ASSERT_EQUAL(original, decompressed); + } + + void testProcess_ChunkSize() { + std::vector<char> data; + data.reserve(1024); + for (unsigned int i = 0; i < 1024; ++i) { + data.push_back(static_cast<char>(i)); + } + SafeByteArray original(createSafeByteArray(&data[0], data.size())); + SafeByteArray compressed = ZLibCompressor().process(original); + SafeByteArray decompressed = ZLibDecompressor().process(compressed); + + CPPUNIT_ASSERT_EQUAL(original, decompressed); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(ZLibDecompressorTest); diff --git a/Swiften/Compress/ZLibCodecompressor.cpp b/Swiften/Compress/ZLibCodecompressor.cpp index 7c413b7..fd6d3b0 100644 --- a/Swiften/Compress/ZLibCodecompressor.cpp +++ b/Swiften/Compress/ZLibCodecompressor.cpp @@ -23,36 +23,36 @@ static const size_t CHUNK_SIZE = 1024; // If you change this, also change the un ZLibCodecompressor::ZLibCodecompressor() : p(boost::make_shared<Private>()) { - memset(&p->stream, 0, sizeof(z_stream)); - p->stream.zalloc = Z_NULL; - p->stream.zfree = Z_NULL; - p->stream.opaque = Z_NULL; + memset(&p->stream, 0, sizeof(z_stream)); + p->stream.zalloc = Z_NULL; + p->stream.zfree = Z_NULL; + p->stream.opaque = Z_NULL; } ZLibCodecompressor::~ZLibCodecompressor() { } SafeByteArray ZLibCodecompressor::process(const SafeByteArray& input) { - SafeByteArray output; - p->stream.avail_in = static_cast<unsigned int>(input.size()); - p->stream.next_in = reinterpret_cast<Bytef*>(const_cast<unsigned char*>(vecptr(input))); - size_t outputPosition = 0; - do { - output.resize(outputPosition + CHUNK_SIZE); - p->stream.avail_out = CHUNK_SIZE; - p->stream.next_out = reinterpret_cast<Bytef*>(vecptr(output) + outputPosition); - int result = processZStream(); - if (result != Z_OK && result != Z_BUF_ERROR) { - throw ZLibException(/* p->stream.msg */); - } - outputPosition += CHUNK_SIZE; - } - while (p->stream.avail_out == 0); - if (p->stream.avail_in != 0) { - throw ZLibException(); - } - output.resize(outputPosition - p->stream.avail_out); - return output; + SafeByteArray output; + p->stream.avail_in = static_cast<unsigned int>(input.size()); + p->stream.next_in = reinterpret_cast<Bytef*>(const_cast<unsigned char*>(vecptr(input))); + size_t outputPosition = 0; + do { + output.resize(outputPosition + CHUNK_SIZE); + p->stream.avail_out = CHUNK_SIZE; + p->stream.next_out = reinterpret_cast<Bytef*>(vecptr(output) + outputPosition); + int result = processZStream(); + if (result != Z_OK && result != Z_BUF_ERROR) { + throw ZLibException(/* p->stream.msg */); + } + outputPosition += CHUNK_SIZE; + } + while (p->stream.avail_out == 0); + if (p->stream.avail_in != 0) { + throw ZLibException(); + } + output.resize(outputPosition - p->stream.avail_out); + return output; } } diff --git a/Swiften/Compress/ZLibCodecompressor.h b/Swiften/Compress/ZLibCodecompressor.h index 3907258..253c34a 100644 --- a/Swiften/Compress/ZLibCodecompressor.h +++ b/Swiften/Compress/ZLibCodecompressor.h @@ -10,16 +10,16 @@ #include <Swiften/Base/SafeByteArray.h> namespace Swift { - class SWIFTEN_API ZLibCodecompressor { - public: - ZLibCodecompressor(); - virtual ~ZLibCodecompressor(); + class SWIFTEN_API ZLibCodecompressor { + public: + ZLibCodecompressor(); + virtual ~ZLibCodecompressor(); - SafeByteArray process(const SafeByteArray& data); - virtual int processZStream() = 0; + SafeByteArray process(const SafeByteArray& data); + virtual int processZStream() = 0; - protected: - struct Private; - boost::shared_ptr<Private> p; - }; + protected: + struct Private; + boost::shared_ptr<Private> p; + }; } diff --git a/Swiften/Compress/ZLibCodecompressor_Private.h b/Swiften/Compress/ZLibCodecompressor_Private.h index db761c3..2adc4b6 100644 --- a/Swiften/Compress/ZLibCodecompressor_Private.h +++ b/Swiften/Compress/ZLibCodecompressor_Private.h @@ -11,7 +11,7 @@ #include <Swiften/Compress/ZLibCodecompressor.h> namespace Swift { - struct ZLibCodecompressor::Private { - z_stream stream; - }; + struct ZLibCodecompressor::Private { + z_stream stream; + }; } diff --git a/Swiften/Compress/ZLibCompressor.cpp b/Swiften/Compress/ZLibCompressor.cpp index 8887c46..a2fef15 100644 --- a/Swiften/Compress/ZLibCompressor.cpp +++ b/Swiften/Compress/ZLibCompressor.cpp @@ -16,17 +16,17 @@ namespace Swift { ZLibCompressor::ZLibCompressor() { - int result = deflateInit(&p->stream, COMPRESSION_LEVEL); - assert(result == Z_OK); - (void) result; + int result = deflateInit(&p->stream, COMPRESSION_LEVEL); + assert(result == Z_OK); + (void) result; } ZLibCompressor::~ZLibCompressor() { - deflateEnd(&p->stream); + deflateEnd(&p->stream); } int ZLibCompressor::processZStream() { - return deflate(&p->stream, Z_SYNC_FLUSH); + return deflate(&p->stream, Z_SYNC_FLUSH); } } diff --git a/Swiften/Compress/ZLibCompressor.h b/Swiften/Compress/ZLibCompressor.h index c92b8c0..59ebbb9 100644 --- a/Swiften/Compress/ZLibCompressor.h +++ b/Swiften/Compress/ZLibCompressor.h @@ -10,14 +10,14 @@ #include <Swiften/Compress/ZLibCodecompressor.h> namespace Swift { - class SWIFTEN_API ZLibCompressor : public ZLibCodecompressor { - public: - ZLibCompressor(); - virtual ~ZLibCompressor(); + class SWIFTEN_API ZLibCompressor : public ZLibCodecompressor { + public: + ZLibCompressor(); + virtual ~ZLibCompressor(); - virtual int processZStream(); + virtual int processZStream(); - private: - static const int COMPRESSION_LEVEL = 9; - }; + private: + static const int COMPRESSION_LEVEL = 9; + }; } diff --git a/Swiften/Compress/ZLibDecompressor.cpp b/Swiften/Compress/ZLibDecompressor.cpp index 3024150..adc40c5 100644 --- a/Swiften/Compress/ZLibDecompressor.cpp +++ b/Swiften/Compress/ZLibDecompressor.cpp @@ -16,17 +16,17 @@ namespace Swift { ZLibDecompressor::ZLibDecompressor() { - int result = inflateInit(&p->stream); - assert(result == Z_OK); - (void) result; + int result = inflateInit(&p->stream); + assert(result == Z_OK); + (void) result; } ZLibDecompressor::~ZLibDecompressor() { - inflateEnd(&p->stream); + inflateEnd(&p->stream); } int ZLibDecompressor::processZStream() { - return inflate(&p->stream, Z_SYNC_FLUSH); + return inflate(&p->stream, Z_SYNC_FLUSH); } } diff --git a/Swiften/Compress/ZLibDecompressor.h b/Swiften/Compress/ZLibDecompressor.h index b758be3..9c2dd4f 100644 --- a/Swiften/Compress/ZLibDecompressor.h +++ b/Swiften/Compress/ZLibDecompressor.h @@ -10,11 +10,11 @@ #include <Swiften/Compress/ZLibCodecompressor.h> namespace Swift { - class SWIFTEN_API ZLibDecompressor : public ZLibCodecompressor { - public: - ZLibDecompressor(); - virtual ~ZLibDecompressor(); + class SWIFTEN_API ZLibDecompressor : public ZLibCodecompressor { + public: + ZLibDecompressor(); + virtual ~ZLibDecompressor(); - virtual int processZStream(); - }; + virtual int processZStream(); + }; } diff --git a/Swiften/Compress/ZLibException.h b/Swiften/Compress/ZLibException.h index e73bcec..2201e62 100644 --- a/Swiften/Compress/ZLibException.h +++ b/Swiften/Compress/ZLibException.h @@ -7,8 +7,8 @@ #pragma once namespace Swift { - class ZLibException { - public: - ZLibException() {} - }; + class ZLibException { + public: + ZLibException() {} + }; } diff --git a/Swiften/Config/swiften-config.cpp b/Swiften/Config/swiften-config.cpp index 6016d5f..1a15702 100644 --- a/Swiften/Config/swiften-config.cpp +++ b/Swiften/Config/swiften-config.cpp @@ -24,103 +24,103 @@ using namespace Swift; static void printFlags(const std::vector<std::string>& flags) { - for (size_t i = 0; i < flags.size(); ++i) { - if (i > 0) { - std::cout << " "; - } - std::cout << flags[i]; - } - std::cout << std::endl; + for (size_t i = 0; i < flags.size(); ++i) { + if (i > 0) { + std::cout << " "; + } + std::cout << flags[i]; + } + std::cout << std::endl; } int main(int argc, char* argv[]) { - boost::program_options::options_description desc; - desc.add_options() - ("help", "Show this help message") - ("version", "Show version information") - ("libs", "List the library flags") - ("cflags", "List the compiler & preprocessor flags") - ; - boost::program_options::variables_map vm; - try { - boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); - boost::program_options::notify(vm); - } - catch (const boost::program_options::unknown_option& option) { + boost::program_options::options_description desc; + desc.add_options() + ("help", "Show this help message") + ("version", "Show version information") + ("libs", "List the library flags") + ("cflags", "List the compiler & preprocessor flags") + ; + boost::program_options::variables_map vm; + try { + boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); + boost::program_options::notify(vm); + } + catch (const boost::program_options::unknown_option& option) { #if BOOST_VERSION >= 104200 - std::cout << "Ignoring unknown option " << option.get_option_name() << std::endl; + std::cout << "Ignoring unknown option " << option.get_option_name() << std::endl; #else - std::cout << "Error: " << option.what() << std::endl; + std::cout << "Error: " << option.what() << std::endl; #endif - } - catch (const boost::program_options::error& e) { - std::cout << "Error: " << e.what() << std::endl; - return -1; - } + } + catch (const boost::program_options::error& e) { + std::cout << "Error: " << e.what() << std::endl; + return -1; + } - if (vm.count("help") > 0) { - std::cout << "swiften-config outputs the Swiften build options." << std::endl; - std::cout << std::endl; - std::cout << "Usage: swiften-config [OPTIONS]..." << std::endl; - std::cout << std::endl; - std::cout << desc << "\n"; - return 0; - } - if (vm.count("version") > 0) { - std::cout << "swiften-config " << SWIFTEN_VERSION_STRING << std::endl; - return 0; - } + if (vm.count("help") > 0) { + std::cout << "swiften-config outputs the Swiften build options." << std::endl; + std::cout << std::endl; + std::cout << "Usage: swiften-config [OPTIONS]..." << std::endl; + std::cout << std::endl; + std::cout << desc << "\n"; + return 0; + } + if (vm.count("version") > 0) { + std::cout << "swiften-config " << SWIFTEN_VERSION_STRING << std::endl; + return 0; + } - // Read in all variables - std::vector<std::string> libs; - for (size_t i = 0; LIBFLAGS[i]; ++i) { - libs.push_back(LIBFLAGS[i]); - } - std::vector<std::string> cflags; - for (size_t i = 0; CPPFLAGS[i]; ++i) { - cflags.push_back(CPPFLAGS[i]); - } + // Read in all variables + std::vector<std::string> libs; + for (size_t i = 0; LIBFLAGS[i]; ++i) { + libs.push_back(LIBFLAGS[i]); + } + std::vector<std::string> cflags; + for (size_t i = 0; CPPFLAGS[i]; ++i) { + cflags.push_back(CPPFLAGS[i]); + } - // Detect whether we're running in-place or not - boost::filesystem::path executablePath = Paths::getExecutablePath(); - boost::filesystem::path topSourcePath = executablePath / ".." / ".."; - boost::filesystem::path topInstallPath = executablePath / ".."; - bool inPlace = !boost::filesystem::exists(topInstallPath / "include" / "Swiften" / "Swiften.h"); + // Detect whether we're running in-place or not + boost::filesystem::path executablePath = Paths::getExecutablePath(); + boost::filesystem::path topSourcePath = executablePath / ".." / ".."; + boost::filesystem::path topInstallPath = executablePath / ".."; + bool inPlace = !boost::filesystem::exists(topInstallPath / "include" / "Swiften" / "Swiften.h"); - // Replace "#" variables with the correct path - for(size_t i = 0; i < libs.size(); ++i) { - if (inPlace) { - std::string lib = libs[i]; - boost::replace_all(lib, "#", pathToString(topSourcePath)); - libs[i] = lib; - } - else { - std::string lib = libs[i]; - boost::replace_all(lib, "#", pathToString(topInstallPath / "lib")); - boost::erase_all(lib, "/Swiften"); - libs[i] = lib; - } - } - for(size_t i = 0; i < cflags.size(); ++i) { - if (inPlace) { - std::string cflag = cflags[i]; - boost::replace_all(cflag, "#", pathToString(topSourcePath)); - cflags[i] = cflag; - } - else { - std::string cflag = cflags[i]; - boost::replace_all(cflag, "#", pathToString(topInstallPath / "include")); - cflags[i] = cflag; - } - } + // Replace "#" variables with the correct path + for(size_t i = 0; i < libs.size(); ++i) { + if (inPlace) { + std::string lib = libs[i]; + boost::replace_all(lib, "#", pathToString(topSourcePath)); + libs[i] = lib; + } + else { + std::string lib = libs[i]; + boost::replace_all(lib, "#", pathToString(topInstallPath / "lib")); + boost::erase_all(lib, "/Swiften"); + libs[i] = lib; + } + } + for(size_t i = 0; i < cflags.size(); ++i) { + if (inPlace) { + std::string cflag = cflags[i]; + boost::replace_all(cflag, "#", pathToString(topSourcePath)); + cflags[i] = cflag; + } + else { + std::string cflag = cflags[i]; + boost::replace_all(cflag, "#", pathToString(topInstallPath / "include")); + cflags[i] = cflag; + } + } - // Print the requested variable - if (vm.count("libs") > 0) { - printFlags(libs); - } - if (vm.count("cflags") > 0) { - printFlags(cflags); - } - return 0; + // Print the requested variable + if (vm.count("libs") > 0) { + printFlags(libs); + } + if (vm.count("cflags") > 0) { + printFlags(cflags); + } + return 0; } diff --git a/Swiften/Crypto/CommonCryptoCryptoProvider.cpp b/Swiften/Crypto/CommonCryptoCryptoProvider.cpp index 27bbb09..9fbdb2a 100644 --- a/Swiften/Crypto/CommonCryptoCryptoProvider.cpp +++ b/Swiften/Crypto/CommonCryptoCryptoProvider.cpp @@ -19,94 +19,94 @@ using namespace Swift; namespace { - class SHA1Hash : public Hash { - public: - SHA1Hash() : finalized(false) { - if (!CC_SHA1_Init(&context)) { - assert(false); - } - } - - ~SHA1Hash() { - } - - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { - assert(!finalized); - std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH); - CC_SHA1_Final(vecptr(result), &context); - return result; - } - - private: - template<typename ContainerType> - Hash& updateInternal(const ContainerType& data) { - assert(!finalized); - if (!CC_SHA1_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { - assert(false); - } - return *this; - } - - private: - CC_SHA1_CTX context; - bool finalized; - }; - - class MD5Hash : public Hash { - public: - MD5Hash() : finalized(false) { - if (!CC_MD5_Init(&context)) { - assert(false); - } - } - - ~MD5Hash() { - } - - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { - assert(!finalized); - std::vector<unsigned char> result(CC_MD5_DIGEST_LENGTH); - CC_MD5_Final(vecptr(result), &context); - return result; - } - - private: - template<typename ContainerType> - Hash& updateInternal(const ContainerType& data) { - assert(!finalized); - if (!CC_MD5_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { - assert(false); - } - return *this; - } - - private: - CC_MD5_CTX context; - bool finalized; - }; - - template<typename T> - ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) { - std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH); - CCHmac(kCCHmacAlgSHA1, vecptr(key), key.size(), vecptr(data), boost::numeric_cast<CC_LONG>(data.size()), vecptr(result)); - return result; - } + class SHA1Hash : public Hash { + public: + SHA1Hash() : finalized(false) { + if (!CC_SHA1_Init(&context)) { + assert(false); + } + } + + ~SHA1Hash() { + } + + virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + assert(!finalized); + std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH); + CC_SHA1_Final(vecptr(result), &context); + return result; + } + + private: + template<typename ContainerType> + Hash& updateInternal(const ContainerType& data) { + assert(!finalized); + if (!CC_SHA1_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { + assert(false); + } + return *this; + } + + private: + CC_SHA1_CTX context; + bool finalized; + }; + + class MD5Hash : public Hash { + public: + MD5Hash() : finalized(false) { + if (!CC_MD5_Init(&context)) { + assert(false); + } + } + + ~MD5Hash() { + } + + virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + assert(!finalized); + std::vector<unsigned char> result(CC_MD5_DIGEST_LENGTH); + CC_MD5_Final(vecptr(result), &context); + return result; + } + + private: + template<typename ContainerType> + Hash& updateInternal(const ContainerType& data) { + assert(!finalized); + if (!CC_MD5_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { + assert(false); + } + return *this; + } + + private: + CC_MD5_CTX context; + bool finalized; + }; + + template<typename T> + ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) { + std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH); + CCHmac(kCCHmacAlgSHA1, vecptr(key), key.size(), vecptr(data), boost::numeric_cast<CC_LONG>(data.size()), vecptr(result)); + return result; + } } CommonCryptoCryptoProvider::CommonCryptoCryptoProvider() { @@ -116,22 +116,22 @@ CommonCryptoCryptoProvider::~CommonCryptoCryptoProvider() { } Hash* CommonCryptoCryptoProvider::createSHA1() { - return new SHA1Hash(); + return new SHA1Hash(); } Hash* CommonCryptoCryptoProvider::createMD5() { - return new MD5Hash(); + return new MD5Hash(); } ByteArray CommonCryptoCryptoProvider::getHMACSHA1(const SafeByteArray& key, const ByteArray& data) { - return getHMACSHA1Internal(key, data); + return getHMACSHA1Internal(key, data); } ByteArray CommonCryptoCryptoProvider::getHMACSHA1(const ByteArray& key, const ByteArray& data) { - return getHMACSHA1Internal(key, data); + return getHMACSHA1Internal(key, data); } bool CommonCryptoCryptoProvider::isMD5AllowedForCrypto() const { - return true; + return true; } diff --git a/Swiften/Crypto/CommonCryptoCryptoProvider.h b/Swiften/Crypto/CommonCryptoCryptoProvider.h index b9e14fc..8fa7fa6 100644 --- a/Swiften/Crypto/CommonCryptoCryptoProvider.h +++ b/Swiften/Crypto/CommonCryptoCryptoProvider.h @@ -11,15 +11,15 @@ #include <Swiften/Crypto/CryptoProvider.h> namespace Swift { - class SWIFTEN_API CommonCryptoCryptoProvider : public CryptoProvider { - public: - CommonCryptoCryptoProvider(); - ~CommonCryptoCryptoProvider(); + class SWIFTEN_API CommonCryptoCryptoProvider : public CryptoProvider { + public: + CommonCryptoCryptoProvider(); + ~CommonCryptoCryptoProvider(); - virtual Hash* createSHA1() SWIFTEN_OVERRIDE; - virtual Hash* createMD5() SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; - }; + virtual Hash* createSHA1() SWIFTEN_OVERRIDE; + virtual Hash* createMD5() SWIFTEN_OVERRIDE; + virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; + virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; + virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; + }; } diff --git a/Swiften/Crypto/CryptoProvider.h b/Swiften/Crypto/CryptoProvider.h index 1fe2b2c..a86468c 100644 --- a/Swiften/Crypto/CryptoProvider.h +++ b/Swiften/Crypto/CryptoProvider.h @@ -12,25 +12,25 @@ #include <Swiften/Crypto/Hash.h> namespace Swift { - class Hash; + class Hash; - class SWIFTEN_API CryptoProvider { - public: - virtual ~CryptoProvider(); + class SWIFTEN_API CryptoProvider { + public: + virtual ~CryptoProvider(); - virtual Hash* createSHA1() = 0; - virtual Hash* createMD5() = 0; - virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) = 0; - virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) = 0; - virtual bool isMD5AllowedForCrypto() const = 0; + virtual Hash* createSHA1() = 0; + virtual Hash* createMD5() = 0; + virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) = 0; + virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) = 0; + virtual bool isMD5AllowedForCrypto() const = 0; - // Convenience - template<typename T> ByteArray getSHA1Hash(const T& data) { - return boost::shared_ptr<Hash>(createSHA1())->update(data).getHash(); - } + // Convenience + template<typename T> ByteArray getSHA1Hash(const T& data) { + return boost::shared_ptr<Hash>(createSHA1())->update(data).getHash(); + } - template<typename T> ByteArray getMD5Hash(const T& data) { - return boost::shared_ptr<Hash>(createMD5())->update(data).getHash(); - } - }; + template<typename T> ByteArray getMD5Hash(const T& data) { + return boost::shared_ptr<Hash>(createMD5())->update(data).getHash(); + } + }; } diff --git a/Swiften/Crypto/Hash.h b/Swiften/Crypto/Hash.h index f3a8937..a9ed323 100644 --- a/Swiften/Crypto/Hash.h +++ b/Swiften/Crypto/Hash.h @@ -13,13 +13,13 @@ #include <Swiften/Base/SafeByteArray.h> namespace Swift { - class SWIFTEN_API Hash { - public: - virtual ~Hash(); + class SWIFTEN_API Hash { + public: + virtual ~Hash(); - virtual Hash& update(const ByteArray& data) = 0; - virtual Hash& update(const SafeByteArray& data) = 0; + virtual Hash& update(const ByteArray& data) = 0; + virtual Hash& update(const SafeByteArray& data) = 0; - virtual std::vector<unsigned char> getHash() = 0; - }; + virtual std::vector<unsigned char> getHash() = 0; + }; } diff --git a/Swiften/Crypto/OpenSSLCryptoProvider.cpp b/Swiften/Crypto/OpenSSLCryptoProvider.cpp index 91387d2..c785041 100644 --- a/Swiften/Crypto/OpenSSLCryptoProvider.cpp +++ b/Swiften/Crypto/OpenSSLCryptoProvider.cpp @@ -20,96 +20,96 @@ using namespace Swift; namespace { - class SHA1Hash : public Hash { - public: - SHA1Hash() : finalized(false) { - if (!SHA1_Init(&context)) { - assert(false); - } - } - - ~SHA1Hash() { - } - - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { - assert(!finalized); - std::vector<unsigned char> result(SHA_DIGEST_LENGTH); - SHA1_Final(vecptr(result), &context); - return result; - } - - private: - template<typename ContainerType> - Hash& updateInternal(const ContainerType& data) { - assert(!finalized); - if (!SHA1_Update(&context, vecptr(data), data.size())) { - assert(false); - } - return *this; - } - - private: - SHA_CTX context; - bool finalized; - }; - - class MD5Hash : public Hash { - public: - MD5Hash() : finalized(false) { - if (!MD5_Init(&context)) { - assert(false); - } - } - - ~MD5Hash() { - } - - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { - assert(!finalized); - std::vector<unsigned char> result(MD5_DIGEST_LENGTH); - MD5_Final(vecptr(result), &context); - return result; - } - - private: - template<typename ContainerType> - Hash& updateInternal(const ContainerType& data) { - assert(!finalized); - if (!MD5_Update(&context, vecptr(data), data.size())) { - assert(false); - } - return *this; - } - - private: - MD5_CTX context; - bool finalized; - }; - - - template<typename T> - ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) { - unsigned int len = SHA_DIGEST_LENGTH; - std::vector<unsigned char> result(len); - HMAC(EVP_sha1(), vecptr(key), boost::numeric_cast<int>(key.size()), vecptr(data), data.size(), vecptr(result), &len); - return result; - } + class SHA1Hash : public Hash { + public: + SHA1Hash() : finalized(false) { + if (!SHA1_Init(&context)) { + assert(false); + } + } + + ~SHA1Hash() { + } + + virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + assert(!finalized); + std::vector<unsigned char> result(SHA_DIGEST_LENGTH); + SHA1_Final(vecptr(result), &context); + return result; + } + + private: + template<typename ContainerType> + Hash& updateInternal(const ContainerType& data) { + assert(!finalized); + if (!SHA1_Update(&context, vecptr(data), data.size())) { + assert(false); + } + return *this; + } + + private: + SHA_CTX context; + bool finalized; + }; + + class MD5Hash : public Hash { + public: + MD5Hash() : finalized(false) { + if (!MD5_Init(&context)) { + assert(false); + } + } + + ~MD5Hash() { + } + + virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + assert(!finalized); + std::vector<unsigned char> result(MD5_DIGEST_LENGTH); + MD5_Final(vecptr(result), &context); + return result; + } + + private: + template<typename ContainerType> + Hash& updateInternal(const ContainerType& data) { + assert(!finalized); + if (!MD5_Update(&context, vecptr(data), data.size())) { + assert(false); + } + return *this; + } + + private: + MD5_CTX context; + bool finalized; + }; + + + template<typename T> + ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) { + unsigned int len = SHA_DIGEST_LENGTH; + std::vector<unsigned char> result(len); + HMAC(EVP_sha1(), vecptr(key), boost::numeric_cast<int>(key.size()), vecptr(data), data.size(), vecptr(result), &len); + return result; + } } OpenSSLCryptoProvider::OpenSSLCryptoProvider() { @@ -119,22 +119,22 @@ OpenSSLCryptoProvider::~OpenSSLCryptoProvider() { } Hash* OpenSSLCryptoProvider::createSHA1() { - return new SHA1Hash(); + return new SHA1Hash(); } Hash* OpenSSLCryptoProvider::createMD5() { - return new MD5Hash(); + return new MD5Hash(); } ByteArray OpenSSLCryptoProvider::getHMACSHA1(const SafeByteArray& key, const ByteArray& data) { - return getHMACSHA1Internal(key, data); + return getHMACSHA1Internal(key, data); } ByteArray OpenSSLCryptoProvider::getHMACSHA1(const ByteArray& key, const ByteArray& data) { - return getHMACSHA1Internal(key, data); + return getHMACSHA1Internal(key, data); } bool OpenSSLCryptoProvider::isMD5AllowedForCrypto() const { - return true; + return true; } diff --git a/Swiften/Crypto/OpenSSLCryptoProvider.h b/Swiften/Crypto/OpenSSLCryptoProvider.h index 3cc528a..6e0c01b 100644 --- a/Swiften/Crypto/OpenSSLCryptoProvider.h +++ b/Swiften/Crypto/OpenSSLCryptoProvider.h @@ -10,15 +10,15 @@ #include <Swiften/Crypto/CryptoProvider.h> namespace Swift { - class OpenSSLCryptoProvider : public CryptoProvider { - public: - OpenSSLCryptoProvider(); - ~OpenSSLCryptoProvider(); + class OpenSSLCryptoProvider : public CryptoProvider { + public: + OpenSSLCryptoProvider(); + ~OpenSSLCryptoProvider(); - virtual Hash* createSHA1() SWIFTEN_OVERRIDE; - virtual Hash* createMD5() SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; - }; + virtual Hash* createSHA1() SWIFTEN_OVERRIDE; + virtual Hash* createMD5() SWIFTEN_OVERRIDE; + virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; + virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; + virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; + }; } diff --git a/Swiften/Crypto/PlatformCryptoProvider.cpp b/Swiften/Crypto/PlatformCryptoProvider.cpp index 759909d..d67b284 100644 --- a/Swiften/Crypto/PlatformCryptoProvider.cpp +++ b/Swiften/Crypto/PlatformCryptoProvider.cpp @@ -21,12 +21,12 @@ using namespace Swift; CryptoProvider* PlatformCryptoProvider::create() { #if defined(SWIFTEN_PLATFORM_WIN32) - return new WindowsCryptoProvider(); + return new WindowsCryptoProvider(); #elif defined(HAVE_COMMONCRYPTO_CRYPTO_PROVIDER) - return new CommonCryptoCryptoProvider(); + return new CommonCryptoCryptoProvider(); #elif defined(HAVE_OPENSSL_CRYPTO_PROVIDER) - return new OpenSSLCryptoProvider(); + return new OpenSSLCryptoProvider(); #endif - assert(false); - return NULL; + assert(false); + return NULL; } diff --git a/Swiften/Crypto/PlatformCryptoProvider.h b/Swiften/Crypto/PlatformCryptoProvider.h index 9584ab9..1133ae5 100644 --- a/Swiften/Crypto/PlatformCryptoProvider.h +++ b/Swiften/Crypto/PlatformCryptoProvider.h @@ -9,9 +9,9 @@ #include <Swiften/Base/API.h> namespace Swift { - class CryptoProvider; + class CryptoProvider; - namespace PlatformCryptoProvider { - SWIFTEN_API CryptoProvider* create(); - } + namespace PlatformCryptoProvider { + SWIFTEN_API CryptoProvider* create(); + } } diff --git a/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp b/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp index 3e40ecf..d37e776 100644 --- a/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp +++ b/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp @@ -26,123 +26,123 @@ using namespace Swift; template <typename CryptoProviderType> class CryptoProviderTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(CryptoProviderTest); + CPPUNIT_TEST_SUITE(CryptoProviderTest); - CPPUNIT_TEST(testGetSHA1Hash); - CPPUNIT_TEST(testGetSHA1Hash_TwoUpdates); - CPPUNIT_TEST(testGetSHA1Hash_NoData); - CPPUNIT_TEST(testGetSHA1HashStatic); - CPPUNIT_TEST(testGetSHA1HashStatic_Twice); - CPPUNIT_TEST(testGetSHA1HashStatic_NoData); + CPPUNIT_TEST(testGetSHA1Hash); + CPPUNIT_TEST(testGetSHA1Hash_TwoUpdates); + CPPUNIT_TEST(testGetSHA1Hash_NoData); + CPPUNIT_TEST(testGetSHA1HashStatic); + CPPUNIT_TEST(testGetSHA1HashStatic_Twice); + CPPUNIT_TEST(testGetSHA1HashStatic_NoData); - CPPUNIT_TEST(testGetMD5Hash_Empty); - CPPUNIT_TEST(testGetMD5Hash_Alphabet); - CPPUNIT_TEST(testMD5Incremental); + CPPUNIT_TEST(testGetMD5Hash_Empty); + CPPUNIT_TEST(testGetMD5Hash_Alphabet); + CPPUNIT_TEST(testMD5Incremental); - CPPUNIT_TEST(testGetHMACSHA1); - CPPUNIT_TEST(testGetHMACSHA1_KeyLongerThanBlockSize); - - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST(testGetHMACSHA1); + CPPUNIT_TEST(testGetHMACSHA1_KeyLongerThanBlockSize); - public: - void setUp() { - provider = new CryptoProviderType(); - } + CPPUNIT_TEST_SUITE_END(); - void tearDown() { - delete provider; - } + public: + void setUp() { + provider = new CryptoProviderType(); + } - //////////////////////////////////////////////////////////// - // SHA-1 - //////////////////////////////////////////////////////////// - - void testGetSHA1Hash() { - boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1()); - sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")); + void tearDown() { + delete provider; + } - CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash()); - } + //////////////////////////////////////////////////////////// + // SHA-1 + //////////////////////////////////////////////////////////// - void testGetSHA1Hash_TwoUpdates() { - boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1()); - sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<")); - sha->update(createByteArray("http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")); + void testGetSHA1Hash() { + boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1()); + sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash()); - } + CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash()); + } - void testGetSHA1Hash_NoData() { - boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1()); - sha->update(std::vector<unsigned char>()); + void testGetSHA1Hash_TwoUpdates() { + boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1()); + sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<")); + sha->update(createByteArray("http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")); - CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), sha->getHash()); - } + CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash()); + } - void testGetSHA1HashStatic() { - ByteArray result(provider->getSHA1Hash(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"))); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result); - } + void testGetSHA1Hash_NoData() { + boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1()); + sha->update(std::vector<unsigned char>()); + CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), sha->getHash()); + } - void testGetSHA1HashStatic_Twice() { - ByteArray input(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")); - provider->getSHA1Hash(input); - ByteArray result(provider->getSHA1Hash(input)); + void testGetSHA1HashStatic() { + ByteArray result(provider->getSHA1Hash(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"))); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result); + } - CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result); - } - void testGetSHA1HashStatic_NoData() { - ByteArray result(provider->getSHA1Hash(ByteArray())); + void testGetSHA1HashStatic_Twice() { + ByteArray input(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")); + provider->getSHA1Hash(input); + ByteArray result(provider->getSHA1Hash(input)); - CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), result); - } - - - //////////////////////////////////////////////////////////// - // MD5 - //////////////////////////////////////////////////////////// + CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result); + } - void testGetMD5Hash_Empty() { - ByteArray result(provider->getMD5Hash(createByteArray(""))); + void testGetSHA1HashStatic_NoData() { + ByteArray result(provider->getSHA1Hash(ByteArray())); - CPPUNIT_ASSERT_EQUAL(createByteArray("\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\x09\x98\xec\xf8\x42\x7e", 16), result); - } + CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), result); + } - void testGetMD5Hash_Alphabet() { - ByteArray result(provider->getMD5Hash(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))); - CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result); - } + //////////////////////////////////////////////////////////// + // MD5 + //////////////////////////////////////////////////////////// - void testMD5Incremental() { - boost::shared_ptr<Hash> testling = boost::shared_ptr<Hash>(provider->createMD5()); - testling->update(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); - testling->update(createByteArray("abcdefghijklmnopqrstuvwxyz0123456789")); + void testGetMD5Hash_Empty() { + ByteArray result(provider->getMD5Hash(createByteArray(""))); - ByteArray result = testling->getHash(); + CPPUNIT_ASSERT_EQUAL(createByteArray("\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\x09\x98\xec\xf8\x42\x7e", 16), result); + } - CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result); - } + void testGetMD5Hash_Alphabet() { + ByteArray result(provider->getMD5Hash(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))); + CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result); + } - //////////////////////////////////////////////////////////// - // HMAC-SHA1 - //////////////////////////////////////////////////////////// + void testMD5Incremental() { + boost::shared_ptr<Hash> testling = boost::shared_ptr<Hash>(provider->createMD5()); + testling->update(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + testling->update(createByteArray("abcdefghijklmnopqrstuvwxyz0123456789")); - void testGetHMACSHA1() { - ByteArray result(provider->getHMACSHA1(createSafeByteArray("foo"), createByteArray("foobar"))); - CPPUNIT_ASSERT_EQUAL(createByteArray("\xa4\xee\xba\x8e\x63\x3d\x77\x88\x69\xf5\x68\xd0\x5a\x1b\x3d\xc7\x2b\xfd\x4\xdd"), result); - } + ByteArray result = testling->getHash(); - void testGetHMACSHA1_KeyLongerThanBlockSize() { - ByteArray result(provider->getHMACSHA1(createSafeByteArray("---------|---------|---------|---------|---------|----------|---------|"), createByteArray("foobar"))); - CPPUNIT_ASSERT_EQUAL(createByteArray("\xd6""n""\x8f""P|1""\xd3"",""\x6"" ""\xb9\xe3""gg""\x8e\xcf"" ]+""\xa"), result); - } + CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result); + } - private: - CryptoProviderType* provider; + + //////////////////////////////////////////////////////////// + // HMAC-SHA1 + //////////////////////////////////////////////////////////// + + void testGetHMACSHA1() { + ByteArray result(provider->getHMACSHA1(createSafeByteArray("foo"), createByteArray("foobar"))); + CPPUNIT_ASSERT_EQUAL(createByteArray("\xa4\xee\xba\x8e\x63\x3d\x77\x88\x69\xf5\x68\xd0\x5a\x1b\x3d\xc7\x2b\xfd\x4\xdd"), result); + } + + void testGetHMACSHA1_KeyLongerThanBlockSize() { + ByteArray result(provider->getHMACSHA1(createSafeByteArray("---------|---------|---------|---------|---------|----------|---------|"), createByteArray("foobar"))); + CPPUNIT_ASSERT_EQUAL(createByteArray("\xd6""n""\x8f""P|1""\xd3"",""\x6"" ""\xb9\xe3""gg""\x8e\xcf"" ]+""\xa"), result); + } + + private: + CryptoProviderType* provider; }; #ifdef SWIFTEN_PLATFORM_WIN32 diff --git a/Swiften/Crypto/WindowsCryptoProvider.cpp b/Swiften/Crypto/WindowsCryptoProvider.cpp index db4b2bf..e0410c6 100644 --- a/Swiften/Crypto/WindowsCryptoProvider.cpp +++ b/Swiften/Crypto/WindowsCryptoProvider.cpp @@ -27,196 +27,196 @@ using namespace Swift; struct WindowsCryptoProvider::Private { - HCRYPTPROV context; + HCRYPTPROV context; }; namespace { - class WindowsHash : public Hash { - public: - WindowsHash(HCRYPTPROV context, ALG_ID algorithm) : hash(NULL) { - if (!CryptCreateHash(context, algorithm, 0, 0, &hash)) { - assert(false); - } - } - - virtual ~WindowsHash() { - CryptDestroyHash(hash); - } - - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual std::vector<unsigned char> getHash() { - std::vector<unsigned char> result; - DWORD hashLength = sizeof(DWORD); - DWORD hashSize; - CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0); - result.resize(static_cast<size_t>(hashSize)); - if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) { - assert(false); - } - result.resize(static_cast<size_t>(hashSize)); - return result; - } - - private: - template<typename ContainerType> - Hash& updateInternal(const ContainerType& data) { - if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) { - assert(false); - } - return *this; - } - - private: - HCRYPTHASH hash; - }; + class WindowsHash : public Hash { + public: + WindowsHash(HCRYPTPROV context, ALG_ID algorithm) : hash(NULL) { + if (!CryptCreateHash(context, algorithm, 0, 0, &hash)) { + assert(false); + } + } + + virtual ~WindowsHash() { + CryptDestroyHash(hash); + } + + virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual std::vector<unsigned char> getHash() { + std::vector<unsigned char> result; + DWORD hashLength = sizeof(DWORD); + DWORD hashSize; + CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0); + result.resize(static_cast<size_t>(hashSize)); + if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) { + assert(false); + } + result.resize(static_cast<size_t>(hashSize)); + return result; + } + + private: + template<typename ContainerType> + Hash& updateInternal(const ContainerType& data) { + if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) { + assert(false); + } + return *this; + } + + private: + HCRYPTHASH hash; + }; #if 0 // NOT YET DONE - // Haven't tested the code below properly yet, but figured out after writing - // it that PLAINTEXTKEYBLOB doesn't work on XP or 2k, and the workaround is a - // bit too ugly to try this now. So, using our own algorithm for now. See - // http://support.microsoft.com/kb/228786/en-us - - // MSDN describes this as PLAINTEXTKEYBLOB, but this struct doesn't exist, - // and seems to even conflict with the PLAINTEXTKEYBLOB constant. Redefining - // here. - struct PlainTextKeyBlob { - BLOBHEADER hdr; - DWORD dwKeySize; - }; - - class HMACHash : public Hash { - public: - template<typename T> - HMACHash(HCRYPTPROV context, const T& rawKey) : hash(NULL) { - // Import raw key - T blobData(sizeof(PlainTextKeyBlob) + rawKey.size()); - PlainTextKeyBlob* blob = reinterpret_cast<PlainTextKeyBlob*>(vecptr(blobData)); - blob->hdr.bType = PLAINTEXTKEYBLOB; - blob->hdr.bVersion = CUR_BLOB_VERSION; - blob->hdr.reserved = 0; - blob->hdr.aiKeyAlg = CALG_RC2; - blob->dwKeySize = rawKey.size(); - std::copy(rawKey.begin(), rawKey.end(), blobData.begin() + sizeof(PlainTextKeyBlob)); - HCRYPTKEY key; - if (!CryptImportKey(context, vecptr(blobData), blobData.size(), 0, CRYPT_IPSEC_HMAC_KEY, &key)) { - assert(false); - return; - } - - // Create hash - if (!CryptCreateHash(context, CALG_HMAC, key, 0, &hash)) { - assert(false); - return; - } - ZeroMemory(&info, sizeof(info)); - info.HashAlgid = CALG_SHA1; - } - - ~HMACHash() { - CryptDestroyHash(hash); - } - - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { - return updateInternal(data); - } - - virtual std::vector<unsigned char> getHash() { - std::vector<unsigned char> result; - DWORD hashLength = sizeof(DWORD); - DWORD hashSize; - CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0); - result.resize(static_cast<size_t>(hashSize)); - if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) { - assert(false); - } - result.resize(static_cast<size_t>(hashSize)); - return result; - } - - private: - template<typename ContainerType> - Hash& updateInternal(const ContainerType& data) { - if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) { - assert(false); - } - return *this; - } - - private: - HCRYPTHASH hash; - HMAC_INFO info; - }; + // Haven't tested the code below properly yet, but figured out after writing + // it that PLAINTEXTKEYBLOB doesn't work on XP or 2k, and the workaround is a + // bit too ugly to try this now. So, using our own algorithm for now. See + // http://support.microsoft.com/kb/228786/en-us + + // MSDN describes this as PLAINTEXTKEYBLOB, but this struct doesn't exist, + // and seems to even conflict with the PLAINTEXTKEYBLOB constant. Redefining + // here. + struct PlainTextKeyBlob { + BLOBHEADER hdr; + DWORD dwKeySize; + }; + + class HMACHash : public Hash { + public: + template<typename T> + HMACHash(HCRYPTPROV context, const T& rawKey) : hash(NULL) { + // Import raw key + T blobData(sizeof(PlainTextKeyBlob) + rawKey.size()); + PlainTextKeyBlob* blob = reinterpret_cast<PlainTextKeyBlob*>(vecptr(blobData)); + blob->hdr.bType = PLAINTEXTKEYBLOB; + blob->hdr.bVersion = CUR_BLOB_VERSION; + blob->hdr.reserved = 0; + blob->hdr.aiKeyAlg = CALG_RC2; + blob->dwKeySize = rawKey.size(); + std::copy(rawKey.begin(), rawKey.end(), blobData.begin() + sizeof(PlainTextKeyBlob)); + HCRYPTKEY key; + if (!CryptImportKey(context, vecptr(blobData), blobData.size(), 0, CRYPT_IPSEC_HMAC_KEY, &key)) { + assert(false); + return; + } + + // Create hash + if (!CryptCreateHash(context, CALG_HMAC, key, 0, &hash)) { + assert(false); + return; + } + ZeroMemory(&info, sizeof(info)); + info.HashAlgid = CALG_SHA1; + } + + ~HMACHash() { + CryptDestroyHash(hash); + } + + virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + return updateInternal(data); + } + + virtual std::vector<unsigned char> getHash() { + std::vector<unsigned char> result; + DWORD hashLength = sizeof(DWORD); + DWORD hashSize; + CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0); + result.resize(static_cast<size_t>(hashSize)); + if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) { + assert(false); + } + result.resize(static_cast<size_t>(hashSize)); + return result; + } + + private: + template<typename ContainerType> + Hash& updateInternal(const ContainerType& data) { + if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) { + assert(false); + } + return *this; + } + + private: + HCRYPTHASH hash; + HMAC_INFO info; + }; #endif - // Simple implementation. - template<typename T> - ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data, CryptoProvider* crypto) { - static const int BLOCK_SIZE = 64; - - T paddedKey; - if (key.size() <= BLOCK_SIZE) { - paddedKey = key; - } - else { - assign(paddedKey, crypto->getSHA1Hash(key)); - } - paddedKey.resize(BLOCK_SIZE, 0x0); - - // Create the first value - T x(paddedKey); - for (unsigned int i = 0; i < x.size(); ++i) { - x[i] ^= 0x36; - } - append(x, data); - - // Create the second value - T y(paddedKey); - for (unsigned int i = 0; i < y.size(); ++i) { - y[i] ^= 0x5c; - } - append(y, crypto->getSHA1Hash(x)); - return crypto->getSHA1Hash(y); - } + // Simple implementation. + template<typename T> + ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data, CryptoProvider* crypto) { + static const int BLOCK_SIZE = 64; + + T paddedKey; + if (key.size() <= BLOCK_SIZE) { + paddedKey = key; + } + else { + assign(paddedKey, crypto->getSHA1Hash(key)); + } + paddedKey.resize(BLOCK_SIZE, 0x0); + + // Create the first value + T x(paddedKey); + for (unsigned int i = 0; i < x.size(); ++i) { + x[i] ^= 0x36; + } + append(x, data); + + // Create the second value + T y(paddedKey); + for (unsigned int i = 0; i < y.size(); ++i) { + y[i] ^= 0x5c; + } + append(y, crypto->getSHA1Hash(x)); + return crypto->getSHA1Hash(y); + } } WindowsCryptoProvider::WindowsCryptoProvider() { - p = boost::make_shared<Private>(); - if (!CryptAcquireContext(&p->context, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { - assert(false); - } + p = boost::make_shared<Private>(); + if (!CryptAcquireContext(&p->context, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { + assert(false); + } } WindowsCryptoProvider::~WindowsCryptoProvider() { - CryptReleaseContext(p->context, 0); + CryptReleaseContext(p->context, 0); } Hash* WindowsCryptoProvider::createSHA1() { - return new WindowsHash(p->context, CALG_SHA1); + return new WindowsHash(p->context, CALG_SHA1); } Hash* WindowsCryptoProvider::createMD5() { - return new WindowsHash(p->context, CALG_MD5); + return new WindowsHash(p->context, CALG_MD5); } bool WindowsCryptoProvider::isMD5AllowedForCrypto() const { - return !WindowsRegistry::isFIPSEnabled(); + return !WindowsRegistry::isFIPSEnabled(); } ByteArray WindowsCryptoProvider::getHMACSHA1(const SafeByteArray& key, const ByteArray& data) { - return getHMACSHA1Internal(key, data, this); + return getHMACSHA1Internal(key, data, this); } ByteArray WindowsCryptoProvider::getHMACSHA1(const ByteArray& key, const ByteArray& data) { - return getHMACSHA1Internal(key, data, this); + return getHMACSHA1Internal(key, data, this); } diff --git a/Swiften/Crypto/WindowsCryptoProvider.h b/Swiften/Crypto/WindowsCryptoProvider.h index b3f6f29..4c998d2 100644 --- a/Swiften/Crypto/WindowsCryptoProvider.h +++ b/Swiften/Crypto/WindowsCryptoProvider.h @@ -13,19 +13,19 @@ #include <Swiften/Crypto/CryptoProvider.h> namespace Swift { - class WindowsCryptoProvider : public CryptoProvider, public boost::noncopyable { - public: - WindowsCryptoProvider(); - virtual ~WindowsCryptoProvider(); + class WindowsCryptoProvider : public CryptoProvider, public boost::noncopyable { + public: + WindowsCryptoProvider(); + virtual ~WindowsCryptoProvider(); - virtual Hash* createSHA1() SWIFTEN_OVERRIDE; - virtual Hash* createMD5() SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; + virtual Hash* createSHA1() SWIFTEN_OVERRIDE; + virtual Hash* createMD5() SWIFTEN_OVERRIDE; + virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; + virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; + virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; - private: - struct Private; - boost::shared_ptr<Private> p; - }; + private: + struct Private; + boost::shared_ptr<Private> p; + }; } diff --git a/Swiften/Disco/CapsInfoGenerator.cpp b/Swiften/Disco/CapsInfoGenerator.cpp index 1b07c43..b4637c7 100644 --- a/Swiften/Disco/CapsInfoGenerator.cpp +++ b/Swiften/Disco/CapsInfoGenerator.cpp @@ -15,9 +15,9 @@ #include <Swiften/StringCodecs/Base64.h> namespace { - bool compareFields(Swift::FormField::ref f1, Swift::FormField::ref f2) { - return f1->getName() < f2->getName(); - } + bool compareFields(Swift::FormField::ref f1, Swift::FormField::ref f2) { + return f1->getName() < f2->getName(); + } } namespace Swift { @@ -26,39 +26,39 @@ CapsInfoGenerator::CapsInfoGenerator(const std::string& node, CryptoProvider* cr } CapsInfo CapsInfoGenerator::generateCapsInfo(const DiscoInfo& discoInfo) const { - std::string serializedCaps; + std::string serializedCaps; - std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities()); - std::sort(identities.begin(), identities.end()); - foreach (const DiscoInfo::Identity& identity, identities) { - serializedCaps += identity.getCategory() + "/" + identity.getType() + "/" + identity.getLanguage() + "/" + identity.getName() + "<"; - } + std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities()); + std::sort(identities.begin(), identities.end()); + foreach (const DiscoInfo::Identity& identity, identities) { + serializedCaps += identity.getCategory() + "/" + identity.getType() + "/" + identity.getLanguage() + "/" + identity.getName() + "<"; + } - std::vector<std::string> features(discoInfo.getFeatures()); - std::sort(features.begin(), features.end()); - foreach (const std::string& feature, features) { - serializedCaps += feature + "<"; - } + std::vector<std::string> features(discoInfo.getFeatures()); + std::sort(features.begin(), features.end()); + foreach (const std::string& feature, features) { + serializedCaps += feature + "<"; + } - foreach(Form::ref extension, discoInfo.getExtensions()) { - serializedCaps += extension->getFormType() + "<"; - std::vector<FormField::ref> fields(extension->getFields()); - std::sort(fields.begin(), fields.end(), &compareFields); - foreach(FormField::ref field, fields) { - if (field->getName() == "FORM_TYPE") { - continue; - } - serializedCaps += field->getName() + "<"; - std::vector<std::string> values(field->getValues()); - std::sort(values.begin(), values.end()); - foreach(const std::string& value, values) { - serializedCaps += value + "<"; - } - } - } + foreach(Form::ref extension, discoInfo.getExtensions()) { + serializedCaps += extension->getFormType() + "<"; + std::vector<FormField::ref> fields(extension->getFields()); + std::sort(fields.begin(), fields.end(), &compareFields); + foreach(FormField::ref field, fields) { + if (field->getName() == "FORM_TYPE") { + continue; + } + serializedCaps += field->getName() + "<"; + std::vector<std::string> values(field->getValues()); + std::sort(values.begin(), values.end()); + foreach(const std::string& value, values) { + serializedCaps += value + "<"; + } + } + } - std::string version(Base64::encode(crypto_->getSHA1Hash(createByteArray(serializedCaps)))); - return CapsInfo(node_, version, "sha-1"); + std::string version(Base64::encode(crypto_->getSHA1Hash(createByteArray(serializedCaps)))); + return CapsInfo(node_, version, "sha-1"); } } diff --git a/Swiften/Disco/CapsInfoGenerator.h b/Swiften/Disco/CapsInfoGenerator.h index b964816..ed1b1bd 100644 --- a/Swiften/Disco/CapsInfoGenerator.h +++ b/Swiften/Disco/CapsInfoGenerator.h @@ -12,17 +12,17 @@ #include <Swiften/Elements/CapsInfo.h> namespace Swift { - class DiscoInfo; - class CryptoProvider; + class DiscoInfo; + class CryptoProvider; - class SWIFTEN_API CapsInfoGenerator { - public: - CapsInfoGenerator(const std::string& node, CryptoProvider* crypto); + class SWIFTEN_API CapsInfoGenerator { + public: + CapsInfoGenerator(const std::string& node, CryptoProvider* crypto); - CapsInfo generateCapsInfo(const DiscoInfo& discoInfo) const; + CapsInfo generateCapsInfo(const DiscoInfo& discoInfo) const; - private: - std::string node_; - CryptoProvider* crypto_; - }; + private: + std::string node_; + CryptoProvider* crypto_; + }; } diff --git a/Swiften/Disco/CapsManager.cpp b/Swiften/Disco/CapsManager.cpp index 5616f0a..139ee6c 100644 --- a/Swiften/Disco/CapsManager.cpp +++ b/Swiften/Disco/CapsManager.cpp @@ -19,66 +19,66 @@ namespace Swift { CapsManager::CapsManager(CapsStorage* capsStorage, StanzaChannel* stanzaChannel, IQRouter* iqRouter, CryptoProvider* crypto) : iqRouter(iqRouter), crypto(crypto), capsStorage(capsStorage), warnOnInvalidHash(true) { - stanzaChannel->onPresenceReceived.connect(boost::bind(&CapsManager::handlePresenceReceived, this, _1)); - stanzaChannel->onAvailableChanged.connect(boost::bind(&CapsManager::handleStanzaChannelAvailableChanged, this, _1)); + stanzaChannel->onPresenceReceived.connect(boost::bind(&CapsManager::handlePresenceReceived, this, _1)); + stanzaChannel->onAvailableChanged.connect(boost::bind(&CapsManager::handleStanzaChannelAvailableChanged, this, _1)); } void CapsManager::handlePresenceReceived(boost::shared_ptr<Presence> presence) { - boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>(); - if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) { - return; - } - std::string hash = capsInfo->getVersion(); - if (capsStorage->getDiscoInfo(hash)) { - return; - } - if (failingCaps.find(std::make_pair(presence->getFrom(), hash)) != failingCaps.end()) { - return; - } - if (requestedDiscoInfos.find(hash) != requestedDiscoInfos.end()) { - fallbacks[hash].insert(std::make_pair(presence->getFrom(), capsInfo->getNode())); - return; - } - requestDiscoInfo(presence->getFrom(), capsInfo->getNode(), hash); + boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>(); + if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) { + return; + } + std::string hash = capsInfo->getVersion(); + if (capsStorage->getDiscoInfo(hash)) { + return; + } + if (failingCaps.find(std::make_pair(presence->getFrom(), hash)) != failingCaps.end()) { + return; + } + if (requestedDiscoInfos.find(hash) != requestedDiscoInfos.end()) { + fallbacks[hash].insert(std::make_pair(presence->getFrom(), capsInfo->getNode())); + return; + } + requestDiscoInfo(presence->getFrom(), capsInfo->getNode(), hash); } void CapsManager::handleStanzaChannelAvailableChanged(bool available) { - if (available) { - failingCaps.clear(); - fallbacks.clear(); - requestedDiscoInfos.clear(); - } + if (available) { + failingCaps.clear(); + fallbacks.clear(); + requestedDiscoInfos.clear(); + } } void CapsManager::handleDiscoInfoReceived(const JID& from, const std::string& hash, DiscoInfo::ref discoInfo, ErrorPayload::ref error) { - requestedDiscoInfos.erase(hash); - if (error || !discoInfo || CapsInfoGenerator("", crypto).generateCapsInfo(*discoInfo.get()).getVersion() != hash) { - if (warnOnInvalidHash && !error && discoInfo) { - std::cerr << "Warning: Caps from " << from.toString() << " do not verify" << std::endl; - } - failingCaps.insert(std::make_pair(from, hash)); - std::map<std::string, std::set< std::pair<JID, std::string> > >::iterator i = fallbacks.find(hash); - if (i != fallbacks.end() && !i->second.empty()) { - std::pair<JID,std::string> fallbackAndNode = *i->second.begin(); - i->second.erase(i->second.begin()); - requestDiscoInfo(fallbackAndNode.first, fallbackAndNode.second, hash); - } - return; - } - fallbacks.erase(hash); - capsStorage->setDiscoInfo(hash, discoInfo); - onCapsAvailable(hash); + requestedDiscoInfos.erase(hash); + if (error || !discoInfo || CapsInfoGenerator("", crypto).generateCapsInfo(*discoInfo.get()).getVersion() != hash) { + if (warnOnInvalidHash && !error && discoInfo) { + std::cerr << "Warning: Caps from " << from.toString() << " do not verify" << std::endl; + } + failingCaps.insert(std::make_pair(from, hash)); + std::map<std::string, std::set< std::pair<JID, std::string> > >::iterator i = fallbacks.find(hash); + if (i != fallbacks.end() && !i->second.empty()) { + std::pair<JID,std::string> fallbackAndNode = *i->second.begin(); + i->second.erase(i->second.begin()); + requestDiscoInfo(fallbackAndNode.first, fallbackAndNode.second, hash); + } + return; + } + fallbacks.erase(hash); + capsStorage->setDiscoInfo(hash, discoInfo); + onCapsAvailable(hash); } void CapsManager::requestDiscoInfo(const JID& jid, const std::string& node, const std::string& hash) { - GetDiscoInfoRequest::ref request = GetDiscoInfoRequest::create(jid, node + "#" + hash, iqRouter); - request->onResponse.connect(boost::bind(&CapsManager::handleDiscoInfoReceived, this, jid, hash, _1, _2)); - requestedDiscoInfos.insert(hash); - request->send(); + GetDiscoInfoRequest::ref request = GetDiscoInfoRequest::create(jid, node + "#" + hash, iqRouter); + request->onResponse.connect(boost::bind(&CapsManager::handleDiscoInfoReceived, this, jid, hash, _1, _2)); + requestedDiscoInfos.insert(hash); + request->send(); } DiscoInfo::ref CapsManager::getCaps(const std::string& hash) const { - return capsStorage->getDiscoInfo(hash); + return capsStorage->getDiscoInfo(hash); } diff --git a/Swiften/Disco/CapsManager.h b/Swiften/Disco/CapsManager.h index 77e736d..c96db13 100644 --- a/Swiften/Disco/CapsManager.h +++ b/Swiften/Disco/CapsManager.h @@ -18,36 +18,36 @@ #include <Swiften/Elements/Presence.h> namespace Swift { - class StanzaChannel; - class IQRouter; - class JID; - class CapsStorage; - class CryptoProvider; - - class SWIFTEN_API CapsManager : public CapsProvider, public boost::bsignals::trackable { - public: - CapsManager(CapsStorage*, StanzaChannel*, IQRouter*, CryptoProvider*); - - DiscoInfo::ref getCaps(const std::string&) const; - - // Mainly for testing purposes - void setWarnOnInvalidHash(bool b) { - warnOnInvalidHash = b; - } - - private: - void handlePresenceReceived(boost::shared_ptr<Presence>); - void handleStanzaChannelAvailableChanged(bool); - void handleDiscoInfoReceived(const JID&, const std::string& hash, DiscoInfo::ref, ErrorPayload::ref); - void requestDiscoInfo(const JID& jid, const std::string& node, const std::string& hash); - - private: - IQRouter* iqRouter; - CryptoProvider* crypto; - CapsStorage* capsStorage; - bool warnOnInvalidHash; - std::set<std::string> requestedDiscoInfos; - std::set< std::pair<JID, std::string> > failingCaps; - std::map<std::string, std::set< std::pair<JID, std::string> > > fallbacks; - }; + class StanzaChannel; + class IQRouter; + class JID; + class CapsStorage; + class CryptoProvider; + + class SWIFTEN_API CapsManager : public CapsProvider, public boost::bsignals::trackable { + public: + CapsManager(CapsStorage*, StanzaChannel*, IQRouter*, CryptoProvider*); + + DiscoInfo::ref getCaps(const std::string&) const; + + // Mainly for testing purposes + void setWarnOnInvalidHash(bool b) { + warnOnInvalidHash = b; + } + + private: + void handlePresenceReceived(boost::shared_ptr<Presence>); + void handleStanzaChannelAvailableChanged(bool); + void handleDiscoInfoReceived(const JID&, const std::string& hash, DiscoInfo::ref, ErrorPayload::ref); + void requestDiscoInfo(const JID& jid, const std::string& node, const std::string& hash); + + private: + IQRouter* iqRouter; + CryptoProvider* crypto; + CapsStorage* capsStorage; + bool warnOnInvalidHash; + std::set<std::string> requestedDiscoInfos; + std::set< std::pair<JID, std::string> > failingCaps; + std::map<std::string, std::set< std::pair<JID, std::string> > > fallbacks; + }; } diff --git a/Swiften/Disco/CapsMemoryStorage.h b/Swiften/Disco/CapsMemoryStorage.h index e635ea1..39559ec 100644 --- a/Swiften/Disco/CapsMemoryStorage.h +++ b/Swiften/Disco/CapsMemoryStorage.h @@ -15,26 +15,26 @@ #include <Swiften/Disco/CapsStorage.h> namespace Swift { - class SWIFTEN_API CapsMemoryStorage : public CapsStorage { - public: - CapsMemoryStorage() {} - - virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const { - CapsMap::const_iterator i = caps.find(hash); - if (i != caps.end()) { - return i->second; - } - else { - return DiscoInfo::ref(); - } - } - - virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo) { - caps[hash] = discoInfo; - } - - private: - typedef std::map<std::string, DiscoInfo::ref> CapsMap; - CapsMap caps; - }; + class SWIFTEN_API CapsMemoryStorage : public CapsStorage { + public: + CapsMemoryStorage() {} + + virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const { + CapsMap::const_iterator i = caps.find(hash); + if (i != caps.end()) { + return i->second; + } + else { + return DiscoInfo::ref(); + } + } + + virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo) { + caps[hash] = discoInfo; + } + + private: + typedef std::map<std::string, DiscoInfo::ref> CapsMap; + CapsMap caps; + }; } diff --git a/Swiften/Disco/CapsProvider.h b/Swiften/Disco/CapsProvider.h index 0f7e49d..9cba027 100644 --- a/Swiften/Disco/CapsProvider.h +++ b/Swiften/Disco/CapsProvider.h @@ -12,14 +12,14 @@ #include <Swiften/Elements/DiscoInfo.h> namespace Swift { - - class SWIFTEN_API CapsProvider { - public: - virtual ~CapsProvider() {} - virtual DiscoInfo::ref getCaps(const std::string&) const = 0; + class SWIFTEN_API CapsProvider { + public: + virtual ~CapsProvider() {} - boost::signal<void (const std::string&)> onCapsAvailable; - }; + virtual DiscoInfo::ref getCaps(const std::string&) const = 0; + + boost::signal<void (const std::string&)> onCapsAvailable; + }; } diff --git a/Swiften/Disco/CapsStorage.h b/Swiften/Disco/CapsStorage.h index 61c508b..5459ecf 100644 --- a/Swiften/Disco/CapsStorage.h +++ b/Swiften/Disco/CapsStorage.h @@ -12,11 +12,11 @@ #include <Swiften/Elements/DiscoInfo.h> namespace Swift { - class SWIFTEN_API CapsStorage { - public: - virtual ~CapsStorage(); + class SWIFTEN_API CapsStorage { + public: + virtual ~CapsStorage(); - virtual DiscoInfo::ref getDiscoInfo(const std::string&) const = 0; - virtual void setDiscoInfo(const std::string&, DiscoInfo::ref) = 0; - }; + virtual DiscoInfo::ref getDiscoInfo(const std::string&) const = 0; + virtual void setDiscoInfo(const std::string&, DiscoInfo::ref) = 0; + }; } diff --git a/Swiften/Disco/ClientDiscoManager.cpp b/Swiften/Disco/ClientDiscoManager.cpp index 0b6eccf..8c90d2d 100644 --- a/Swiften/Disco/ClientDiscoManager.cpp +++ b/Swiften/Disco/ClientDiscoManager.cpp @@ -13,31 +13,31 @@ namespace Swift { ClientDiscoManager::ClientDiscoManager(IQRouter* iqRouter, PresenceSender* presenceSender, CryptoProvider* crypto) : crypto(crypto) { - discoInfoResponder = new DiscoInfoResponder(iqRouter); - discoInfoResponder->start(); - this->presenceSender = new PayloadAddingPresenceSender(presenceSender); + discoInfoResponder = new DiscoInfoResponder(iqRouter); + discoInfoResponder->start(); + this->presenceSender = new PayloadAddingPresenceSender(presenceSender); } ClientDiscoManager::~ClientDiscoManager() { - delete presenceSender; - discoInfoResponder->stop(); - delete discoInfoResponder; + delete presenceSender; + discoInfoResponder->stop(); + delete discoInfoResponder; } void ClientDiscoManager::setCapsNode(const std::string& node) { - capsNode = node; + capsNode = node; } void ClientDiscoManager::setDiscoInfo(const DiscoInfo& discoInfo) { - capsInfo = CapsInfo::ref(new CapsInfo(CapsInfoGenerator(capsNode, crypto).generateCapsInfo(discoInfo))); - discoInfoResponder->clearDiscoInfo(); - discoInfoResponder->setDiscoInfo(discoInfo); - discoInfoResponder->setDiscoInfo(capsInfo->getNode() + "#" + capsInfo->getVersion(), discoInfo); - presenceSender->setPayload(capsInfo); + capsInfo = CapsInfo::ref(new CapsInfo(CapsInfoGenerator(capsNode, crypto).generateCapsInfo(discoInfo))); + discoInfoResponder->clearDiscoInfo(); + discoInfoResponder->setDiscoInfo(discoInfo); + discoInfoResponder->setDiscoInfo(capsInfo->getNode() + "#" + capsInfo->getVersion(), discoInfo); + presenceSender->setPayload(capsInfo); } void ClientDiscoManager::handleConnected() { - presenceSender->reset(); + presenceSender->reset(); } } diff --git a/Swiften/Disco/ClientDiscoManager.h b/Swiften/Disco/ClientDiscoManager.h index 560c69a..fe68dd7 100644 --- a/Swiften/Disco/ClientDiscoManager.h +++ b/Swiften/Disco/ClientDiscoManager.h @@ -12,66 +12,66 @@ #include <Swiften/Presence/PayloadAddingPresenceSender.h> namespace Swift { - class IQRouter; - class DiscoInfoResponder; - class PayloadAddingPresenceSender; - class PresenceSender; - class CryptoProvider; + class IQRouter; + class DiscoInfoResponder; + class PayloadAddingPresenceSender; + class PresenceSender; + class CryptoProvider; - /** - * Class responsible for managing outgoing disco information for a client. - * - * The manager will respond to disco#info requests, and add entity capabilities information - * to outgoing presence. - * - * To use this class, call setCapsNode() once with the caps URI of the client. After this, - * call setDiscoInfo() with the capabilities for the client. This can be - * called whenever the capabilities change. - */ - class SWIFTEN_API ClientDiscoManager { - public: - /** - * Constructs the manager - * - * \param iqRouter the router on which requests will be answered - * \param presenceSender the presence sender to which all outgoing presence - * (with caps information) will be sent. - */ - ClientDiscoManager(IQRouter* iqRouter, PresenceSender* presenceSender, CryptoProvider* crypto); - ~ClientDiscoManager(); + /** + * Class responsible for managing outgoing disco information for a client. + * + * The manager will respond to disco#info requests, and add entity capabilities information + * to outgoing presence. + * + * To use this class, call setCapsNode() once with the caps URI of the client. After this, + * call setDiscoInfo() with the capabilities for the client. This can be + * called whenever the capabilities change. + */ + class SWIFTEN_API ClientDiscoManager { + public: + /** + * Constructs the manager + * + * \param iqRouter the router on which requests will be answered + * \param presenceSender the presence sender to which all outgoing presence + * (with caps information) will be sent. + */ + ClientDiscoManager(IQRouter* iqRouter, PresenceSender* presenceSender, CryptoProvider* crypto); + ~ClientDiscoManager(); - /** - * Needs to be called before calling setDiscoInfo(). - */ - void setCapsNode(const std::string& node); + /** + * Needs to be called before calling setDiscoInfo(). + */ + void setCapsNode(const std::string& node); - /** - * Sets the capabilities of the client. - */ - void setDiscoInfo(const DiscoInfo& info); + /** + * Sets the capabilities of the client. + */ + void setDiscoInfo(const DiscoInfo& info); - /** - * Returns the presence sender through which all outgoing presence - * should be sent. - * The manager will add the necessary caps information, and forward it to - * the presence sender passed at construction time. - */ - PresenceSender* getPresenceSender() const { - return presenceSender; - } + /** + * Returns the presence sender through which all outgoing presence + * should be sent. + * The manager will add the necessary caps information, and forward it to + * the presence sender passed at construction time. + */ + PresenceSender* getPresenceSender() const { + return presenceSender; + } - /** - * Called when the client is connected. - * This resets the presence sender, such that it assumes initial presence - * hasn't been sent yet. - */ - void handleConnected(); + /** + * Called when the client is connected. + * This resets the presence sender, such that it assumes initial presence + * hasn't been sent yet. + */ + void handleConnected(); - private: - PayloadAddingPresenceSender* presenceSender; - CryptoProvider* crypto; - DiscoInfoResponder* discoInfoResponder; - std::string capsNode; - CapsInfo::ref capsInfo; - }; + private: + PayloadAddingPresenceSender* presenceSender; + CryptoProvider* crypto; + DiscoInfoResponder* discoInfoResponder; + std::string capsNode; + CapsInfo::ref capsInfo; + }; } diff --git a/Swiften/Disco/DiscoInfoResponder.cpp b/Swiften/Disco/DiscoInfoResponder.cpp index bb3937a..cf18f43 100644 --- a/Swiften/Disco/DiscoInfoResponder.cpp +++ b/Swiften/Disco/DiscoInfoResponder.cpp @@ -17,34 +17,34 @@ DiscoInfoResponder::DiscoInfoResponder(IQRouter* router) : GetResponder<DiscoInf } void DiscoInfoResponder::clearDiscoInfo() { - info_ = DiscoInfo(); - nodeInfo_.clear(); + info_ = DiscoInfo(); + nodeInfo_.clear(); } void DiscoInfoResponder::setDiscoInfo(const DiscoInfo& info) { - info_ = info; + info_ = info; } void DiscoInfoResponder::setDiscoInfo(const std::string& node, const DiscoInfo& info) { - DiscoInfo newInfo(info); - newInfo.setNode(node); - nodeInfo_[node] = newInfo; + DiscoInfo newInfo(info); + newInfo.setNode(node); + nodeInfo_[node] = newInfo; } bool DiscoInfoResponder::handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<DiscoInfo> info) { - if (info->getNode().empty()) { - sendResponse(from, id, boost::make_shared<DiscoInfo>(info_)); - } - else { - std::map<std::string,DiscoInfo>::const_iterator i = nodeInfo_.find(info->getNode()); - if (i != nodeInfo_.end()) { - sendResponse(from, id, boost::make_shared<DiscoInfo>((*i).second)); - } - else { - sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); - } - } - return true; + if (info->getNode().empty()) { + sendResponse(from, id, boost::make_shared<DiscoInfo>(info_)); + } + else { + std::map<std::string,DiscoInfo>::const_iterator i = nodeInfo_.find(info->getNode()); + if (i != nodeInfo_.end()) { + sendResponse(from, id, boost::make_shared<DiscoInfo>((*i).second)); + } + else { + sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); + } + } + return true; } } diff --git a/Swiften/Disco/DiscoInfoResponder.h b/Swiften/Disco/DiscoInfoResponder.h index 92d337b..0781173 100644 --- a/Swiften/Disco/DiscoInfoResponder.h +++ b/Swiften/Disco/DiscoInfoResponder.h @@ -13,21 +13,21 @@ #include <Swiften/Queries/GetResponder.h> namespace Swift { - class IQRouter; + class IQRouter; - class SWIFTEN_API DiscoInfoResponder : public GetResponder<DiscoInfo> { - public: - DiscoInfoResponder(IQRouter* router); + class SWIFTEN_API DiscoInfoResponder : public GetResponder<DiscoInfo> { + public: + DiscoInfoResponder(IQRouter* router); - void clearDiscoInfo(); - void setDiscoInfo(const DiscoInfo& info); - void setDiscoInfo(const std::string& node, const DiscoInfo& info); + void clearDiscoInfo(); + void setDiscoInfo(const DiscoInfo& info); + void setDiscoInfo(const std::string& node, const DiscoInfo& info); - private: - virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload); + private: + virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload); - private: - DiscoInfo info_; - std::map<std::string, DiscoInfo> nodeInfo_; - }; + private: + DiscoInfo info_; + std::map<std::string, DiscoInfo> nodeInfo_; + }; } diff --git a/Swiften/Disco/DiscoServiceWalker.cpp b/Swiften/Disco/DiscoServiceWalker.cpp index 5803602..19170ce 100644 --- a/Swiften/Disco/DiscoServiceWalker.cpp +++ b/Swiften/Disco/DiscoServiceWalker.cpp @@ -18,118 +18,118 @@ DiscoServiceWalker::DiscoServiceWalker(const JID& service, IQRouter* iqRouter, s } void DiscoServiceWalker::beginWalk() { - SWIFT_LOG(debug) << "Starting walk to " << service_ << std::endl; - assert(!active_); - assert(servicesBeingSearched_.empty()); - active_ = true; - walkNode(service_); + SWIFT_LOG(debug) << "Starting walk to " << service_ << std::endl; + assert(!active_); + assert(servicesBeingSearched_.empty()); + active_ = true; + walkNode(service_); } void DiscoServiceWalker::endWalk() { - if (active_) { - SWIFT_LOG(debug) << "Ending walk to " << service_ << std::endl; - foreach (GetDiscoInfoRequest::ref request, pendingDiscoInfoRequests_) { - request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request)); - } - foreach (GetDiscoItemsRequest::ref request, pendingDiscoItemsRequests_) { - request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request)); - } - active_ = false; - onWalkAborted(); - } + if (active_) { + SWIFT_LOG(debug) << "Ending walk to " << service_ << std::endl; + foreach (GetDiscoInfoRequest::ref request, pendingDiscoInfoRequests_) { + request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request)); + } + foreach (GetDiscoItemsRequest::ref request, pendingDiscoItemsRequests_) { + request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request)); + } + active_ = false; + onWalkAborted(); + } } void DiscoServiceWalker::walkNode(const JID& jid) { - SWIFT_LOG(debug) << "Walking node " << jid << std::endl; - servicesBeingSearched_.insert(jid); - searchedServices_.insert(jid); - GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(jid, iqRouter_); - discoInfoRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, discoInfoRequest)); - pendingDiscoInfoRequests_.insert(discoInfoRequest); - discoInfoRequest->send(); + SWIFT_LOG(debug) << "Walking node " << jid << std::endl; + servicesBeingSearched_.insert(jid); + searchedServices_.insert(jid); + GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(jid, iqRouter_); + discoInfoRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, discoInfoRequest)); + pendingDiscoInfoRequests_.insert(discoInfoRequest); + discoInfoRequest->send(); } void DiscoServiceWalker::handleDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request) { - /* If we got canceled, don't do anything */ - if (!active_) { - return; - } - - SWIFT_LOG(debug) << "Disco info response from " << request->getReceiver() << std::endl; - - request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request)); - pendingDiscoInfoRequests_.erase(request); - if (error) { - handleDiscoError(request->getReceiver(), error); - return; - } - - bool couldContainServices = false; - foreach (DiscoInfo::Identity identity, info->getIdentities()) { - if (identity.getCategory() == "server") { - couldContainServices = true; - } - } - bool completed = false; - if (couldContainServices) { - GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(request->getReceiver(), iqRouter_); - discoItemsRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, discoItemsRequest)); - pendingDiscoItemsRequests_.insert(discoItemsRequest); - discoItemsRequest->send(); - } else { - completed = true; - } - onServiceFound(request->getReceiver(), info); - if (completed) { - markNodeCompleted(request->getReceiver()); - } + /* If we got canceled, don't do anything */ + if (!active_) { + return; + } + + SWIFT_LOG(debug) << "Disco info response from " << request->getReceiver() << std::endl; + + request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request)); + pendingDiscoInfoRequests_.erase(request); + if (error) { + handleDiscoError(request->getReceiver(), error); + return; + } + + bool couldContainServices = false; + foreach (DiscoInfo::Identity identity, info->getIdentities()) { + if (identity.getCategory() == "server") { + couldContainServices = true; + } + } + bool completed = false; + if (couldContainServices) { + GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(request->getReceiver(), iqRouter_); + discoItemsRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, discoItemsRequest)); + pendingDiscoItemsRequests_.insert(discoItemsRequest); + discoItemsRequest->send(); + } else { + completed = true; + } + onServiceFound(request->getReceiver(), info); + if (completed) { + markNodeCompleted(request->getReceiver()); + } } void DiscoServiceWalker::handleDiscoItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, GetDiscoItemsRequest::ref request) { - /* If we got canceled, don't do anything */ - if (!active_) { - return; - } - - SWIFT_LOG(debug) << "Received disco items from " << request->getReceiver() << std::endl; - request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request)); - pendingDiscoItemsRequests_.erase(request); - if (error) { - handleDiscoError(request->getReceiver(), error); - return; - } - foreach (DiscoItems::Item item, items->getItems()) { - if (item.getNode().empty()) { - /* Don't look at noded items. It's possible that this will exclude some services, - * but I've never seen one in the wild, and it's an easy fix for not looping. - */ - if (std::find(searchedServices_.begin(), searchedServices_.end(), item.getJID()) == searchedServices_.end()) { /* Don't recurse infinitely */ - SWIFT_LOG(debug) << "Received disco item " << item.getJID() << std::endl; - walkNode(item.getJID()); - } - } - } - markNodeCompleted(request->getReceiver()); + /* If we got canceled, don't do anything */ + if (!active_) { + return; + } + + SWIFT_LOG(debug) << "Received disco items from " << request->getReceiver() << std::endl; + request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request)); + pendingDiscoItemsRequests_.erase(request); + if (error) { + handleDiscoError(request->getReceiver(), error); + return; + } + foreach (DiscoItems::Item item, items->getItems()) { + if (item.getNode().empty()) { + /* Don't look at noded items. It's possible that this will exclude some services, + * but I've never seen one in the wild, and it's an easy fix for not looping. + */ + if (std::find(searchedServices_.begin(), searchedServices_.end(), item.getJID()) == searchedServices_.end()) { /* Don't recurse infinitely */ + SWIFT_LOG(debug) << "Received disco item " << item.getJID() << std::endl; + walkNode(item.getJID()); + } + } + } + markNodeCompleted(request->getReceiver()); } void DiscoServiceWalker::handleDiscoError(const JID& jid, ErrorPayload::ref /*error*/) { - SWIFT_LOG(debug) << "Disco error from " << jid << std::endl; - markNodeCompleted(jid); + SWIFT_LOG(debug) << "Disco error from " << jid << std::endl; + markNodeCompleted(jid); } void DiscoServiceWalker::markNodeCompleted(const JID& jid) { - SWIFT_LOG(debug) << "Node completed " << jid << std::endl; - servicesBeingSearched_.erase(jid); - /* All results are in */ - if (servicesBeingSearched_.empty()) { - active_ = false; - onWalkComplete(); - } - /* Check if we're on a rampage */ - else if (searchedServices_.size() >= maxSteps_) { - active_ = false; - onWalkComplete(); - } + SWIFT_LOG(debug) << "Node completed " << jid << std::endl; + servicesBeingSearched_.erase(jid); + /* All results are in */ + if (servicesBeingSearched_.empty()) { + active_ = false; + onWalkComplete(); + } + /* Check if we're on a rampage */ + else if (searchedServices_.size() >= maxSteps_) { + active_ = false; + onWalkComplete(); + } } } diff --git a/Swiften/Disco/DiscoServiceWalker.h b/Swiften/Disco/DiscoServiceWalker.h index 17376b7..bd8102b 100644 --- a/Swiften/Disco/DiscoServiceWalker.h +++ b/Swiften/Disco/DiscoServiceWalker.h @@ -22,55 +22,55 @@ #include <Swiften/JID/JID.h> namespace Swift { - class IQRouter; - /** - * Recursively walk service discovery trees to find all services offered. - * This stops on any disco item that's not reporting itself as a server. - */ - class SWIFTEN_API DiscoServiceWalker { - public: - DiscoServiceWalker(const JID& service, IQRouter* iqRouter, size_t maxSteps = 200); + class IQRouter; + /** + * Recursively walk service discovery trees to find all services offered. + * This stops on any disco item that's not reporting itself as a server. + */ + class SWIFTEN_API DiscoServiceWalker { + public: + DiscoServiceWalker(const JID& service, IQRouter* iqRouter, size_t maxSteps = 200); - /** - * Start the walk. - * - * Call this exactly once. - */ - void beginWalk(); + /** + * Start the walk. + * + * Call this exactly once. + */ + void beginWalk(); - /** - * End the walk. - */ - void endWalk(); + /** + * End the walk. + */ + void endWalk(); - bool isActive() const { - return active_; - } + bool isActive() const { + return active_; + } - /** Emitted for each service found. */ - boost::signal<void(const JID&, boost::shared_ptr<DiscoInfo>)> onServiceFound; + /** Emitted for each service found. */ + boost::signal<void(const JID&, boost::shared_ptr<DiscoInfo>)> onServiceFound; - /** Emitted when walking is aborted. */ - boost::signal<void()> onWalkAborted; + /** Emitted when walking is aborted. */ + boost::signal<void()> onWalkAborted; - /** Emitted when walking is complete.*/ - boost::signal<void()> onWalkComplete; + /** Emitted when walking is complete.*/ + boost::signal<void()> onWalkComplete; - private: - void walkNode(const JID& jid); - void markNodeCompleted(const JID& jid); - void handleDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request); - void handleDiscoItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, GetDiscoItemsRequest::ref request); - void handleDiscoError(const JID& jid, ErrorPayload::ref error); + private: + void walkNode(const JID& jid); + void markNodeCompleted(const JID& jid); + void handleDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request); + void handleDiscoItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, GetDiscoItemsRequest::ref request); + void handleDiscoError(const JID& jid, ErrorPayload::ref error); - private: - JID service_; - IQRouter* iqRouter_; - size_t maxSteps_; - bool active_; - std::set<JID> servicesBeingSearched_; - std::set<JID> searchedServices_; - std::set<GetDiscoInfoRequest::ref> pendingDiscoInfoRequests_; - std::set<GetDiscoItemsRequest::ref> pendingDiscoItemsRequests_; - }; + private: + JID service_; + IQRouter* iqRouter_; + size_t maxSteps_; + bool active_; + std::set<JID> servicesBeingSearched_; + std::set<JID> searchedServices_; + std::set<GetDiscoInfoRequest::ref> pendingDiscoInfoRequests_; + std::set<GetDiscoItemsRequest::ref> pendingDiscoItemsRequests_; + }; } diff --git a/Swiften/Disco/DummyEntityCapsProvider.cpp b/Swiften/Disco/DummyEntityCapsProvider.cpp index 65baf7a..6e9d898 100644 --- a/Swiften/Disco/DummyEntityCapsProvider.cpp +++ b/Swiften/Disco/DummyEntityCapsProvider.cpp @@ -11,11 +11,11 @@ namespace Swift { DiscoInfo::ref DummyEntityCapsProvider::getCaps(const JID& jid) const { - std::map<JID, DiscoInfo::ref>::const_iterator i = caps.find(jid); - if (i != caps.end()) { - return i->second; - } - return DiscoInfo::ref(); + std::map<JID, DiscoInfo::ref>::const_iterator i = caps.find(jid); + if (i != caps.end()) { + return i->second; + } + return DiscoInfo::ref(); } } diff --git a/Swiften/Disco/DummyEntityCapsProvider.h b/Swiften/Disco/DummyEntityCapsProvider.h index d6b2c82..5171c91 100644 --- a/Swiften/Disco/DummyEntityCapsProvider.h +++ b/Swiften/Disco/DummyEntityCapsProvider.h @@ -12,13 +12,13 @@ #include <Swiften/Disco/EntityCapsProvider.h> namespace Swift { - class SWIFTEN_API DummyEntityCapsProvider : public EntityCapsProvider { - public: - DummyEntityCapsProvider() { - } + class SWIFTEN_API DummyEntityCapsProvider : public EntityCapsProvider { + public: + DummyEntityCapsProvider() { + } - DiscoInfo::ref getCaps(const JID& jid) const; + DiscoInfo::ref getCaps(const JID& jid) const; - std::map<JID, DiscoInfo::ref> caps; - }; + std::map<JID, DiscoInfo::ref> caps; + }; } diff --git a/Swiften/Disco/EntityCapsManager.cpp b/Swiften/Disco/EntityCapsManager.cpp index a79033d..d30af54 100644 --- a/Swiften/Disco/EntityCapsManager.cpp +++ b/Swiften/Disco/EntityCapsManager.cpp @@ -14,66 +14,66 @@ namespace Swift { EntityCapsManager::EntityCapsManager(CapsProvider* capsProvider, StanzaChannel* stanzaChannel) : capsProvider(capsProvider) { - stanzaChannel->onPresenceReceived.connect(boost::bind(&EntityCapsManager::handlePresenceReceived, this, _1)); - stanzaChannel->onAvailableChanged.connect(boost::bind(&EntityCapsManager::handleStanzaChannelAvailableChanged, this, _1)); - capsProvider->onCapsAvailable.connect(boost::bind(&EntityCapsManager::handleCapsAvailable, this, _1)); + stanzaChannel->onPresenceReceived.connect(boost::bind(&EntityCapsManager::handlePresenceReceived, this, _1)); + stanzaChannel->onAvailableChanged.connect(boost::bind(&EntityCapsManager::handleStanzaChannelAvailableChanged, this, _1)); + capsProvider->onCapsAvailable.connect(boost::bind(&EntityCapsManager::handleCapsAvailable, this, _1)); } void EntityCapsManager::handlePresenceReceived(boost::shared_ptr<Presence> presence) { - JID from = presence->getFrom(); - if (presence->isAvailable()) { - boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>(); - if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) { - return; - } - std::string hash = capsInfo->getVersion(); - std::map<JID, std::string>::iterator i = caps.find(from); - if (i == caps.end() || i->second != hash) { - caps.insert(std::make_pair(from, hash)); - DiscoInfo::ref disco = capsProvider->getCaps(hash); - if (disco) { - onCapsChanged(from); - } - else if (i != caps.end()) { - caps.erase(i); - onCapsChanged(from); - } - } - } - else { - std::map<JID, std::string>::iterator i = caps.find(from); - if (i != caps.end()) { - caps.erase(i); - onCapsChanged(from); - } - } + JID from = presence->getFrom(); + if (presence->isAvailable()) { + boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>(); + if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) { + return; + } + std::string hash = capsInfo->getVersion(); + std::map<JID, std::string>::iterator i = caps.find(from); + if (i == caps.end() || i->second != hash) { + caps.insert(std::make_pair(from, hash)); + DiscoInfo::ref disco = capsProvider->getCaps(hash); + if (disco) { + onCapsChanged(from); + } + else if (i != caps.end()) { + caps.erase(i); + onCapsChanged(from); + } + } + } + else { + std::map<JID, std::string>::iterator i = caps.find(from); + if (i != caps.end()) { + caps.erase(i); + onCapsChanged(from); + } + } } void EntityCapsManager::handleStanzaChannelAvailableChanged(bool available) { - if (available) { - std::map<JID, std::string> capsCopy; - capsCopy.swap(caps); - for (std::map<JID,std::string>::const_iterator i = capsCopy.begin(); i != capsCopy.end(); ++i) { - onCapsChanged(i->first); - } - } + if (available) { + std::map<JID, std::string> capsCopy; + capsCopy.swap(caps); + for (std::map<JID,std::string>::const_iterator i = capsCopy.begin(); i != capsCopy.end(); ++i) { + onCapsChanged(i->first); + } + } } void EntityCapsManager::handleCapsAvailable(const std::string& hash) { - // TODO: Use Boost.Bimap ? - for (std::map<JID,std::string>::const_iterator i = caps.begin(); i != caps.end(); ++i) { - if (i->second == hash) { - onCapsChanged(i->first); - } - } + // TODO: Use Boost.Bimap ? + for (std::map<JID,std::string>::const_iterator i = caps.begin(); i != caps.end(); ++i) { + if (i->second == hash) { + onCapsChanged(i->first); + } + } } DiscoInfo::ref EntityCapsManager::getCaps(const JID& jid) const { - std::map<JID, std::string>::const_iterator i = caps.find(jid); - if (i != caps.end()) { - return capsProvider->getCaps(i->second); - } - return DiscoInfo::ref(); + std::map<JID, std::string>::const_iterator i = caps.find(jid); + if (i != caps.end()) { + return capsProvider->getCaps(i->second); + } + return DiscoInfo::ref(); } } diff --git a/Swiften/Disco/EntityCapsManager.h b/Swiften/Disco/EntityCapsManager.h index 62c0002..2a5d2d7 100644 --- a/Swiften/Disco/EntityCapsManager.h +++ b/Swiften/Disco/EntityCapsManager.h @@ -16,31 +16,31 @@ #include <Swiften/Elements/Presence.h> namespace Swift { - class StanzaChannel; - class CapsProvider; - - /** - * This class is responsible for gathering and providing - * information about capabilities of entities on the network. - * This information is provided in the form of service discovery - * information. - */ - class SWIFTEN_API EntityCapsManager : public EntityCapsProvider, public boost::bsignals::trackable { - public: - EntityCapsManager(CapsProvider*, StanzaChannel*); - - /** - * Returns the service discovery information of the given JID. - */ - DiscoInfo::ref getCaps(const JID&) const; - - private: - void handlePresenceReceived(boost::shared_ptr<Presence>); - void handleStanzaChannelAvailableChanged(bool); - void handleCapsAvailable(const std::string&); - - private: - CapsProvider* capsProvider; - std::map<JID, std::string> caps; - }; + class StanzaChannel; + class CapsProvider; + + /** + * This class is responsible for gathering and providing + * information about capabilities of entities on the network. + * This information is provided in the form of service discovery + * information. + */ + class SWIFTEN_API EntityCapsManager : public EntityCapsProvider, public boost::bsignals::trackable { + public: + EntityCapsManager(CapsProvider*, StanzaChannel*); + + /** + * Returns the service discovery information of the given JID. + */ + DiscoInfo::ref getCaps(const JID&) const; + + private: + void handlePresenceReceived(boost::shared_ptr<Presence>); + void handleStanzaChannelAvailableChanged(bool); + void handleCapsAvailable(const std::string&); + + private: + CapsProvider* capsProvider; + std::map<JID, std::string> caps; + }; } diff --git a/Swiften/Disco/EntityCapsProvider.h b/Swiften/Disco/EntityCapsProvider.h index abc5758..34984ca 100644 --- a/Swiften/Disco/EntityCapsProvider.h +++ b/Swiften/Disco/EntityCapsProvider.h @@ -12,23 +12,23 @@ #include <Swiften/JID/JID.h> namespace Swift { - /** - * This class provides information about capabilities of entities on the network. - * This information is provided in the form of service discovery - * information. - */ - class SWIFTEN_API EntityCapsProvider { - public: - virtual ~EntityCapsProvider(); + /** + * This class provides information about capabilities of entities on the network. + * This information is provided in the form of service discovery + * information. + */ + class SWIFTEN_API EntityCapsProvider { + public: + virtual ~EntityCapsProvider(); - /** - * Returns the service discovery information of the given JID. - */ - virtual DiscoInfo::ref getCaps(const JID&) const = 0; + /** + * Returns the service discovery information of the given JID. + */ + virtual DiscoInfo::ref getCaps(const JID&) const = 0; - /** - * Emitted when the capabilities of a JID changes. - */ - boost::signal<void (const JID&)> onCapsChanged; - }; + /** + * Emitted when the capabilities of a JID changes. + */ + boost::signal<void (const JID&)> onCapsChanged; + }; } diff --git a/Swiften/Disco/FeatureOracle.cpp b/Swiften/Disco/FeatureOracle.cpp index 4e61aa9..1267cb0 100644 --- a/Swiften/Disco/FeatureOracle.cpp +++ b/Swiften/Disco/FeatureOracle.cpp @@ -24,74 +24,74 @@ FeatureOracle::FeatureOracle(EntityCapsProvider* capsProvider, PresenceOracle* p } Tristate FeatureOracle::isFileTransferSupported(const JID& jid) { - DiscoInfo::ref discoInfo = getDiscoResultForJID(jid); - if (discoInfo) { - return FileTransferManager::isSupportedBy(discoInfo) ? Yes : No; - } - else { - return Maybe; - } + DiscoInfo::ref discoInfo = getDiscoResultForJID(jid); + if (discoInfo) { + return FileTransferManager::isSupportedBy(discoInfo) ? Yes : No; + } + else { + return Maybe; + } } Tristate FeatureOracle::isMessageReceiptsSupported(const JID& jid) { - return isFeatureSupported(jid, DiscoInfo::MessageDeliveryReceiptsFeature); + return isFeatureSupported(jid, DiscoInfo::MessageDeliveryReceiptsFeature); } Tristate FeatureOracle::isMessageCorrectionSupported(const JID& jid) { - return isFeatureSupported(jid, DiscoInfo::MessageCorrectionFeature); + return isFeatureSupported(jid, DiscoInfo::MessageCorrectionFeature); } DiscoInfo::ref FeatureOracle::getDiscoResultForJID(const JID& jid) { - DiscoInfo::ref discoInfo; - if (jid.isBare()) { - // Calculate the common subset of disco features of all available results and return that. - std::vector<Presence::ref> availablePresences = presenceOracle_->getAllPresence(jid); - - bool commonFeaturesInitialized = false; - std::vector<std::string> commonFeatures; - foreach(Presence::ref presence, availablePresences) { - DiscoInfo::ref presenceDiscoInfo = capsProvider_->getCaps(presence->getFrom()); - if (presenceDiscoInfo) { - std::vector<std::string> features = presenceDiscoInfo->getFeatures(); - if (!commonFeaturesInitialized) { - commonFeatures = features; - commonFeaturesInitialized = true; - } - else { - std::vector<std::string> featuresToRemove; - foreach(const std::string& feature, commonFeatures) { - if (std::find(features.begin(), features.end(), feature) == features.end()) { - featuresToRemove.push_back(feature); - } - } - foreach(const std::string& featureToRemove, featuresToRemove) { - commonFeatures.erase(std::remove(commonFeatures.begin(), commonFeatures.end(), featureToRemove), commonFeatures.end()); - } - } - } - } - discoInfo = boost::make_shared<DiscoInfo>(); - - foreach(const std::string& commonFeature, commonFeatures) { - discoInfo->addFeature(commonFeature); - } - } - else { - // Return the disco result of the full JID. - discoInfo = capsProvider_->getCaps(jid); - } - - return discoInfo; + DiscoInfo::ref discoInfo; + if (jid.isBare()) { + // Calculate the common subset of disco features of all available results and return that. + std::vector<Presence::ref> availablePresences = presenceOracle_->getAllPresence(jid); + + bool commonFeaturesInitialized = false; + std::vector<std::string> commonFeatures; + foreach(Presence::ref presence, availablePresences) { + DiscoInfo::ref presenceDiscoInfo = capsProvider_->getCaps(presence->getFrom()); + if (presenceDiscoInfo) { + std::vector<std::string> features = presenceDiscoInfo->getFeatures(); + if (!commonFeaturesInitialized) { + commonFeatures = features; + commonFeaturesInitialized = true; + } + else { + std::vector<std::string> featuresToRemove; + foreach(const std::string& feature, commonFeatures) { + if (std::find(features.begin(), features.end(), feature) == features.end()) { + featuresToRemove.push_back(feature); + } + } + foreach(const std::string& featureToRemove, featuresToRemove) { + commonFeatures.erase(std::remove(commonFeatures.begin(), commonFeatures.end(), featureToRemove), commonFeatures.end()); + } + } + } + } + discoInfo = boost::make_shared<DiscoInfo>(); + + foreach(const std::string& commonFeature, commonFeatures) { + discoInfo->addFeature(commonFeature); + } + } + else { + // Return the disco result of the full JID. + discoInfo = capsProvider_->getCaps(jid); + } + + return discoInfo; } Tristate FeatureOracle::isFeatureSupported(const JID& jid, const std::string& feature) { - DiscoInfo::ref discoInfo = getDiscoResultForJID(jid); - if (discoInfo) { - return discoInfo->hasFeature(feature) ? Yes : No; - } - else { - return Maybe; - } + DiscoInfo::ref discoInfo = getDiscoResultForJID(jid); + if (discoInfo) { + return discoInfo->hasFeature(feature) ? Yes : No; + } + else { + return Maybe; + } } } diff --git a/Swiften/Disco/FeatureOracle.h b/Swiften/Disco/FeatureOracle.h index d579e5a..d434e86 100644 --- a/Swiften/Disco/FeatureOracle.h +++ b/Swiften/Disco/FeatureOracle.h @@ -20,27 +20,27 @@ class PresenceOracle; * @brief The FeatureOracle class enables direct feature support lookup for client features supported by Swiften. */ class SWIFTEN_API FeatureOracle { - public: - FeatureOracle(EntityCapsProvider* capsProvider, PresenceOracle* presenceOracle); - - public: - Tristate isFileTransferSupported(const JID& jid); - Tristate isMessageReceiptsSupported(const JID& jid); - Tristate isMessageCorrectionSupported(const JID& jid); - - private: - /** - * @brief getDiscoResultForJID returns a shared reference to a DiscoInfo representing features supported by the jid. - * @param jid The JID to return the DiscoInfo::ref for. - * @return DiscoResult::ref - */ - DiscoInfo::ref getDiscoResultForJID(const JID& jid); - - Tristate isFeatureSupported(const JID& jid, const std::string& feature); - - private: - EntityCapsProvider* capsProvider_; - PresenceOracle* presenceOracle_; + public: + FeatureOracle(EntityCapsProvider* capsProvider, PresenceOracle* presenceOracle); + + public: + Tristate isFileTransferSupported(const JID& jid); + Tristate isMessageReceiptsSupported(const JID& jid); + Tristate isMessageCorrectionSupported(const JID& jid); + + private: + /** + * @brief getDiscoResultForJID returns a shared reference to a DiscoInfo representing features supported by the jid. + * @param jid The JID to return the DiscoInfo::ref for. + * @return DiscoResult::ref + */ + DiscoInfo::ref getDiscoResultForJID(const JID& jid); + + Tristate isFeatureSupported(const JID& jid, const std::string& feature); + + private: + EntityCapsProvider* capsProvider_; + PresenceOracle* presenceOracle_; }; } diff --git a/Swiften/Disco/GetDiscoInfoRequest.h b/Swiften/Disco/GetDiscoInfoRequest.h index 81b212c..ccbd3e2 100644 --- a/Swiften/Disco/GetDiscoInfoRequest.h +++ b/Swiften/Disco/GetDiscoInfoRequest.h @@ -13,26 +13,26 @@ #include <Swiften/Queries/GenericRequest.h> namespace Swift { - class SWIFTEN_API GetDiscoInfoRequest : public GenericRequest<DiscoInfo> { - public: - typedef boost::shared_ptr<GetDiscoInfoRequest> ref; - - static ref create(const JID& jid, IQRouter* router) { - return ref(new GetDiscoInfoRequest(jid, router)); - } - - static ref create(const JID& jid, const std::string& node, IQRouter* router) { - return ref(new GetDiscoInfoRequest(jid, node, router)); - } - - private: - GetDiscoInfoRequest(const JID& jid, IQRouter* router) : - GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) { - } - - GetDiscoInfoRequest(const JID& jid, const std::string& node, IQRouter* router) : - GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) { - getPayloadGeneric()->setNode(node); - } - }; + class SWIFTEN_API GetDiscoInfoRequest : public GenericRequest<DiscoInfo> { + public: + typedef boost::shared_ptr<GetDiscoInfoRequest> ref; + + static ref create(const JID& jid, IQRouter* router) { + return ref(new GetDiscoInfoRequest(jid, router)); + } + + static ref create(const JID& jid, const std::string& node, IQRouter* router) { + return ref(new GetDiscoInfoRequest(jid, node, router)); + } + + private: + GetDiscoInfoRequest(const JID& jid, IQRouter* router) : + GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) { + } + + GetDiscoInfoRequest(const JID& jid, const std::string& node, IQRouter* router) : + GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) { + getPayloadGeneric()->setNode(node); + } + }; } diff --git a/Swiften/Disco/GetDiscoItemsRequest.h b/Swiften/Disco/GetDiscoItemsRequest.h index 0a96f96..7f1adc6 100644 --- a/Swiften/Disco/GetDiscoItemsRequest.h +++ b/Swiften/Disco/GetDiscoItemsRequest.h @@ -13,26 +13,26 @@ #include <Swiften/Queries/GenericRequest.h> namespace Swift { - class SWIFTEN_API GetDiscoItemsRequest : public GenericRequest<DiscoItems> { - public: - typedef boost::shared_ptr<GetDiscoItemsRequest> ref; - - static ref create(const JID& jid, IQRouter* router) { - return ref(new GetDiscoItemsRequest(jid, router)); - } - - static ref create(const JID& jid, const std::string& node, IQRouter* router) { - return ref(new GetDiscoItemsRequest(jid, node, router)); - } - - private: - GetDiscoItemsRequest(const JID& jid, IQRouter* router) : - GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) { - } - - GetDiscoItemsRequest(const JID& jid, const std::string& node, IQRouter* router) : - GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) { - getPayloadGeneric()->setNode(node); - } - }; + class SWIFTEN_API GetDiscoItemsRequest : public GenericRequest<DiscoItems> { + public: + typedef boost::shared_ptr<GetDiscoItemsRequest> ref; + + static ref create(const JID& jid, IQRouter* router) { + return ref(new GetDiscoItemsRequest(jid, router)); + } + + static ref create(const JID& jid, const std::string& node, IQRouter* router) { + return ref(new GetDiscoItemsRequest(jid, node, router)); + } + + private: + GetDiscoItemsRequest(const JID& jid, IQRouter* router) : + GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) { + } + + GetDiscoItemsRequest(const JID& jid, const std::string& node, IQRouter* router) : + GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) { + getPayloadGeneric()->setNode(node); + } + }; } diff --git a/Swiften/Disco/JIDDiscoInfoResponder.cpp b/Swiften/Disco/JIDDiscoInfoResponder.cpp index 8803b6b..7bec992 100644 --- a/Swiften/Disco/JIDDiscoInfoResponder.cpp +++ b/Swiften/Disco/JIDDiscoInfoResponder.cpp @@ -17,41 +17,41 @@ JIDDiscoInfoResponder::JIDDiscoInfoResponder(IQRouter* router) : GetResponder<Di } void JIDDiscoInfoResponder::clearDiscoInfo(const JID& jid) { - info.erase(jid); + info.erase(jid); } void JIDDiscoInfoResponder::setDiscoInfo(const JID& jid, const DiscoInfo& discoInfo) { - JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first; - i->second.discoInfo = discoInfo; + JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first; + i->second.discoInfo = discoInfo; } void JIDDiscoInfoResponder::setDiscoInfo(const JID& jid, const std::string& node, const DiscoInfo& discoInfo) { - JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first; - DiscoInfo newInfo(discoInfo); - newInfo.setNode(node); - i->second.nodeDiscoInfo[node] = newInfo; + JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first; + DiscoInfo newInfo(discoInfo); + newInfo.setNode(node); + i->second.nodeDiscoInfo[node] = newInfo; } bool JIDDiscoInfoResponder::handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> discoInfo) { - JIDDiscoInfoMap::const_iterator i = info.find(to); - if (i != info.end()) { - if (discoInfo->getNode().empty()) { - sendResponse(from, to, id, boost::make_shared<DiscoInfo>(i->second.discoInfo)); - } - else { - std::map<std::string,DiscoInfo>::const_iterator j = i->second.nodeDiscoInfo.find(discoInfo->getNode()); - if (j != i->second.nodeDiscoInfo.end()) { - sendResponse(from, to, id, boost::make_shared<DiscoInfo>(j->second)); - } - else { - sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); - } - } - } - else { - sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); - } - return true; + JIDDiscoInfoMap::const_iterator i = info.find(to); + if (i != info.end()) { + if (discoInfo->getNode().empty()) { + sendResponse(from, to, id, boost::make_shared<DiscoInfo>(i->second.discoInfo)); + } + else { + std::map<std::string,DiscoInfo>::const_iterator j = i->second.nodeDiscoInfo.find(discoInfo->getNode()); + if (j != i->second.nodeDiscoInfo.end()) { + sendResponse(from, to, id, boost::make_shared<DiscoInfo>(j->second)); + } + else { + sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); + } + } + } + else { + sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); + } + return true; } } diff --git a/Swiften/Disco/JIDDiscoInfoResponder.h b/Swiften/Disco/JIDDiscoInfoResponder.h index 1323b2d..e2fbb5b7 100644 --- a/Swiften/Disco/JIDDiscoInfoResponder.h +++ b/Swiften/Disco/JIDDiscoInfoResponder.h @@ -14,25 +14,25 @@ #include <Swiften/Queries/GetResponder.h> namespace Swift { - class IQRouter; - - class SWIFTEN_API JIDDiscoInfoResponder : public GetResponder<DiscoInfo> { - public: - JIDDiscoInfoResponder(IQRouter* router); - - void clearDiscoInfo(const JID& jid); - void setDiscoInfo(const JID& jid, const DiscoInfo& info); - void setDiscoInfo(const JID& jid, const std::string& node, const DiscoInfo& info); - - private: - virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload); - - private: - struct JIDDiscoInfo { - DiscoInfo discoInfo; - std::map<std::string, DiscoInfo> nodeDiscoInfo; - }; - typedef std::map<JID, JIDDiscoInfo> JIDDiscoInfoMap; - JIDDiscoInfoMap info; - }; + class IQRouter; + + class SWIFTEN_API JIDDiscoInfoResponder : public GetResponder<DiscoInfo> { + public: + JIDDiscoInfoResponder(IQRouter* router); + + void clearDiscoInfo(const JID& jid); + void setDiscoInfo(const JID& jid, const DiscoInfo& info); + void setDiscoInfo(const JID& jid, const std::string& node, const DiscoInfo& info); + + private: + virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload); + + private: + struct JIDDiscoInfo { + DiscoInfo discoInfo; + std::map<std::string, DiscoInfo> nodeDiscoInfo; + }; + typedef std::map<JID, JIDDiscoInfo> JIDDiscoInfoMap; + JIDDiscoInfoMap info; + }; } diff --git a/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp b/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp index 857d6ff..58c9531 100644 --- a/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp +++ b/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp @@ -15,72 +15,72 @@ using namespace Swift; class CapsInfoGeneratorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(CapsInfoGeneratorTest); - CPPUNIT_TEST(testGenerate_XEP0115SimpleExample); - CPPUNIT_TEST(testGenerate_XEP0115ComplexExample); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(CapsInfoGeneratorTest); + CPPUNIT_TEST(testGenerate_XEP0115SimpleExample); + CPPUNIT_TEST(testGenerate_XEP0115ComplexExample); + CPPUNIT_TEST_SUITE_END(); - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - } + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + } - void testGenerate_XEP0115SimpleExample() { - DiscoInfo discoInfo; - discoInfo.addIdentity(DiscoInfo::Identity("Exodus 0.9.1", "client", "pc")); - discoInfo.addFeature("http://jabber.org/protocol/disco#items"); - discoInfo.addFeature("http://jabber.org/protocol/caps"); - discoInfo.addFeature("http://jabber.org/protocol/disco#info"); - discoInfo.addFeature("http://jabber.org/protocol/muc"); + void testGenerate_XEP0115SimpleExample() { + DiscoInfo discoInfo; + discoInfo.addIdentity(DiscoInfo::Identity("Exodus 0.9.1", "client", "pc")); + discoInfo.addFeature("http://jabber.org/protocol/disco#items"); + discoInfo.addFeature("http://jabber.org/protocol/caps"); + discoInfo.addFeature("http://jabber.org/protocol/disco#info"); + discoInfo.addFeature("http://jabber.org/protocol/muc"); - CapsInfoGenerator testling("http://code.google.com/p/exodus", crypto.get()); - CapsInfo result = testling.generateCapsInfo(discoInfo); + CapsInfoGenerator testling("http://code.google.com/p/exodus", crypto.get()); + CapsInfo result = testling.generateCapsInfo(discoInfo); - CPPUNIT_ASSERT_EQUAL(std::string("http://code.google.com/p/exodus"), result.getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), result.getHash()); - CPPUNIT_ASSERT_EQUAL(std::string("QgayPKawpkPSDYmwT/WM94uAlu0="), result.getVersion()); - } + CPPUNIT_ASSERT_EQUAL(std::string("http://code.google.com/p/exodus"), result.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), result.getHash()); + CPPUNIT_ASSERT_EQUAL(std::string("QgayPKawpkPSDYmwT/WM94uAlu0="), result.getVersion()); + } - void testGenerate_XEP0115ComplexExample() { - DiscoInfo discoInfo; - discoInfo.addIdentity(DiscoInfo::Identity("Psi 0.11", "client", "pc", "en")); - discoInfo.addIdentity(DiscoInfo::Identity("\xce\xa8 0.11", "client", "pc", "el")); - discoInfo.addFeature("http://jabber.org/protocol/disco#items"); - discoInfo.addFeature("http://jabber.org/protocol/caps"); - discoInfo.addFeature("http://jabber.org/protocol/disco#info"); - discoInfo.addFeature("http://jabber.org/protocol/muc"); + void testGenerate_XEP0115ComplexExample() { + DiscoInfo discoInfo; + discoInfo.addIdentity(DiscoInfo::Identity("Psi 0.11", "client", "pc", "en")); + discoInfo.addIdentity(DiscoInfo::Identity("\xce\xa8 0.11", "client", "pc", "el")); + discoInfo.addFeature("http://jabber.org/protocol/disco#items"); + discoInfo.addFeature("http://jabber.org/protocol/caps"); + discoInfo.addFeature("http://jabber.org/protocol/disco#info"); + discoInfo.addFeature("http://jabber.org/protocol/muc"); - Form::ref extension(new Form(Form::ResultType)); - FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "urn:xmpp:dataforms:softwareinfo"); - field->setName("FORM_TYPE"); - extension->addField(field); - field = boost::make_shared<FormField>(FormField::ListMultiType); - field->addValue("ipv6"); - field->addValue("ipv4"); - field->setName("ip_version"); - extension->addField(field); - field = boost::make_shared<FormField>(FormField::TextSingleType, "Psi"); - field->setName("software"); - extension->addField(field); - field = boost::make_shared<FormField>(FormField::TextSingleType, "0.11"); - field->setName("software_version"); - extension->addField(field); - field = boost::make_shared<FormField>(FormField::TextSingleType, "Mac"); - field->setName("os"); - extension->addField(field); - field = boost::make_shared<FormField>(FormField::TextSingleType, "10.5.1"); - field->setName("os_version"); - extension->addField(field); - discoInfo.addExtension(extension); + Form::ref extension(new Form(Form::ResultType)); + FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "urn:xmpp:dataforms:softwareinfo"); + field->setName("FORM_TYPE"); + extension->addField(field); + field = boost::make_shared<FormField>(FormField::ListMultiType); + field->addValue("ipv6"); + field->addValue("ipv4"); + field->setName("ip_version"); + extension->addField(field); + field = boost::make_shared<FormField>(FormField::TextSingleType, "Psi"); + field->setName("software"); + extension->addField(field); + field = boost::make_shared<FormField>(FormField::TextSingleType, "0.11"); + field->setName("software_version"); + extension->addField(field); + field = boost::make_shared<FormField>(FormField::TextSingleType, "Mac"); + field->setName("os"); + extension->addField(field); + field = boost::make_shared<FormField>(FormField::TextSingleType, "10.5.1"); + field->setName("os_version"); + extension->addField(field); + discoInfo.addExtension(extension); - CapsInfoGenerator testling("http://psi-im.org", crypto.get()); - CapsInfo result = testling.generateCapsInfo(discoInfo); + CapsInfoGenerator testling("http://psi-im.org", crypto.get()); + CapsInfo result = testling.generateCapsInfo(discoInfo); - CPPUNIT_ASSERT_EQUAL(std::string("q07IKJEyjvHSyhy//CH0CxmKi8w="), result.getVersion()); - } - - private: - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_ASSERT_EQUAL(std::string("q07IKJEyjvHSyhy//CH0CxmKi8w="), result.getVersion()); + } + + private: + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(CapsInfoGeneratorTest); diff --git a/Swiften/Disco/UnitTest/CapsManagerTest.cpp b/Swiften/Disco/UnitTest/CapsManagerTest.cpp index 50f369c..fe7ee7e 100644 --- a/Swiften/Disco/UnitTest/CapsManagerTest.cpp +++ b/Swiften/Disco/UnitTest/CapsManagerTest.cpp @@ -24,269 +24,269 @@ using namespace Swift; class CapsManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(CapsManagerTest); - CPPUNIT_TEST(testReceiveNewHashRequestsDisco); - CPPUNIT_TEST(testReceiveSameHashDoesNotRequestDisco); - CPPUNIT_TEST(testReceiveLegacyCapsDoesNotRequestDisco); - CPPUNIT_TEST(testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco); - CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco); - CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco); - CPPUNIT_TEST(testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco); - CPPUNIT_TEST(testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco); - CPPUNIT_TEST(testReceiveSuccesfulDiscoStoresCaps); - CPPUNIT_TEST(testReceiveIncorrectVerificationDiscoDoesNotStoreCaps); - CPPUNIT_TEST(testReceiveFailingDiscoFallsBack); - CPPUNIT_TEST(testReceiveNoDiscoFallsBack); - CPPUNIT_TEST(testReceiveFailingFallbackDiscoFallsBack); - CPPUNIT_TEST(testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco); - CPPUNIT_TEST(testReconnectResetsFallback); - CPPUNIT_TEST(testReconnectResetsRequests); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - stanzaChannel = new DummyStanzaChannel(); - iqRouter = new IQRouter(stanzaChannel); - storage = new CapsMemoryStorage(); - user1 = JID("user1@bar.com/bla"); - discoInfo1 = boost::make_shared<DiscoInfo>(); - discoInfo1->addFeature("http://swift.im/feature1"); - capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); - capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); - user2 = JID("user2@foo.com/baz"); - discoInfo2 = boost::make_shared<DiscoInfo>(); - discoInfo2->addFeature("http://swift.im/feature2"); - capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get())); - user3 = JID("user3@foo.com/baz"); - legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", ""); - } - - void tearDown() { - delete storage; - delete iqRouter; - delete stanzaChannel; - } - - void testReceiveNewHashRequestsDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); - boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[0]->getPayload<DiscoInfo>()); - CPPUNIT_ASSERT(discoInfo); - CPPUNIT_ASSERT_EQUAL("http://node1.im#" + capsInfo1->getVersion(), discoInfo->getNode()); - } - - void testReceiveSameHashDoesNotRequestDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testReceiveLegacyCapsDoesNotRequestDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, legacyCapsInfo); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendDiscoInfoResult(discoInfo1); - - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID())); - - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testReceiveSameHashFromSameUserAfterIncorrectVerificationDoesNotRequestDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendDiscoInfoResult(discoInfo2); - - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); - - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user2, capsInfo1); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get)); - } - - void testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendDiscoInfoResult(discoInfo2); - - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user2, capsInfo1); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get)); - } - - void testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID())); - - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user1, capsInfo2); - - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); - } - - void testReceiveSuccesfulDiscoStoresCaps() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendDiscoInfoResult(discoInfo1); - - boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion())); - CPPUNIT_ASSERT(discoInfo); - CPPUNIT_ASSERT(discoInfo->hasFeature("http://swift.im/feature1")); - } - - void testReceiveIncorrectVerificationDiscoDoesNotStoreCaps() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendDiscoInfoResult(discoInfo2); - - boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion())); - CPPUNIT_ASSERT(!discoInfo); - } - - void testReceiveFailingDiscoFallsBack() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendPresenceWithCaps(user2, capsInfo1alt); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); - - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get)); - boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>()); - CPPUNIT_ASSERT(discoInfo); - CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode()); - } - - void testReceiveNoDiscoFallsBack() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendPresenceWithCaps(user2, capsInfo1alt); - stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), boost::shared_ptr<DiscoInfo>())); - - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get)); - boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>()); - CPPUNIT_ASSERT(discoInfo); - CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode()); - } - - void testReceiveFailingFallbackDiscoFallsBack() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendPresenceWithCaps(user2, capsInfo1alt); - sendPresenceWithCaps(user3, capsInfo1); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[1]->getTo(), stanzaChannel->sentStanzas[1]->getID())); - - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(2, user3, IQ::Get)); - } - - void testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - stanzaChannel->sentStanzas.clear(); - - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); - } - - void testReconnectResetsFallback() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - sendPresenceWithCaps(user2, capsInfo1alt); - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - stanzaChannel->sentStanzas.clear(); - sendPresenceWithCaps(user1, capsInfo1); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testReconnectResetsRequests() { - boost::shared_ptr<CapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - stanzaChannel->sentStanzas.clear(); - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); - } - - private: - boost::shared_ptr<CapsManager> createManager() { - boost::shared_ptr<CapsManager> manager(new CapsManager(storage, stanzaChannel, iqRouter, crypto.get())); - manager->setWarnOnInvalidHash(false); - //manager->onCapsChanged.connect(boost::bind(&CapsManagerTest::handleCapsChanged, this, _1)); - return manager; - } - - void handleCapsChanged(const JID& jid) { - changes.push_back(jid); - } - - void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) { - boost::shared_ptr<Presence> presence(new Presence()); - presence->setFrom(jid); - presence->addPayload(caps); - stanzaChannel->onPresenceReceived(presence); - } - - void sendDiscoInfoResult(boost::shared_ptr<DiscoInfo> discoInfo) { - stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), discoInfo)); - } - - private: - DummyStanzaChannel* stanzaChannel; - IQRouter* iqRouter; - CapsStorage* storage; - std::vector<JID> changes; - JID user1; - boost::shared_ptr<DiscoInfo> discoInfo1; - boost::shared_ptr<CapsInfo> capsInfo1; - boost::shared_ptr<CapsInfo> capsInfo1alt; - JID user2; - boost::shared_ptr<DiscoInfo> discoInfo2; - boost::shared_ptr<CapsInfo> capsInfo2; - boost::shared_ptr<CapsInfo> legacyCapsInfo; - JID user3; - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(CapsManagerTest); + CPPUNIT_TEST(testReceiveNewHashRequestsDisco); + CPPUNIT_TEST(testReceiveSameHashDoesNotRequestDisco); + CPPUNIT_TEST(testReceiveLegacyCapsDoesNotRequestDisco); + CPPUNIT_TEST(testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco); + CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco); + CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco); + CPPUNIT_TEST(testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco); + CPPUNIT_TEST(testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco); + CPPUNIT_TEST(testReceiveSuccesfulDiscoStoresCaps); + CPPUNIT_TEST(testReceiveIncorrectVerificationDiscoDoesNotStoreCaps); + CPPUNIT_TEST(testReceiveFailingDiscoFallsBack); + CPPUNIT_TEST(testReceiveNoDiscoFallsBack); + CPPUNIT_TEST(testReceiveFailingFallbackDiscoFallsBack); + CPPUNIT_TEST(testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco); + CPPUNIT_TEST(testReconnectResetsFallback); + CPPUNIT_TEST(testReconnectResetsRequests); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + stanzaChannel = new DummyStanzaChannel(); + iqRouter = new IQRouter(stanzaChannel); + storage = new CapsMemoryStorage(); + user1 = JID("user1@bar.com/bla"); + discoInfo1 = boost::make_shared<DiscoInfo>(); + discoInfo1->addFeature("http://swift.im/feature1"); + capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); + capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); + user2 = JID("user2@foo.com/baz"); + discoInfo2 = boost::make_shared<DiscoInfo>(); + discoInfo2->addFeature("http://swift.im/feature2"); + capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get())); + user3 = JID("user3@foo.com/baz"); + legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", ""); + } + + void tearDown() { + delete storage; + delete iqRouter; + delete stanzaChannel; + } + + void testReceiveNewHashRequestsDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); + boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[0]->getPayload<DiscoInfo>()); + CPPUNIT_ASSERT(discoInfo); + CPPUNIT_ASSERT_EQUAL("http://node1.im#" + capsInfo1->getVersion(), discoInfo->getNode()); + } + + void testReceiveSameHashDoesNotRequestDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testReceiveLegacyCapsDoesNotRequestDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, legacyCapsInfo); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendDiscoInfoResult(discoInfo1); + + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID())); + + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testReceiveSameHashFromSameUserAfterIncorrectVerificationDoesNotRequestDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendDiscoInfoResult(discoInfo2); + + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); + + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user2, capsInfo1); + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get)); + } + + void testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendDiscoInfoResult(discoInfo2); + + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user2, capsInfo1); + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get)); + } + + void testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID())); + + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user1, capsInfo2); + + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); + } + + void testReceiveSuccesfulDiscoStoresCaps() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendDiscoInfoResult(discoInfo1); + + boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion())); + CPPUNIT_ASSERT(discoInfo); + CPPUNIT_ASSERT(discoInfo->hasFeature("http://swift.im/feature1")); + } + + void testReceiveIncorrectVerificationDiscoDoesNotStoreCaps() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendDiscoInfoResult(discoInfo2); + + boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion())); + CPPUNIT_ASSERT(!discoInfo); + } + + void testReceiveFailingDiscoFallsBack() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendPresenceWithCaps(user2, capsInfo1alt); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); + + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get)); + boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>()); + CPPUNIT_ASSERT(discoInfo); + CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode()); + } + + void testReceiveNoDiscoFallsBack() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendPresenceWithCaps(user2, capsInfo1alt); + stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), boost::shared_ptr<DiscoInfo>())); + + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get)); + boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>()); + CPPUNIT_ASSERT(discoInfo); + CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode()); + } + + void testReceiveFailingFallbackDiscoFallsBack() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendPresenceWithCaps(user2, capsInfo1alt); + sendPresenceWithCaps(user3, capsInfo1); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[1]->getTo(), stanzaChannel->sentStanzas[1]->getID())); + + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(2, user3, IQ::Get)); + } + + void testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + stanzaChannel->sentStanzas.clear(); + + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); + } + + void testReconnectResetsFallback() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + sendPresenceWithCaps(user2, capsInfo1alt); + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + stanzaChannel->sentStanzas.clear(); + sendPresenceWithCaps(user1, capsInfo1); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testReconnectResetsRequests() { + boost::shared_ptr<CapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + stanzaChannel->sentStanzas.clear(); + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get)); + } + + private: + boost::shared_ptr<CapsManager> createManager() { + boost::shared_ptr<CapsManager> manager(new CapsManager(storage, stanzaChannel, iqRouter, crypto.get())); + manager->setWarnOnInvalidHash(false); + //manager->onCapsChanged.connect(boost::bind(&CapsManagerTest::handleCapsChanged, this, _1)); + return manager; + } + + void handleCapsChanged(const JID& jid) { + changes.push_back(jid); + } + + void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) { + boost::shared_ptr<Presence> presence(new Presence()); + presence->setFrom(jid); + presence->addPayload(caps); + stanzaChannel->onPresenceReceived(presence); + } + + void sendDiscoInfoResult(boost::shared_ptr<DiscoInfo> discoInfo) { + stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), discoInfo)); + } + + private: + DummyStanzaChannel* stanzaChannel; + IQRouter* iqRouter; + CapsStorage* storage; + std::vector<JID> changes; + JID user1; + boost::shared_ptr<DiscoInfo> discoInfo1; + boost::shared_ptr<CapsInfo> capsInfo1; + boost::shared_ptr<CapsInfo> capsInfo1alt; + JID user2; + boost::shared_ptr<DiscoInfo> discoInfo2; + boost::shared_ptr<CapsInfo> capsInfo2; + boost::shared_ptr<CapsInfo> legacyCapsInfo; + JID user3; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(CapsManagerTest); diff --git a/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp b/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp index 2bd50a3..907029e 100644 --- a/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp +++ b/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp @@ -16,82 +16,82 @@ using namespace Swift; class DiscoInfoResponderTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(DiscoInfoResponderTest); - CPPUNIT_TEST(testHandleRequest_GetToplevelInfo); - CPPUNIT_TEST(testHandleRequest_GetNodeInfo); - CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - channel_ = new DummyIQChannel(); - router_ = new IQRouter(channel_); - } - - void tearDown() { - delete router_; - delete channel_; - } - - void testHandleRequest_GetToplevelInfo() { - DiscoInfoResponder testling(router_); - testling.start(); - DiscoInfo discoInfo; - discoInfo.addFeature("foo"); - testling.setDiscoInfo(discoInfo); - - boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); - channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); - boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); - CPPUNIT_ASSERT(payload); - CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode()); - CPPUNIT_ASSERT(payload->hasFeature("foo")); - - testling.stop(); - } - - void testHandleRequest_GetNodeInfo() { - DiscoInfoResponder testling(router_); - testling.start(); - DiscoInfo discoInfo; - discoInfo.addFeature("foo"); - testling.setDiscoInfo(discoInfo); - DiscoInfo discoInfoBar; - discoInfoBar.addFeature("bar"); - testling.setDiscoInfo("bar-node", discoInfoBar); - - boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); - query->setNode("bar-node"); - channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); - boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); - CPPUNIT_ASSERT(payload); - CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode()); - CPPUNIT_ASSERT(payload->hasFeature("bar")); - - testling.stop(); - } - - void testHandleRequest_GetInvalidNodeInfo() { - DiscoInfoResponder testling(router_); - boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); - query->setNode("bar-node"); - channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query)); - testling.start(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); - boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>()); - CPPUNIT_ASSERT(payload); - - testling.stop(); - } - - private: - IQRouter* router_; - DummyIQChannel* channel_; + CPPUNIT_TEST_SUITE(DiscoInfoResponderTest); + CPPUNIT_TEST(testHandleRequest_GetToplevelInfo); + CPPUNIT_TEST(testHandleRequest_GetNodeInfo); + CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + channel_ = new DummyIQChannel(); + router_ = new IQRouter(channel_); + } + + void tearDown() { + delete router_; + delete channel_; + } + + void testHandleRequest_GetToplevelInfo() { + DiscoInfoResponder testling(router_); + testling.start(); + DiscoInfo discoInfo; + discoInfo.addFeature("foo"); + testling.setDiscoInfo(discoInfo); + + boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); + channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); + boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); + CPPUNIT_ASSERT(payload); + CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode()); + CPPUNIT_ASSERT(payload->hasFeature("foo")); + + testling.stop(); + } + + void testHandleRequest_GetNodeInfo() { + DiscoInfoResponder testling(router_); + testling.start(); + DiscoInfo discoInfo; + discoInfo.addFeature("foo"); + testling.setDiscoInfo(discoInfo); + DiscoInfo discoInfoBar; + discoInfoBar.addFeature("bar"); + testling.setDiscoInfo("bar-node", discoInfoBar); + + boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); + query->setNode("bar-node"); + channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); + boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); + CPPUNIT_ASSERT(payload); + CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode()); + CPPUNIT_ASSERT(payload->hasFeature("bar")); + + testling.stop(); + } + + void testHandleRequest_GetInvalidNodeInfo() { + DiscoInfoResponder testling(router_); + boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); + query->setNode("bar-node"); + channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query)); + testling.start(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); + boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>()); + CPPUNIT_ASSERT(payload); + + testling.stop(); + } + + private: + IQRouter* router_; + DummyIQChannel* channel_; }; CPPUNIT_TEST_SUITE_REGISTRATION(DiscoInfoResponderTest); diff --git a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp index 0a52dec..4062753 100644 --- a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp +++ b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp @@ -22,174 +22,174 @@ using namespace Swift; class EntityCapsManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(EntityCapsManagerTest); - CPPUNIT_TEST(testReceiveKnownHash); - CPPUNIT_TEST(testReceiveKnownHashTwiceDoesNotTriggerChange); - CPPUNIT_TEST(testReceiveUnknownHashDoesNotTriggerChange); - CPPUNIT_TEST(testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps); - CPPUNIT_TEST(testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps); - CPPUNIT_TEST(testReconnectTriggersChangeAndClearsCaps); - CPPUNIT_TEST(testHashAvailable); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - - stanzaChannel = new DummyStanzaChannel(); - capsProvider = new DummyCapsProvider(); - - user1 = JID("user1@bar.com/bla"); - discoInfo1 = boost::make_shared<DiscoInfo>(); - discoInfo1->addFeature("http://swift.im/feature1"); - capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); - capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); - user2 = JID("user2@foo.com/baz"); - discoInfo2 = boost::make_shared<DiscoInfo>(); - discoInfo2->addFeature("http://swift.im/feature2"); - capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get())); - user3 = JID("user3@foo.com/baz"); - legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", ""); - } - - void tearDown() { - delete capsProvider; - delete stanzaChannel; - } - - void testReceiveKnownHash() { - boost::shared_ptr<EntityCapsManager> testling = createManager(); - capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1)); - } - - void testReceiveKnownHashTwiceDoesNotTriggerChange() { - boost::shared_ptr<EntityCapsManager> testling = createManager(); - capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; - sendPresenceWithCaps(user1, capsInfo1); - changes.clear(); - - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); - } - - void testReceiveUnknownHashDoesNotTriggerChange() { - boost::shared_ptr<EntityCapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); - } - - void testHashAvailable() { - boost::shared_ptr<EntityCapsManager> testling = createManager(); - sendPresenceWithCaps(user1, capsInfo1); - - capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; - capsProvider->onCapsAvailable(capsInfo1->getVersion()); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1)); - } - - void testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps() { - boost::shared_ptr<EntityCapsManager> testling = createManager(); - capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; - sendPresenceWithCaps(user1, capsInfo1); - changes.clear(); - sendPresenceWithCaps(user1, capsInfo2); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - CPPUNIT_ASSERT(!testling->getCaps(user1)); - } - - void testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps() { - boost::shared_ptr<EntityCapsManager> testling = createManager(); - capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; - sendPresenceWithCaps(user1, capsInfo1); - changes.clear(); - sendUnavailablePresence(user1); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - CPPUNIT_ASSERT(!testling->getCaps(user1)); - } - - void testReconnectTriggersChangeAndClearsCaps() { - boost::shared_ptr<EntityCapsManager> testling = createManager(); - capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; - capsProvider->caps[capsInfo2->getVersion()] = discoInfo2; - sendPresenceWithCaps(user1, capsInfo1); - sendPresenceWithCaps(user2, capsInfo2); - changes.clear(); - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size())); - CPPUNIT_ASSERT_EQUAL(user1, changes[0]); - CPPUNIT_ASSERT(!testling->getCaps(user1)); - CPPUNIT_ASSERT_EQUAL(user2, changes[1]); - CPPUNIT_ASSERT(!testling->getCaps(user2)); - } - - private: - boost::shared_ptr<EntityCapsManager> createManager() { - boost::shared_ptr<EntityCapsManager> manager(new EntityCapsManager(capsProvider, stanzaChannel)); - manager->onCapsChanged.connect(boost::bind(&EntityCapsManagerTest::handleCapsChanged, this, _1)); - return manager; - } - - void handleCapsChanged(const JID& jid) { - changes.push_back(jid); - } - - void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) { - boost::shared_ptr<Presence> presence(new Presence()); - presence->setFrom(jid); - presence->addPayload(caps); - stanzaChannel->onPresenceReceived(presence); - } - - void sendUnavailablePresence(const JID& jid) { - boost::shared_ptr<Presence> presence(new Presence()); - presence->setFrom(jid); - presence->setType(Presence::Unavailable); - stanzaChannel->onPresenceReceived(presence); - } - - private: - struct DummyCapsProvider : public CapsProvider { - virtual DiscoInfo::ref getCaps(const std::string& hash) const { - std::map<std::string, DiscoInfo::ref>::const_iterator i = caps.find(hash); - if (i != caps.end()) { - return i->second; - } - return DiscoInfo::ref(); - } - - std::map<std::string, DiscoInfo::ref> caps; - }; - - private: - DummyStanzaChannel* stanzaChannel; - DummyCapsProvider* capsProvider; - JID user1; - boost::shared_ptr<DiscoInfo> discoInfo1; - boost::shared_ptr<CapsInfo> capsInfo1; - boost::shared_ptr<CapsInfo> capsInfo1alt; - JID user2; - boost::shared_ptr<DiscoInfo> discoInfo2; - boost::shared_ptr<CapsInfo> capsInfo2; - boost::shared_ptr<CapsInfo> legacyCapsInfo; - JID user3; - std::vector<JID> changes; - boost::shared_ptr<CryptoProvider> crypto; + CPPUNIT_TEST_SUITE(EntityCapsManagerTest); + CPPUNIT_TEST(testReceiveKnownHash); + CPPUNIT_TEST(testReceiveKnownHashTwiceDoesNotTriggerChange); + CPPUNIT_TEST(testReceiveUnknownHashDoesNotTriggerChange); + CPPUNIT_TEST(testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps); + CPPUNIT_TEST(testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps); + CPPUNIT_TEST(testReconnectTriggersChangeAndClearsCaps); + CPPUNIT_TEST(testHashAvailable); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + + stanzaChannel = new DummyStanzaChannel(); + capsProvider = new DummyCapsProvider(); + + user1 = JID("user1@bar.com/bla"); + discoInfo1 = boost::make_shared<DiscoInfo>(); + discoInfo1->addFeature("http://swift.im/feature1"); + capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); + capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); + user2 = JID("user2@foo.com/baz"); + discoInfo2 = boost::make_shared<DiscoInfo>(); + discoInfo2->addFeature("http://swift.im/feature2"); + capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get())); + user3 = JID("user3@foo.com/baz"); + legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", ""); + } + + void tearDown() { + delete capsProvider; + delete stanzaChannel; + } + + void testReceiveKnownHash() { + boost::shared_ptr<EntityCapsManager> testling = createManager(); + capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1)); + } + + void testReceiveKnownHashTwiceDoesNotTriggerChange() { + boost::shared_ptr<EntityCapsManager> testling = createManager(); + capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; + sendPresenceWithCaps(user1, capsInfo1); + changes.clear(); + + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); + } + + void testReceiveUnknownHashDoesNotTriggerChange() { + boost::shared_ptr<EntityCapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size())); + } + + void testHashAvailable() { + boost::shared_ptr<EntityCapsManager> testling = createManager(); + sendPresenceWithCaps(user1, capsInfo1); + + capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; + capsProvider->onCapsAvailable(capsInfo1->getVersion()); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1)); + } + + void testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps() { + boost::shared_ptr<EntityCapsManager> testling = createManager(); + capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; + sendPresenceWithCaps(user1, capsInfo1); + changes.clear(); + sendPresenceWithCaps(user1, capsInfo2); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + CPPUNIT_ASSERT(!testling->getCaps(user1)); + } + + void testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps() { + boost::shared_ptr<EntityCapsManager> testling = createManager(); + capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; + sendPresenceWithCaps(user1, capsInfo1); + changes.clear(); + sendUnavailablePresence(user1); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + CPPUNIT_ASSERT(!testling->getCaps(user1)); + } + + void testReconnectTriggersChangeAndClearsCaps() { + boost::shared_ptr<EntityCapsManager> testling = createManager(); + capsProvider->caps[capsInfo1->getVersion()] = discoInfo1; + capsProvider->caps[capsInfo2->getVersion()] = discoInfo2; + sendPresenceWithCaps(user1, capsInfo1); + sendPresenceWithCaps(user2, capsInfo2); + changes.clear(); + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size())); + CPPUNIT_ASSERT_EQUAL(user1, changes[0]); + CPPUNIT_ASSERT(!testling->getCaps(user1)); + CPPUNIT_ASSERT_EQUAL(user2, changes[1]); + CPPUNIT_ASSERT(!testling->getCaps(user2)); + } + + private: + boost::shared_ptr<EntityCapsManager> createManager() { + boost::shared_ptr<EntityCapsManager> manager(new EntityCapsManager(capsProvider, stanzaChannel)); + manager->onCapsChanged.connect(boost::bind(&EntityCapsManagerTest::handleCapsChanged, this, _1)); + return manager; + } + + void handleCapsChanged(const JID& jid) { + changes.push_back(jid); + } + + void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) { + boost::shared_ptr<Presence> presence(new Presence()); + presence->setFrom(jid); + presence->addPayload(caps); + stanzaChannel->onPresenceReceived(presence); + } + + void sendUnavailablePresence(const JID& jid) { + boost::shared_ptr<Presence> presence(new Presence()); + presence->setFrom(jid); + presence->setType(Presence::Unavailable); + stanzaChannel->onPresenceReceived(presence); + } + + private: + struct DummyCapsProvider : public CapsProvider { + virtual DiscoInfo::ref getCaps(const std::string& hash) const { + std::map<std::string, DiscoInfo::ref>::const_iterator i = caps.find(hash); + if (i != caps.end()) { + return i->second; + } + return DiscoInfo::ref(); + } + + std::map<std::string, DiscoInfo::ref> caps; + }; + + private: + DummyStanzaChannel* stanzaChannel; + DummyCapsProvider* capsProvider; + JID user1; + boost::shared_ptr<DiscoInfo> discoInfo1; + boost::shared_ptr<CapsInfo> capsInfo1; + boost::shared_ptr<CapsInfo> capsInfo1alt; + JID user2; + boost::shared_ptr<DiscoInfo> discoInfo2; + boost::shared_ptr<CapsInfo> capsInfo2; + boost::shared_ptr<CapsInfo> legacyCapsInfo; + JID user3; + std::vector<JID> changes; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(EntityCapsManagerTest); diff --git a/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp b/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp index 613b049..3c1a057 100644 --- a/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp +++ b/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp @@ -16,104 +16,104 @@ using namespace Swift; class JIDDiscoInfoResponderTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(JIDDiscoInfoResponderTest); - CPPUNIT_TEST(testHandleRequest_GetToplevelInfo); - CPPUNIT_TEST(testHandleRequest_GetNodeInfo); - CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo); - CPPUNIT_TEST(testHandleRequest_GetUnknownJID); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - channel_ = new DummyIQChannel(); - router_ = new IQRouter(channel_); - } - - void tearDown() { - delete router_; - delete channel_; - } - - void testHandleRequest_GetToplevelInfo() { - JIDDiscoInfoResponder testling(router_); - testling.start(); - DiscoInfo discoInfo; - discoInfo.addFeature("foo"); - testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); - - boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); - channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); - boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); - CPPUNIT_ASSERT(payload); - CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode()); - CPPUNIT_ASSERT(payload->hasFeature("foo")); - - testling.stop(); - } - - void testHandleRequest_GetNodeInfo() { - JIDDiscoInfoResponder testling(router_); - testling.start(); - DiscoInfo discoInfo; - discoInfo.addFeature("foo"); - testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); - DiscoInfo discoInfoBar; - discoInfoBar.addFeature("bar"); - testling.setDiscoInfo(JID("foo@bar.com/baz"), "bar-node", discoInfoBar); - - boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); - query->setNode("bar-node"); - channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); - boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); - CPPUNIT_ASSERT(payload); - CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode()); - CPPUNIT_ASSERT(payload->hasFeature("bar")); - - testling.stop(); - } - - void testHandleRequest_GetInvalidNodeInfo() { - JIDDiscoInfoResponder testling(router_); - DiscoInfo discoInfo; - discoInfo.addFeature("foo"); - testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); - testling.start(); - - boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); - query->setNode("bar-node"); - channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); - boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>()); - CPPUNIT_ASSERT(payload); - - testling.stop(); - } - - void testHandleRequest_GetUnknownJID() { - JIDDiscoInfoResponder testling(router_); - DiscoInfo discoInfo; - discoInfo.addFeature("foo"); - testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); - testling.start(); - - boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); - channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/fum"), "id-1", query)); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); - boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>()); - CPPUNIT_ASSERT(payload); - - testling.stop(); - } - - private: - IQRouter* router_; - DummyIQChannel* channel_; + CPPUNIT_TEST_SUITE(JIDDiscoInfoResponderTest); + CPPUNIT_TEST(testHandleRequest_GetToplevelInfo); + CPPUNIT_TEST(testHandleRequest_GetNodeInfo); + CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo); + CPPUNIT_TEST(testHandleRequest_GetUnknownJID); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + channel_ = new DummyIQChannel(); + router_ = new IQRouter(channel_); + } + + void tearDown() { + delete router_; + delete channel_; + } + + void testHandleRequest_GetToplevelInfo() { + JIDDiscoInfoResponder testling(router_); + testling.start(); + DiscoInfo discoInfo; + discoInfo.addFeature("foo"); + testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); + + boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); + channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); + boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); + CPPUNIT_ASSERT(payload); + CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode()); + CPPUNIT_ASSERT(payload->hasFeature("foo")); + + testling.stop(); + } + + void testHandleRequest_GetNodeInfo() { + JIDDiscoInfoResponder testling(router_); + testling.start(); + DiscoInfo discoInfo; + discoInfo.addFeature("foo"); + testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); + DiscoInfo discoInfoBar; + discoInfoBar.addFeature("bar"); + testling.setDiscoInfo(JID("foo@bar.com/baz"), "bar-node", discoInfoBar); + + boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); + query->setNode("bar-node"); + channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); + boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>()); + CPPUNIT_ASSERT(payload); + CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode()); + CPPUNIT_ASSERT(payload->hasFeature("bar")); + + testling.stop(); + } + + void testHandleRequest_GetInvalidNodeInfo() { + JIDDiscoInfoResponder testling(router_); + DiscoInfo discoInfo; + discoInfo.addFeature("foo"); + testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); + testling.start(); + + boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); + query->setNode("bar-node"); + channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); + boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>()); + CPPUNIT_ASSERT(payload); + + testling.stop(); + } + + void testHandleRequest_GetUnknownJID() { + JIDDiscoInfoResponder testling(router_); + DiscoInfo discoInfo; + discoInfo.addFeature("foo"); + testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo); + testling.start(); + + boost::shared_ptr<DiscoInfo> query(new DiscoInfo()); + channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/fum"), "id-1", query)); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size())); + boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>()); + CPPUNIT_ASSERT(payload); + + testling.stop(); + } + + private: + IQRouter* router_; + DummyIQChannel* channel_; }; CPPUNIT_TEST_SUITE_REGISTRATION(JIDDiscoInfoResponderTest); diff --git a/Swiften/Elements/AuthChallenge.h b/Swiften/Elements/AuthChallenge.h index 61a72ec..0c43980 100644 --- a/Swiften/Elements/AuthChallenge.h +++ b/Swiften/Elements/AuthChallenge.h @@ -14,23 +14,23 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API AuthChallenge : public ToplevelElement { - public: - AuthChallenge() { - } + class SWIFTEN_API AuthChallenge : public ToplevelElement { + public: + AuthChallenge() { + } - AuthChallenge(const std::vector<unsigned char>& value) : value(value) { - } + AuthChallenge(const std::vector<unsigned char>& value) : value(value) { + } - const boost::optional< std::vector<unsigned char> >& getValue() const { - return value; - } + const boost::optional< std::vector<unsigned char> >& getValue() const { + return value; + } - void setValue(const std::vector<unsigned char>& value) { - this->value = boost::optional<std::vector<unsigned char> >(value); - } + void setValue(const std::vector<unsigned char>& value) { + this->value = boost::optional<std::vector<unsigned char> >(value); + } - private: - boost::optional< std::vector<unsigned char> > value; - }; + private: + boost::optional< std::vector<unsigned char> > value; + }; } diff --git a/Swiften/Elements/AuthFailure.h b/Swiften/Elements/AuthFailure.h index e722d04..8f6702c 100644 --- a/Swiften/Elements/AuthFailure.h +++ b/Swiften/Elements/AuthFailure.h @@ -12,10 +12,10 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API AuthFailure : public ToplevelElement { - public: - typedef boost::shared_ptr<AuthFailure> ref; + class SWIFTEN_API AuthFailure : public ToplevelElement { + public: + typedef boost::shared_ptr<AuthFailure> ref; - AuthFailure() {} - }; + AuthFailure() {} + }; } diff --git a/Swiften/Elements/AuthRequest.h b/Swiften/Elements/AuthRequest.h index 8043d1a..33b25b4 100644 --- a/Swiften/Elements/AuthRequest.h +++ b/Swiften/Elements/AuthRequest.h @@ -16,37 +16,37 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API AuthRequest : public ToplevelElement { - public: - AuthRequest(const std::string& mechanism = "") : mechanism_(mechanism) { - } - - AuthRequest(const std::string& mechanism, const SafeByteArray& message) : - mechanism_(mechanism), message_(message) { - } - - AuthRequest(const std::string& mechanism, const boost::optional<SafeByteArray>& message) : - mechanism_(mechanism), message_(message) { - } - - const boost::optional<SafeByteArray>& getMessage() const { - return message_; - } - - void setMessage(const SafeByteArray& message) { - message_ = boost::optional<SafeByteArray>(message); - } - - const std::string& getMechanism() const { - return mechanism_; - } - - void setMechanism(const std::string& mechanism) { - mechanism_ = mechanism; - } - - private: - std::string mechanism_; - boost::optional<SafeByteArray> message_; - }; + class SWIFTEN_API AuthRequest : public ToplevelElement { + public: + AuthRequest(const std::string& mechanism = "") : mechanism_(mechanism) { + } + + AuthRequest(const std::string& mechanism, const SafeByteArray& message) : + mechanism_(mechanism), message_(message) { + } + + AuthRequest(const std::string& mechanism, const boost::optional<SafeByteArray>& message) : + mechanism_(mechanism), message_(message) { + } + + const boost::optional<SafeByteArray>& getMessage() const { + return message_; + } + + void setMessage(const SafeByteArray& message) { + message_ = boost::optional<SafeByteArray>(message); + } + + const std::string& getMechanism() const { + return mechanism_; + } + + void setMechanism(const std::string& mechanism) { + mechanism_ = mechanism; + } + + private: + std::string mechanism_; + boost::optional<SafeByteArray> message_; + }; } diff --git a/Swiften/Elements/AuthResponse.h b/Swiften/Elements/AuthResponse.h index a6ba96f..a88e8d0 100644 --- a/Swiften/Elements/AuthResponse.h +++ b/Swiften/Elements/AuthResponse.h @@ -15,26 +15,26 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API AuthResponse : public ToplevelElement { - public: - AuthResponse() { - } + class SWIFTEN_API AuthResponse : public ToplevelElement { + public: + AuthResponse() { + } - AuthResponse(const SafeByteArray& value) : value(value) { - } + AuthResponse(const SafeByteArray& value) : value(value) { + } - AuthResponse(const boost::optional<SafeByteArray>& value) : value(value) { - } + AuthResponse(const boost::optional<SafeByteArray>& value) : value(value) { + } - const boost::optional<SafeByteArray>& getValue() const { - return value; - } + const boost::optional<SafeByteArray>& getValue() const { + return value; + } - void setValue(const SafeByteArray& value) { - this->value = boost::optional<SafeByteArray>(value); - } + void setValue(const SafeByteArray& value) { + this->value = boost::optional<SafeByteArray>(value); + } - private: - boost::optional<SafeByteArray> value; - }; + private: + boost::optional<SafeByteArray> value; + }; } diff --git a/Swiften/Elements/AuthSuccess.h b/Swiften/Elements/AuthSuccess.h index d649574..860702c 100644 --- a/Swiften/Elements/AuthSuccess.h +++ b/Swiften/Elements/AuthSuccess.h @@ -14,19 +14,19 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API AuthSuccess : public ToplevelElement { - public: - AuthSuccess() {} + class SWIFTEN_API AuthSuccess : public ToplevelElement { + public: + AuthSuccess() {} - const boost::optional<std::vector<unsigned char> >& getValue() const { - return value; - } + const boost::optional<std::vector<unsigned char> >& getValue() const { + return value; + } - void setValue(const std::vector<unsigned char>& value) { - this->value = boost::optional<std::vector<unsigned char> >(value); - } + void setValue(const std::vector<unsigned char>& value) { + this->value = boost::optional<std::vector<unsigned char> >(value); + } - private: - boost::optional<std::vector<unsigned char> > value; - }; + private: + boost::optional<std::vector<unsigned char> > value; + }; } diff --git a/Swiften/Elements/BlockListPayload.h b/Swiften/Elements/BlockListPayload.h index 94f5150..acc9df4 100644 --- a/Swiften/Elements/BlockListPayload.h +++ b/Swiften/Elements/BlockListPayload.h @@ -13,20 +13,20 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API BlockListPayload : public Payload { - public: - BlockListPayload(const std::vector<JID>& items = std::vector<JID>()) : items(items) { - } + class SWIFTEN_API BlockListPayload : public Payload { + public: + BlockListPayload(const std::vector<JID>& items = std::vector<JID>()) : items(items) { + } - void addItem(const JID& item) { - items.push_back(item); - } + void addItem(const JID& item) { + items.push_back(item); + } - const std::vector<JID>& getItems() const { - return items; - } + const std::vector<JID>& getItems() const { + return items; + } - private: - std::vector<JID> items; - }; + private: + std::vector<JID> items; + }; } diff --git a/Swiften/Elements/BlockPayload.h b/Swiften/Elements/BlockPayload.h index 7fae9d2..df8d150 100644 --- a/Swiften/Elements/BlockPayload.h +++ b/Swiften/Elements/BlockPayload.h @@ -13,20 +13,20 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API BlockPayload : public Payload { - public: - BlockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) { - } + class SWIFTEN_API BlockPayload : public Payload { + public: + BlockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) { + } - void addItem(const JID& jid) { - items.push_back(jid); - } + void addItem(const JID& jid) { + items.push_back(jid); + } - const std::vector<JID>& getItems() const { - return items; - } + const std::vector<JID>& getItems() const { + return items; + } - private: - std::vector<JID> items; - }; + private: + std::vector<JID> items; + }; } diff --git a/Swiften/Elements/Body.h b/Swiften/Elements/Body.h index fc7016f..8761d5a 100644 --- a/Swiften/Elements/Body.h +++ b/Swiften/Elements/Body.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Body : public Payload { - public: - Body(const std::string& text = "") : text_(text) { - } + class SWIFTEN_API Body : public Payload { + public: + Body(const std::string& text = "") : text_(text) { + } - void setText(const std::string& text) { - text_ = text; - } + void setText(const std::string& text) { + text_ = text; + } - const std::string& getText() const { - return text_; - } + const std::string& getText() const { + return text_; + } - private: - std::string text_; - }; + private: + std::string text_; + }; } diff --git a/Swiften/Elements/Bytestreams.h b/Swiften/Elements/Bytestreams.h index 5d2ca30..dc6ec78 100644 --- a/Swiften/Elements/Bytestreams.h +++ b/Swiften/Elements/Bytestreams.h @@ -17,47 +17,47 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API Bytestreams : public Payload { - public: - typedef boost::shared_ptr<Bytestreams> ref; + class SWIFTEN_API Bytestreams : public Payload { + public: + typedef boost::shared_ptr<Bytestreams> ref; - struct StreamHost { - StreamHost(const std::string& host = "", const JID& jid = JID(), int port = -1) : host(host), jid(jid), port(port) {} + struct StreamHost { + StreamHost(const std::string& host = "", const JID& jid = JID(), int port = -1) : host(host), jid(jid), port(port) {} - std::string host; - JID jid; - int port; - }; + std::string host; + JID jid; + int port; + }; - Bytestreams() {} + Bytestreams() {} - const std::string& getStreamID() const { - return id; - } + const std::string& getStreamID() const { + return id; + } - void setStreamID(const std::string& id) { - this->id = id; - } + void setStreamID(const std::string& id) { + this->id = id; + } - const boost::optional<JID>& getUsedStreamHost() const { - return usedStreamHost; - } + const boost::optional<JID>& getUsedStreamHost() const { + return usedStreamHost; + } - void setUsedStreamHost(const JID& host) { - usedStreamHost = host; - } + void setUsedStreamHost(const JID& host) { + usedStreamHost = host; + } - const std::vector<StreamHost>& getStreamHosts() const { - return streamHosts; - } + const std::vector<StreamHost>& getStreamHosts() const { + return streamHosts; + } - void addStreamHost(const StreamHost& streamHost) { - streamHosts.push_back(streamHost); - } + void addStreamHost(const StreamHost& streamHost) { + streamHosts.push_back(streamHost); + } - private: - std::string id; - boost::optional<JID> usedStreamHost; - std::vector<StreamHost> streamHosts; - }; + private: + std::string id; + boost::optional<JID> usedStreamHost; + std::vector<StreamHost> streamHosts; + }; } diff --git a/Swiften/Elements/CapsInfo.h b/Swiften/Elements/CapsInfo.h index fc92b10..875ede4 100644 --- a/Swiften/Elements/CapsInfo.h +++ b/Swiften/Elements/CapsInfo.h @@ -14,48 +14,48 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API CapsInfo : public Payload { - public: - typedef boost::shared_ptr<CapsInfo> ref; - - CapsInfo(const std::string& node = "", const std::string& version = "", const std::string& hash = "sha-1") : node_(node), version_(version), hash_(hash) {} - - bool operator==(const CapsInfo& o) const { - return o.node_ == node_ && o.version_ == version_ && o.hash_ == hash_; - } - - bool operator<(const CapsInfo& o) const { - if (o.node_ == node_) { - if (o.version_ == version_) { - return hash_ < o.hash_; - } - else { - return version_ < o.version_; - } - } - else { - return node_ < o.node_; - } - } - - const std::string& getNode() const { return node_; } - void setNode(const std::string& node) { - node_ = node; - } - - const std::string& getVersion() const { return version_; } - void setVersion(const std::string& version) { - version_ = version; - } - - const std::string& getHash() const { return hash_; } - void setHash(const std::string& hash) { - hash_ = hash; - } - - private: - std::string node_; - std::string version_; - std::string hash_; - }; + class SWIFTEN_API CapsInfo : public Payload { + public: + typedef boost::shared_ptr<CapsInfo> ref; + + CapsInfo(const std::string& node = "", const std::string& version = "", const std::string& hash = "sha-1") : node_(node), version_(version), hash_(hash) {} + + bool operator==(const CapsInfo& o) const { + return o.node_ == node_ && o.version_ == version_ && o.hash_ == hash_; + } + + bool operator<(const CapsInfo& o) const { + if (o.node_ == node_) { + if (o.version_ == version_) { + return hash_ < o.hash_; + } + else { + return version_ < o.version_; + } + } + else { + return node_ < o.node_; + } + } + + const std::string& getNode() const { return node_; } + void setNode(const std::string& node) { + node_ = node; + } + + const std::string& getVersion() const { return version_; } + void setVersion(const std::string& version) { + version_ = version; + } + + const std::string& getHash() const { return hash_; } + void setHash(const std::string& hash) { + hash_ = hash; + } + + private: + std::string node_; + std::string version_; + std::string hash_; + }; } diff --git a/Swiften/Elements/CarbonsDisable.cpp b/Swiften/Elements/CarbonsDisable.cpp index b5d80ca..848fa92 100644 --- a/Swiften/Elements/CarbonsDisable.cpp +++ b/Swiften/Elements/CarbonsDisable.cpp @@ -7,6 +7,6 @@ #include <Swiften/Elements/CarbonsDisable.h> namespace Swift { - CarbonsDisable::~CarbonsDisable() { - } + CarbonsDisable::~CarbonsDisable() { + } } diff --git a/Swiften/Elements/CarbonsDisable.h b/Swiften/Elements/CarbonsDisable.h index e31526d..f6c9a38 100644 --- a/Swiften/Elements/CarbonsDisable.h +++ b/Swiften/Elements/CarbonsDisable.h @@ -12,11 +12,11 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API CarbonsDisable : public Payload { - public: - typedef boost::shared_ptr<CarbonsDisable> ref; + class SWIFTEN_API CarbonsDisable : public Payload { + public: + typedef boost::shared_ptr<CarbonsDisable> ref; - public: - virtual ~CarbonsDisable(); - }; + public: + virtual ~CarbonsDisable(); + }; } diff --git a/Swiften/Elements/CarbonsEnable.cpp b/Swiften/Elements/CarbonsEnable.cpp index 7d38be1..c927cfb 100644 --- a/Swiften/Elements/CarbonsEnable.cpp +++ b/Swiften/Elements/CarbonsEnable.cpp @@ -7,6 +7,6 @@ #include <Swiften/Elements/CarbonsEnable.h> namespace Swift { - CarbonsEnable::~CarbonsEnable() { - } + CarbonsEnable::~CarbonsEnable() { + } } diff --git a/Swiften/Elements/CarbonsEnable.h b/Swiften/Elements/CarbonsEnable.h index b100e8d..1cb64ad 100644 --- a/Swiften/Elements/CarbonsEnable.h +++ b/Swiften/Elements/CarbonsEnable.h @@ -12,11 +12,11 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API CarbonsEnable : public Payload { - public: - typedef boost::shared_ptr<CarbonsEnable> ref; + class SWIFTEN_API CarbonsEnable : public Payload { + public: + typedef boost::shared_ptr<CarbonsEnable> ref; - public: - virtual ~CarbonsEnable(); - }; + public: + virtual ~CarbonsEnable(); + }; } diff --git a/Swiften/Elements/CarbonsPrivate.cpp b/Swiften/Elements/CarbonsPrivate.cpp index a0c6369..4ebcd31 100644 --- a/Swiften/Elements/CarbonsPrivate.cpp +++ b/Swiften/Elements/CarbonsPrivate.cpp @@ -7,6 +7,6 @@ #include <Swiften/Elements/CarbonsPrivate.h> namespace Swift { - CarbonsPrivate::~CarbonsPrivate() { - } + CarbonsPrivate::~CarbonsPrivate() { + } } diff --git a/Swiften/Elements/CarbonsPrivate.h b/Swiften/Elements/CarbonsPrivate.h index e363b5c..fdd3944 100644 --- a/Swiften/Elements/CarbonsPrivate.h +++ b/Swiften/Elements/CarbonsPrivate.h @@ -12,11 +12,11 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API CarbonsPrivate : public Payload { - public: - typedef boost::shared_ptr<CarbonsPrivate> ref; + class SWIFTEN_API CarbonsPrivate : public Payload { + public: + typedef boost::shared_ptr<CarbonsPrivate> ref; - public: - virtual ~CarbonsPrivate(); - }; + public: + virtual ~CarbonsPrivate(); + }; } diff --git a/Swiften/Elements/CarbonsReceived.cpp b/Swiften/Elements/CarbonsReceived.cpp index d906f8e..1c0a72b 100644 --- a/Swiften/Elements/CarbonsReceived.cpp +++ b/Swiften/Elements/CarbonsReceived.cpp @@ -7,15 +7,15 @@ #include <Swiften/Elements/CarbonsReceived.h> namespace Swift { - CarbonsReceived::~CarbonsReceived() { + CarbonsReceived::~CarbonsReceived() { - } + } - void CarbonsReceived::setForwarded(boost::shared_ptr<Forwarded> forwarded) { - forwarded_ = forwarded; - } + void CarbonsReceived::setForwarded(boost::shared_ptr<Forwarded> forwarded) { + forwarded_ = forwarded; + } - boost::shared_ptr<Forwarded> CarbonsReceived::getForwarded() const { - return forwarded_; - } + boost::shared_ptr<Forwarded> CarbonsReceived::getForwarded() const { + return forwarded_; + } } diff --git a/Swiften/Elements/CarbonsReceived.h b/Swiften/Elements/CarbonsReceived.h index b057893..82ccff9 100644 --- a/Swiften/Elements/CarbonsReceived.h +++ b/Swiften/Elements/CarbonsReceived.h @@ -13,16 +13,16 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API CarbonsReceived : public Payload { - public: - typedef boost::shared_ptr<CarbonsReceived> ref; + class SWIFTEN_API CarbonsReceived : public Payload { + public: + typedef boost::shared_ptr<CarbonsReceived> ref; - public: - virtual ~CarbonsReceived(); - void setForwarded(boost::shared_ptr<Forwarded> forwarded); - boost::shared_ptr<Forwarded> getForwarded() const; + public: + virtual ~CarbonsReceived(); + void setForwarded(boost::shared_ptr<Forwarded> forwarded); + boost::shared_ptr<Forwarded> getForwarded() const; - private: - boost::shared_ptr<Forwarded> forwarded_; - }; + private: + boost::shared_ptr<Forwarded> forwarded_; + }; } diff --git a/Swiften/Elements/CarbonsSent.cpp b/Swiften/Elements/CarbonsSent.cpp index 08b2e13..c2380c6 100644 --- a/Swiften/Elements/CarbonsSent.cpp +++ b/Swiften/Elements/CarbonsSent.cpp @@ -7,15 +7,15 @@ #include <Swiften/Elements/CarbonsSent.h> namespace Swift { - CarbonsSent::~CarbonsSent() { - - } + CarbonsSent::~CarbonsSent() { - void CarbonsSent::setForwarded(boost::shared_ptr<Forwarded> forwarded) { - forwarded_ = forwarded; - } + } - boost::shared_ptr<Forwarded> CarbonsSent::getForwarded() const { - return forwarded_; - } + void CarbonsSent::setForwarded(boost::shared_ptr<Forwarded> forwarded) { + forwarded_ = forwarded; + } + + boost::shared_ptr<Forwarded> CarbonsSent::getForwarded() const { + return forwarded_; + } } diff --git a/Swiften/Elements/CarbonsSent.h b/Swiften/Elements/CarbonsSent.h index f6b2b53..d025a0d 100644 --- a/Swiften/Elements/CarbonsSent.h +++ b/Swiften/Elements/CarbonsSent.h @@ -13,16 +13,16 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API CarbonsSent : public Payload { - public: - typedef boost::shared_ptr<CarbonsSent> ref; + class SWIFTEN_API CarbonsSent : public Payload { + public: + typedef boost::shared_ptr<CarbonsSent> ref; - public: - virtual ~CarbonsSent(); - void setForwarded(boost::shared_ptr<Forwarded> forwarded); - boost::shared_ptr<Forwarded> getForwarded() const; + public: + virtual ~CarbonsSent(); + void setForwarded(boost::shared_ptr<Forwarded> forwarded); + boost::shared_ptr<Forwarded> getForwarded() const; - private: - boost::shared_ptr<Forwarded> forwarded_; - }; + private: + boost::shared_ptr<Forwarded> forwarded_; + }; } diff --git a/Swiften/Elements/ChatState.h b/Swiften/Elements/ChatState.h index 5f0bb9b..c1ae68e 100644 --- a/Swiften/Elements/ChatState.h +++ b/Swiften/Elements/ChatState.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API ChatState : public Payload { - public: - typedef boost::shared_ptr<ChatState> ref; + class SWIFTEN_API ChatState : public Payload { + public: + typedef boost::shared_ptr<ChatState> ref; - public: - enum ChatStateType {Active, Composing, Paused, Inactive, Gone}; - ChatState(ChatStateType state = Active) { - state_ = state; - } + public: + enum ChatStateType {Active, Composing, Paused, Inactive, Gone}; + ChatState(ChatStateType state = Active) { + state_ = state; + } - ChatStateType getChatState() const { return state_; } - void setChatState(ChatStateType state) {state_ = state;} + ChatStateType getChatState() const { return state_; } + void setChatState(ChatStateType state) {state_ = state;} - private: - ChatStateType state_; - }; + private: + ChatStateType state_; + }; } diff --git a/Swiften/Elements/Command.h b/Swiften/Elements/Command.h index e628c36..fff3d6b 100644 --- a/Swiften/Elements/Command.h +++ b/Swiften/Elements/Command.h @@ -15,69 +15,69 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - /** - * Ad-Hoc Command (XEP-0050). - */ - class SWIFTEN_API Command : public Payload { - public: - typedef boost::shared_ptr<Command> ref; - - enum Status {Executing, Completed, Canceled, NoStatus}; - enum Action {Cancel, Execute, Complete, Prev, Next, NoAction}; - - struct Note { - enum Type {Info, Warn, Error}; - - Note(std::string note, Type type) : note(note), type(type) {} - - std::string note; - Type type; - }; - - public: - Command(const std::string& node, const std::string& sessionID, Status status) { constructor(node, sessionID, NoAction, status);} - Command(const std::string& node = "", const std::string& sessionID = "", Action action = Execute) { constructor(node, sessionID, action, NoStatus); } - - const std::string& getNode() const { return node_; } - void setNode(const std::string& node) { node_ = node; } - - const std::string& getSessionID() const { return sessionID_; } - void setSessionID(const std::string& id) { sessionID_ = id; } - - Action getAction() const { return action_; } - void setAction(Action action) { action_ = action; } - - void setExecuteAction(Action action) { executeAction_ = action; } - Action getExecuteAction() const { return executeAction_; } - - Status getStatus() const { return status_; } - void setStatus(Status status) { status_ = status; } - - void addAvailableAction(Action action) { availableActions_.push_back(action); } - const std::vector<Action>& getAvailableActions() const { return availableActions_; } - void addNote(const Note& note) { notes_.push_back(note); } - const std::vector<Note>& getNotes() const { return notes_; } - - Form::ref getForm() const { return form_; } - void setForm(Form::ref payload) { form_ = payload; } - - private: - void constructor(const std::string& node, const std::string& sessionID, Action action, Status status) { - node_ = node; - sessionID_ = sessionID; - action_ = action; - status_ = status; - executeAction_ = NoAction; - } - - private: - std::string node_; - std::string sessionID_; - Action action_; - Status status_; - Action executeAction_; - std::vector<Action> availableActions_; - std::vector<Note> notes_; - Form::ref form_; - }; + /** + * Ad-Hoc Command (XEP-0050). + */ + class SWIFTEN_API Command : public Payload { + public: + typedef boost::shared_ptr<Command> ref; + + enum Status {Executing, Completed, Canceled, NoStatus}; + enum Action {Cancel, Execute, Complete, Prev, Next, NoAction}; + + struct Note { + enum Type {Info, Warn, Error}; + + Note(std::string note, Type type) : note(note), type(type) {} + + std::string note; + Type type; + }; + + public: + Command(const std::string& node, const std::string& sessionID, Status status) { constructor(node, sessionID, NoAction, status);} + Command(const std::string& node = "", const std::string& sessionID = "", Action action = Execute) { constructor(node, sessionID, action, NoStatus); } + + const std::string& getNode() const { return node_; } + void setNode(const std::string& node) { node_ = node; } + + const std::string& getSessionID() const { return sessionID_; } + void setSessionID(const std::string& id) { sessionID_ = id; } + + Action getAction() const { return action_; } + void setAction(Action action) { action_ = action; } + + void setExecuteAction(Action action) { executeAction_ = action; } + Action getExecuteAction() const { return executeAction_; } + + Status getStatus() const { return status_; } + void setStatus(Status status) { status_ = status; } + + void addAvailableAction(Action action) { availableActions_.push_back(action); } + const std::vector<Action>& getAvailableActions() const { return availableActions_; } + void addNote(const Note& note) { notes_.push_back(note); } + const std::vector<Note>& getNotes() const { return notes_; } + + Form::ref getForm() const { return form_; } + void setForm(Form::ref payload) { form_ = payload; } + + private: + void constructor(const std::string& node, const std::string& sessionID, Action action, Status status) { + node_ = node; + sessionID_ = sessionID; + action_ = action; + status_ = status; + executeAction_ = NoAction; + } + + private: + std::string node_; + std::string sessionID_; + Action action_; + Status status_; + Action executeAction_; + std::vector<Action> availableActions_; + std::vector<Note> notes_; + Form::ref form_; + }; } diff --git a/Swiften/Elements/ComponentHandshake.h b/Swiften/Elements/ComponentHandshake.h index 8efd618..e8afc18 100644 --- a/Swiften/Elements/ComponentHandshake.h +++ b/Swiften/Elements/ComponentHandshake.h @@ -14,22 +14,22 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API ComponentHandshake : public ToplevelElement { - public: - typedef boost::shared_ptr<ComponentHandshake> ref; + class SWIFTEN_API ComponentHandshake : public ToplevelElement { + public: + typedef boost::shared_ptr<ComponentHandshake> ref; - ComponentHandshake(const std::string& data = "") : data(data) { - } + ComponentHandshake(const std::string& data = "") : data(data) { + } - void setData(const std::string& d) { - data = d; - } + void setData(const std::string& d) { + data = d; + } - const std::string& getData() const { - return data; - } + const std::string& getData() const { + return data; + } - private: - std::string data; - }; + private: + std::string data; + }; } diff --git a/Swiften/Elements/CompressFailure.h b/Swiften/Elements/CompressFailure.h index a32ba27..8cdd268 100644 --- a/Swiften/Elements/CompressFailure.h +++ b/Swiften/Elements/CompressFailure.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API CompressFailure : public ToplevelElement { - public: - CompressFailure() {} - }; + class SWIFTEN_API CompressFailure : public ToplevelElement { + public: + CompressFailure() {} + }; } diff --git a/Swiften/Elements/CompressRequest.h b/Swiften/Elements/CompressRequest.h index 1c3fb39..7e813b9 100644 --- a/Swiften/Elements/CompressRequest.h +++ b/Swiften/Elements/CompressRequest.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API CompressRequest : public ToplevelElement - { - public: - CompressRequest(const std::string& method = "") : method_(method) {} + class SWIFTEN_API CompressRequest : public ToplevelElement + { + public: + CompressRequest(const std::string& method = "") : method_(method) {} - const std::string& getMethod() const { - return method_; - } + const std::string& getMethod() const { + return method_; + } - void setMethod(const std::string& method) { - method_ = method; - } + void setMethod(const std::string& method) { + method_ = method; + } - private: - std::string method_; - }; + private: + std::string method_; + }; } diff --git a/Swiften/Elements/Compressed.h b/Swiften/Elements/Compressed.h index bcfcacc..a2e236f 100644 --- a/Swiften/Elements/Compressed.h +++ b/Swiften/Elements/Compressed.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API Compressed : public ToplevelElement { - public: - Compressed() {} - }; + class SWIFTEN_API Compressed : public ToplevelElement { + public: + Compressed() {} + }; } diff --git a/Swiften/Elements/ContainerPayload.h b/Swiften/Elements/ContainerPayload.h index 30e7541..7435f34 100644 --- a/Swiften/Elements/ContainerPayload.h +++ b/Swiften/Elements/ContainerPayload.h @@ -15,21 +15,21 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - template<typename T> - class SWIFTEN_API ContainerPayload : public Payload { - public: - ContainerPayload() {} - ContainerPayload(boost::shared_ptr<T> payload) : payload(payload) {} - - void setPayload(boost::shared_ptr<T> payload) { - this->payload = payload; - } - - boost::shared_ptr<T> getPayload() const { - return payload; - } - - private: - boost::shared_ptr<T> payload; - }; + template<typename T> + class SWIFTEN_API ContainerPayload : public Payload { + public: + ContainerPayload() {} + ContainerPayload(boost::shared_ptr<T> payload) : payload(payload) {} + + void setPayload(boost::shared_ptr<T> payload) { + this->payload = payload; + } + + boost::shared_ptr<T> getPayload() const { + return payload; + } + + private: + boost::shared_ptr<T> payload; + }; } diff --git a/Swiften/Elements/Delay.h b/Swiften/Elements/Delay.h index 2cfb1d0..b154dea 100644 --- a/Swiften/Elements/Delay.h +++ b/Swiften/Elements/Delay.h @@ -14,19 +14,19 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API Delay : public Payload { - public: - Delay() {} - Delay(const boost::posix_time::ptime& time, const JID& from = JID()) : time_(time), from_(from) {} + class SWIFTEN_API Delay : public Payload { + public: + Delay() {} + Delay(const boost::posix_time::ptime& time, const JID& from = JID()) : time_(time), from_(from) {} - const boost::posix_time::ptime& getStamp() const {return time_;} - void setStamp(const boost::posix_time::ptime& time) {time_ = time;} + const boost::posix_time::ptime& getStamp() const {return time_;} + void setStamp(const boost::posix_time::ptime& time) {time_ = time;} - const boost::optional<JID>& getFrom() const {return from_;} - void setFrom(const JID& from) {from_ = from;} + const boost::optional<JID>& getFrom() const {return from_;} + void setFrom(const JID& from) {from_ = from;} - private: - boost::posix_time::ptime time_; - boost::optional<JID> from_; - }; + private: + boost::posix_time::ptime time_; + boost::optional<JID> from_; + }; } diff --git a/Swiften/Elements/DeliveryReceipt.h b/Swiften/Elements/DeliveryReceipt.h index eac5280..a4936a5 100644 --- a/Swiften/Elements/DeliveryReceipt.h +++ b/Swiften/Elements/DeliveryReceipt.h @@ -20,24 +20,24 @@ namespace Swift { class SWIFTEN_API DeliveryReceipt : public Payload { - public: - typedef boost::shared_ptr<DeliveryReceipt> ref; + public: + typedef boost::shared_ptr<DeliveryReceipt> ref; - public: - DeliveryReceipt() {} + public: + DeliveryReceipt() {} - DeliveryReceipt(const std::string& msgId) : receivedID_(msgId) {} + DeliveryReceipt(const std::string& msgId) : receivedID_(msgId) {} - void setReceivedID(const std::string& msgId) { - receivedID_ = msgId; - } + void setReceivedID(const std::string& msgId) { + receivedID_ = msgId; + } - std::string getReceivedID() const { - return receivedID_; - } + std::string getReceivedID() const { + return receivedID_; + } - private: - std::string receivedID_; + private: + std::string receivedID_; }; } diff --git a/Swiften/Elements/DeliveryReceiptRequest.h b/Swiften/Elements/DeliveryReceiptRequest.h index 1f03c5a..58086df 100644 --- a/Swiften/Elements/DeliveryReceiptRequest.h +++ b/Swiften/Elements/DeliveryReceiptRequest.h @@ -18,11 +18,11 @@ namespace Swift { class SWIFTEN_API DeliveryReceiptRequest : public Payload { - public: - typedef boost::shared_ptr<DeliveryReceiptRequest> ref; + public: + typedef boost::shared_ptr<DeliveryReceiptRequest> ref; - public: - DeliveryReceiptRequest() {} + public: + DeliveryReceiptRequest() {} }; } diff --git a/Swiften/Elements/DiscoInfo.cpp b/Swiften/Elements/DiscoInfo.cpp index 84f5ed3..29676b5 100644 --- a/Swiften/Elements/DiscoInfo.cpp +++ b/Swiften/Elements/DiscoInfo.cpp @@ -26,26 +26,26 @@ const std::string DiscoInfo::WhiteboardFeature = std::string("http://swift.im/wh const std::string DiscoInfo::BlockingCommandFeature = std::string("urn:xmpp:blocking"); bool DiscoInfo::Identity::operator<(const Identity& other) const { - if (category_ == other.category_) { - if (type_ == other.type_) { - if (lang_ == other.lang_) { - return name_ < other.name_; - } - else { - return lang_ < other.lang_; - } - } - else { - return type_ < other.type_; - } - } - else { - return category_ < other.category_; - } + if (category_ == other.category_) { + if (type_ == other.type_) { + if (lang_ == other.lang_) { + return name_ < other.name_; + } + else { + return lang_ < other.lang_; + } + } + else { + return type_ < other.type_; + } + } + else { + return category_ < other.category_; + } } bool DiscoInfo::hasFeature(const std::string& feature) const { - return std::find(features_.begin(), features_.end(), feature) != features_.end(); + return std::find(features_.begin(), features_.end(), feature) != features_.end(); } } diff --git a/Swiften/Elements/DiscoInfo.h b/Swiften/Elements/DiscoInfo.h index 01a49bd..d6ca6b8 100644 --- a/Swiften/Elements/DiscoInfo.h +++ b/Swiften/Elements/DiscoInfo.h @@ -14,100 +14,100 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - /** - * disco#info from XEP-0030 - */ - class SWIFTEN_API DiscoInfo : public Payload { - public: - typedef boost::shared_ptr<DiscoInfo> ref; - - static const std::string ChatStatesFeature; - static const std::string SecurityLabelsFeature; - static const std::string SecurityLabelsCatalogFeature; - static const std::string JabberSearchFeature; - static const std::string CommandsFeature; - static const std::string MessageCorrectionFeature; - static const std::string JingleFeature; - static const std::string JingleFTFeature; - static const std::string JingleTransportsIBBFeature; - static const std::string JingleTransportsS5BFeature; - static const std::string Bytestream; - static const std::string MessageDeliveryReceiptsFeature; - static const std::string WhiteboardFeature; - static const std::string BlockingCommandFeature; - - class Identity { - public: - Identity(const std::string& name, const std::string& category = "client", const std::string& type = "pc", const std::string& lang = "") : name_(name), category_(category), type_(type), lang_(lang) { - } - - const std::string& getCategory() const { - return category_; - } - - const std::string& getType() const { - return type_; - } - - const std::string& getLanguage() const { - return lang_; - } - - const std::string& getName() const { - return name_; - } - - // Sorted according to XEP-115 rules - bool operator<(const Identity& other) const; - - private: - std::string name_; - std::string category_; - std::string type_; - std::string lang_; - }; - - DiscoInfo() { - } - - const std::string& getNode() const { - return node_; - } - - void setNode(const std::string& node) { - node_ = node; - } - - const std::vector<Identity>& getIdentities() const { - return identities_; - } - - void addIdentity(const Identity& identity) { - identities_.push_back(identity); - } - - const std::vector<std::string>& getFeatures() const { - return features_; - } - - void addFeature(const std::string& feature) { - features_.push_back(feature); - } - - bool hasFeature(const std::string& feature) const; - - void addExtension(Form::ref form) { - extensions_.push_back(form); - } - - const std::vector<Form::ref>& getExtensions() const { - return extensions_; - } - - private: - std::string node_; - std::vector<Identity> identities_; - std::vector<std::string> features_; - std::vector<Form::ref> extensions_; - }; + /** + * disco#info from XEP-0030 + */ + class SWIFTEN_API DiscoInfo : public Payload { + public: + typedef boost::shared_ptr<DiscoInfo> ref; + + static const std::string ChatStatesFeature; + static const std::string SecurityLabelsFeature; + static const std::string SecurityLabelsCatalogFeature; + static const std::string JabberSearchFeature; + static const std::string CommandsFeature; + static const std::string MessageCorrectionFeature; + static const std::string JingleFeature; + static const std::string JingleFTFeature; + static const std::string JingleTransportsIBBFeature; + static const std::string JingleTransportsS5BFeature; + static const std::string Bytestream; + static const std::string MessageDeliveryReceiptsFeature; + static const std::string WhiteboardFeature; + static const std::string BlockingCommandFeature; + + class Identity { + public: + Identity(const std::string& name, const std::string& category = "client", const std::string& type = "pc", const std::string& lang = "") : name_(name), category_(category), type_(type), lang_(lang) { + } + + const std::string& getCategory() const { + return category_; + } + + const std::string& getType() const { + return type_; + } + + const std::string& getLanguage() const { + return lang_; + } + + const std::string& getName() const { + return name_; + } + + // Sorted according to XEP-115 rules + bool operator<(const Identity& other) const; + + private: + std::string name_; + std::string category_; + std::string type_; + std::string lang_; + }; + + DiscoInfo() { + } + + const std::string& getNode() const { + return node_; + } + + void setNode(const std::string& node) { + node_ = node; + } + + const std::vector<Identity>& getIdentities() const { + return identities_; + } + + void addIdentity(const Identity& identity) { + identities_.push_back(identity); + } + + const std::vector<std::string>& getFeatures() const { + return features_; + } + + void addFeature(const std::string& feature) { + features_.push_back(feature); + } + + bool hasFeature(const std::string& feature) const; + + void addExtension(Form::ref form) { + extensions_.push_back(form); + } + + const std::vector<Form::ref>& getExtensions() const { + return extensions_; + } + + private: + std::string node_; + std::vector<Identity> identities_; + std::vector<std::string> features_; + std::vector<Form::ref> extensions_; + }; } diff --git a/Swiften/Elements/DiscoItems.h b/Swiften/Elements/DiscoItems.h index 4672444..9c06b8d 100644 --- a/Swiften/Elements/DiscoItems.h +++ b/Swiften/Elements/DiscoItems.h @@ -14,58 +14,58 @@ #include <Swiften/JID/JID.h> namespace Swift { - /** - * Service discovery disco#items from XEP-0030. - */ - class SWIFTEN_API DiscoItems : public Payload { - public: - /** - * A single result item. - */ - class Item { - public: - Item(const std::string& name, const JID& jid, const std::string& node="") : name_(name), jid_(jid), node_(node) { - } + /** + * Service discovery disco#items from XEP-0030. + */ + class SWIFTEN_API DiscoItems : public Payload { + public: + /** + * A single result item. + */ + class Item { + public: + Item(const std::string& name, const JID& jid, const std::string& node="") : name_(name), jid_(jid), node_(node) { + } - const std::string& getName() const { - return name_; - } + const std::string& getName() const { + return name_; + } - const std::string& getNode() const { - return node_; - } + const std::string& getNode() const { + return node_; + } - const JID& getJID() const { - return jid_; - } + const JID& getJID() const { + return jid_; + } - private: - std::string name_; - JID jid_; - std::string node_; - }; + private: + std::string name_; + JID jid_; + std::string node_; + }; - DiscoItems() { - } + DiscoItems() { + } - const std::string& getNode() const { - return node_; - } + const std::string& getNode() const { + return node_; + } - void setNode(const std::string& node) { - node_ = node; - } + void setNode(const std::string& node) { + node_ = node; + } - const std::vector<Item>& getItems() const { - return items_; - } + const std::vector<Item>& getItems() const { + return items_; + } - void addItem(const Item& item) { - items_.push_back(item); - } + void addItem(const Item& item) { + items_.push_back(item); + } - private: - std::string node_; - std::vector<Item> items_; - }; + private: + std::string node_; + std::vector<Item> items_; + }; } diff --git a/Swiften/Elements/Element.h b/Swiften/Elements/Element.h index 3cd5f94..b036a29 100644 --- a/Swiften/Elements/Element.h +++ b/Swiften/Elements/Element.h @@ -9,12 +9,12 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API Element { - public: - Element() {} - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Element) - virtual ~Element(); + class SWIFTEN_API Element { + public: + Element() {} + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Element) + virtual ~Element(); - SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Element) - }; + SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Element) + }; } diff --git a/Swiften/Elements/EnableStreamManagement.h b/Swiften/Elements/EnableStreamManagement.h index c16a290..bf867e2 100644 --- a/Swiften/Elements/EnableStreamManagement.h +++ b/Swiften/Elements/EnableStreamManagement.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API EnableStreamManagement : public ToplevelElement { - public: - EnableStreamManagement() {} - }; + class SWIFTEN_API EnableStreamManagement : public ToplevelElement { + public: + EnableStreamManagement() {} + }; } diff --git a/Swiften/Elements/ErrorPayload.h b/Swiften/Elements/ErrorPayload.h index d2556f9..800ff22 100644 --- a/Swiften/Elements/ErrorPayload.h +++ b/Swiften/Elements/ErrorPayload.h @@ -14,75 +14,75 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API ErrorPayload : public Payload { - public: - typedef boost::shared_ptr<ErrorPayload> ref; - - enum Type { Cancel, Continue, Modify, Auth, Wait }; - - enum Condition { - BadRequest, - Conflict, - FeatureNotImplemented, - Forbidden, - Gone, - InternalServerError, - ItemNotFound, - JIDMalformed, - NotAcceptable, - NotAllowed, - NotAuthorized, - PaymentRequired, - RecipientUnavailable, - Redirect, - RegistrationRequired, - RemoteServerNotFound, - RemoteServerTimeout, - ResourceConstraint, - ServiceUnavailable, - SubscriptionRequired, - UndefinedCondition, - UnexpectedRequest - }; - - ErrorPayload(Condition condition = UndefinedCondition, Type type = Cancel, const std::string& text = std::string()) : type_(type), condition_(condition), text_(text) { } - - Type getType() const { - return type_; - } - - void setType(Type type) { - type_ = type; - } - - Condition getCondition() const { - return condition_; - } - - void setCondition(Condition condition) { - condition_ = condition; - } - - void setText(const std::string& text) { - text_ = text; - } - - const std::string& getText() const { - return text_; - } - - void setPayload(boost::shared_ptr<Payload> payload) { - payload_ = payload; - } - - boost::shared_ptr<Payload> getPayload() const { - return payload_; - } - - private: - Type type_; - Condition condition_; - std::string text_; - boost::shared_ptr<Payload> payload_; - }; + class SWIFTEN_API ErrorPayload : public Payload { + public: + typedef boost::shared_ptr<ErrorPayload> ref; + + enum Type { Cancel, Continue, Modify, Auth, Wait }; + + enum Condition { + BadRequest, + Conflict, + FeatureNotImplemented, + Forbidden, + Gone, + InternalServerError, + ItemNotFound, + JIDMalformed, + NotAcceptable, + NotAllowed, + NotAuthorized, + PaymentRequired, + RecipientUnavailable, + Redirect, + RegistrationRequired, + RemoteServerNotFound, + RemoteServerTimeout, + ResourceConstraint, + ServiceUnavailable, + SubscriptionRequired, + UndefinedCondition, + UnexpectedRequest + }; + + ErrorPayload(Condition condition = UndefinedCondition, Type type = Cancel, const std::string& text = std::string()) : type_(type), condition_(condition), text_(text) { } + + Type getType() const { + return type_; + } + + void setType(Type type) { + type_ = type; + } + + Condition getCondition() const { + return condition_; + } + + void setCondition(Condition condition) { + condition_ = condition; + } + + void setText(const std::string& text) { + text_ = text; + } + + const std::string& getText() const { + return text_; + } + + void setPayload(boost::shared_ptr<Payload> payload) { + payload_ = payload; + } + + boost::shared_ptr<Payload> getPayload() const { + return payload_; + } + + private: + Type type_; + Condition condition_; + std::string text_; + boost::shared_ptr<Payload> payload_; + }; } diff --git a/Swiften/Elements/Form.cpp b/Swiften/Elements/Form.cpp index d6de8ff..f8414b2 100644 --- a/Swiften/Elements/Form.cpp +++ b/Swiften/Elements/Form.cpp @@ -11,56 +11,56 @@ namespace Swift { std::string Form::getFormType() const { - FormField::ref field = getField("FORM_TYPE"); - if (field && field->getType() == FormField::HiddenType) { - return field->getValues().empty() ? "" : field->getValues()[0]; - } - return ""; + FormField::ref field = getField("FORM_TYPE"); + if (field && field->getType() == FormField::HiddenType) { + return field->getValues().empty() ? "" : field->getValues()[0]; + } + return ""; } FormField::ref Form::getField(const std::string& name) const { - foreach(FormField::ref field, fields_) { - if (field->getName() == name) { - return field; - } - } - return FormField::ref(); + foreach(FormField::ref field, fields_) { + if (field->getName() == name) { + return field; + } + } + return FormField::ref(); } void Form::addReportedField(FormField::ref field) { - reportedFields_.push_back(field); + reportedFields_.push_back(field); } const std::vector<FormField::ref>& Form::getReportedFields() const { - return reportedFields_; + return reportedFields_; } void Form::addItem(const Form::FormItem& item) { - items_.push_back(item); + items_.push_back(item); } const std::vector<Form::FormItem>& Form::getItems() const { - return items_; + return items_; } void Form::clearEmptyTextFields() { - std::vector<FormField::ref> populatedFields; - foreach (FormField::ref field, fields_) { - if (field->getType() == FormField::TextSingleType) { - if (!field->getTextSingleValue().empty()) { - populatedFields.push_back(field); - } - } - else if (field->getType() == FormField::TextMultiType) { - if (!field->getTextMultiValue().empty()) { - populatedFields.push_back(field); - } - } - else { - populatedFields.push_back(field); - } - } - fields_ = populatedFields; + std::vector<FormField::ref> populatedFields; + foreach (FormField::ref field, fields_) { + if (field->getType() == FormField::TextSingleType) { + if (!field->getTextSingleValue().empty()) { + populatedFields.push_back(field); + } + } + else if (field->getType() == FormField::TextMultiType) { + if (!field->getTextMultiValue().empty()) { + populatedFields.push_back(field); + } + } + else { + populatedFields.push_back(field); + } + } + fields_ = populatedFields; } } diff --git a/Swiften/Elements/Form.h b/Swiften/Elements/Form.h index 31faf25..ebdb161 100644 --- a/Swiften/Elements/Form.h +++ b/Swiften/Elements/Form.h @@ -17,107 +17,107 @@ #include <Swiften/JID/JID.h> namespace Swift { - /** - * XEP-0004 Data form. - * For the relevant Fields, the parsers and serialisers protect the API user against - * the strange multi-value instead of newline thing by transforming them. - */ - class SWIFTEN_API Form : public Payload { - public: - typedef boost::shared_ptr<Form> ref; - typedef std::vector<FormField::ref> FormItem; - - enum Type { FormType, SubmitType, CancelType, ResultType }; - - public: - Form(Type type = FormType) : type_(type) {} - - void addPage(boost::shared_ptr<FormPage> page) { - assert(page); - pages_.push_back(page); - } - - const std::vector<boost::shared_ptr<FormPage> >& getPages() const { - return pages_; - } - - void addField(boost::shared_ptr<FormField> field) { - assert(field); - fields_.push_back(field); - } - - const std::vector<boost::shared_ptr<FormField> >& getFields() const { - return fields_; - } - - void clearFields() { - fields_.clear(); - } - - void addTextElement(boost::shared_ptr<FormText> text) { - assert(text); - textElements_.push_back(text); - } - - const std::vector<boost::shared_ptr<FormText> >& getTextElements() const { - return textElements_; - } - - void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) { - assert(reportedRef); - reportedRefs_.push_back(reportedRef); - } - - const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const { - return reportedRefs_; - } - - void setTitle(const std::string& title) { - title_ = title; - } - - const std::string& getTitle() const { - return title_; - } - - void setInstructions(const std::string& instructions) { - instructions_ = instructions; - } - - const std::string& getInstructions() const { - return instructions_; - } - - Type getType() const { - return type_; - } - - void setType(Type type) { - type_ = type; - } - - std::string getFormType() const; - FormField::ref getField(const std::string& name) const; - void addItem(const FormItem& item); - const std::vector<FormItem>& getItems() const; - void clearItems() { items_.clear(); } - - void clearEmptyTextFields(); - - void addReportedField(FormField::ref field); - const std::vector<FormField::ref> & getReportedFields() const; - void clearReportedFields() { reportedFields_.clear(); } - - private: - std::vector<boost::shared_ptr<FormReportedRef> >reportedRefs_; - std::vector<boost::shared_ptr<FormText> > textElements_; - std::vector<boost::shared_ptr<FormPage> > pages_; - std::vector<boost::shared_ptr<FormField> > fields_; - std::vector<boost::shared_ptr<FormField> > reportedFields_; - std::vector<FormItem> items_; - boost::shared_ptr<FormReportedRef> reportedRef_; - std::string title_; - std::string instructions_; - Type type_; - }; + /** + * XEP-0004 Data form. + * For the relevant Fields, the parsers and serialisers protect the API user against + * the strange multi-value instead of newline thing by transforming them. + */ + class SWIFTEN_API Form : public Payload { + public: + typedef boost::shared_ptr<Form> ref; + typedef std::vector<FormField::ref> FormItem; + + enum Type { FormType, SubmitType, CancelType, ResultType }; + + public: + Form(Type type = FormType) : type_(type) {} + + void addPage(boost::shared_ptr<FormPage> page) { + assert(page); + pages_.push_back(page); + } + + const std::vector<boost::shared_ptr<FormPage> >& getPages() const { + return pages_; + } + + void addField(boost::shared_ptr<FormField> field) { + assert(field); + fields_.push_back(field); + } + + const std::vector<boost::shared_ptr<FormField> >& getFields() const { + return fields_; + } + + void clearFields() { + fields_.clear(); + } + + void addTextElement(boost::shared_ptr<FormText> text) { + assert(text); + textElements_.push_back(text); + } + + const std::vector<boost::shared_ptr<FormText> >& getTextElements() const { + return textElements_; + } + + void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) { + assert(reportedRef); + reportedRefs_.push_back(reportedRef); + } + + const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const { + return reportedRefs_; + } + + void setTitle(const std::string& title) { + title_ = title; + } + + const std::string& getTitle() const { + return title_; + } + + void setInstructions(const std::string& instructions) { + instructions_ = instructions; + } + + const std::string& getInstructions() const { + return instructions_; + } + + Type getType() const { + return type_; + } + + void setType(Type type) { + type_ = type; + } + + std::string getFormType() const; + FormField::ref getField(const std::string& name) const; + void addItem(const FormItem& item); + const std::vector<FormItem>& getItems() const; + void clearItems() { items_.clear(); } + + void clearEmptyTextFields(); + + void addReportedField(FormField::ref field); + const std::vector<FormField::ref> & getReportedFields() const; + void clearReportedFields() { reportedFields_.clear(); } + + private: + std::vector<boost::shared_ptr<FormReportedRef> >reportedRefs_; + std::vector<boost::shared_ptr<FormText> > textElements_; + std::vector<boost::shared_ptr<FormPage> > pages_; + std::vector<boost::shared_ptr<FormField> > fields_; + std::vector<boost::shared_ptr<FormField> > reportedFields_; + std::vector<FormItem> items_; + boost::shared_ptr<FormReportedRef> reportedRef_; + std::string title_; + std::string instructions_; + Type type_; + }; } diff --git a/Swiften/Elements/FormField.cpp b/Swiften/Elements/FormField.cpp index f8ebbca..d4bc9f4 100644 --- a/Swiften/Elements/FormField.cpp +++ b/Swiften/Elements/FormField.cpp @@ -16,17 +16,17 @@ FormField::~FormField() { } std::string FormField::getTextMultiValue() const { - assert(type == TextMultiType || type == UnknownType); - return boost::algorithm::join(values, "\n"); + assert(type == TextMultiType || type == UnknownType); + return boost::algorithm::join(values, "\n"); } void FormField::setTextMultiValue(const std::string& value) { - assert(type == TextMultiType || type == UnknownType); - values.clear(); - boost::split(values, value, boost::is_any_of("\n")); + assert(type == TextMultiType || type == UnknownType); + values.clear(); + boost::split(values, value, boost::is_any_of("\n")); } void FormField::setBoolValue(bool b) { - values.clear(); - values.push_back(b ? "1" : "0"); + values.clear(); + values.push_back(b ? "1" : "0"); } diff --git a/Swiften/Elements/FormField.h b/Swiften/Elements/FormField.h index d84dbb6..e62dec4 100644 --- a/Swiften/Elements/FormField.h +++ b/Swiften/Elements/FormField.h @@ -15,126 +15,126 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API FormField { - public: - typedef boost::shared_ptr<FormField> ref; - - enum Type { - UnknownType, - BooleanType, - FixedType, - HiddenType, - ListSingleType, - TextMultiType, - TextPrivateType, - TextSingleType, - JIDSingleType, - JIDMultiType, - ListMultiType - }; - - FormField(Type type = UnknownType) : type(type), required(false) {} - FormField(Type type, const std::string& value) : type(type), required(false) { - addValue(value); - } - virtual ~FormField(); - - struct Option { - Option(const std::string& label, const std::string& value) : label(label), value(value) {} - std::string label; - std::string value; - }; - - void setName(const std::string& name) { this->name = name; } - const std::string& getName() const { return name; } - - void setLabel(const std::string& label) { this->label = label; } - const std::string& getLabel() const { return label; } - - void setDescription(const std::string& description) { this->description = description; } - const std::string& getDescription() const { return description; } - - void setRequired(bool required) { this->required = required; } - bool getRequired() const { return required; } - - void addOption(const Option& option) { - options.push_back(option); - } - - const std::vector<Option>& getOptions() const { - return options; - } - - void clearOptions() { - options.clear(); - } - - const std::vector<std::string>& getValues() const { - return values; - } - - void addValue(const std::string& value) { - values.push_back(value); - } - - Type getType() const { - return type; - } - - void setType(Type type) { - this->type = type; - } - - // Type specific - - bool getBoolValue() const { - assert(type == BooleanType || type == UnknownType); - if (values.empty()) { - return false; - } - return values[0] == "true" || values[0] == "1"; - } - - void setBoolValue(bool b); - - JID getJIDSingleValue() const { - assert(type == JIDSingleType || type == UnknownType); - return values.empty() ? JID() : JID(values[0]); - } - - JID getJIDMultiValue(size_t index) const { - assert(type == JIDMultiType || type == UnknownType); - return values.empty() ? JID() : JID(values[index]); - } - - std::string getTextPrivateValue() const { - assert(type == TextPrivateType || type == UnknownType); - return values.empty() ? "" : values[0]; - } - - std::string getFixedValue() const { - assert(type == FixedType || type == UnknownType); - return values.empty() ? "" : values[0]; - } - - std::string getTextSingleValue() const { - assert(type == TextSingleType || type == UnknownType); - return values.empty() ? "" : values[0]; - } - - std::string getTextMultiValue() const; - void setTextMultiValue(const std::string& value); - - protected: - - private: - Type type; - std::string name; - std::string label; - std::string description; - bool required; - std::vector<Option> options; - std::vector<std::string> values; - }; + class SWIFTEN_API FormField { + public: + typedef boost::shared_ptr<FormField> ref; + + enum Type { + UnknownType, + BooleanType, + FixedType, + HiddenType, + ListSingleType, + TextMultiType, + TextPrivateType, + TextSingleType, + JIDSingleType, + JIDMultiType, + ListMultiType + }; + + FormField(Type type = UnknownType) : type(type), required(false) {} + FormField(Type type, const std::string& value) : type(type), required(false) { + addValue(value); + } + virtual ~FormField(); + + struct Option { + Option(const std::string& label, const std::string& value) : label(label), value(value) {} + std::string label; + std::string value; + }; + + void setName(const std::string& name) { this->name = name; } + const std::string& getName() const { return name; } + + void setLabel(const std::string& label) { this->label = label; } + const std::string& getLabel() const { return label; } + + void setDescription(const std::string& description) { this->description = description; } + const std::string& getDescription() const { return description; } + + void setRequired(bool required) { this->required = required; } + bool getRequired() const { return required; } + + void addOption(const Option& option) { + options.push_back(option); + } + + const std::vector<Option>& getOptions() const { + return options; + } + + void clearOptions() { + options.clear(); + } + + const std::vector<std::string>& getValues() const { + return values; + } + + void addValue(const std::string& value) { + values.push_back(value); + } + + Type getType() const { + return type; + } + + void setType(Type type) { + this->type = type; + } + + // Type specific + + bool getBoolValue() const { + assert(type == BooleanType || type == UnknownType); + if (values.empty()) { + return false; + } + return values[0] == "true" || values[0] == "1"; + } + + void setBoolValue(bool b); + + JID getJIDSingleValue() const { + assert(type == JIDSingleType || type == UnknownType); + return values.empty() ? JID() : JID(values[0]); + } + + JID getJIDMultiValue(size_t index) const { + assert(type == JIDMultiType || type == UnknownType); + return values.empty() ? JID() : JID(values[index]); + } + + std::string getTextPrivateValue() const { + assert(type == TextPrivateType || type == UnknownType); + return values.empty() ? "" : values[0]; + } + + std::string getFixedValue() const { + assert(type == FixedType || type == UnknownType); + return values.empty() ? "" : values[0]; + } + + std::string getTextSingleValue() const { + assert(type == TextSingleType || type == UnknownType); + return values.empty() ? "" : values[0]; + } + + std::string getTextMultiValue() const; + void setTextMultiValue(const std::string& value); + + protected: + + private: + Type type; + std::string name; + std::string label; + std::string description; + bool required; + std::vector<Option> options; + std::vector<std::string> values; + }; } diff --git a/Swiften/Elements/FormPage.cpp b/Swiften/Elements/FormPage.cpp index db7979f..a4e1616 100644 --- a/Swiften/Elements/FormPage.cpp +++ b/Swiften/Elements/FormPage.cpp @@ -14,51 +14,51 @@ FormPage::~FormPage() { } void FormPage::setLabel(const std::string& label) { - label_ = label; + label_ = label; } const std::string& FormPage::getLabel() const { - return label_; + return label_; } void FormPage::addChildSection(boost::shared_ptr<FormSection> section) { - childSections_.push_back(section); + childSections_.push_back(section); } const std::vector<boost::shared_ptr<FormSection> >& FormPage::getChildSections() const { - return childSections_; + return childSections_; } void FormPage::addTextElement(boost::shared_ptr<FormText> textElement) { - textElements_.push_back(textElement); + textElements_.push_back(textElement); } const std::vector<boost::shared_ptr<FormText> >& FormPage::getTextElements() const { - return textElements_; + return textElements_; } void FormPage::addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) { - reportedRefs_.push_back(reportedRef); + reportedRefs_.push_back(reportedRef); } const std::vector<boost::shared_ptr<FormReportedRef> >& FormPage::getReportedRefs() const { - return reportedRefs_; + return reportedRefs_; } void FormPage::addField(boost::shared_ptr<FormField> field) { - fields_.push_back(field); + fields_.push_back(field); } const std::vector<boost::shared_ptr<FormField> >& FormPage::getFields() const { - return fields_; + return fields_; } void FormPage::addFieldRef(std::string ref) { - fieldRefs_.push_back(ref); + fieldRefs_.push_back(ref); } const std::vector<std::string> FormPage::getFieldRefs() const { - return fieldRefs_; + return fieldRefs_; } } diff --git a/Swiften/Elements/FormPage.h b/Swiften/Elements/FormPage.h index 35bf63b..f7a4a9a 100644 --- a/Swiften/Elements/FormPage.h +++ b/Swiften/Elements/FormPage.h @@ -18,30 +18,30 @@ namespace Swift { - class SWIFTEN_API FormPage { - public: - typedef boost::shared_ptr<FormPage> page; - FormPage (); - ~FormPage(); - void setLabel(const std::string& label); - const std::string& getLabel() const; - void addChildSection(boost::shared_ptr<FormSection> section); - const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const; - void addTextElement(boost::shared_ptr<FormText> textElement); - const std::vector<boost::shared_ptr<FormText> >& getTextElements() const; - void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef); - const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const; - void addField(boost::shared_ptr<FormField> field); - const std::vector<boost::shared_ptr<FormField> >& getFields() const; - void addFieldRef(std::string ref); - const std::vector<std::string> getFieldRefs() const; + class SWIFTEN_API FormPage { + public: + typedef boost::shared_ptr<FormPage> page; + FormPage (); + ~FormPage(); + void setLabel(const std::string& label); + const std::string& getLabel() const; + void addChildSection(boost::shared_ptr<FormSection> section); + const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const; + void addTextElement(boost::shared_ptr<FormText> textElement); + const std::vector<boost::shared_ptr<FormText> >& getTextElements() const; + void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef); + const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const; + void addField(boost::shared_ptr<FormField> field); + const std::vector<boost::shared_ptr<FormField> >& getFields() const; + void addFieldRef(std::string ref); + const std::vector<std::string> getFieldRefs() const; - private: - std::string label_; - std::vector<boost::shared_ptr<FormText> > textElements_; - std::vector<boost::shared_ptr<FormSection> > childSections_; - std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_; - std::vector<boost::shared_ptr<FormField> > fields_; - std::vector<std::string> fieldRefs_; - }; + private: + std::string label_; + std::vector<boost::shared_ptr<FormText> > textElements_; + std::vector<boost::shared_ptr<FormSection> > childSections_; + std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_; + std::vector<boost::shared_ptr<FormField> > fields_; + std::vector<std::string> fieldRefs_; + }; } diff --git a/Swiften/Elements/FormReportedRef.h b/Swiften/Elements/FormReportedRef.h index 03a89d1..a972f10 100644 --- a/Swiften/Elements/FormReportedRef.h +++ b/Swiften/Elements/FormReportedRef.h @@ -11,9 +11,9 @@ namespace Swift { - class SWIFTEN_API FormReportedRef { + class SWIFTEN_API FormReportedRef { - public: - typedef boost::shared_ptr<FormReportedRef> ref; - }; + public: + typedef boost::shared_ptr<FormReportedRef> ref; + }; } diff --git a/Swiften/Elements/FormSection.cpp b/Swiften/Elements/FormSection.cpp index 7b254df..2fe1954 100644 --- a/Swiften/Elements/FormSection.cpp +++ b/Swiften/Elements/FormSection.cpp @@ -14,51 +14,51 @@ FormSection::~FormSection() { } void FormSection::setLabel(const std::string& label) { - label_ = label; + label_ = label; } const std::string& FormSection::getLabel() const { - return label_; + return label_; } void FormSection::addTextElement(boost::shared_ptr<FormText> textElement) { - textElements_.push_back(textElement); + textElements_.push_back(textElement); } const std::vector<boost::shared_ptr<FormText> >& FormSection::getTextElements() const { - return textElements_; + return textElements_; } void FormSection::addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) { - reportedRefs_.push_back(reportedRef); + reportedRefs_.push_back(reportedRef); } const std::vector<boost::shared_ptr<FormReportedRef> >& FormSection::getReportedRefs() const { - return reportedRefs_; + return reportedRefs_; } void FormSection::addChildSection(boost::shared_ptr<FormSection> childSection) { - childSections_.push_back(childSection); + childSections_.push_back(childSection); } const std::vector<boost::shared_ptr<FormSection> >& FormSection::getChildSections() const { - return childSections_; + return childSections_; } void FormSection::addField(boost::shared_ptr<FormField> field) { - fields_.push_back(field); + fields_.push_back(field); } const std::vector<boost::shared_ptr<FormField> >& FormSection::getFields() const { - return fields_; + return fields_; } void FormSection::addFieldRef(std::string ref) { - fieldRefs_.push_back(ref); + fieldRefs_.push_back(ref); } const std::vector<std::string> FormSection::getFieldRefs() const { - return fieldRefs_; + return fieldRefs_; } } diff --git a/Swiften/Elements/FormSection.h b/Swiften/Elements/FormSection.h index 523d507..69638c4 100644 --- a/Swiften/Elements/FormSection.h +++ b/Swiften/Elements/FormSection.h @@ -17,30 +17,30 @@ namespace Swift { - class SWIFTEN_API FormSection { - public: - typedef boost::shared_ptr<FormSection> section; - FormSection(); - ~FormSection(); - void setLabel(const std::string& label); - const std::string& getLabel() const; - void addTextElement(boost::shared_ptr<FormText> textElement); - const std::vector<boost::shared_ptr<FormText> >& getTextElements() const; - void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef); - const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const; - void addChildSection(boost::shared_ptr<FormSection> childSection); - const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const; - void addField(boost::shared_ptr<FormField> field); - const std::vector<boost::shared_ptr<FormField> >& getFields() const; - void addFieldRef(std::string ref); - const std::vector<std::string> getFieldRefs() const; + class SWIFTEN_API FormSection { + public: + typedef boost::shared_ptr<FormSection> section; + FormSection(); + ~FormSection(); + void setLabel(const std::string& label); + const std::string& getLabel() const; + void addTextElement(boost::shared_ptr<FormText> textElement); + const std::vector<boost::shared_ptr<FormText> >& getTextElements() const; + void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef); + const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const; + void addChildSection(boost::shared_ptr<FormSection> childSection); + const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const; + void addField(boost::shared_ptr<FormField> field); + const std::vector<boost::shared_ptr<FormField> >& getFields() const; + void addFieldRef(std::string ref); + const std::vector<std::string> getFieldRefs() const; - private: - std::string label_; - std::vector<boost::shared_ptr<FormText> > textElements_; - std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_; - std::vector<boost::shared_ptr<FormSection> > childSections_; - std::vector<boost::shared_ptr<FormField> > fields_; - std::vector<std::string> fieldRefs_; - }; + private: + std::string label_; + std::vector<boost::shared_ptr<FormText> > textElements_; + std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_; + std::vector<boost::shared_ptr<FormSection> > childSections_; + std::vector<boost::shared_ptr<FormField> > fields_; + std::vector<std::string> fieldRefs_; + }; } diff --git a/Swiften/Elements/FormText.cpp b/Swiften/Elements/FormText.cpp index cbbfbe4..2180e13 100644 --- a/Swiften/Elements/FormText.cpp +++ b/Swiften/Elements/FormText.cpp @@ -14,11 +14,11 @@ FormText::~FormText() { } void FormText::setTextString(const std::string& text) { - text_ = text; + text_ = text; } const std::string& FormText::getTextString() const { - return text_; + return text_; } } diff --git a/Swiften/Elements/FormText.h b/Swiften/Elements/FormText.h index 5df1a25..1d95a3a 100644 --- a/Swiften/Elements/FormText.h +++ b/Swiften/Elements/FormText.h @@ -13,16 +13,16 @@ namespace Swift { - class SWIFTEN_API FormText{ + class SWIFTEN_API FormText{ - public: - typedef boost::shared_ptr<FormText> text; - FormText(); - virtual ~FormText(); - void setTextString(const std::string& text); - const std::string& getTextString() const; + public: + typedef boost::shared_ptr<FormText> text; + FormText(); + virtual ~FormText(); + void setTextString(const std::string& text); + const std::string& getTextString() const; - private: - std::string text_; - }; + private: + std::string text_; + }; } diff --git a/Swiften/Elements/Forwarded.h b/Swiften/Elements/Forwarded.h index b39f5a5..8401fe1 100644 --- a/Swiften/Elements/Forwarded.h +++ b/Swiften/Elements/Forwarded.h @@ -13,21 +13,21 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class Delay; - class Stanza; + class Delay; + class Stanza; - class SWIFTEN_API Forwarded : public Payload { - public: - virtual ~Forwarded(); + class SWIFTEN_API Forwarded : public Payload { + public: + virtual ~Forwarded(); - void setDelay(boost::shared_ptr<Delay> delay) { delay_ = delay; } - const boost::shared_ptr<Delay>& getDelay() const { return delay_; } + void setDelay(boost::shared_ptr<Delay> delay) { delay_ = delay; } + const boost::shared_ptr<Delay>& getDelay() const { return delay_; } - void setStanza(boost::shared_ptr<Stanza> stanza) { stanza_ = stanza; } - const boost::shared_ptr<Stanza>& getStanza() const { return stanza_; } + void setStanza(boost::shared_ptr<Stanza> stanza) { stanza_ = stanza; } + const boost::shared_ptr<Stanza>& getStanza() const { return stanza_; } - private: - boost::shared_ptr<Delay> delay_; - boost::shared_ptr<Stanza> stanza_; - }; + private: + boost::shared_ptr<Delay> delay_; + boost::shared_ptr<Stanza> stanza_; + }; } diff --git a/Swiften/Elements/HashElement.h b/Swiften/Elements/HashElement.h index cc5a0e4..bbe4d1c 100644 --- a/Swiften/Elements/HashElement.h +++ b/Swiften/Elements/HashElement.h @@ -12,34 +12,34 @@ #include <Swiften/Base/ByteArray.h> namespace Swift { - /* - * @brief This class represents a XEP-0300 <hash/> element. - */ - class SWIFTEN_API HashElement { - public: - HashElement(const std::string& algorithm, const ByteArray& hash) : algorithm_(algorithm), hash_(hash) { - } - - void setHashValue(const std::string& algorithm, const ByteArray& hash) { - algorithm_ = algorithm; - hash_ = hash; - } - - const std::string& getAlgorithm() const { - return algorithm_; - } - - const ByteArray& getHashValue() const { - return hash_; - } - - bool operator==(const HashElement& rhs) const { - return (algorithm_ == rhs.algorithm_) && (hash_ == rhs.hash_); - } - - - private: - std::string algorithm_; - ByteArray hash_; - }; + /* + * @brief This class represents a XEP-0300 <hash/> element. + */ + class SWIFTEN_API HashElement { + public: + HashElement(const std::string& algorithm, const ByteArray& hash) : algorithm_(algorithm), hash_(hash) { + } + + void setHashValue(const std::string& algorithm, const ByteArray& hash) { + algorithm_ = algorithm; + hash_ = hash; + } + + const std::string& getAlgorithm() const { + return algorithm_; + } + + const ByteArray& getHashValue() const { + return hash_; + } + + bool operator==(const HashElement& rhs) const { + return (algorithm_ == rhs.algorithm_) && (hash_ == rhs.hash_); + } + + + private: + std::string algorithm_; + ByteArray hash_; + }; } diff --git a/Swiften/Elements/IBB.h b/Swiften/Elements/IBB.h index a06e3bc..97a46bb 100644 --- a/Swiften/Elements/IBB.h +++ b/Swiften/Elements/IBB.h @@ -16,94 +16,94 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API IBB : public Payload { - public: - typedef boost::shared_ptr<IBB> ref; - - enum Action { - Open, - Close, - Data - }; - enum StanzaType { - IQStanza, - MessageStanza - }; - - IBB(Action action = Open, const std::string& streamID = "") : action(action), streamID(streamID), stanzaType(IQStanza), blockSize(-1), sequenceNumber(-1) { - } - - static IBB::ref createIBBOpen(const std::string& streamID, int blockSize) { - IBB::ref result = boost::make_shared<IBB>(Open, streamID); - result->setBlockSize(blockSize); - return result; - } - - static IBB::ref createIBBData(const std::string& streamID, int sequenceNumber, const std::vector<unsigned char>& data) { - IBB::ref result = boost::make_shared<IBB>(Data, streamID); - result->setSequenceNumber(sequenceNumber); - result->setData(data); - return result; - } - - static IBB::ref createIBBClose(const std::string& streamID) { - return boost::make_shared<IBB>(Close, streamID); - } - - void setAction(Action action) { - this->action = action; - } - - Action getAction() const { - return action; - } - - void setStanzaType(StanzaType stanzaType) { - this->stanzaType = stanzaType; - } - - StanzaType getStanzaType() const { - return stanzaType; - } - - void setStreamID(const std::string& id) { - streamID = id; - } - - const std::string& getStreamID() const { - return streamID; - } - - const std::vector<unsigned char>& getData() const { - return data; - } - - void setData(const std::vector<unsigned char>& data) { - this->data = data; - } - - int getBlockSize() const { - return blockSize; - } - - void setBlockSize(int blockSize) { - this->blockSize = blockSize; - } - - int getSequenceNumber() const { - return sequenceNumber; - } - - void setSequenceNumber(int i) { - sequenceNumber = i; - } - - private: - Action action; - std::string streamID; - std::vector<unsigned char> data; - StanzaType stanzaType; - int blockSize; - int sequenceNumber; - }; + class SWIFTEN_API IBB : public Payload { + public: + typedef boost::shared_ptr<IBB> ref; + + enum Action { + Open, + Close, + Data + }; + enum StanzaType { + IQStanza, + MessageStanza + }; + + IBB(Action action = Open, const std::string& streamID = "") : action(action), streamID(streamID), stanzaType(IQStanza), blockSize(-1), sequenceNumber(-1) { + } + + static IBB::ref createIBBOpen(const std::string& streamID, int blockSize) { + IBB::ref result = boost::make_shared<IBB>(Open, streamID); + result->setBlockSize(blockSize); + return result; + } + + static IBB::ref createIBBData(const std::string& streamID, int sequenceNumber, const std::vector<unsigned char>& data) { + IBB::ref result = boost::make_shared<IBB>(Data, streamID); + result->setSequenceNumber(sequenceNumber); + result->setData(data); + return result; + } + + static IBB::ref createIBBClose(const std::string& streamID) { + return boost::make_shared<IBB>(Close, streamID); + } + + void setAction(Action action) { + this->action = action; + } + + Action getAction() const { + return action; + } + + void setStanzaType(StanzaType stanzaType) { + this->stanzaType = stanzaType; + } + + StanzaType getStanzaType() const { + return stanzaType; + } + + void setStreamID(const std::string& id) { + streamID = id; + } + + const std::string& getStreamID() const { + return streamID; + } + + const std::vector<unsigned char>& getData() const { + return data; + } + + void setData(const std::vector<unsigned char>& data) { + this->data = data; + } + + int getBlockSize() const { + return blockSize; + } + + void setBlockSize(int blockSize) { + this->blockSize = blockSize; + } + + int getSequenceNumber() const { + return sequenceNumber; + } + + void setSequenceNumber(int i) { + sequenceNumber = i; + } + + private: + Action action; + std::string streamID; + std::vector<unsigned char> data; + StanzaType stanzaType; + int blockSize; + int sequenceNumber; + }; } diff --git a/Swiften/Elements/IQ.cpp b/Swiften/Elements/IQ.cpp index 343a205..cd1498e 100644 --- a/Swiften/Elements/IQ.cpp +++ b/Swiften/Elements/IQ.cpp @@ -11,58 +11,58 @@ namespace Swift { boost::shared_ptr<IQ> IQ::createRequest( - Type type, const JID& to, const std::string& id, boost::shared_ptr<Payload> payload) { - boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(type); - if (to.isValid()) { - iq->setTo(to); - } - iq->setID(id); - if (payload) { - iq->addPayload(payload); - } - return iq; + Type type, const JID& to, const std::string& id, boost::shared_ptr<Payload> payload) { + boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(type); + if (to.isValid()) { + iq->setTo(to); + } + iq->setID(id); + if (payload) { + iq->addPayload(payload); + } + return iq; } boost::shared_ptr<IQ> IQ::createResult(const JID& to, const std::string& id, boost::shared_ptr<Payload> payload) { - boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result); - iq->setTo(to); - iq->setID(id); - if (payload) { - iq->addPayload(payload); - } - return iq; + boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result); + iq->setTo(to); + iq->setID(id); + if (payload) { + iq->addPayload(payload); + } + return iq; } boost::shared_ptr<IQ> IQ::createResult(const JID& to, const JID& from, const std::string& id, boost::shared_ptr<Payload> payload) { - boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result); - iq->setTo(to); - iq->setFrom(from); - iq->setID(id); - if (payload) { - iq->addPayload(payload); - } - return iq; + boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result); + iq->setTo(to); + iq->setFrom(from); + iq->setID(id); + if (payload) { + iq->addPayload(payload); + } + return iq; } boost::shared_ptr<IQ> IQ::createError(const JID& to, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, boost::shared_ptr<Payload> payload) { - boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error); - iq->setTo(to); - iq->setID(id); - boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type); - errorPayload->setPayload(payload); - iq->addPayload(errorPayload); - return iq; + boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error); + iq->setTo(to); + iq->setID(id); + boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type); + errorPayload->setPayload(payload); + iq->addPayload(errorPayload); + return iq; } boost::shared_ptr<IQ> IQ::createError(const JID& to, const JID& from, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, boost::shared_ptr<Payload> payload) { - boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error); - iq->setTo(to); - iq->setFrom(from); - iq->setID(id); - boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type); - errorPayload->setPayload(payload); - iq->addPayload(errorPayload); - return iq; + boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error); + iq->setTo(to); + iq->setFrom(from); + iq->setID(id); + boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type); + errorPayload->setPayload(payload); + iq->addPayload(errorPayload); + return iq; } } diff --git a/Swiften/Elements/IQ.h b/Swiften/Elements/IQ.h index b77dd03..275c00e 100644 --- a/Swiften/Elements/IQ.h +++ b/Swiften/Elements/IQ.h @@ -13,46 +13,46 @@ #include <Swiften/Elements/Stanza.h> namespace Swift { - class SWIFTEN_API IQ : public Stanza { - public: - typedef boost::shared_ptr<IQ> ref; - - enum Type { Get, Set, Result, Error }; - - IQ(Type type = Get) : type_(type) { } - - Type getType() const { return type_; } - void setType(Type type) { type_ = type; } - - static boost::shared_ptr<IQ> createRequest( - Type type, - const JID& to, - const std::string& id, - boost::shared_ptr<Payload> payload); - static boost::shared_ptr<IQ> createResult( - const JID& to, - const std::string& id, - boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); - static boost::shared_ptr<IQ> createResult( - const JID& to, - const JID& from, - const std::string& id, - boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); - static boost::shared_ptr<IQ> createError( - const JID& to, - const std::string& id, - ErrorPayload::Condition condition = ErrorPayload::BadRequest, - ErrorPayload::Type type = ErrorPayload::Cancel, - boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); - static boost::shared_ptr<IQ> createError( - const JID& to, - const JID& from, - const std::string& id, - ErrorPayload::Condition condition = ErrorPayload::BadRequest, - ErrorPayload::Type type = ErrorPayload::Cancel, - boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); - - private: - Type type_; - }; + class SWIFTEN_API IQ : public Stanza { + public: + typedef boost::shared_ptr<IQ> ref; + + enum Type { Get, Set, Result, Error }; + + IQ(Type type = Get) : type_(type) { } + + Type getType() const { return type_; } + void setType(Type type) { type_ = type; } + + static boost::shared_ptr<IQ> createRequest( + Type type, + const JID& to, + const std::string& id, + boost::shared_ptr<Payload> payload); + static boost::shared_ptr<IQ> createResult( + const JID& to, + const std::string& id, + boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); + static boost::shared_ptr<IQ> createResult( + const JID& to, + const JID& from, + const std::string& id, + boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); + static boost::shared_ptr<IQ> createError( + const JID& to, + const std::string& id, + ErrorPayload::Condition condition = ErrorPayload::BadRequest, + ErrorPayload::Type type = ErrorPayload::Cancel, + boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); + static boost::shared_ptr<IQ> createError( + const JID& to, + const JID& from, + const std::string& id, + ErrorPayload::Condition condition = ErrorPayload::BadRequest, + ErrorPayload::Type type = ErrorPayload::Cancel, + boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()); + + private: + Type type_; + }; } diff --git a/Swiften/Elements/Idle.h b/Swiften/Elements/Idle.h index ec170fb..07ecc74 100644 --- a/Swiften/Elements/Idle.h +++ b/Swiften/Elements/Idle.h @@ -20,25 +20,25 @@ namespace Swift { - class SWIFTEN_API Idle : public Payload { - public: - typedef boost::shared_ptr<Idle> ref; - - public: - Idle() {} - Idle(boost::posix_time::ptime since) : since_(since) { - } - - void setSince(boost::posix_time::ptime since) { - since_ = since; - } - - boost::posix_time::ptime getSince() const { - return since_; - } - - private: - boost::posix_time::ptime since_; - }; + class SWIFTEN_API Idle : public Payload { + public: + typedef boost::shared_ptr<Idle> ref; + + public: + Idle() {} + Idle(boost::posix_time::ptime since) : since_(since) { + } + + void setSince(boost::posix_time::ptime since) { + since_ = since; + } + + boost::posix_time::ptime getSince() const { + return since_; + } + + private: + boost::posix_time::ptime since_; + }; } diff --git a/Swiften/Elements/InBandRegistrationPayload.h b/Swiften/Elements/InBandRegistrationPayload.h index ef40c8f..a282df8 100644 --- a/Swiften/Elements/InBandRegistrationPayload.h +++ b/Swiften/Elements/InBandRegistrationPayload.h @@ -16,196 +16,196 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API InBandRegistrationPayload : public Payload { - public: - typedef boost::shared_ptr<InBandRegistrationPayload> ref; + class SWIFTEN_API InBandRegistrationPayload : public Payload { + public: + typedef boost::shared_ptr<InBandRegistrationPayload> ref; - InBandRegistrationPayload() : registered(false), remove(false) {} + InBandRegistrationPayload() : registered(false), remove(false) {} - Form::ref getForm() const { return form; } - void setForm(Form::ref f) { form = f; } + Form::ref getForm() const { return form; } + void setForm(Form::ref f) { form = f; } - bool isRegistered() const { - return registered; - } + bool isRegistered() const { + return registered; + } - void setRegistered(bool b) { - registered = b; - } + void setRegistered(bool b) { + registered = b; + } - bool isRemove() const { - return remove; - } + bool isRemove() const { + return remove; + } - void setRemove(bool b) { - remove = b; - } + void setRemove(bool b) { + remove = b; + } - const boost::optional<std::string>& getInstructions() const { - return instructions; - } + const boost::optional<std::string>& getInstructions() const { + return instructions; + } - const boost::optional<std::string>& getUsername() const { - return username; - } + const boost::optional<std::string>& getUsername() const { + return username; + } - const boost::optional<std::string>& getNick() const { - return nick; - } + const boost::optional<std::string>& getNick() const { + return nick; + } - const boost::optional<std::string>& getPassword() const { - return password; - } + const boost::optional<std::string>& getPassword() const { + return password; + } - const boost::optional<std::string>& getName() const { - return name; - } + const boost::optional<std::string>& getName() const { + return name; + } - const boost::optional<std::string>& getFirst() const { - return first; - } + const boost::optional<std::string>& getFirst() const { + return first; + } - const boost::optional<std::string>& getLast() const { - return last; - } + const boost::optional<std::string>& getLast() const { + return last; + } - const boost::optional<std::string>& getEMail() const { - return email; - } + const boost::optional<std::string>& getEMail() const { + return email; + } - const boost::optional<std::string>& getAddress() const { - return address; - } + const boost::optional<std::string>& getAddress() const { + return address; + } - const boost::optional<std::string>& getCity() const { - return city; - } + const boost::optional<std::string>& getCity() const { + return city; + } - const boost::optional<std::string>& getState() const { - return state; - } + const boost::optional<std::string>& getState() const { + return state; + } - const boost::optional<std::string>& getZip() const { - return zip; - } + const boost::optional<std::string>& getZip() const { + return zip; + } - const boost::optional<std::string>& getPhone() const { - return phone; - } - - const boost::optional<std::string>& getURL() const { - return url; - } - - const boost::optional<std::string>& getDate() const { - return date; - } - - const boost::optional<std::string>& getMisc() const { - return misc; - } - - const boost::optional<std::string>& getText() const { - return text; - } - - const boost::optional<std::string>& getKey() const { - return key; - } - - void setInstructions(const std::string& v) { - this->instructions = v; - } - - void setUsername(const std::string& v) { - this->username = v; - } - - void setNick(const std::string& v) { - this->nick = v; - } - - void setPassword(const std::string& v) { - this->password = v; - } - - void setName(const std::string& v) { - this->name = v; - } - - void setFirst(const std::string& v) { - this->first = v; - } - - void setLast(const std::string& v) { - this->last = v; - } - - void setEMail(const std::string& v) { - this->email = v; - } - - void setAddress(const std::string& v) { - this->address = v; - } - - void setCity(const std::string& v) { - this->city = v; - } - - void setState(const std::string& v) { - this->state = v; - } - - void setZip(const std::string& v) { - this->zip = v; - } - - void setPhone(const std::string& v) { - this->phone = v; - } - - void setURL(const std::string& v) { - this->url = v; - } - - void setDate(const std::string& v) { - this->date = v; - } - - void setMisc(const std::string& v) { - this->misc = v; - } - - void setText(const std::string& v) { - this->text = v; - } - - void setKey(const std::string& v) { - this->key = v; - } - - private: - Form::ref form; - bool registered; - bool remove; - boost::optional<std::string> instructions; - boost::optional<std::string> username; - boost::optional<std::string> nick; - boost::optional<std::string> password; - boost::optional<std::string> name; - boost::optional<std::string> first; - boost::optional<std::string> last; - boost::optional<std::string> email; - boost::optional<std::string> address; - boost::optional<std::string> city; - boost::optional<std::string> state; - boost::optional<std::string> zip; - boost::optional<std::string> phone; - boost::optional<std::string> url; - boost::optional<std::string> date; - boost::optional<std::string> misc; - boost::optional<std::string> text; - boost::optional<std::string> key; - }; + const boost::optional<std::string>& getPhone() const { + return phone; + } + + const boost::optional<std::string>& getURL() const { + return url; + } + + const boost::optional<std::string>& getDate() const { + return date; + } + + const boost::optional<std::string>& getMisc() const { + return misc; + } + + const boost::optional<std::string>& getText() const { + return text; + } + + const boost::optional<std::string>& getKey() const { + return key; + } + + void setInstructions(const std::string& v) { + this->instructions = v; + } + + void setUsername(const std::string& v) { + this->username = v; + } + + void setNick(const std::string& v) { + this->nick = v; + } + + void setPassword(const std::string& v) { + this->password = v; + } + + void setName(const std::string& v) { + this->name = v; + } + + void setFirst(const std::string& v) { + this->first = v; + } + + void setLast(const std::string& v) { + this->last = v; + } + + void setEMail(const std::string& v) { + this->email = v; + } + + void setAddress(const std::string& v) { + this->address = v; + } + + void setCity(const std::string& v) { + this->city = v; + } + + void setState(const std::string& v) { + this->state = v; + } + + void setZip(const std::string& v) { + this->zip = v; + } + + void setPhone(const std::string& v) { + this->phone = v; + } + + void setURL(const std::string& v) { + this->url = v; + } + + void setDate(const std::string& v) { + this->date = v; + } + + void setMisc(const std::string& v) { + this->misc = v; + } + + void setText(const std::string& v) { + this->text = v; + } + + void setKey(const std::string& v) { + this->key = v; + } + + private: + Form::ref form; + bool registered; + bool remove; + boost::optional<std::string> instructions; + boost::optional<std::string> username; + boost::optional<std::string> nick; + boost::optional<std::string> password; + boost::optional<std::string> name; + boost::optional<std::string> first; + boost::optional<std::string> last; + boost::optional<std::string> email; + boost::optional<std::string> address; + boost::optional<std::string> city; + boost::optional<std::string> state; + boost::optional<std::string> zip; + boost::optional<std::string> phone; + boost::optional<std::string> url; + boost::optional<std::string> date; + boost::optional<std::string> misc; + boost::optional<std::string> text; + boost::optional<std::string> key; + }; } diff --git a/Swiften/Elements/IsodeIQDelegation.h b/Swiften/Elements/IsodeIQDelegation.h index 7bd618c..12fd9bd 100644 --- a/Swiften/Elements/IsodeIQDelegation.h +++ b/Swiften/Elements/IsodeIQDelegation.h @@ -14,23 +14,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API IsodeIQDelegation : public Payload { - public: - - IsodeIQDelegation(); - - virtual ~IsodeIQDelegation(); + class SWIFTEN_API IsodeIQDelegation : public Payload { + public: - boost::shared_ptr<Forwarded> getForward() const { - return forward; - } + IsodeIQDelegation(); - void setForward(boost::shared_ptr<Forwarded> value) { - this->forward = value ; - } + virtual ~IsodeIQDelegation(); + boost::shared_ptr<Forwarded> getForward() const { + return forward; + } - private: - boost::shared_ptr<Forwarded> forward; - }; + void setForward(boost::shared_ptr<Forwarded> value) { + this->forward = value ; + } + + + private: + boost::shared_ptr<Forwarded> forward; + }; } diff --git a/Swiften/Elements/JingleContentPayload.h b/Swiften/Elements/JingleContentPayload.h index 5ec2e33..46751fd 100644 --- a/Swiften/Elements/JingleContentPayload.h +++ b/Swiften/Elements/JingleContentPayload.h @@ -18,85 +18,85 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API JingleContentPayload : public Payload { - public: - typedef boost::shared_ptr<JingleContentPayload> ref; - - enum Creator { - UnknownCreator, - InitiatorCreator, - ResponderCreator - }; - - JingleContentPayload() : creator(UnknownCreator) { - } - - /*enum Senders { - NoSenders, - InitiatorSender, - ResponderSender, - BothSenders, - };*/ - - Creator getCreator() const { - return creator; - } - - void setCreator(Creator creator) { - this->creator = creator; - } - - const std::string& getName() const { - return name; - } - - void setName(const std::string& name) { - this->name = name; - } - - const std::vector<JingleDescription::ref>& getDescriptions() const { - return descriptions; - } - - void addDescription(JingleDescription::ref description) { - descriptions.push_back(description); - } - - const std::vector<boost::shared_ptr<JingleTransportPayload> >& getTransports() const { - return transports; - } - - void addTransport(boost::shared_ptr<JingleTransportPayload> transport) { - transports.push_back(transport); - } - - template<typename T> - boost::shared_ptr<T> getDescription() const { - for (size_t i = 0; i < descriptions.size(); ++i) { - boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(descriptions[i])); - if (result) { - return result; - } - } - return boost::shared_ptr<T>(); - } - - template<typename T> - boost::shared_ptr<T> getTransport() const { - for (size_t i = 0; i < transports.size(); ++i) { - boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(transports[i])); - if (result) { - return result; - } - } - return boost::shared_ptr<T>(); - } - - private: - Creator creator; - std::string name; - //Senders senders; - std::vector<JingleDescription::ref> descriptions; - std::vector<boost::shared_ptr<JingleTransportPayload> > transports; - }; + class SWIFTEN_API JingleContentPayload : public Payload { + public: + typedef boost::shared_ptr<JingleContentPayload> ref; + + enum Creator { + UnknownCreator, + InitiatorCreator, + ResponderCreator + }; + + JingleContentPayload() : creator(UnknownCreator) { + } + + /*enum Senders { + NoSenders, + InitiatorSender, + ResponderSender, + BothSenders, + };*/ + + Creator getCreator() const { + return creator; + } + + void setCreator(Creator creator) { + this->creator = creator; + } + + const std::string& getName() const { + return name; + } + + void setName(const std::string& name) { + this->name = name; + } + + const std::vector<JingleDescription::ref>& getDescriptions() const { + return descriptions; + } + + void addDescription(JingleDescription::ref description) { + descriptions.push_back(description); + } + + const std::vector<boost::shared_ptr<JingleTransportPayload> >& getTransports() const { + return transports; + } + + void addTransport(boost::shared_ptr<JingleTransportPayload> transport) { + transports.push_back(transport); + } + + template<typename T> + boost::shared_ptr<T> getDescription() const { + for (size_t i = 0; i < descriptions.size(); ++i) { + boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(descriptions[i])); + if (result) { + return result; + } + } + return boost::shared_ptr<T>(); + } + + template<typename T> + boost::shared_ptr<T> getTransport() const { + for (size_t i = 0; i < transports.size(); ++i) { + boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(transports[i])); + if (result) { + return result; + } + } + return boost::shared_ptr<T>(); + } + + private: + Creator creator; + std::string name; + //Senders senders; + std::vector<JingleDescription::ref> descriptions; + std::vector<boost::shared_ptr<JingleTransportPayload> > transports; + }; } diff --git a/Swiften/Elements/JingleDescription.h b/Swiften/Elements/JingleDescription.h index 7577383..b52291e 100644 --- a/Swiften/Elements/JingleDescription.h +++ b/Swiften/Elements/JingleDescription.h @@ -12,8 +12,8 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API JingleDescription : public Payload { - public: - typedef boost::shared_ptr<JingleDescription> ref; - }; + class SWIFTEN_API JingleDescription : public Payload { + public: + typedef boost::shared_ptr<JingleDescription> ref; + }; } diff --git a/Swiften/Elements/JingleFileTransferDescription.h b/Swiften/Elements/JingleFileTransferDescription.h index e37f2c6..4389bb2 100644 --- a/Swiften/Elements/JingleFileTransferDescription.h +++ b/Swiften/Elements/JingleFileTransferDescription.h @@ -15,19 +15,19 @@ #include <Swiften/Elements/JingleFileTransferFileInfo.h> namespace Swift { - class SWIFTEN_API JingleFileTransferDescription : public JingleDescription { - public: - typedef boost::shared_ptr<JingleFileTransferDescription> ref; + class SWIFTEN_API JingleFileTransferDescription : public JingleDescription { + public: + typedef boost::shared_ptr<JingleFileTransferDescription> ref; - void setFileInfo(const JingleFileTransferFileInfo& fileInfo) { - fileInfo_ = fileInfo; - } + void setFileInfo(const JingleFileTransferFileInfo& fileInfo) { + fileInfo_ = fileInfo; + } - const JingleFileTransferFileInfo& getFileInfo() { - return fileInfo_; - } + const JingleFileTransferFileInfo& getFileInfo() { + return fileInfo_; + } - private: - JingleFileTransferFileInfo fileInfo_; - }; + private: + JingleFileTransferFileInfo fileInfo_; + }; } diff --git a/Swiften/Elements/JingleFileTransferFileInfo.h b/Swiften/Elements/JingleFileTransferFileInfo.h index 40640c8..cc592c4 100644 --- a/Swiften/Elements/JingleFileTransferFileInfo.h +++ b/Swiften/Elements/JingleFileTransferFileInfo.h @@ -20,102 +20,102 @@ namespace Swift { - /** - * @brief This class represents the file info used in XEP-0234. - */ - class SWIFTEN_API JingleFileTransferFileInfo : public Payload { - typedef boost::shared_ptr<JingleFileTransferFileInfo> ref; - - public: - JingleFileTransferFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0, const boost::posix_time::ptime &date = boost::posix_time::ptime()) : - name_(name), description_(description), size_(size), date_(date), supportsRangeRequests_(false), rangeOffset_(0) { - } - - public: - typedef std::map<std::string, ByteArray> HashElementMap; - - public: - void setName(const std::string& name) { - name_ = name;; - } - - const std::string& getName() const { - return name_; - } - - void setDescription(const std::string& description) { - description_ = description; - } - - const std::string& getDescription() const { - return description_; - } - - void setMediaType(const std::string& mediaType) { - mediaType_ = mediaType; - } - - const std::string& getMediaType() const { - return mediaType_; - } - - void setSize(const boost::uintmax_t size) { - size_ = size; - } - - boost::uintmax_t getSize() const { - return size_; - } - - void setDate(const boost::posix_time::ptime& date) { - date_ = date; - } - - const boost::posix_time::ptime& getDate() const { - return date_; - } - - void setSupportsRangeRequests(const bool supportsIt) { - supportsRangeRequests_ = supportsIt; - } - - bool getSupportsRangeRequests() const { - return supportsRangeRequests_; - } - - void setRangeOffset(const boost::uintmax_t offset) { - supportsRangeRequests_ = true; - rangeOffset_ = offset; - } - - boost::uintmax_t getRangeOffset() const { - return rangeOffset_; - } - - void addHash(const HashElement& hash) { - hashes_[hash.getAlgorithm()] = hash.getHashValue(); - } - - const std::map<std::string, ByteArray>& getHashes() const { - return hashes_; - } - - boost::optional<ByteArray> getHash(const std::string& algorithm) const { - boost::optional<ByteArray> ret; - if (hashes_.find(algorithm) != hashes_.end()) { - ret = boost::optional<ByteArray>(hashes_.find(algorithm)->second); - } - return ret; - } - - private: - std::string name_; - std::string description_; - std::string mediaType_; - boost::uintmax_t size_; - boost::posix_time::ptime date_; - bool supportsRangeRequests_; - boost::uintmax_t rangeOffset_; - HashElementMap hashes_; - }; + /** + * @brief This class represents the file info used in XEP-0234. + */ + class SWIFTEN_API JingleFileTransferFileInfo : public Payload { + typedef boost::shared_ptr<JingleFileTransferFileInfo> ref; + + public: + JingleFileTransferFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0, const boost::posix_time::ptime &date = boost::posix_time::ptime()) : + name_(name), description_(description), size_(size), date_(date), supportsRangeRequests_(false), rangeOffset_(0) { + } + + public: + typedef std::map<std::string, ByteArray> HashElementMap; + + public: + void setName(const std::string& name) { + name_ = name;; + } + + const std::string& getName() const { + return name_; + } + + void setDescription(const std::string& description) { + description_ = description; + } + + const std::string& getDescription() const { + return description_; + } + + void setMediaType(const std::string& mediaType) { + mediaType_ = mediaType; + } + + const std::string& getMediaType() const { + return mediaType_; + } + + void setSize(const boost::uintmax_t size) { + size_ = size; + } + + boost::uintmax_t getSize() const { + return size_; + } + + void setDate(const boost::posix_time::ptime& date) { + date_ = date; + } + + const boost::posix_time::ptime& getDate() const { + return date_; + } + + void setSupportsRangeRequests(const bool supportsIt) { + supportsRangeRequests_ = supportsIt; + } + + bool getSupportsRangeRequests() const { + return supportsRangeRequests_; + } + + void setRangeOffset(const boost::uintmax_t offset) { + supportsRangeRequests_ = true; + rangeOffset_ = offset; + } + + boost::uintmax_t getRangeOffset() const { + return rangeOffset_; + } + + void addHash(const HashElement& hash) { + hashes_[hash.getAlgorithm()] = hash.getHashValue(); + } + + const std::map<std::string, ByteArray>& getHashes() const { + return hashes_; + } + + boost::optional<ByteArray> getHash(const std::string& algorithm) const { + boost::optional<ByteArray> ret; + if (hashes_.find(algorithm) != hashes_.end()) { + ret = boost::optional<ByteArray>(hashes_.find(algorithm)->second); + } + return ret; + } + + private: + std::string name_; + std::string description_; + std::string mediaType_; + boost::uintmax_t size_; + boost::posix_time::ptime date_; + bool supportsRangeRequests_; + boost::uintmax_t rangeOffset_; + HashElementMap hashes_; + }; } diff --git a/Swiften/Elements/JingleFileTransferHash.h b/Swiften/Elements/JingleFileTransferHash.h index 7c56fe8..42fc23c 100644 --- a/Swiften/Elements/JingleFileTransferHash.h +++ b/Swiften/Elements/JingleFileTransferHash.h @@ -25,18 +25,18 @@ namespace Swift { class SWIFTEN_API JingleFileTransferHash : public Payload { public: - typedef boost::shared_ptr<JingleFileTransferHash> ref; + typedef boost::shared_ptr<JingleFileTransferHash> ref; - void setFileInfo(const JingleFileTransferFileInfo& fileInfo) { - fileInfo_ = fileInfo; - } + void setFileInfo(const JingleFileTransferFileInfo& fileInfo) { + fileInfo_ = fileInfo; + } - JingleFileTransferFileInfo& getFileInfo() { - return fileInfo_; - } + JingleFileTransferFileInfo& getFileInfo() { + return fileInfo_; + } private: - JingleFileTransferFileInfo fileInfo_; + JingleFileTransferFileInfo fileInfo_; }; - + } diff --git a/Swiften/Elements/JingleIBBTransportPayload.h b/Swiften/Elements/JingleIBBTransportPayload.h index efadf0b..6626f51 100644 --- a/Swiften/Elements/JingleIBBTransportPayload.h +++ b/Swiften/Elements/JingleIBBTransportPayload.h @@ -15,36 +15,36 @@ #include <Swiften/Elements/JingleTransportPayload.h> namespace Swift { - class SWIFTEN_API JingleIBBTransportPayload : public JingleTransportPayload { - public: - typedef boost::shared_ptr<JingleIBBTransportPayload> ref; - - enum StanzaType { - IQStanza, - MessageStanza - }; - - JingleIBBTransportPayload() : stanzaType(IQStanza) { - } - - void setStanzaType(StanzaType stanzaType) { - this->stanzaType = stanzaType; - } - - StanzaType getStanzaType() const { - return stanzaType; - } - - boost::optional<unsigned int> getBlockSize() const { - return blockSize; - } - - void setBlockSize(unsigned int blockSize) { - this->blockSize = blockSize; - } - - private: - boost::optional<unsigned int> blockSize; - StanzaType stanzaType; - }; + class SWIFTEN_API JingleIBBTransportPayload : public JingleTransportPayload { + public: + typedef boost::shared_ptr<JingleIBBTransportPayload> ref; + + enum StanzaType { + IQStanza, + MessageStanza + }; + + JingleIBBTransportPayload() : stanzaType(IQStanza) { + } + + void setStanzaType(StanzaType stanzaType) { + this->stanzaType = stanzaType; + } + + StanzaType getStanzaType() const { + return stanzaType; + } + + boost::optional<unsigned int> getBlockSize() const { + return blockSize; + } + + void setBlockSize(unsigned int blockSize) { + this->blockSize = blockSize; + } + + private: + boost::optional<unsigned int> blockSize; + StanzaType stanzaType; + }; } diff --git a/Swiften/Elements/JinglePayload.h b/Swiften/Elements/JinglePayload.h index 359e3ca..a862c41 100644 --- a/Swiften/Elements/JinglePayload.h +++ b/Swiften/Elements/JinglePayload.h @@ -18,150 +18,150 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API JinglePayload : public Payload { - public: - typedef boost::shared_ptr<JinglePayload> ref; - struct Reason : public Payload { - enum Type { - UnknownType, - AlternativeSession, - Busy, - Cancel, - ConnectivityError, - Decline, - Expired, - FailedApplication, - FailedTransport, - GeneralError, - Gone, - IncompatibleParameters, - MediaError, - SecurityError, - Success, - Timeout, - UnsupportedApplications, - UnsupportedTransports - }; - Reason() : type(UnknownType), text("") {} - Reason(Type type, const std::string& text = "") : type(type), text(text) {} - Type type; - std::string text; - }; - - enum Action { - UnknownAction, - ContentAccept, - ContentAdd, - ContentModify, - ContentReject, - ContentRemove, - DescriptionInfo, - SecurityInfo, - SessionAccept, - SessionInfo, - SessionInitiate, - SessionTerminate, - TransportAccept, - TransportInfo, - TransportReject, - TransportReplace - }; - JinglePayload() : action(SessionTerminate), sessionID("") { - } - - JinglePayload(Action action, const std::string& sessionID) : action(action), sessionID(sessionID) { - - } - - void setAction(Action action) { - this->action = action; - } - - Action getAction() const { - return action; - } - - void setInitiator(const JID& initiator) { - this->initiator = initiator; - } - - const JID& getInitiator() const { - return initiator; - } - - void setResponder(const JID& responder) { - this->responder = responder; - } - - const JID& getResponder() const { - return responder; - } - - void setSessionID(const std::string& id) { - sessionID = id; - } - - const std::string& getSessionID() const { - return sessionID; - } - - void addContent(JingleContentPayload::ref content) { - this->payloads.push_back(content); - } - - void addPayload(boost::shared_ptr<Payload> payload) { - this->payloads.push_back(payload); - } - - const std::vector<JingleContentPayload::ref> getContents() const { - return getPayloads<JingleContentPayload>(); - } - - const std::vector<boost::shared_ptr<Payload> > getPayloads() const { - return payloads; - } - - template<typename T> - const std::vector<boost::shared_ptr<T> > getPayloads() const { - std::vector<boost::shared_ptr<T> > matched_payloads; - for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) { - boost::shared_ptr<T> result = boost::dynamic_pointer_cast<T>(*i); - if (result) { - matched_payloads.push_back(result); - } - } - - return matched_payloads; - - } - - template<typename T> - const boost::shared_ptr<T> getPayload() const { - boost::shared_ptr<T> result; - for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) { - result = boost::dynamic_pointer_cast<T>(*i); - if (result) { - return result; - } - } - - return result; - } - - void setReason(const Reason& reason) { - this->reason = reason; - } - - const boost::optional<Reason>& getReason() const { - return reason; - } - - private: - Action action; - JID initiator; - JID responder; - std::string sessionID; - std::vector<boost::shared_ptr<Payload> > payloads; - boost::optional<Reason> reason; - }; + class SWIFTEN_API JinglePayload : public Payload { + public: + typedef boost::shared_ptr<JinglePayload> ref; + struct Reason : public Payload { + enum Type { + UnknownType, + AlternativeSession, + Busy, + Cancel, + ConnectivityError, + Decline, + Expired, + FailedApplication, + FailedTransport, + GeneralError, + Gone, + IncompatibleParameters, + MediaError, + SecurityError, + Success, + Timeout, + UnsupportedApplications, + UnsupportedTransports + }; + Reason() : type(UnknownType), text("") {} + Reason(Type type, const std::string& text = "") : type(type), text(text) {} + Type type; + std::string text; + }; + + enum Action { + UnknownAction, + ContentAccept, + ContentAdd, + ContentModify, + ContentReject, + ContentRemove, + DescriptionInfo, + SecurityInfo, + SessionAccept, + SessionInfo, + SessionInitiate, + SessionTerminate, + TransportAccept, + TransportInfo, + TransportReject, + TransportReplace + }; + JinglePayload() : action(SessionTerminate), sessionID("") { + } + + JinglePayload(Action action, const std::string& sessionID) : action(action), sessionID(sessionID) { + + } + + void setAction(Action action) { + this->action = action; + } + + Action getAction() const { + return action; + } + + void setInitiator(const JID& initiator) { + this->initiator = initiator; + } + + const JID& getInitiator() const { + return initiator; + } + + void setResponder(const JID& responder) { + this->responder = responder; + } + + const JID& getResponder() const { + return responder; + } + + void setSessionID(const std::string& id) { + sessionID = id; + } + + const std::string& getSessionID() const { + return sessionID; + } + + void addContent(JingleContentPayload::ref content) { + this->payloads.push_back(content); + } + + void addPayload(boost::shared_ptr<Payload> payload) { + this->payloads.push_back(payload); + } + + const std::vector<JingleContentPayload::ref> getContents() const { + return getPayloads<JingleContentPayload>(); + } + + const std::vector<boost::shared_ptr<Payload> > getPayloads() const { + return payloads; + } + + template<typename T> + const std::vector<boost::shared_ptr<T> > getPayloads() const { + std::vector<boost::shared_ptr<T> > matched_payloads; + for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) { + boost::shared_ptr<T> result = boost::dynamic_pointer_cast<T>(*i); + if (result) { + matched_payloads.push_back(result); + } + } + + return matched_payloads; + + } + + template<typename T> + const boost::shared_ptr<T> getPayload() const { + boost::shared_ptr<T> result; + for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) { + result = boost::dynamic_pointer_cast<T>(*i); + if (result) { + return result; + } + } + + return result; + } + + void setReason(const Reason& reason) { + this->reason = reason; + } + + const boost::optional<Reason>& getReason() const { + return reason; + } + + private: + Action action; + JID initiator; + JID responder; + std::string sessionID; + std::vector<boost::shared_ptr<Payload> > payloads; + boost::optional<Reason> reason; + }; } diff --git a/Swiften/Elements/JingleS5BTransportPayload.h b/Swiften/Elements/JingleS5BTransportPayload.h index 4b0e7d4..bb542f0 100644 --- a/Swiften/Elements/JingleS5BTransportPayload.h +++ b/Swiften/Elements/JingleS5BTransportPayload.h @@ -16,106 +16,106 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class SWIFTEN_API JingleS5BTransportPayload : public JingleTransportPayload { - public: - enum Mode { - TCPMode, // default case - UDPMode - }; - - struct Candidate { - enum Type { - DirectType, // default case - AssistedType, - TunnelType, - ProxyType - }; - - Candidate() : priority(0), type(DirectType) {} - - std::string cid; - JID jid; - HostAddressPort hostPort; - int priority; - Type type; - }; - - struct CompareCandidate { - bool operator() (const JingleS5BTransportPayload::Candidate& c1, const JingleS5BTransportPayload::Candidate& c2) const { - if (c1.priority < c2.priority) return true; - return false; - } - }; - - public: - JingleS5BTransportPayload() : mode(TCPMode), candidateError(false), proxyError(false) {} - - Mode getMode() const { - return mode; - } - - void setMode(Mode mode) { - this->mode = mode; - } - - const std::vector<Candidate>& getCandidates() const { - return candidates; - } - - void addCandidate(const Candidate& candidate) { - candidates.push_back(candidate); - } - - void setCandidateUsed(const std::string& cid) { - candidateUsedCID = cid; - } - - const std::string& getCandidateUsed() const { - return candidateUsedCID; - } - - void setActivated(const std::string& cid) { - activatedCID = cid; - } - - const std::string& getActivated() const { - return activatedCID; - } - - void setDstAddr(const std::string& addr) { - dstAddr = addr; - } - - const std::string& getDstAddr() const { - return dstAddr; - } - - void setCandidateError(bool hasError) { - candidateError = hasError; - } - - bool hasCandidateError() const { - return candidateError; - } - - void setProxyError(bool hasError) { - proxyError = hasError; - } - - bool hasProxyError() const { - return proxyError; - } - public: - typedef boost::shared_ptr<JingleS5BTransportPayload> ref; - - private: - Mode mode; - std::vector<Candidate> candidates; - - std::string candidateUsedCID; - std::string activatedCID; - std::string dstAddr; - bool candidateError; - bool proxyError; - }; + class SWIFTEN_API JingleS5BTransportPayload : public JingleTransportPayload { + public: + enum Mode { + TCPMode, // default case + UDPMode + }; + + struct Candidate { + enum Type { + DirectType, // default case + AssistedType, + TunnelType, + ProxyType + }; + + Candidate() : priority(0), type(DirectType) {} + + std::string cid; + JID jid; + HostAddressPort hostPort; + int priority; + Type type; + }; + + struct CompareCandidate { + bool operator() (const JingleS5BTransportPayload::Candidate& c1, const JingleS5BTransportPayload::Candidate& c2) const { + if (c1.priority < c2.priority) return true; + return false; + } + }; + + public: + JingleS5BTransportPayload() : mode(TCPMode), candidateError(false), proxyError(false) {} + + Mode getMode() const { + return mode; + } + + void setMode(Mode mode) { + this->mode = mode; + } + + const std::vector<Candidate>& getCandidates() const { + return candidates; + } + + void addCandidate(const Candidate& candidate) { + candidates.push_back(candidate); + } + + void setCandidateUsed(const std::string& cid) { + candidateUsedCID = cid; + } + + const std::string& getCandidateUsed() const { + return candidateUsedCID; + } + + void setActivated(const std::string& cid) { + activatedCID = cid; + } + + const std::string& getActivated() const { + return activatedCID; + } + + void setDstAddr(const std::string& addr) { + dstAddr = addr; + } + + const std::string& getDstAddr() const { + return dstAddr; + } + + void setCandidateError(bool hasError) { + candidateError = hasError; + } + + bool hasCandidateError() const { + return candidateError; + } + + void setProxyError(bool hasError) { + proxyError = hasError; + } + + bool hasProxyError() const { + return proxyError; + } + public: + typedef boost::shared_ptr<JingleS5BTransportPayload> ref; + + private: + Mode mode; + std::vector<Candidate> candidates; + + std::string candidateUsedCID; + std::string activatedCID; + std::string dstAddr; + bool candidateError; + bool proxyError; + }; } diff --git a/Swiften/Elements/JingleTransportPayload.h b/Swiften/Elements/JingleTransportPayload.h index 70f3d25..12a08cd 100644 --- a/Swiften/Elements/JingleTransportPayload.h +++ b/Swiften/Elements/JingleTransportPayload.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API JingleTransportPayload : public Payload { - public: - void setSessionID(const std::string& id) { - sessionID = id; - } + class SWIFTEN_API JingleTransportPayload : public Payload { + public: + void setSessionID(const std::string& id) { + sessionID = id; + } - const std::string& getSessionID() const { - return sessionID; - } + const std::string& getSessionID() const { + return sessionID; + } - public: - typedef boost::shared_ptr<JingleTransportPayload> ref; + public: + typedef boost::shared_ptr<JingleTransportPayload> ref; - private: - std::string sessionID; - }; + private: + std::string sessionID; + }; } diff --git a/Swiften/Elements/Last.h b/Swiften/Elements/Last.h index 68cf7a7..869dab4 100644 --- a/Swiften/Elements/Last.h +++ b/Swiften/Elements/Last.h @@ -10,14 +10,14 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Last : public Payload { - public: - Last(int seconds = 0) : seconds_(seconds) {} + class SWIFTEN_API Last : public Payload { + public: + Last(int seconds = 0) : seconds_(seconds) {} - int getSeconds() const {return seconds_;} - void setSeconds(int seconds) {seconds_ = seconds;} + int getSeconds() const {return seconds_;} + void setSeconds(int seconds) {seconds_ = seconds;} - private: - int seconds_; - }; + private: + int seconds_; + }; } diff --git a/Swiften/Elements/MAMFin.h b/Swiften/Elements/MAMFin.h index 96e410e..dd1f7bf 100644 --- a/Swiften/Elements/MAMFin.h +++ b/Swiften/Elements/MAMFin.h @@ -16,48 +16,48 @@ #include <Swiften/Elements/ResultSet.h> namespace Swift { - class SWIFTEN_API MAMFin : public Payload { - public: - MAMFin() : isComplete_(false), isStable_(true) {} - virtual ~MAMFin(); - - void setComplete(const bool isComplete) { - isComplete_ = isComplete; - } - - bool isComplete() const { - return isComplete_; - } - - void setStable(const bool isStable) { - isStable_ = isStable; - } - - bool isStable() const { - return isStable_; - } - - void setResultSet(boost::shared_ptr<ResultSet> resultSet) { - resultSet_ = resultSet; - } - - boost::shared_ptr<ResultSet> getResultSet() const { - return resultSet_; - } - - void setQueryID(const std::string& queryID) { - queryID_ = queryID; - } - - const boost::optional<std::string>& getQueryID() const { - return queryID_; - } - - - private: - bool isComplete_; - bool isStable_; - boost::shared_ptr<ResultSet> resultSet_; - boost::optional<std::string> queryID_; - }; + class SWIFTEN_API MAMFin : public Payload { + public: + MAMFin() : isComplete_(false), isStable_(true) {} + virtual ~MAMFin(); + + void setComplete(const bool isComplete) { + isComplete_ = isComplete; + } + + bool isComplete() const { + return isComplete_; + } + + void setStable(const bool isStable) { + isStable_ = isStable; + } + + bool isStable() const { + return isStable_; + } + + void setResultSet(boost::shared_ptr<ResultSet> resultSet) { + resultSet_ = resultSet; + } + + boost::shared_ptr<ResultSet> getResultSet() const { + return resultSet_; + } + + void setQueryID(const std::string& queryID) { + queryID_ = queryID; + } + + const boost::optional<std::string>& getQueryID() const { + return queryID_; + } + + + private: + bool isComplete_; + bool isStable_; + boost::shared_ptr<ResultSet> resultSet_; + boost::optional<std::string> queryID_; + }; } diff --git a/Swiften/Elements/MAMQuery.h b/Swiften/Elements/MAMQuery.h index 2a795dc..253fa0c 100644 --- a/Swiften/Elements/MAMQuery.h +++ b/Swiften/Elements/MAMQuery.h @@ -17,26 +17,26 @@ #include <Swiften/Elements/ResultSet.h> namespace Swift { - class SWIFTEN_API MAMQuery : public Payload { - public: - virtual ~MAMQuery(); + class SWIFTEN_API MAMQuery : public Payload { + public: + virtual ~MAMQuery(); - void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; } - const boost::optional<std::string>& getQueryID() const { return queryID_; } + void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; } + const boost::optional<std::string>& getQueryID() const { return queryID_; } - void setNode(const boost::optional<std::string>& node) { node_ = node; } - const boost::optional<std::string>& getNode() const { return node_; } + void setNode(const boost::optional<std::string>& node) { node_ = node; } + const boost::optional<std::string>& getNode() const { return node_; } - void setForm(boost::shared_ptr<Form> form) { form_ = form; } - const boost::shared_ptr<Form>& getForm() const { return form_; } + void setForm(boost::shared_ptr<Form> form) { form_ = form; } + const boost::shared_ptr<Form>& getForm() const { return form_; } - void setResultSet(boost::shared_ptr<ResultSet> resultSet) { resultSet_ = resultSet; } - const boost::shared_ptr<ResultSet>& getResultSet() const { return resultSet_; } + void setResultSet(boost::shared_ptr<ResultSet> resultSet) { resultSet_ = resultSet; } + const boost::shared_ptr<ResultSet>& getResultSet() const { return resultSet_; } - private: - boost::optional<std::string> queryID_; - boost::optional<std::string> node_; - boost::shared_ptr<Form> form_; - boost::shared_ptr<ResultSet> resultSet_; - }; + private: + boost::optional<std::string> queryID_; + boost::optional<std::string> node_; + boost::shared_ptr<Form> form_; + boost::shared_ptr<ResultSet> resultSet_; + }; } diff --git a/Swiften/Elements/MAMResult.h b/Swiften/Elements/MAMResult.h index de69fba..88ec8f0 100644 --- a/Swiften/Elements/MAMResult.h +++ b/Swiften/Elements/MAMResult.h @@ -15,18 +15,18 @@ #include <Swiften/Elements/Forwarded.h> namespace Swift { - class SWIFTEN_API MAMResult : public ContainerPayload<Forwarded> { - public: - virtual ~MAMResult(); + class SWIFTEN_API MAMResult : public ContainerPayload<Forwarded> { + public: + virtual ~MAMResult(); - void setID(const std::string& id) { id_ = id; } - const std::string& getID() const { return id_; } + void setID(const std::string& id) { id_ = id; } + const std::string& getID() const { return id_; } - void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; } - const boost::optional<std::string>& getQueryID() const { return queryID_; } + void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; } + const boost::optional<std::string>& getQueryID() const { return queryID_; } - private: - std::string id_; - boost::optional<std::string> queryID_; - }; + private: + std::string id_; + boost::optional<std::string> queryID_; + }; } diff --git a/Swiften/Elements/MUCAdminPayload.h b/Swiften/Elements/MUCAdminPayload.h index f16111d..c9b01d9 100644 --- a/Swiften/Elements/MUCAdminPayload.h +++ b/Swiften/Elements/MUCAdminPayload.h @@ -19,19 +19,19 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API MUCAdminPayload : public Payload { - public: - typedef boost::shared_ptr<MUCAdminPayload> ref; + class SWIFTEN_API MUCAdminPayload : public Payload { + public: + typedef boost::shared_ptr<MUCAdminPayload> ref; - MUCAdminPayload() { - } + MUCAdminPayload() { + } - void addItem(const MUCItem& item) {items_.push_back(item);} + void addItem(const MUCItem& item) {items_.push_back(item);} - const std::vector<MUCItem>& getItems() const {return items_;} + const std::vector<MUCItem>& getItems() const {return items_;} - private: - std::vector<MUCItem> items_; - }; + private: + std::vector<MUCItem> items_; + }; } diff --git a/Swiften/Elements/MUCDestroyPayload.h b/Swiften/Elements/MUCDestroyPayload.h index b68f97c..80eb83e 100644 --- a/Swiften/Elements/MUCDestroyPayload.h +++ b/Swiften/Elements/MUCDestroyPayload.h @@ -13,31 +13,31 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API MUCDestroyPayload : public Payload { - public: - typedef boost::shared_ptr<MUCDestroyPayload> ref; + class SWIFTEN_API MUCDestroyPayload : public Payload { + public: + typedef boost::shared_ptr<MUCDestroyPayload> ref; - MUCDestroyPayload() { - } + MUCDestroyPayload() { + } - void setNewVenue(const JID& jid) { - newVenue_ = jid; - } + void setNewVenue(const JID& jid) { + newVenue_ = jid; + } - const JID& getNewVenue() const { - return newVenue_; - } + const JID& getNewVenue() const { + return newVenue_; + } - void setReason(const std::string& reason) { - reason_ = reason; - } + void setReason(const std::string& reason) { + reason_ = reason; + } - const std::string& getReason() const { - return reason_; - } + const std::string& getReason() const { + return reason_; + } - private: - JID newVenue_; - std::string reason_; - }; + private: + JID newVenue_; + std::string reason_; + }; } diff --git a/Swiften/Elements/MUCInvitationPayload.h b/Swiften/Elements/MUCInvitationPayload.h index fd92a83..508a8ec 100644 --- a/Swiften/Elements/MUCInvitationPayload.h +++ b/Swiften/Elements/MUCInvitationPayload.h @@ -13,66 +13,66 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API MUCInvitationPayload : public Payload { - public: - typedef boost::shared_ptr<MUCInvitationPayload> ref; - MUCInvitationPayload() : continuation_(false), impromptu_(false) { - } - - void setIsContinuation(bool b) { - continuation_ = b; - } - - bool getIsContinuation() const { - return continuation_; - } - - void setIsImpromptu(bool b) { - impromptu_ = b; - } - - bool getIsImpromptu() const { - return impromptu_; - } - - void setJID(const JID& jid) { - jid_ = jid; - } - - const JID& getJID() const { - return jid_; - } - - void setPassword(const std::string& password) { - password_ = password; - } - - const std::string& getPassword() const { - return password_; - } - - void setReason(const std::string& text) { - reason_ = text; - } - - const std::string& getReason() const { - return reason_; - } - - void setThread(const std::string& thread) { - thread_ = thread; - } - - const std::string& getThread() const { - return thread_; - } - - private: - bool continuation_; - bool impromptu_; - JID jid_; - std::string password_; - std::string reason_; - std::string thread_; - }; + class SWIFTEN_API MUCInvitationPayload : public Payload { + public: + typedef boost::shared_ptr<MUCInvitationPayload> ref; + MUCInvitationPayload() : continuation_(false), impromptu_(false) { + } + + void setIsContinuation(bool b) { + continuation_ = b; + } + + bool getIsContinuation() const { + return continuation_; + } + + void setIsImpromptu(bool b) { + impromptu_ = b; + } + + bool getIsImpromptu() const { + return impromptu_; + } + + void setJID(const JID& jid) { + jid_ = jid; + } + + const JID& getJID() const { + return jid_; + } + + void setPassword(const std::string& password) { + password_ = password; + } + + const std::string& getPassword() const { + return password_; + } + + void setReason(const std::string& text) { + reason_ = text; + } + + const std::string& getReason() const { + return reason_; + } + + void setThread(const std::string& thread) { + thread_ = thread; + } + + const std::string& getThread() const { + return thread_; + } + + private: + bool continuation_; + bool impromptu_; + JID jid_; + std::string password_; + std::string reason_; + std::string thread_; + }; } diff --git a/Swiften/Elements/MUCItem.h b/Swiften/Elements/MUCItem.h index 40f4572..9ea6d77 100644 --- a/Swiften/Elements/MUCItem.h +++ b/Swiften/Elements/MUCItem.h @@ -10,12 +10,12 @@ #include <Swiften/JID/JID.h> namespace Swift { struct MUCItem { - MUCItem() {} - boost::optional<JID> realJID; - boost::optional<std::string> nick; - boost::optional<MUCOccupant::Affiliation> affiliation; - boost::optional<MUCOccupant::Role> role; - boost::optional<JID> actor; - boost::optional<std::string> reason; + MUCItem() {} + boost::optional<JID> realJID; + boost::optional<std::string> nick; + boost::optional<MUCOccupant::Affiliation> affiliation; + boost::optional<MUCOccupant::Role> role; + boost::optional<JID> actor; + boost::optional<std::string> reason; }; } diff --git a/Swiften/Elements/MUCOccupant.cpp b/Swiften/Elements/MUCOccupant.cpp index c2d2f3d..edd6eb6 100644 --- a/Swiften/Elements/MUCOccupant.cpp +++ b/Swiften/Elements/MUCOccupant.cpp @@ -19,28 +19,28 @@ MUCOccupant::MUCOccupant(const MUCOccupant& other) : nick_(other.getNick()), rol } std::string MUCOccupant::getNick() const { - return nick_; + return nick_; } MUCOccupant::Role MUCOccupant::getRole() const { - return role_; + return role_; } MUCOccupant::Affiliation MUCOccupant::getAffiliation() const { - return affiliation_; + return affiliation_; } void MUCOccupant::setRealJID(const JID& realJID) { - realJID_ = realJID; + realJID_ = realJID; } void MUCOccupant::setNick(const std::string& nick) { - nick_ = nick; + nick_ = nick; } boost::optional<JID> MUCOccupant::getRealJID() const { - return realJID_; + return realJID_; } } diff --git a/Swiften/Elements/MUCOccupant.h b/Swiften/Elements/MUCOccupant.h index 0eb9169..eb7df2c 100644 --- a/Swiften/Elements/MUCOccupant.h +++ b/Swiften/Elements/MUCOccupant.h @@ -14,30 +14,30 @@ #include <Swiften/JID/JID.h> namespace Swift { - class Client; - - class SWIFTEN_API MUCOccupant { - public: - enum Role {Moderator, Participant, Visitor, NoRole}; - enum Affiliation {Owner, Admin, Member, Outcast, NoAffiliation}; - - MUCOccupant(const std::string &nick, Role role, Affiliation affiliation); - MUCOccupant(const MUCOccupant& other); - ~MUCOccupant(); - - std::string getNick() const; - Role getRole() const; - Affiliation getAffiliation() const; - boost::optional<JID> getRealJID() const; - void setRealJID(const JID& jid); - void setNick(const std::string& nick); - - private: - std::string nick_; - Role role_; - Affiliation affiliation_; - boost::optional<JID> realJID_; - /* If you add a field, remember to update the const copy constructor */ - }; + class Client; + + class SWIFTEN_API MUCOccupant { + public: + enum Role {Moderator, Participant, Visitor, NoRole}; + enum Affiliation {Owner, Admin, Member, Outcast, NoAffiliation}; + + MUCOccupant(const std::string &nick, Role role, Affiliation affiliation); + MUCOccupant(const MUCOccupant& other); + ~MUCOccupant(); + + std::string getNick() const; + Role getRole() const; + Affiliation getAffiliation() const; + boost::optional<JID> getRealJID() const; + void setRealJID(const JID& jid); + void setNick(const std::string& nick); + + private: + std::string nick_; + Role role_; + Affiliation affiliation_; + boost::optional<JID> realJID_; + /* If you add a field, remember to update the const copy constructor */ + }; } diff --git a/Swiften/Elements/MUCOwnerPayload.h b/Swiften/Elements/MUCOwnerPayload.h index 890b031..f75f677 100644 --- a/Swiften/Elements/MUCOwnerPayload.h +++ b/Swiften/Elements/MUCOwnerPayload.h @@ -13,26 +13,26 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API MUCOwnerPayload : public Payload { - public: - typedef boost::shared_ptr<MUCOwnerPayload> ref; + class SWIFTEN_API MUCOwnerPayload : public Payload { + public: + typedef boost::shared_ptr<MUCOwnerPayload> ref; - MUCOwnerPayload() { - } + MUCOwnerPayload() { + } - boost::shared_ptr<Payload> getPayload() const { - return payload; - } + boost::shared_ptr<Payload> getPayload() const { + return payload; + } - void setPayload(boost::shared_ptr<Payload> p) { - payload = p; - } + void setPayload(boost::shared_ptr<Payload> p) { + payload = p; + } - Form::ref getForm() { - return boost::dynamic_pointer_cast<Form>(payload); - } + Form::ref getForm() { + return boost::dynamic_pointer_cast<Form>(payload); + } - private: - boost::shared_ptr<Payload> payload; - }; + private: + boost::shared_ptr<Payload> payload; + }; } diff --git a/Swiften/Elements/MUCPayload.h b/Swiften/Elements/MUCPayload.h index af70f48..8588ca2 100644 --- a/Swiften/Elements/MUCPayload.h +++ b/Swiften/Elements/MUCPayload.h @@ -16,61 +16,61 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API MUCPayload : public Payload { - public: - typedef boost::shared_ptr<MUCPayload> ref; - - MUCPayload() { - maxChars_ = -1; - maxStanzas_ = -1; - seconds_ = -1; - } - - void setMaxChars(int maxChars) { - maxChars_ = maxChars; - } - - void setMaxStanzas(int maxStanzas) { - maxStanzas_ = maxStanzas; - } - - void setSeconds(int seconds) { - seconds_ = seconds; - } - - void setSince(boost::posix_time::ptime since) { - since_ = since; - } - - void setPassword(const std::string& password) { - password_ = password; - } - - int getMaxChars() const{ - return maxChars_; - } - - int getMaxStanzas() const{ - return maxStanzas_; - } - - int getSeconds() const { - return seconds_; - } - - const boost::optional<std::string>& getPassword() const { - return password_; - } - - const boost::posix_time::ptime& getSince() const { - return since_; - } - - private: - int maxChars_; - int maxStanzas_; - int seconds_; - boost::posix_time::ptime since_; - boost::optional<std::string> password_; - }; + class SWIFTEN_API MUCPayload : public Payload { + public: + typedef boost::shared_ptr<MUCPayload> ref; + + MUCPayload() { + maxChars_ = -1; + maxStanzas_ = -1; + seconds_ = -1; + } + + void setMaxChars(int maxChars) { + maxChars_ = maxChars; + } + + void setMaxStanzas(int maxStanzas) { + maxStanzas_ = maxStanzas; + } + + void setSeconds(int seconds) { + seconds_ = seconds; + } + + void setSince(boost::posix_time::ptime since) { + since_ = since; + } + + void setPassword(const std::string& password) { + password_ = password; + } + + int getMaxChars() const{ + return maxChars_; + } + + int getMaxStanzas() const{ + return maxStanzas_; + } + + int getSeconds() const { + return seconds_; + } + + const boost::optional<std::string>& getPassword() const { + return password_; + } + + const boost::posix_time::ptime& getSince() const { + return since_; + } + + private: + int maxChars_; + int maxStanzas_; + int seconds_; + boost::posix_time::ptime since_; + boost::optional<std::string> password_; + }; } diff --git a/Swiften/Elements/MUCUserPayload.h b/Swiften/Elements/MUCUserPayload.h index 6d2de30..e83c2d0 100644 --- a/Swiften/Elements/MUCUserPayload.h +++ b/Swiften/Elements/MUCUserPayload.h @@ -19,79 +19,79 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API MUCUserPayload : public Payload { - public: - typedef boost::shared_ptr<MUCUserPayload> ref; + class SWIFTEN_API MUCUserPayload : public Payload { + public: + typedef boost::shared_ptr<MUCUserPayload> ref; - struct StatusCode { - StatusCode() : code(0) {} - StatusCode(int code) : code(code) {} - int code; - }; + struct StatusCode { + StatusCode() : code(0) {} + StatusCode(int code) : code(code) {} + int code; + }; - //struct Password { + //struct Password { - //} + //} - // struct History { + // struct History { - // } + // } - /** - * reason is optional. - * from and to are mutually exclusive. - * From is used for MUC sending to invited client. To is used sending to MUC from inviting client. - * from is the JID the MUC claims the invite is from. - * to is the JID to send the invite to. - */ - struct Invite { - std::string reason; - JID from; - JID to; - }; + /** + * reason is optional. + * from and to are mutually exclusive. + * From is used for MUC sending to invited client. To is used sending to MUC from inviting client. + * from is the JID the MUC claims the invite is from. + * to is the JID to send the invite to. + */ + struct Invite { + std::string reason; + JID from; + JID to; + }; - MUCUserPayload() { - } + MUCUserPayload() { + } - void addItem(const MUCItem& item) {items_.push_back(item);} - - void addStatusCode(StatusCode code) {statusCodes_.push_back(code);} + void addItem(const MUCItem& item) {items_.push_back(item);} - const std::vector<MUCItem>& getItems() const {return items_;} + void addStatusCode(StatusCode code) {statusCodes_.push_back(code);} - const std::vector<StatusCode>& getStatusCodes() const {return statusCodes_;} + const std::vector<MUCItem>& getItems() const {return items_;} - boost::shared_ptr<Payload> getPayload() const { - return payload_; - } + const std::vector<StatusCode>& getStatusCodes() const {return statusCodes_;} - void setPayload(boost::shared_ptr<Payload> p) { - payload_ = p; - } + boost::shared_ptr<Payload> getPayload() const { + return payload_; + } - const boost::optional<std::string>& getPassword() const { - return password_; - } + void setPayload(boost::shared_ptr<Payload> p) { + payload_ = p; + } - void setPassword(const std::string& password) { - password_ = password; - } + const boost::optional<std::string>& getPassword() const { + return password_; + } + void setPassword(const std::string& password) { + password_ = password; + } - const boost::optional<Invite>& getInvite() const { - return invite_; - } - void setInvite(const Invite& invite) { - invite_ = invite; - } + const boost::optional<Invite>& getInvite() const { + return invite_; + } + void setInvite(const Invite& invite) { + invite_ = invite; + } - private: - std::vector<MUCItem> items_; - std::vector<StatusCode> statusCodes_; - boost::shared_ptr<Payload> payload_; - boost::optional<std::string> password_; - boost::optional<Invite> invite_; - }; + + private: + std::vector<MUCItem> items_; + std::vector<StatusCode> statusCodes_; + boost::shared_ptr<Payload> payload_; + boost::optional<std::string> password_; + boost::optional<Invite> invite_; + }; } diff --git a/Swiften/Elements/Message.h b/Swiften/Elements/Message.h index 0f0d380..c55e04b 100644 --- a/Swiften/Elements/Message.h +++ b/Swiften/Elements/Message.h @@ -20,63 +20,63 @@ #include <Swiften/Elements/Subject.h> namespace Swift { - class SWIFTEN_API Message : public Stanza { - public: - typedef boost::shared_ptr<Message> ref; - - enum Type { Normal, Chat, Error, Groupchat, Headline }; - - Message() : type_(Chat) { } - - std::string getSubject() const { - boost::shared_ptr<Subject> subject(getPayload<Subject>()); - if (subject) { - return subject->getText(); - } - return ""; - } - - void setSubject(const std::string& subject) { - updatePayload(boost::make_shared<Subject>(subject)); - } - - // Explicitly convert to bool. In C++11, it would be cleaner to - // compare to nullptr. - bool hasSubject() { - return static_cast<bool>(getPayload<Subject>()); - } - - boost::optional<std::string> getBody() const { - boost::shared_ptr<Body> body(getPayload<Body>()); - boost::optional<std::string> bodyData; - if (body) { - bodyData = body->getText(); - } - return bodyData; - } - - void setBody(const std::string& body) { - setBody(boost::optional<std::string>(body)); - } - - void setBody(const boost::optional<std::string>& body) { - if (body) { - updatePayload(boost::make_shared<Body>(body.get())); - } - else { - removePayloadOfSameType(boost::make_shared<Body>()); - } - } - - bool isError() { - boost::shared_ptr<Swift::ErrorPayload> error(getPayload<Swift::ErrorPayload>()); - return getType() == Message::Error || error; - } - - Type getType() const { return type_; } - void setType(Type type) { type_ = type; } - - private: - Type type_; - }; + class SWIFTEN_API Message : public Stanza { + public: + typedef boost::shared_ptr<Message> ref; + + enum Type { Normal, Chat, Error, Groupchat, Headline }; + + Message() : type_(Chat) { } + + std::string getSubject() const { + boost::shared_ptr<Subject> subject(getPayload<Subject>()); + if (subject) { + return subject->getText(); + } + return ""; + } + + void setSubject(const std::string& subject) { + updatePayload(boost::make_shared<Subject>(subject)); + } + + // Explicitly convert to bool. In C++11, it would be cleaner to + // compare to nullptr. + bool hasSubject() { + return static_cast<bool>(getPayload<Subject>()); + } + + boost::optional<std::string> getBody() const { + boost::shared_ptr<Body> body(getPayload<Body>()); + boost::optional<std::string> bodyData; + if (body) { + bodyData = body->getText(); + } + return bodyData; + } + + void setBody(const std::string& body) { + setBody(boost::optional<std::string>(body)); + } + + void setBody(const boost::optional<std::string>& body) { + if (body) { + updatePayload(boost::make_shared<Body>(body.get())); + } + else { + removePayloadOfSameType(boost::make_shared<Body>()); + } + } + + bool isError() { + boost::shared_ptr<Swift::ErrorPayload> error(getPayload<Swift::ErrorPayload>()); + return getType() == Message::Error || error; + } + + Type getType() const { return type_; } + void setType(Type type) { type_ = type; } + + private: + Type type_; + }; } diff --git a/Swiften/Elements/Nickname.h b/Swiften/Elements/Nickname.h index 7a9e7b5..123c156 100644 --- a/Swiften/Elements/Nickname.h +++ b/Swiften/Elements/Nickname.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Nickname : public Payload { - public: - Nickname(const std::string& nickname = "") : nickname(nickname) { - } + class SWIFTEN_API Nickname : public Payload { + public: + Nickname(const std::string& nickname = "") : nickname(nickname) { + } - void setNickname(const std::string& nickname) { - this->nickname = nickname; - } + void setNickname(const std::string& nickname) { + this->nickname = nickname; + } - const std::string& getNickname() const { - return nickname; - } + const std::string& getNickname() const { + return nickname; + } - private: - std::string nickname; - }; + private: + std::string nickname; + }; } diff --git a/Swiften/Elements/Payload.h b/Swiften/Elements/Payload.h index dfa74b2..e31afa9 100644 --- a/Swiften/Elements/Payload.h +++ b/Swiften/Elements/Payload.h @@ -12,14 +12,14 @@ #include <Swiften/Elements/Element.h> namespace Swift { - class SWIFTEN_API Payload : public Element { - public: - typedef boost::shared_ptr<Payload> ref; - public: - Payload() {} - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Payload) - virtual ~Payload(); + class SWIFTEN_API Payload : public Element { + public: + typedef boost::shared_ptr<Payload> ref; + public: + Payload() {} + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Payload) + virtual ~Payload(); - SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Payload) - }; + SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Payload) + }; } diff --git a/Swiften/Elements/Presence.cpp b/Swiften/Elements/Presence.cpp index cf1f0d8..344efc1 100644 --- a/Swiften/Elements/Presence.cpp +++ b/Swiften/Elements/Presence.cpp @@ -15,31 +15,31 @@ Presence::Presence() : type_(Available) /*, showType_(Online)*/ { } Presence::Presence(const std::string& status) : type_(Available) { - setStatus(status); + setStatus(status); } Presence::~Presence() { } int Presence::getPriority() const { - boost::shared_ptr<Priority> priority(getPayload<Priority>()); - return (priority ? priority->getPriority() : 0); + boost::shared_ptr<Priority> priority(getPayload<Priority>()); + return (priority ? priority->getPriority() : 0); } void Presence::setPriority(int priority) { - updatePayload(boost::make_shared<Priority>(priority)); + updatePayload(boost::make_shared<Priority>(priority)); } -std::string Presence::getStatus() const { - boost::shared_ptr<Status> status(getPayload<Status>()); - if (status) { - return status->getText(); - } - return ""; +std::string Presence::getStatus() const { + boost::shared_ptr<Status> status(getPayload<Status>()); + if (status) { + return status->getText(); + } + return ""; } -void Presence::setStatus(const std::string& status) { - updatePayload(boost::make_shared<Status>(status)); +void Presence::setStatus(const std::string& status) { + updatePayload(boost::make_shared<Status>(status)); } } diff --git a/Swiften/Elements/Presence.h b/Swiften/Elements/Presence.h index 6327761..0b6ee5f 100644 --- a/Swiften/Elements/Presence.h +++ b/Swiften/Elements/Presence.h @@ -13,59 +13,59 @@ #include <Swiften/Elements/StatusShow.h> namespace Swift { - class SWIFTEN_API Presence : public Stanza { - public: - typedef boost::shared_ptr<Presence> ref; + class SWIFTEN_API Presence : public Stanza { + public: + typedef boost::shared_ptr<Presence> ref; - enum Type { Available, Error, Probe, Subscribe, Subscribed, Unavailable, Unsubscribe, Unsubscribed }; + enum Type { Available, Error, Probe, Subscribe, Subscribed, Unavailable, Unsubscribe, Unsubscribed }; - Presence(); - Presence(const std::string& status); - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Presence) - virtual ~Presence(); + Presence(); + Presence(const std::string& status); + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Presence) + virtual ~Presence(); - static ref create() { - return boost::make_shared<Presence>(); - } + static ref create() { + return boost::make_shared<Presence>(); + } - static ref create(const std::string& status) { - return boost::make_shared<Presence>(status); - } + static ref create(const std::string& status) { + return boost::make_shared<Presence>(status); + } - static ref create(Presence::ref presence) { - return boost::make_shared<Presence>(*presence); - } + static ref create(Presence::ref presence) { + return boost::make_shared<Presence>(*presence); + } - Type getType() const { return type_; } - void setType(Type type) { type_ = type; } + Type getType() const { return type_; } + void setType(Type type) { type_ = type; } - StatusShow::Type getShow() const { - boost::shared_ptr<StatusShow> show(getPayload<StatusShow>()); - if (show) { - return show->getType(); - } - return type_ == Available ? StatusShow::Online : StatusShow::None; - } + StatusShow::Type getShow() const { + boost::shared_ptr<StatusShow> show(getPayload<StatusShow>()); + if (show) { + return show->getType(); + } + return type_ == Available ? StatusShow::Online : StatusShow::None; + } - void setShow(const StatusShow::Type &show) { - updatePayload(boost::make_shared<StatusShow>(show)); - } + void setShow(const StatusShow::Type &show) { + updatePayload(boost::make_shared<StatusShow>(show)); + } - std::string getStatus() const; - void setStatus(const std::string& status); + std::string getStatus() const; + void setStatus(const std::string& status); - int getPriority() const; - void setPriority(int priority); + int getPriority() const; + void setPriority(int priority); - boost::shared_ptr<Presence> clone() const { - return boost::make_shared<Presence>(*this); - } + boost::shared_ptr<Presence> clone() const { + return boost::make_shared<Presence>(*this); + } - bool isAvailable() const { - return type_ == Available; - } + bool isAvailable() const { + return type_ == Available; + } - private: - Presence::Type type_; - }; + private: + Presence::Type type_; + }; } diff --git a/Swiften/Elements/Priority.h b/Swiften/Elements/Priority.h index 6de42b4..56e493c 100644 --- a/Swiften/Elements/Priority.h +++ b/Swiften/Elements/Priority.h @@ -10,20 +10,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Priority : public Payload { - public: - Priority(int priority = 0) : priority_(priority) { - } + class SWIFTEN_API Priority : public Payload { + public: + Priority(int priority = 0) : priority_(priority) { + } - void setPriority(int priority) { - priority_ = priority; - } + void setPriority(int priority) { + priority_ = priority; + } - int getPriority() const { - return priority_; - } + int getPriority() const { + return priority_; + } - private: - int priority_; - }; + private: + int priority_; + }; } diff --git a/Swiften/Elements/PrivateStorage.h b/Swiften/Elements/PrivateStorage.h index 15455b8..e1f97d5 100644 --- a/Swiften/Elements/PrivateStorage.h +++ b/Swiften/Elements/PrivateStorage.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PrivateStorage : public Payload { - public: - PrivateStorage(boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()) : payload(payload) { - } + class SWIFTEN_API PrivateStorage : public Payload { + public: + PrivateStorage(boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()) : payload(payload) { + } - boost::shared_ptr<Payload> getPayload() const { - return payload; - } + boost::shared_ptr<Payload> getPayload() const { + return payload; + } - void setPayload(boost::shared_ptr<Payload> p) { - payload = p; - } + void setPayload(boost::shared_ptr<Payload> p) { + payload = p; + } - private: - boost::shared_ptr<Payload> payload; - }; + private: + boost::shared_ptr<Payload> payload; + }; } diff --git a/Swiften/Elements/ProtocolHeader.h b/Swiften/Elements/ProtocolHeader.h index a38f806..4ae545a 100644 --- a/Swiften/Elements/ProtocolHeader.h +++ b/Swiften/Elements/ProtocolHeader.h @@ -11,34 +11,34 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API ProtocolHeader { - public: - ProtocolHeader() : version("1.0") {} - - const std::string& getTo() const { return to; } - void setTo(const std::string& a) { - to = a; - } - - const std::string& getFrom() const { return from; } - void setFrom(const std::string& a) { - from = a; - } - - const std::string& getVersion() const { return version; } - void setVersion(const std::string& a) { - version = a; - } - - const std::string& getID() const { return id; } - void setID(const std::string& a) { - id = a; - } - - private: - std::string to; - std::string from; - std::string id; - std::string version; - }; + class SWIFTEN_API ProtocolHeader { + public: + ProtocolHeader() : version("1.0") {} + + const std::string& getTo() const { return to; } + void setTo(const std::string& a) { + to = a; + } + + const std::string& getFrom() const { return from; } + void setFrom(const std::string& a) { + from = a; + } + + const std::string& getVersion() const { return version; } + void setVersion(const std::string& a) { + version = a; + } + + const std::string& getID() const { return id; } + void setID(const std::string& a) { + id = a; + } + + private: + std::string to; + std::string from; + std::string id; + std::string version; + }; } diff --git a/Swiften/Elements/PubSub.h b/Swiften/Elements/PubSub.h index fb75c80..d62c54e 100644 --- a/Swiften/Elements/PubSub.h +++ b/Swiften/Elements/PubSub.h @@ -12,9 +12,9 @@ #include <Swiften/Elements/PubSubPayload.h> namespace Swift { - class SWIFTEN_API PubSub : public ContainerPayload<PubSubPayload> { - public: - PubSub(); - virtual ~PubSub(); - }; + class SWIFTEN_API PubSub : public ContainerPayload<PubSubPayload> { + public: + PubSub(); + virtual ~PubSub(); + }; } diff --git a/Swiften/Elements/PubSubAffiliation.h b/Swiften/Elements/PubSubAffiliation.h index 61198ff..b19e84b 100644 --- a/Swiften/Elements/PubSubAffiliation.h +++ b/Swiften/Elements/PubSubAffiliation.h @@ -13,40 +13,40 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubAffiliation : public Payload { - public: - enum Type { - None, - Member, - Outcast, - Owner, - Publisher, - PublishOnly - }; - - PubSubAffiliation(); - PubSubAffiliation(const std::string& node) : node(node), type(None) {} - virtual ~PubSubAffiliation(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - Type getType() const { - return type; - } - - void setType(Type value) { - this->type = value ; - } - - - private: - std::string node; - Type type; - }; + class SWIFTEN_API PubSubAffiliation : public Payload { + public: + enum Type { + None, + Member, + Outcast, + Owner, + Publisher, + PublishOnly + }; + + PubSubAffiliation(); + PubSubAffiliation(const std::string& node) : node(node), type(None) {} + virtual ~PubSubAffiliation(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + Type getType() const { + return type; + } + + void setType(Type value) { + this->type = value ; + } + + + private: + std::string node; + Type type; + }; } diff --git a/Swiften/Elements/PubSubAffiliations.h b/Swiften/Elements/PubSubAffiliations.h index e8f0382..9f66056 100644 --- a/Swiften/Elements/PubSubAffiliations.h +++ b/Swiften/Elements/PubSubAffiliations.h @@ -19,36 +19,36 @@ #include <Swiften/Elements/PubSubPayload.h> namespace Swift { - class SWIFTEN_API PubSubAffiliations : public PubSubPayload { - public: - - PubSubAffiliations(); - - virtual ~PubSubAffiliations(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubAffiliation> >& getAffiliations() const { - return affiliations; - } - - void setAffiliations(const std::vector< boost::shared_ptr<PubSubAffiliation> >& value) { - this->affiliations = value ; - } - - void addAffiliation(boost::shared_ptr<PubSubAffiliation> value) { - this->affiliations.push_back(value); - } - - - private: - boost::optional< std::string > node; - std::vector< boost::shared_ptr<PubSubAffiliation> > affiliations; - }; + class SWIFTEN_API PubSubAffiliations : public PubSubPayload { + public: + + PubSubAffiliations(); + + virtual ~PubSubAffiliations(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubAffiliation> >& getAffiliations() const { + return affiliations; + } + + void setAffiliations(const std::vector< boost::shared_ptr<PubSubAffiliation> >& value) { + this->affiliations = value ; + } + + void addAffiliation(boost::shared_ptr<PubSubAffiliation> value) { + this->affiliations.push_back(value); + } + + + private: + boost::optional< std::string > node; + std::vector< boost::shared_ptr<PubSubAffiliation> > affiliations; + }; } diff --git a/Swiften/Elements/PubSubConfigure.h b/Swiften/Elements/PubSubConfigure.h index 4cd219c..e8f3cbc 100644 --- a/Swiften/Elements/PubSubConfigure.h +++ b/Swiften/Elements/PubSubConfigure.h @@ -14,23 +14,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubConfigure : public Payload { - public: - - PubSubConfigure(); - - virtual ~PubSubConfigure(); + class SWIFTEN_API PubSubConfigure : public Payload { + public: - boost::shared_ptr<Form> getData() const { - return data; - } + PubSubConfigure(); - void setData(boost::shared_ptr<Form> value) { - this->data = value ; - } + virtual ~PubSubConfigure(); + boost::shared_ptr<Form> getData() const { + return data; + } - private: - boost::shared_ptr<Form> data; - }; + void setData(boost::shared_ptr<Form> value) { + this->data = value ; + } + + + private: + boost::shared_ptr<Form> data; + }; } diff --git a/Swiften/Elements/PubSubCreate.h b/Swiften/Elements/PubSubCreate.h index f535a89..b2226c4 100644 --- a/Swiften/Elements/PubSubCreate.h +++ b/Swiften/Elements/PubSubCreate.h @@ -17,32 +17,32 @@ #include <Swiften/Elements/PubSubPayload.h> namespace Swift { - class SWIFTEN_API PubSubCreate : public PubSubPayload { - public: - - PubSubCreate(); - PubSubCreate(const std::string& node) : node(node) {} - virtual ~PubSubCreate(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - boost::shared_ptr<PubSubConfigure> getConfigure() const { - return configure; - } - - void setConfigure(boost::shared_ptr<PubSubConfigure> value) { - this->configure = value ; - } - - - private: - std::string node; - boost::shared_ptr<PubSubConfigure> configure; - }; + class SWIFTEN_API PubSubCreate : public PubSubPayload { + public: + + PubSubCreate(); + PubSubCreate(const std::string& node) : node(node) {} + virtual ~PubSubCreate(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + boost::shared_ptr<PubSubConfigure> getConfigure() const { + return configure; + } + + void setConfigure(boost::shared_ptr<PubSubConfigure> value) { + this->configure = value ; + } + + + private: + std::string node; + boost::shared_ptr<PubSubConfigure> configure; + }; } diff --git a/Swiften/Elements/PubSubDefault.h b/Swiften/Elements/PubSubDefault.h index f4e7595..08482b4 100644 --- a/Swiften/Elements/PubSubDefault.h +++ b/Swiften/Elements/PubSubDefault.h @@ -16,37 +16,37 @@ #include <Swiften/Elements/PubSubPayload.h> namespace Swift { - class SWIFTEN_API PubSubDefault : public PubSubPayload { - public: - enum Type { - None, - Collection, - Leaf - }; - - PubSubDefault(); - - virtual ~PubSubDefault(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - Type getType() const { - return type; - } - - void setType(Type value) { - this->type = value ; - } - - - private: - boost::optional< std::string > node; - Type type; - }; + class SWIFTEN_API PubSubDefault : public PubSubPayload { + public: + enum Type { + None, + Collection, + Leaf + }; + + PubSubDefault(); + + virtual ~PubSubDefault(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + Type getType() const { + return type; + } + + void setType(Type value) { + this->type = value ; + } + + + private: + boost::optional< std::string > node; + Type type; + }; } diff --git a/Swiften/Elements/PubSubError.h b/Swiften/Elements/PubSubError.h index 8fc957c..2d4452a 100644 --- a/Swiften/Elements/PubSubError.h +++ b/Swiften/Elements/PubSubError.h @@ -9,103 +9,103 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubError : public Payload { - public: - enum Type { - UnknownType = 0, - ClosedNode, - ConfigurationRequired, - InvalidJID, - InvalidOptions, - InvalidPayload, - InvalidSubscriptionID, - ItemForbidden, - ItemRequired, - JIDRequired, - MaximumItemsExceeded, - MaximumNodesExceeded, - NodeIDRequired, - NotInRosterGroup, - NotSubscribed, - PayloadTooBig, - PayloadRequired, - PendingSubscription, - PresenceSubscriptionRequired, - SubscriptionIDRequired, - TooManySubscriptions, - Unsupported, - UnsupportedAccessModel - }; + class SWIFTEN_API PubSubError : public Payload { + public: + enum Type { + UnknownType = 0, + ClosedNode, + ConfigurationRequired, + InvalidJID, + InvalidOptions, + InvalidPayload, + InvalidSubscriptionID, + ItemForbidden, + ItemRequired, + JIDRequired, + MaximumItemsExceeded, + MaximumNodesExceeded, + NodeIDRequired, + NotInRosterGroup, + NotSubscribed, + PayloadTooBig, + PayloadRequired, + PendingSubscription, + PresenceSubscriptionRequired, + SubscriptionIDRequired, + TooManySubscriptions, + Unsupported, + UnsupportedAccessModel + }; - enum UnsupportedFeatureType { - UnknownUnsupportedFeatureType = 0, - AccessAuthorize, - AccessOpen, - AccessPresence, - AccessRoster, - AccessWhitelist, - AutoCreate, - AutoSubscribe, - Collections, - ConfigNode, - CreateAndConfigure, - CreateNodes, - DeleteItems, - DeleteNodes, - FilteredNotifications, - GetPending, - InstantNodes, - ItemIDs, - LastPublished, - LeasedSubscription, - ManageSubscriptions, - MemberAffiliation, - MetaData, - ModifyAffiliations, - MultiCollection, - MultiSubscribe, - OutcastAffiliation, - PersistentItems, - PresenceNotifications, - PresenceSubscribe, - Publish, - PublishOptions, - PublishOnlyAffiliation, - PublisherAffiliation, - PurgeNodes, - RetractItems, - RetrieveAffiliations, - RetrieveDefault, - RetrieveItems, - RetrieveSubscriptions, - Subscribe, - SubscriptionOptions, - SubscriptionNotifications - }; + enum UnsupportedFeatureType { + UnknownUnsupportedFeatureType = 0, + AccessAuthorize, + AccessOpen, + AccessPresence, + AccessRoster, + AccessWhitelist, + AutoCreate, + AutoSubscribe, + Collections, + ConfigNode, + CreateAndConfigure, + CreateNodes, + DeleteItems, + DeleteNodes, + FilteredNotifications, + GetPending, + InstantNodes, + ItemIDs, + LastPublished, + LeasedSubscription, + ManageSubscriptions, + MemberAffiliation, + MetaData, + ModifyAffiliations, + MultiCollection, + MultiSubscribe, + OutcastAffiliation, + PersistentItems, + PresenceNotifications, + PresenceSubscribe, + Publish, + PublishOptions, + PublishOnlyAffiliation, + PublisherAffiliation, + PurgeNodes, + RetractItems, + RetrieveAffiliations, + RetrieveDefault, + RetrieveItems, + RetrieveSubscriptions, + Subscribe, + SubscriptionOptions, + SubscriptionNotifications + }; - PubSubError(Type type = UnknownType) : type(type), unsupportedType(UnknownUnsupportedFeatureType) { - } + PubSubError(Type type = UnknownType) : type(type), unsupportedType(UnknownUnsupportedFeatureType) { + } - virtual ~PubSubError(); + virtual ~PubSubError(); - Type getType() const { - return type; - } + Type getType() const { + return type; + } - void setType(Type type) { - this->type = type; - } + void setType(Type type) { + this->type = type; + } - UnsupportedFeatureType getUnsupportedFeatureType() const { - return unsupportedType; - } + UnsupportedFeatureType getUnsupportedFeatureType() const { + return unsupportedType; + } - void setUnsupportedFeatureType(UnsupportedFeatureType unsupportedType) { - this->unsupportedType = unsupportedType; - } + void setUnsupportedFeatureType(UnsupportedFeatureType unsupportedType) { + this->unsupportedType = unsupportedType; + } - private: - Type type; - UnsupportedFeatureType unsupportedType; - }; + private: + Type type; + UnsupportedFeatureType unsupportedType; + }; } diff --git a/Swiften/Elements/PubSubEvent.h b/Swiften/Elements/PubSubEvent.h index 2029945..85d9bed 100644 --- a/Swiften/Elements/PubSubEvent.h +++ b/Swiften/Elements/PubSubEvent.h @@ -15,9 +15,9 @@ #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { - class SWIFTEN_API PubSubEvent : public ContainerPayload<PubSubEventPayload> { - public: - PubSubEvent(); - virtual ~PubSubEvent(); - }; + class SWIFTEN_API PubSubEvent : public ContainerPayload<PubSubEventPayload> { + public: + PubSubEvent(); + virtual ~PubSubEvent(); + }; } diff --git a/Swiften/Elements/PubSubEventAssociate.h b/Swiften/Elements/PubSubEventAssociate.h index 73cd3b9..5d963a0 100644 --- a/Swiften/Elements/PubSubEventAssociate.h +++ b/Swiften/Elements/PubSubEventAssociate.h @@ -13,23 +13,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubEventAssociate : public Payload { - public: - - PubSubEventAssociate(); - - virtual ~PubSubEventAssociate(); + class SWIFTEN_API PubSubEventAssociate : public Payload { + public: - const std::string& getNode() const { - return node; - } + PubSubEventAssociate(); - void setNode(const std::string& value) { - this->node = value ; - } + virtual ~PubSubEventAssociate(); + const std::string& getNode() const { + return node; + } - private: - std::string node; - }; + void setNode(const std::string& value) { + this->node = value ; + } + + + private: + std::string node; + }; } diff --git a/Swiften/Elements/PubSubEventCollection.h b/Swiften/Elements/PubSubEventCollection.h index 5910c9f..390fa58 100644 --- a/Swiften/Elements/PubSubEventCollection.h +++ b/Swiften/Elements/PubSubEventCollection.h @@ -19,41 +19,41 @@ #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { - class SWIFTEN_API PubSubEventCollection : public PubSubEventPayload { - public: - - PubSubEventCollection(); - - virtual ~PubSubEventCollection(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - boost::shared_ptr<PubSubEventDisassociate> getDisassociate() const { - return disassociate; - } - - void setDisassociate(boost::shared_ptr<PubSubEventDisassociate> value) { - this->disassociate = value ; - } - - boost::shared_ptr<PubSubEventAssociate> getAssociate() const { - return associate; - } - - void setAssociate(boost::shared_ptr<PubSubEventAssociate> value) { - this->associate = value ; - } - - - private: - boost::optional< std::string > node; - boost::shared_ptr<PubSubEventDisassociate> disassociate; - boost::shared_ptr<PubSubEventAssociate> associate; - }; + class SWIFTEN_API PubSubEventCollection : public PubSubEventPayload { + public: + + PubSubEventCollection(); + + virtual ~PubSubEventCollection(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + boost::shared_ptr<PubSubEventDisassociate> getDisassociate() const { + return disassociate; + } + + void setDisassociate(boost::shared_ptr<PubSubEventDisassociate> value) { + this->disassociate = value ; + } + + boost::shared_ptr<PubSubEventAssociate> getAssociate() const { + return associate; + } + + void setAssociate(boost::shared_ptr<PubSubEventAssociate> value) { + this->associate = value ; + } + + + private: + boost::optional< std::string > node; + boost::shared_ptr<PubSubEventDisassociate> disassociate; + boost::shared_ptr<PubSubEventAssociate> associate; + }; } diff --git a/Swiften/Elements/PubSubEventConfiguration.h b/Swiften/Elements/PubSubEventConfiguration.h index da42fcb..14639ab 100644 --- a/Swiften/Elements/PubSubEventConfiguration.h +++ b/Swiften/Elements/PubSubEventConfiguration.h @@ -17,32 +17,32 @@ #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { - class SWIFTEN_API PubSubEventConfiguration : public PubSubEventPayload { - public: - - PubSubEventConfiguration(); - - virtual ~PubSubEventConfiguration(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - boost::shared_ptr<Form> getData() const { - return data; - } - - void setData(boost::shared_ptr<Form> value) { - this->data = value ; - } - - - private: - std::string node; - boost::shared_ptr<Form> data; - }; + class SWIFTEN_API PubSubEventConfiguration : public PubSubEventPayload { + public: + + PubSubEventConfiguration(); + + virtual ~PubSubEventConfiguration(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + boost::shared_ptr<Form> getData() const { + return data; + } + + void setData(boost::shared_ptr<Form> value) { + this->data = value ; + } + + + private: + std::string node; + boost::shared_ptr<Form> data; + }; } diff --git a/Swiften/Elements/PubSubEventDelete.h b/Swiften/Elements/PubSubEventDelete.h index 1a2c74f..a778276 100644 --- a/Swiften/Elements/PubSubEventDelete.h +++ b/Swiften/Elements/PubSubEventDelete.h @@ -17,32 +17,32 @@ #include <Swiften/Elements/PubSubEventRedirect.h> namespace Swift { - class SWIFTEN_API PubSubEventDelete : public PubSubEventPayload { - public: - - PubSubEventDelete(); - - virtual ~PubSubEventDelete(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - boost::shared_ptr<PubSubEventRedirect> getRedirects() const { - return redirects; - } - - void setRedirects(boost::shared_ptr<PubSubEventRedirect> value) { - this->redirects = value ; - } - - - private: - std::string node; - boost::shared_ptr<PubSubEventRedirect> redirects; - }; + class SWIFTEN_API PubSubEventDelete : public PubSubEventPayload { + public: + + PubSubEventDelete(); + + virtual ~PubSubEventDelete(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + boost::shared_ptr<PubSubEventRedirect> getRedirects() const { + return redirects; + } + + void setRedirects(boost::shared_ptr<PubSubEventRedirect> value) { + this->redirects = value ; + } + + + private: + std::string node; + boost::shared_ptr<PubSubEventRedirect> redirects; + }; } diff --git a/Swiften/Elements/PubSubEventDisassociate.h b/Swiften/Elements/PubSubEventDisassociate.h index d4c3452..826b1f4 100644 --- a/Swiften/Elements/PubSubEventDisassociate.h +++ b/Swiften/Elements/PubSubEventDisassociate.h @@ -13,23 +13,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubEventDisassociate : public Payload { - public: - - PubSubEventDisassociate(); - - virtual ~PubSubEventDisassociate(); + class SWIFTEN_API PubSubEventDisassociate : public Payload { + public: - const std::string& getNode() const { - return node; - } + PubSubEventDisassociate(); - void setNode(const std::string& value) { - this->node = value ; - } + virtual ~PubSubEventDisassociate(); + const std::string& getNode() const { + return node; + } - private: - std::string node; - }; + void setNode(const std::string& value) { + this->node = value ; + } + + + private: + std::string node; + }; } diff --git a/Swiften/Elements/PubSubEventItem.h b/Swiften/Elements/PubSubEventItem.h index 3b4f930..bbadab9 100644 --- a/Swiften/Elements/PubSubEventItem.h +++ b/Swiften/Elements/PubSubEventItem.h @@ -17,54 +17,54 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubEventItem : public Payload { - public: - - PubSubEventItem(); - - virtual ~PubSubEventItem(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - const boost::optional< std::string >& getPublisher() const { - return publisher; - } - - void setPublisher(const boost::optional< std::string >& value) { - this->publisher = value ; - } - - const std::vector< boost::shared_ptr<Payload> >& getData() const { - return data; - } - - void setData(const std::vector< boost::shared_ptr<Payload> >& value) { - this->data = value ; - } - - void addData(boost::shared_ptr<Payload> value) { - this->data.push_back(value); - } - - const boost::optional< std::string >& getID() const { - return id; - } - - void setID(const boost::optional< std::string >& value) { - this->id = value ; - } - - - private: - boost::optional< std::string > node; - boost::optional< std::string > publisher; - std::vector< boost::shared_ptr<Payload> > data; - boost::optional< std::string > id; - }; + class SWIFTEN_API PubSubEventItem : public Payload { + public: + + PubSubEventItem(); + + virtual ~PubSubEventItem(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + const boost::optional< std::string >& getPublisher() const { + return publisher; + } + + void setPublisher(const boost::optional< std::string >& value) { + this->publisher = value ; + } + + const std::vector< boost::shared_ptr<Payload> >& getData() const { + return data; + } + + void setData(const std::vector< boost::shared_ptr<Payload> >& value) { + this->data = value ; + } + + void addData(boost::shared_ptr<Payload> value) { + this->data.push_back(value); + } + + const boost::optional< std::string >& getID() const { + return id; + } + + void setID(const boost::optional< std::string >& value) { + this->id = value ; + } + + + private: + boost::optional< std::string > node; + boost::optional< std::string > publisher; + std::vector< boost::shared_ptr<Payload> > data; + boost::optional< std::string > id; + }; } diff --git a/Swiften/Elements/PubSubEventItems.h b/Swiften/Elements/PubSubEventItems.h index c3be21a..9d1e09b 100644 --- a/Swiften/Elements/PubSubEventItems.h +++ b/Swiften/Elements/PubSubEventItems.h @@ -19,49 +19,49 @@ #include <Swiften/Elements/PubSubEventRetract.h> namespace Swift { - class SWIFTEN_API PubSubEventItems : public PubSubEventPayload { - public: - - PubSubEventItems(); - - virtual ~PubSubEventItems(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubEventItem> >& getItems() const { - return items; - } - - void setItems(const std::vector< boost::shared_ptr<PubSubEventItem> >& value) { - this->items = value ; - } - - void addItem(boost::shared_ptr<PubSubEventItem> value) { - this->items.push_back(value); - } - - const std::vector< boost::shared_ptr<PubSubEventRetract> >& getRetracts() const { - return retracts; - } - - void setRetracts(const std::vector< boost::shared_ptr<PubSubEventRetract> >& value) { - this->retracts = value ; - } - - void addRetract(boost::shared_ptr<PubSubEventRetract> value) { - this->retracts.push_back(value); - } - - - private: - std::string node; - std::vector< boost::shared_ptr<PubSubEventItem> > items; - std::vector< boost::shared_ptr<PubSubEventRetract> > retracts; - }; + class SWIFTEN_API PubSubEventItems : public PubSubEventPayload { + public: + + PubSubEventItems(); + + virtual ~PubSubEventItems(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubEventItem> >& getItems() const { + return items; + } + + void setItems(const std::vector< boost::shared_ptr<PubSubEventItem> >& value) { + this->items = value ; + } + + void addItem(boost::shared_ptr<PubSubEventItem> value) { + this->items.push_back(value); + } + + const std::vector< boost::shared_ptr<PubSubEventRetract> >& getRetracts() const { + return retracts; + } + + void setRetracts(const std::vector< boost::shared_ptr<PubSubEventRetract> >& value) { + this->retracts = value ; + } + + void addRetract(boost::shared_ptr<PubSubEventRetract> value) { + this->retracts.push_back(value); + } + + + private: + std::string node; + std::vector< boost::shared_ptr<PubSubEventItem> > items; + std::vector< boost::shared_ptr<PubSubEventRetract> > retracts; + }; } diff --git a/Swiften/Elements/PubSubEventPayload.h b/Swiften/Elements/PubSubEventPayload.h index f1e3890..f4abc06 100644 --- a/Swiften/Elements/PubSubEventPayload.h +++ b/Swiften/Elements/PubSubEventPayload.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubEventPayload : public Payload { - public: - virtual ~PubSubEventPayload(); - }; + class SWIFTEN_API PubSubEventPayload : public Payload { + public: + virtual ~PubSubEventPayload(); + }; } diff --git a/Swiften/Elements/PubSubEventPurge.h b/Swiften/Elements/PubSubEventPurge.h index a19a8a2..743cc25 100644 --- a/Swiften/Elements/PubSubEventPurge.h +++ b/Swiften/Elements/PubSubEventPurge.h @@ -14,23 +14,23 @@ #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { - class SWIFTEN_API PubSubEventPurge : public PubSubEventPayload { - public: - - PubSubEventPurge(); - - virtual ~PubSubEventPurge(); + class SWIFTEN_API PubSubEventPurge : public PubSubEventPayload { + public: - const std::string& getNode() const { - return node; - } + PubSubEventPurge(); - void setNode(const std::string& value) { - this->node = value ; - } + virtual ~PubSubEventPurge(); + const std::string& getNode() const { + return node; + } - private: - std::string node; - }; + void setNode(const std::string& value) { + this->node = value ; + } + + + private: + std::string node; + }; } diff --git a/Swiften/Elements/PubSubEventRedirect.h b/Swiften/Elements/PubSubEventRedirect.h index 13dc865..e0e351f 100644 --- a/Swiften/Elements/PubSubEventRedirect.h +++ b/Swiften/Elements/PubSubEventRedirect.h @@ -13,23 +13,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubEventRedirect : public Payload { - public: - - PubSubEventRedirect(); - - virtual ~PubSubEventRedirect(); + class SWIFTEN_API PubSubEventRedirect : public Payload { + public: - const std::string& getURI() const { - return uri; - } + PubSubEventRedirect(); - void setURI(const std::string& value) { - this->uri = value ; - } + virtual ~PubSubEventRedirect(); + const std::string& getURI() const { + return uri; + } - private: - std::string uri; - }; + void setURI(const std::string& value) { + this->uri = value ; + } + + + private: + std::string uri; + }; } diff --git a/Swiften/Elements/PubSubEventRetract.h b/Swiften/Elements/PubSubEventRetract.h index 6681061..b0aea96 100644 --- a/Swiften/Elements/PubSubEventRetract.h +++ b/Swiften/Elements/PubSubEventRetract.h @@ -13,23 +13,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubEventRetract : public Payload { - public: - - PubSubEventRetract(); - - virtual ~PubSubEventRetract(); + class SWIFTEN_API PubSubEventRetract : public Payload { + public: - const std::string& getID() const { - return id; - } + PubSubEventRetract(); - void setID(const std::string& value) { - this->id = value ; - } + virtual ~PubSubEventRetract(); + const std::string& getID() const { + return id; + } - private: - std::string id; - }; + void setID(const std::string& value) { + this->id = value ; + } + + + private: + std::string id; + }; } diff --git a/Swiften/Elements/PubSubEventSubscription.h b/Swiften/Elements/PubSubEventSubscription.h index 6416d21..0b8297c 100644 --- a/Swiften/Elements/PubSubEventSubscription.h +++ b/Swiften/Elements/PubSubEventSubscription.h @@ -18,65 +18,65 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API PubSubEventSubscription : public PubSubEventPayload { - public: - enum SubscriptionType { - None, - Pending, - Subscribed, - Unconfigured - }; - - PubSubEventSubscription(); - - virtual ~PubSubEventSubscription(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const JID& getJID() const { - return jid; - } - - void setJID(const JID& value) { - this->jid = value ; - } - - SubscriptionType getSubscription() const { - return subscription; - } - - void setSubscription(SubscriptionType value) { - this->subscription = value ; - } - - const boost::optional< std::string >& getSubscriptionID() const { - return subscriptionID; - } - - void setSubscriptionID(const boost::optional< std::string >& value) { - this->subscriptionID = value ; - } - - const boost::posix_time::ptime& getExpiry() const { - return expiry; - } - - void setExpiry(const boost::posix_time::ptime& value) { - this->expiry = value ; - } - - - private: - std::string node; - JID jid; - SubscriptionType subscription; - boost::optional< std::string > subscriptionID; - boost::posix_time::ptime expiry; - }; + class SWIFTEN_API PubSubEventSubscription : public PubSubEventPayload { + public: + enum SubscriptionType { + None, + Pending, + Subscribed, + Unconfigured + }; + + PubSubEventSubscription(); + + virtual ~PubSubEventSubscription(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const JID& getJID() const { + return jid; + } + + void setJID(const JID& value) { + this->jid = value ; + } + + SubscriptionType getSubscription() const { + return subscription; + } + + void setSubscription(SubscriptionType value) { + this->subscription = value ; + } + + const boost::optional< std::string >& getSubscriptionID() const { + return subscriptionID; + } + + void setSubscriptionID(const boost::optional< std::string >& value) { + this->subscriptionID = value ; + } + + const boost::posix_time::ptime& getExpiry() const { + return expiry; + } + + void setExpiry(const boost::posix_time::ptime& value) { + this->expiry = value ; + } + + + private: + std::string node; + JID jid; + SubscriptionType subscription; + boost::optional< std::string > subscriptionID; + boost::posix_time::ptime expiry; + }; } diff --git a/Swiften/Elements/PubSubItem.h b/Swiften/Elements/PubSubItem.h index 63b374b..5a16edc 100644 --- a/Swiften/Elements/PubSubItem.h +++ b/Swiften/Elements/PubSubItem.h @@ -16,36 +16,36 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubItem : public Payload { - public: - - PubSubItem(); - - virtual ~PubSubItem(); - - const std::vector< boost::shared_ptr<Payload> >& getData() const { - return data; - } - - void setData(const std::vector< boost::shared_ptr<Payload> >& value) { - this->data = value ; - } - - void addData(boost::shared_ptr<Payload> value) { - this->data.push_back(value); - } - - const std::string& getID() const { - return id; - } - - void setID(const std::string& value) { - this->id = value ; - } - - - private: - std::vector< boost::shared_ptr<Payload> > data; - std::string id; - }; + class SWIFTEN_API PubSubItem : public Payload { + public: + + PubSubItem(); + + virtual ~PubSubItem(); + + const std::vector< boost::shared_ptr<Payload> >& getData() const { + return data; + } + + void setData(const std::vector< boost::shared_ptr<Payload> >& value) { + this->data = value ; + } + + void addData(boost::shared_ptr<Payload> value) { + this->data.push_back(value); + } + + const std::string& getID() const { + return id; + } + + void setID(const std::string& value) { + this->id = value ; + } + + + private: + std::vector< boost::shared_ptr<Payload> > data; + std::string id; + }; } diff --git a/Swiften/Elements/PubSubItems.h b/Swiften/Elements/PubSubItems.h index 7665ca4..b7d8fcc 100644 --- a/Swiften/Elements/PubSubItems.h +++ b/Swiften/Elements/PubSubItems.h @@ -19,54 +19,54 @@ #include <Swiften/Elements/PubSubPayload.h> namespace Swift { - class SWIFTEN_API PubSubItems : public PubSubPayload { - public: - - PubSubItems(); - PubSubItems(const std::string& node) : node(node) {} - virtual ~PubSubItems(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const { - return items; - } - - void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) { - this->items = value ; - } - - void addItem(boost::shared_ptr<PubSubItem> value) { - this->items.push_back(value); - } - - const boost::optional< unsigned int >& getMaximumItems() const { - return maximumItems; - } - - void setMaximumItems(const boost::optional< unsigned int >& value) { - this->maximumItems = value ; - } - - const boost::optional< std::string >& getSubscriptionID() const { - return subscriptionID; - } - - void setSubscriptionID(const boost::optional< std::string >& value) { - this->subscriptionID = value ; - } - - - private: - std::string node; - std::vector< boost::shared_ptr<PubSubItem> > items; - boost::optional< unsigned int > maximumItems; - boost::optional< std::string > subscriptionID; - }; + class SWIFTEN_API PubSubItems : public PubSubPayload { + public: + + PubSubItems(); + PubSubItems(const std::string& node) : node(node) {} + virtual ~PubSubItems(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const { + return items; + } + + void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) { + this->items = value ; + } + + void addItem(boost::shared_ptr<PubSubItem> value) { + this->items.push_back(value); + } + + const boost::optional< unsigned int >& getMaximumItems() const { + return maximumItems; + } + + void setMaximumItems(const boost::optional< unsigned int >& value) { + this->maximumItems = value ; + } + + const boost::optional< std::string >& getSubscriptionID() const { + return subscriptionID; + } + + void setSubscriptionID(const boost::optional< std::string >& value) { + this->subscriptionID = value ; + } + + + private: + std::string node; + std::vector< boost::shared_ptr<PubSubItem> > items; + boost::optional< unsigned int > maximumItems; + boost::optional< std::string > subscriptionID; + }; } diff --git a/Swiften/Elements/PubSubOptions.h b/Swiften/Elements/PubSubOptions.h index 9a953fe..fffc175 100644 --- a/Swiften/Elements/PubSubOptions.h +++ b/Swiften/Elements/PubSubOptions.h @@ -19,50 +19,50 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API PubSubOptions : public PubSubPayload { - public: - - PubSubOptions(); - - virtual ~PubSubOptions(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const JID& getJID() const { - return jid; - } - - void setJID(const JID& value) { - this->jid = value ; - } - - boost::shared_ptr<Form> getData() const { - return data; - } - - void setData(boost::shared_ptr<Form> value) { - this->data = value ; - } - - const boost::optional< std::string >& getSubscriptionID() const { - return subscriptionID; - } - - void setSubscriptionID(const boost::optional< std::string >& value) { - this->subscriptionID = value ; - } - - - private: - std::string node; - JID jid; - boost::shared_ptr<Form> data; - boost::optional< std::string > subscriptionID; - }; + class SWIFTEN_API PubSubOptions : public PubSubPayload { + public: + + PubSubOptions(); + + virtual ~PubSubOptions(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const JID& getJID() const { + return jid; + } + + void setJID(const JID& value) { + this->jid = value ; + } + + boost::shared_ptr<Form> getData() const { + return data; + } + + void setData(boost::shared_ptr<Form> value) { + this->data = value ; + } + + const boost::optional< std::string >& getSubscriptionID() const { + return subscriptionID; + } + + void setSubscriptionID(const boost::optional< std::string >& value) { + this->subscriptionID = value ; + } + + + private: + std::string node; + JID jid; + boost::shared_ptr<Form> data; + boost::optional< std::string > subscriptionID; + }; } diff --git a/Swiften/Elements/PubSubOwnerAffiliation.h b/Swiften/Elements/PubSubOwnerAffiliation.h index d064873..a8c1d91 100644 --- a/Swiften/Elements/PubSubOwnerAffiliation.h +++ b/Swiften/Elements/PubSubOwnerAffiliation.h @@ -12,40 +12,40 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API PubSubOwnerAffiliation : public Payload { - public: - enum Type { - None, - Member, - Outcast, - Owner, - Publisher, - PublishOnly - }; - - PubSubOwnerAffiliation(); - - virtual ~PubSubOwnerAffiliation(); - - const JID& getJID() const { - return jid; - } - - void setJID(const JID& value) { - this->jid = value ; - } - - Type getType() const { - return type; - } - - void setType(Type value) { - this->type = value ; - } - - - private: - JID jid; - Type type; - }; + class SWIFTEN_API PubSubOwnerAffiliation : public Payload { + public: + enum Type { + None, + Member, + Outcast, + Owner, + Publisher, + PublishOnly + }; + + PubSubOwnerAffiliation(); + + virtual ~PubSubOwnerAffiliation(); + + const JID& getJID() const { + return jid; + } + + void setJID(const JID& value) { + this->jid = value ; + } + + Type getType() const { + return type; + } + + void setType(Type value) { + this->type = value ; + } + + + private: + JID jid; + Type type; + }; } diff --git a/Swiften/Elements/PubSubOwnerAffiliations.h b/Swiften/Elements/PubSubOwnerAffiliations.h index 23739a7..5005b01 100644 --- a/Swiften/Elements/PubSubOwnerAffiliations.h +++ b/Swiften/Elements/PubSubOwnerAffiliations.h @@ -18,36 +18,36 @@ #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { - class SWIFTEN_API PubSubOwnerAffiliations : public PubSubOwnerPayload { - public: - - PubSubOwnerAffiliations(); - - virtual ~PubSubOwnerAffiliations(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& getAffiliations() const { - return affiliations; - } - - void setAffiliations(const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& value) { - this->affiliations = value ; - } - - void addAffiliation(boost::shared_ptr<PubSubOwnerAffiliation> value) { - this->affiliations.push_back(value); - } - - - private: - std::string node; - std::vector< boost::shared_ptr<PubSubOwnerAffiliation> > affiliations; - }; + class SWIFTEN_API PubSubOwnerAffiliations : public PubSubOwnerPayload { + public: + + PubSubOwnerAffiliations(); + + virtual ~PubSubOwnerAffiliations(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& getAffiliations() const { + return affiliations; + } + + void setAffiliations(const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& value) { + this->affiliations = value ; + } + + void addAffiliation(boost::shared_ptr<PubSubOwnerAffiliation> value) { + this->affiliations.push_back(value); + } + + + private: + std::string node; + std::vector< boost::shared_ptr<PubSubOwnerAffiliation> > affiliations; + }; } diff --git a/Swiften/Elements/PubSubOwnerConfigure.h b/Swiften/Elements/PubSubOwnerConfigure.h index d29342d..086095c 100644 --- a/Swiften/Elements/PubSubOwnerConfigure.h +++ b/Swiften/Elements/PubSubOwnerConfigure.h @@ -18,32 +18,32 @@ #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { - class SWIFTEN_API PubSubOwnerConfigure : public PubSubOwnerPayload { - public: - - PubSubOwnerConfigure(); - PubSubOwnerConfigure(const std::string& node) : node(node) {} - virtual ~PubSubOwnerConfigure(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - boost::shared_ptr<Form> getData() const { - return data; - } - - void setData(boost::shared_ptr<Form> value) { - this->data = value ; - } - - - private: - boost::optional< std::string > node; - boost::shared_ptr<Form> data; - }; + class SWIFTEN_API PubSubOwnerConfigure : public PubSubOwnerPayload { + public: + + PubSubOwnerConfigure(); + PubSubOwnerConfigure(const std::string& node) : node(node) {} + virtual ~PubSubOwnerConfigure(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + boost::shared_ptr<Form> getData() const { + return data; + } + + void setData(boost::shared_ptr<Form> value) { + this->data = value ; + } + + + private: + boost::optional< std::string > node; + boost::shared_ptr<Form> data; + }; } diff --git a/Swiften/Elements/PubSubOwnerDefault.h b/Swiften/Elements/PubSubOwnerDefault.h index 17717db..a0b82f7 100644 --- a/Swiften/Elements/PubSubOwnerDefault.h +++ b/Swiften/Elements/PubSubOwnerDefault.h @@ -15,23 +15,23 @@ #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { - class SWIFTEN_API PubSubOwnerDefault : public PubSubOwnerPayload { - public: - - PubSubOwnerDefault(); - - virtual ~PubSubOwnerDefault(); + class SWIFTEN_API PubSubOwnerDefault : public PubSubOwnerPayload { + public: - boost::shared_ptr<Form> getData() const { - return data; - } + PubSubOwnerDefault(); - void setData(boost::shared_ptr<Form> value) { - this->data = value ; - } + virtual ~PubSubOwnerDefault(); + boost::shared_ptr<Form> getData() const { + return data; + } - private: - boost::shared_ptr<Form> data; - }; + void setData(boost::shared_ptr<Form> value) { + this->data = value ; + } + + + private: + boost::shared_ptr<Form> data; + }; } diff --git a/Swiften/Elements/PubSubOwnerDelete.h b/Swiften/Elements/PubSubOwnerDelete.h index b4f60a2..7f908a1 100644 --- a/Swiften/Elements/PubSubOwnerDelete.h +++ b/Swiften/Elements/PubSubOwnerDelete.h @@ -17,32 +17,32 @@ #include <Swiften/Elements/PubSubOwnerRedirect.h> namespace Swift { - class SWIFTEN_API PubSubOwnerDelete : public PubSubOwnerPayload { - public: - - PubSubOwnerDelete(); - PubSubOwnerDelete(const std::string& node) : node(node) {} - virtual ~PubSubOwnerDelete(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - boost::shared_ptr<PubSubOwnerRedirect> getRedirect() const { - return redirect; - } - - void setRedirect(boost::shared_ptr<PubSubOwnerRedirect> value) { - this->redirect = value ; - } - - - private: - std::string node; - boost::shared_ptr<PubSubOwnerRedirect> redirect; - }; + class SWIFTEN_API PubSubOwnerDelete : public PubSubOwnerPayload { + public: + + PubSubOwnerDelete(); + PubSubOwnerDelete(const std::string& node) : node(node) {} + virtual ~PubSubOwnerDelete(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + boost::shared_ptr<PubSubOwnerRedirect> getRedirect() const { + return redirect; + } + + void setRedirect(boost::shared_ptr<PubSubOwnerRedirect> value) { + this->redirect = value ; + } + + + private: + std::string node; + boost::shared_ptr<PubSubOwnerRedirect> redirect; + }; } diff --git a/Swiften/Elements/PubSubOwnerPayload.h b/Swiften/Elements/PubSubOwnerPayload.h index 3a90d8e..8381a17 100644 --- a/Swiften/Elements/PubSubOwnerPayload.h +++ b/Swiften/Elements/PubSubOwnerPayload.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubOwnerPayload : public Payload { - public: - virtual ~PubSubOwnerPayload(); - }; + class SWIFTEN_API PubSubOwnerPayload : public Payload { + public: + virtual ~PubSubOwnerPayload(); + }; } diff --git a/Swiften/Elements/PubSubOwnerPubSub.h b/Swiften/Elements/PubSubOwnerPubSub.h index 50a4370..f3474cf 100644 --- a/Swiften/Elements/PubSubOwnerPubSub.h +++ b/Swiften/Elements/PubSubOwnerPubSub.h @@ -12,9 +12,9 @@ #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { - class SWIFTEN_API PubSubOwnerPubSub : public ContainerPayload<PubSubOwnerPayload> { - public: - PubSubOwnerPubSub(); - virtual ~PubSubOwnerPubSub(); - }; + class SWIFTEN_API PubSubOwnerPubSub : public ContainerPayload<PubSubOwnerPayload> { + public: + PubSubOwnerPubSub(); + virtual ~PubSubOwnerPubSub(); + }; } diff --git a/Swiften/Elements/PubSubOwnerPurge.h b/Swiften/Elements/PubSubOwnerPurge.h index 2b1b64f..aca48e1 100644 --- a/Swiften/Elements/PubSubOwnerPurge.h +++ b/Swiften/Elements/PubSubOwnerPurge.h @@ -14,23 +14,23 @@ #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { - class SWIFTEN_API PubSubOwnerPurge : public PubSubOwnerPayload { - public: - - PubSubOwnerPurge(); - - virtual ~PubSubOwnerPurge(); + class SWIFTEN_API PubSubOwnerPurge : public PubSubOwnerPayload { + public: - const std::string& getNode() const { - return node; - } + PubSubOwnerPurge(); - void setNode(const std::string& value) { - this->node = value ; - } + virtual ~PubSubOwnerPurge(); + const std::string& getNode() const { + return node; + } - private: - std::string node; - }; + void setNode(const std::string& value) { + this->node = value ; + } + + + private: + std::string node; + }; } diff --git a/Swiften/Elements/PubSubOwnerRedirect.h b/Swiften/Elements/PubSubOwnerRedirect.h index 7659889..c481f98 100644 --- a/Swiften/Elements/PubSubOwnerRedirect.h +++ b/Swiften/Elements/PubSubOwnerRedirect.h @@ -13,23 +13,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubOwnerRedirect : public Payload { - public: - - PubSubOwnerRedirect(); - - virtual ~PubSubOwnerRedirect(); + class SWIFTEN_API PubSubOwnerRedirect : public Payload { + public: - const std::string& getURI() const { - return uri; - } + PubSubOwnerRedirect(); - void setURI(const std::string& value) { - this->uri = value ; - } + virtual ~PubSubOwnerRedirect(); + const std::string& getURI() const { + return uri; + } - private: - std::string uri; - }; + void setURI(const std::string& value) { + this->uri = value ; + } + + + private: + std::string uri; + }; } diff --git a/Swiften/Elements/PubSubOwnerSubscription.h b/Swiften/Elements/PubSubOwnerSubscription.h index 2b8964d..6a3fcc1 100644 --- a/Swiften/Elements/PubSubOwnerSubscription.h +++ b/Swiften/Elements/PubSubOwnerSubscription.h @@ -12,38 +12,38 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API PubSubOwnerSubscription : public Payload { - public: - enum SubscriptionType { - None, - Pending, - Subscribed, - Unconfigured - }; - - PubSubOwnerSubscription(); - - virtual ~PubSubOwnerSubscription(); - - const JID& getJID() const { - return jid; - } - - void setJID(const JID& value) { - this->jid = value ; - } - - SubscriptionType getSubscription() const { - return subscription; - } - - void setSubscription(SubscriptionType value) { - this->subscription = value ; - } - - - private: - JID jid; - SubscriptionType subscription; - }; + class SWIFTEN_API PubSubOwnerSubscription : public Payload { + public: + enum SubscriptionType { + None, + Pending, + Subscribed, + Unconfigured + }; + + PubSubOwnerSubscription(); + + virtual ~PubSubOwnerSubscription(); + + const JID& getJID() const { + return jid; + } + + void setJID(const JID& value) { + this->jid = value ; + } + + SubscriptionType getSubscription() const { + return subscription; + } + + void setSubscription(SubscriptionType value) { + this->subscription = value ; + } + + + private: + JID jid; + SubscriptionType subscription; + }; } diff --git a/Swiften/Elements/PubSubOwnerSubscriptions.h b/Swiften/Elements/PubSubOwnerSubscriptions.h index caa5da8..44c31b8 100644 --- a/Swiften/Elements/PubSubOwnerSubscriptions.h +++ b/Swiften/Elements/PubSubOwnerSubscriptions.h @@ -18,36 +18,36 @@ #include <Swiften/Elements/PubSubOwnerSubscription.h> namespace Swift { - class SWIFTEN_API PubSubOwnerSubscriptions : public PubSubOwnerPayload { - public: - - PubSubOwnerSubscriptions(); - - virtual ~PubSubOwnerSubscriptions(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& getSubscriptions() const { - return subscriptions; - } - - void setSubscriptions(const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& value) { - this->subscriptions = value ; - } - - void addSubscription(boost::shared_ptr<PubSubOwnerSubscription> value) { - this->subscriptions.push_back(value); - } - - - private: - std::string node; - std::vector< boost::shared_ptr<PubSubOwnerSubscription> > subscriptions; - }; + class SWIFTEN_API PubSubOwnerSubscriptions : public PubSubOwnerPayload { + public: + + PubSubOwnerSubscriptions(); + + virtual ~PubSubOwnerSubscriptions(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& getSubscriptions() const { + return subscriptions; + } + + void setSubscriptions(const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& value) { + this->subscriptions = value ; + } + + void addSubscription(boost::shared_ptr<PubSubOwnerSubscription> value) { + this->subscriptions.push_back(value); + } + + + private: + std::string node; + std::vector< boost::shared_ptr<PubSubOwnerSubscription> > subscriptions; + }; } diff --git a/Swiften/Elements/PubSubPayload.h b/Swiften/Elements/PubSubPayload.h index c0fb905..7fc1882 100644 --- a/Swiften/Elements/PubSubPayload.h +++ b/Swiften/Elements/PubSubPayload.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubPayload : public Payload { - public: - virtual ~PubSubPayload(); - }; + class SWIFTEN_API PubSubPayload : public Payload { + public: + virtual ~PubSubPayload(); + }; } diff --git a/Swiften/Elements/PubSubPublish.h b/Swiften/Elements/PubSubPublish.h index 11a3ab2..a6fca8d 100644 --- a/Swiften/Elements/PubSubPublish.h +++ b/Swiften/Elements/PubSubPublish.h @@ -18,36 +18,36 @@ #include <Swiften/Elements/PubSubPayload.h> namespace Swift { - class SWIFTEN_API PubSubPublish : public PubSubPayload { - public: - - PubSubPublish(); - - virtual ~PubSubPublish(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const { - return items; - } - - void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) { - this->items = value ; - } - - void addItem(boost::shared_ptr<PubSubItem> value) { - this->items.push_back(value); - } - - - private: - std::string node; - std::vector< boost::shared_ptr<PubSubItem> > items; - }; + class SWIFTEN_API PubSubPublish : public PubSubPayload { + public: + + PubSubPublish(); + + virtual ~PubSubPublish(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const { + return items; + } + + void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) { + this->items = value ; + } + + void addItem(boost::shared_ptr<PubSubItem> value) { + this->items.push_back(value); + } + + + private: + std::string node; + std::vector< boost::shared_ptr<PubSubItem> > items; + }; } diff --git a/Swiften/Elements/PubSubRetract.h b/Swiften/Elements/PubSubRetract.h index 3863bef..60ceb28 100644 --- a/Swiften/Elements/PubSubRetract.h +++ b/Swiften/Elements/PubSubRetract.h @@ -18,45 +18,45 @@ #include <Swiften/Elements/PubSubPayload.h> namespace Swift { - class SWIFTEN_API PubSubRetract : public PubSubPayload { - public: - - PubSubRetract(); - - virtual ~PubSubRetract(); - - const std::string& getNode() const { - return node; - } - - void setNode(const std::string& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const { - return items; - } - - void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) { - this->items = value ; - } - - void addItem(boost::shared_ptr<PubSubItem> value) { - this->items.push_back(value); - } - - bool isNotify() const { - return notify; - } - - void setNotify(bool value) { - this->notify = value ; - } - - - private: - std::string node; - std::vector< boost::shared_ptr<PubSubItem> > items; - bool notify; - }; + class SWIFTEN_API PubSubRetract : public PubSubPayload { + public: + + PubSubRetract(); + + virtual ~PubSubRetract(); + + const std::string& getNode() const { + return node; + } + + void setNode(const std::string& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const { + return items; + } + + void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) { + this->items = value ; + } + + void addItem(boost::shared_ptr<PubSubItem> value) { + this->items.push_back(value); + } + + bool isNotify() const { + return notify; + } + + void setNotify(bool value) { + this->notify = value ; + } + + + private: + std::string node; + std::vector< boost::shared_ptr<PubSubItem> > items; + bool notify; + }; } diff --git a/Swiften/Elements/PubSubSubscribe.h b/Swiften/Elements/PubSubSubscribe.h index fe4ecd3..8c57a21 100644 --- a/Swiften/Elements/PubSubSubscribe.h +++ b/Swiften/Elements/PubSubSubscribe.h @@ -19,41 +19,41 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API PubSubSubscribe : public PubSubPayload { - public: - - PubSubSubscribe(); - - virtual ~PubSubSubscribe(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - const JID& getJID() const { - return jid; - } - - void setJID(const JID& value) { - this->jid = value ; - } - - boost::shared_ptr<PubSubOptions> getOptions() const { - return options; - } - - void setOptions(boost::shared_ptr<PubSubOptions> value) { - this->options = value ; - } - - - private: - boost::optional< std::string > node; - JID jid; - boost::shared_ptr<PubSubOptions> options; - }; + class SWIFTEN_API PubSubSubscribe : public PubSubPayload { + public: + + PubSubSubscribe(); + + virtual ~PubSubSubscribe(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + const JID& getJID() const { + return jid; + } + + void setJID(const JID& value) { + this->jid = value ; + } + + boost::shared_ptr<PubSubOptions> getOptions() const { + return options; + } + + void setOptions(boost::shared_ptr<PubSubOptions> value) { + this->options = value ; + } + + + private: + boost::optional< std::string > node; + JID jid; + boost::shared_ptr<PubSubOptions> options; + }; } diff --git a/Swiften/Elements/PubSubSubscribeOptions.h b/Swiften/Elements/PubSubSubscribeOptions.h index 4b168c7..c837787 100644 --- a/Swiften/Elements/PubSubSubscribeOptions.h +++ b/Swiften/Elements/PubSubSubscribeOptions.h @@ -11,23 +11,23 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API PubSubSubscribeOptions : public Payload { - public: - - PubSubSubscribeOptions(); - - virtual ~PubSubSubscribeOptions(); + class SWIFTEN_API PubSubSubscribeOptions : public Payload { + public: - bool isRequired() const { - return required; - } + PubSubSubscribeOptions(); - void setRequired(bool value) { - this->required = value ; - } + virtual ~PubSubSubscribeOptions(); + bool isRequired() const { + return required; + } - private: - bool required; - }; + void setRequired(bool value) { + this->required = value ; + } + + + private: + bool required; + }; } diff --git a/Swiften/Elements/PubSubSubscription.h b/Swiften/Elements/PubSubSubscription.h index bd27a83..5bb1194 100644 --- a/Swiften/Elements/PubSubSubscription.h +++ b/Swiften/Elements/PubSubSubscription.h @@ -19,65 +19,65 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API PubSubSubscription : public PubSubPayload { - public: - enum SubscriptionType { - None, - Pending, - Subscribed, - Unconfigured - }; - - PubSubSubscription(); - - virtual ~PubSubSubscription(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - const boost::optional< std::string >& getSubscriptionID() const { - return subscriptionID; - } - - void setSubscriptionID(const boost::optional< std::string >& value) { - this->subscriptionID = value ; - } - - const JID& getJID() const { - return jid; - } - - void setJID(const JID& value) { - this->jid = value ; - } - - boost::shared_ptr<PubSubSubscribeOptions> getOptions() const { - return options; - } - - void setOptions(boost::shared_ptr<PubSubSubscribeOptions> value) { - this->options = value ; - } - - SubscriptionType getSubscription() const { - return subscription; - } - - void setSubscription(SubscriptionType value) { - this->subscription = value ; - } - - - private: - boost::optional< std::string > node; - boost::optional< std::string > subscriptionID; - JID jid; - boost::shared_ptr<PubSubSubscribeOptions> options; - SubscriptionType subscription; - }; + class SWIFTEN_API PubSubSubscription : public PubSubPayload { + public: + enum SubscriptionType { + None, + Pending, + Subscribed, + Unconfigured + }; + + PubSubSubscription(); + + virtual ~PubSubSubscription(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + const boost::optional< std::string >& getSubscriptionID() const { + return subscriptionID; + } + + void setSubscriptionID(const boost::optional< std::string >& value) { + this->subscriptionID = value ; + } + + const JID& getJID() const { + return jid; + } + + void setJID(const JID& value) { + this->jid = value ; + } + + boost::shared_ptr<PubSubSubscribeOptions> getOptions() const { + return options; + } + + void setOptions(boost::shared_ptr<PubSubSubscribeOptions> value) { + this->options = value ; + } + + SubscriptionType getSubscription() const { + return subscription; + } + + void setSubscription(SubscriptionType value) { + this->subscription = value ; + } + + + private: + boost::optional< std::string > node; + boost::optional< std::string > subscriptionID; + JID jid; + boost::shared_ptr<PubSubSubscribeOptions> options; + SubscriptionType subscription; + }; } diff --git a/Swiften/Elements/PubSubSubscriptions.h b/Swiften/Elements/PubSubSubscriptions.h index ae08471..63fc402 100644 --- a/Swiften/Elements/PubSubSubscriptions.h +++ b/Swiften/Elements/PubSubSubscriptions.h @@ -19,36 +19,36 @@ #include <Swiften/Elements/PubSubSubscription.h> namespace Swift { - class SWIFTEN_API PubSubSubscriptions : public PubSubPayload { - public: - - PubSubSubscriptions(); - PubSubSubscriptions(const std::string& node) : node(node) {} - virtual ~PubSubSubscriptions(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - const std::vector< boost::shared_ptr<PubSubSubscription> >& getSubscriptions() const { - return subscriptions; - } - - void setSubscriptions(const std::vector< boost::shared_ptr<PubSubSubscription> >& value) { - this->subscriptions = value ; - } - - void addSubscription(boost::shared_ptr<PubSubSubscription> value) { - this->subscriptions.push_back(value); - } - - - private: - boost::optional< std::string > node; - std::vector< boost::shared_ptr<PubSubSubscription> > subscriptions; - }; + class SWIFTEN_API PubSubSubscriptions : public PubSubPayload { + public: + + PubSubSubscriptions(); + PubSubSubscriptions(const std::string& node) : node(node) {} + virtual ~PubSubSubscriptions(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + const std::vector< boost::shared_ptr<PubSubSubscription> >& getSubscriptions() const { + return subscriptions; + } + + void setSubscriptions(const std::vector< boost::shared_ptr<PubSubSubscription> >& value) { + this->subscriptions = value ; + } + + void addSubscription(boost::shared_ptr<PubSubSubscription> value) { + this->subscriptions.push_back(value); + } + + + private: + boost::optional< std::string > node; + std::vector< boost::shared_ptr<PubSubSubscription> > subscriptions; + }; } diff --git a/Swiften/Elements/PubSubUnsubscribe.h b/Swiften/Elements/PubSubUnsubscribe.h index 4ea44b0..305af9a 100644 --- a/Swiften/Elements/PubSubUnsubscribe.h +++ b/Swiften/Elements/PubSubUnsubscribe.h @@ -17,41 +17,41 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API PubSubUnsubscribe : public PubSubPayload { - public: - - PubSubUnsubscribe(); - - virtual ~PubSubUnsubscribe(); - - const boost::optional< std::string >& getNode() const { - return node; - } - - void setNode(const boost::optional< std::string >& value) { - this->node = value ; - } - - const JID& getJID() const { - return jid; - } - - void setJID(const JID& value) { - this->jid = value ; - } - - const boost::optional< std::string >& getSubscriptionID() const { - return subscriptionID; - } - - void setSubscriptionID(const boost::optional< std::string >& value) { - this->subscriptionID = value ; - } - - - private: - boost::optional< std::string > node; - JID jid; - boost::optional< std::string > subscriptionID; - }; + class SWIFTEN_API PubSubUnsubscribe : public PubSubPayload { + public: + + PubSubUnsubscribe(); + + virtual ~PubSubUnsubscribe(); + + const boost::optional< std::string >& getNode() const { + return node; + } + + void setNode(const boost::optional< std::string >& value) { + this->node = value ; + } + + const JID& getJID() const { + return jid; + } + + void setJID(const JID& value) { + this->jid = value ; + } + + const boost::optional< std::string >& getSubscriptionID() const { + return subscriptionID; + } + + void setSubscriptionID(const boost::optional< std::string >& value) { + this->subscriptionID = value ; + } + + + private: + boost::optional< std::string > node; + JID jid; + boost::optional< std::string > subscriptionID; + }; } diff --git a/Swiften/Elements/RawXMLPayload.h b/Swiften/Elements/RawXMLPayload.h index d1b104d..65901bc 100644 --- a/Swiften/Elements/RawXMLPayload.h +++ b/Swiften/Elements/RawXMLPayload.h @@ -12,19 +12,19 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API RawXMLPayload : public Payload { - public: - RawXMLPayload(const std::string& data = "") : rawXML_(data) {} + class SWIFTEN_API RawXMLPayload : public Payload { + public: + RawXMLPayload(const std::string& data = "") : rawXML_(data) {} - void setRawXML(const std::string& data) { - rawXML_ = data; - } + void setRawXML(const std::string& data) { + rawXML_ = data; + } - const std::string& getRawXML() const { - return rawXML_; - } + const std::string& getRawXML() const { + return rawXML_; + } - private: - std::string rawXML_; - }; + private: + std::string rawXML_; + }; } diff --git a/Swiften/Elements/Replace.h b/Swiften/Elements/Replace.h index 1152040..b64777f 100644 --- a/Swiften/Elements/Replace.h +++ b/Swiften/Elements/Replace.h @@ -20,17 +20,17 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Replace : public Payload { - public: - typedef boost::shared_ptr<Replace> ref; - Replace(const std::string& id = std::string()) : replaceID_(id) {} - const std::string& getID() const { - return replaceID_; - } - void setID(const std::string& id) { - replaceID_ = id; - } - private: - std::string replaceID_; - }; + class SWIFTEN_API Replace : public Payload { + public: + typedef boost::shared_ptr<Replace> ref; + Replace(const std::string& id = std::string()) : replaceID_(id) {} + const std::string& getID() const { + return replaceID_; + } + void setID(const std::string& id) { + replaceID_ = id; + } + private: + std::string replaceID_; + }; } diff --git a/Swiften/Elements/ResourceBind.h b/Swiften/Elements/ResourceBind.h index 01d7e8b..fd6d4c7 100644 --- a/Swiften/Elements/ResourceBind.h +++ b/Swiften/Elements/ResourceBind.h @@ -8,33 +8,33 @@ #include <string> -#include <Swiften/Base/API.h> +#include <Swiften/Base/API.h> #include <Swiften/Elements/Payload.h> #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API ResourceBind : public Payload { - public: - ResourceBind() {} - - void setJID(const JID& jid) { - jid_ = jid; - } - - const JID& getJID() const { - return jid_; - } - - void setResource(const std::string& resource) { - resource_ = resource; - } - - const std::string& getResource() const { - return resource_; - } - - private: - JID jid_; - std::string resource_; - }; + class SWIFTEN_API ResourceBind : public Payload { + public: + ResourceBind() {} + + void setJID(const JID& jid) { + jid_ = jid; + } + + const JID& getJID() const { + return jid_; + } + + void setResource(const std::string& resource) { + resource_ = resource; + } + + const std::string& getResource() const { + return resource_; + } + + private: + JID jid_; + std::string resource_; + }; } diff --git a/Swiften/Elements/ResultSet.h b/Swiften/Elements/ResultSet.h index dc3692f..44995d1 100644 --- a/Swiften/Elements/ResultSet.h +++ b/Swiften/Elements/ResultSet.h @@ -12,43 +12,43 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API ResultSet : public Payload { - public: - virtual ~ResultSet(); + class SWIFTEN_API ResultSet : public Payload { + public: + virtual ~ResultSet(); - void setMaxItems(const boost::optional<int>& maxItems) { maxItems_ = maxItems; } - const boost::optional<int>& getMaxItems() const { return maxItems_; } + void setMaxItems(const boost::optional<int>& maxItems) { maxItems_ = maxItems; } + const boost::optional<int>& getMaxItems() const { return maxItems_; } - void setCount(const boost::optional<int>& count) { count_ = count; } - const boost::optional<int>& getCount() const { return count_; } + void setCount(const boost::optional<int>& count) { count_ = count; } + const boost::optional<int>& getCount() const { return count_; } - void setIndex(const boost::optional<int>& index) { index_ = index; } - const boost::optional<int>& getIndex() const { return index_; } + void setIndex(const boost::optional<int>& index) { index_ = index; } + const boost::optional<int>& getIndex() const { return index_; } - void setFirstIDIndex(const boost::optional<int>& firstIndex) { firstIndex_ = firstIndex; } - const boost::optional<int>& getFirstIDIndex() const { return firstIndex_; } + void setFirstIDIndex(const boost::optional<int>& firstIndex) { firstIndex_ = firstIndex; } + const boost::optional<int>& getFirstIDIndex() const { return firstIndex_; } - void setFirstID(const boost::optional<std::string>& firstID) { firstID_ = firstID; } - const boost::optional<std::string>& getFirstID() const { return firstID_; } + void setFirstID(const boost::optional<std::string>& firstID) { firstID_ = firstID; } + const boost::optional<std::string>& getFirstID() const { return firstID_; } - void setLastID(const boost::optional<std::string>& lastID) { lastID_ = lastID; } - const boost::optional<std::string>& getLastID() const { return lastID_; } + void setLastID(const boost::optional<std::string>& lastID) { lastID_ = lastID; } + const boost::optional<std::string>& getLastID() const { return lastID_; } - void setBefore(const boost::optional<std::string>& before) { before_ = before; } - const boost::optional<std::string>& getBefore() const { return before_; } + void setBefore(const boost::optional<std::string>& before) { before_ = before; } + const boost::optional<std::string>& getBefore() const { return before_; } - void setAfter(const boost::optional<std::string>& after) { after_ = after; } - const boost::optional<std::string>& getAfter() const { return after_; } + void setAfter(const boost::optional<std::string>& after) { after_ = after; } + const boost::optional<std::string>& getAfter() const { return after_; } - private: - boost::optional<int> maxItems_; - boost::optional<int> count_; - boost::optional<int> index_; - boost::optional<int> firstIndex_; - boost::optional<std::string> firstID_; - boost::optional<std::string> lastID_; - boost::optional<std::string> before_; - boost::optional<std::string> after_; - }; + private: + boost::optional<int> maxItems_; + boost::optional<int> count_; + boost::optional<int> index_; + boost::optional<int> firstIndex_; + boost::optional<std::string> firstID_; + boost::optional<std::string> lastID_; + boost::optional<std::string> before_; + boost::optional<std::string> after_; + }; } diff --git a/Swiften/Elements/RosterItemExchangePayload.h b/Swiften/Elements/RosterItemExchangePayload.h index b1d9fe2..5090aff 100644 --- a/Swiften/Elements/RosterItemExchangePayload.h +++ b/Swiften/Elements/RosterItemExchangePayload.h @@ -22,73 +22,73 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API RosterItemExchangePayload : public Payload { - public: - typedef boost::shared_ptr<RosterItemExchangePayload> ref; + class SWIFTEN_API RosterItemExchangePayload : public Payload { + public: + typedef boost::shared_ptr<RosterItemExchangePayload> ref; - class SWIFTEN_API Item { - public: - enum Action { Add, Modify, Delete }; + class SWIFTEN_API Item { + public: + enum Action { Add, Modify, Delete }; - Item(Action action = Add); + Item(Action action = Add); - Action getAction() const { - return action; - } + Action getAction() const { + return action; + } - void setAction(Action action) { - this->action = action; - } + void setAction(Action action) { + this->action = action; + } - const JID& getJID() const { - return jid; - } + const JID& getJID() const { + return jid; + } - void setJID(const JID& jid) { - this->jid = jid; - } + void setJID(const JID& jid) { + this->jid = jid; + } - const std::string& getName() const { - return name; - } + const std::string& getName() const { + return name; + } - void setName(const std::string& name) { - this->name = name; - } + void setName(const std::string& name) { + this->name = name; + } - const std::vector<std::string>& getGroups() const { - return groups; - } + const std::vector<std::string>& getGroups() const { + return groups; + } - void setGroups(const std::vector<std::string> &groups) { - this->groups = groups; - } + void setGroups(const std::vector<std::string> &groups) { + this->groups = groups; + } - void addGroup(const std::string& group) { - groups.push_back(group); - } + void addGroup(const std::string& group) { + groups.push_back(group); + } - private: - Action action; - JID jid; - std::string name; - std::vector<std::string> groups; - }; + private: + Action action; + JID jid; + std::string name; + std::vector<std::string> groups; + }; - typedef std::vector<RosterItemExchangePayload::Item> RosterItemExchangePayloadItems; + typedef std::vector<RosterItemExchangePayload::Item> RosterItemExchangePayloadItems; - public: - RosterItemExchangePayload(); + public: + RosterItemExchangePayload(); - void addItem(const RosterItemExchangePayload::Item& item) { - items_.push_back(item); - } + void addItem(const RosterItemExchangePayload::Item& item) { + items_.push_back(item); + } - const RosterItemExchangePayloadItems& getItems() const { - return items_; - } + const RosterItemExchangePayloadItems& getItems() const { + return items_; + } - private: - RosterItemExchangePayloadItems items_; - }; + private: + RosterItemExchangePayloadItems items_; + }; } diff --git a/Swiften/Elements/RosterItemPayload.h b/Swiften/Elements/RosterItemPayload.h index 6fb6ebe..ea19fa5 100644 --- a/Swiften/Elements/RosterItemPayload.h +++ b/Swiften/Elements/RosterItemPayload.h @@ -13,40 +13,40 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API RosterItemPayload { - public: - enum Subscription { None, To, From, Both, Remove }; - - RosterItemPayload() : subscription_(None), ask_(false) {} - RosterItemPayload(const JID& jid, const std::string& name, Subscription subscription, const std::vector<std::string>& groups = std::vector<std::string>()) : jid_(jid), name_(name), subscription_(subscription), groups_(groups), ask_(false) { } - - void setJID(const JID& jid) { jid_ = jid; } - const JID& getJID() const { return jid_; } - - void setName(const std::string& name) { name_ = name; } - const std::string& getName() const { return name_; } - - void setSubscription(Subscription subscription) { subscription_ = subscription; } - const Subscription& getSubscription() const { return subscription_; } - - void addGroup(const std::string& group) { groups_.push_back(group); } - void setGroups(const std::vector<std::string>& groups) { groups_ = groups; } - const std::vector<std::string>& getGroups() const { return groups_; } - - void setSubscriptionRequested() { ask_ = true; } - bool getSubscriptionRequested() const { return ask_; } - - const std::string& getUnknownContent() const { return unknownContent_; } - void addUnknownContent(const std::string& c) { - unknownContent_ += c; - } - - private: - JID jid_; - std::string name_; - Subscription subscription_; - std::vector<std::string> groups_; - bool ask_; - std::string unknownContent_; - }; + class SWIFTEN_API RosterItemPayload { + public: + enum Subscription { None, To, From, Both, Remove }; + + RosterItemPayload() : subscription_(None), ask_(false) {} + RosterItemPayload(const JID& jid, const std::string& name, Subscription subscription, const std::vector<std::string>& groups = std::vector<std::string>()) : jid_(jid), name_(name), subscription_(subscription), groups_(groups), ask_(false) { } + + void setJID(const JID& jid) { jid_ = jid; } + const JID& getJID() const { return jid_; } + + void setName(const std::string& name) { name_ = name; } + const std::string& getName() const { return name_; } + + void setSubscription(Subscription subscription) { subscription_ = subscription; } + const Subscription& getSubscription() const { return subscription_; } + + void addGroup(const std::string& group) { groups_.push_back(group); } + void setGroups(const std::vector<std::string>& groups) { groups_ = groups; } + const std::vector<std::string>& getGroups() const { return groups_; } + + void setSubscriptionRequested() { ask_ = true; } + bool getSubscriptionRequested() const { return ask_; } + + const std::string& getUnknownContent() const { return unknownContent_; } + void addUnknownContent(const std::string& c) { + unknownContent_ += c; + } + + private: + JID jid_; + std::string name_; + Subscription subscription_; + std::vector<std::string> groups_; + bool ask_; + std::string unknownContent_; + }; } diff --git a/Swiften/Elements/RosterPayload.cpp b/Swiften/Elements/RosterPayload.cpp index d9bdc9a..b4be7d1 100644 --- a/Swiften/Elements/RosterPayload.cpp +++ b/Swiften/Elements/RosterPayload.cpp @@ -11,14 +11,14 @@ namespace Swift { boost::optional<RosterItemPayload> RosterPayload::getItem(const JID& jid) const { - foreach(const RosterItemPayload& item, items_) { - // FIXME: MSVC rejects this. Find out why. - //if (item.getJID() == jid) { - if (item.getJID().equals(jid, JID::WithResource)) { - return boost::optional<RosterItemPayload>(item); - } - } - return boost::optional<RosterItemPayload>(); + foreach(const RosterItemPayload& item, items_) { + // FIXME: MSVC rejects this. Find out why. + //if (item.getJID() == jid) { + if (item.getJID().equals(jid, JID::WithResource)) { + return boost::optional<RosterItemPayload>(item); + } + } + return boost::optional<RosterItemPayload>(); } } diff --git a/Swiften/Elements/RosterPayload.h b/Swiften/Elements/RosterPayload.h index e205ce9..35e81cd 100644 --- a/Swiften/Elements/RosterPayload.h +++ b/Swiften/Elements/RosterPayload.h @@ -16,34 +16,34 @@ #include <Swiften/Elements/RosterItemPayload.h> namespace Swift { - class SWIFTEN_API RosterPayload : public Payload { - public: - typedef boost::shared_ptr<RosterPayload> ref; - typedef std::vector<RosterItemPayload> RosterItemPayloads; + class SWIFTEN_API RosterPayload : public Payload { + public: + typedef boost::shared_ptr<RosterPayload> ref; + typedef std::vector<RosterItemPayload> RosterItemPayloads; - public: - RosterPayload() {} + public: + RosterPayload() {} - boost::optional<RosterItemPayload> getItem(const JID& jid) const; + boost::optional<RosterItemPayload> getItem(const JID& jid) const; - void addItem(const RosterItemPayload& item) { - items_.push_back(item); - } + void addItem(const RosterItemPayload& item) { + items_.push_back(item); + } - const RosterItemPayloads& getItems() const { - return items_; - } + const RosterItemPayloads& getItems() const { + return items_; + } - const boost::optional<std::string>& getVersion() const { - return version_; - } + const boost::optional<std::string>& getVersion() const { + return version_; + } - void setVersion(const std::string& version) { - version_ = version; - } + void setVersion(const std::string& version) { + version_ = version; + } - private: - RosterItemPayloads items_; - boost::optional<std::string> version_; - }; + private: + RosterItemPayloads items_; + boost::optional<std::string> version_; + }; } diff --git a/Swiften/Elements/S5BProxyRequest.h b/Swiften/Elements/S5BProxyRequest.h index 2732f18..cbc7d5b 100644 --- a/Swiften/Elements/S5BProxyRequest.h +++ b/Swiften/Elements/S5BProxyRequest.h @@ -25,45 +25,45 @@ namespace Swift { class SWIFTEN_API S5BProxyRequest : public Payload { public: - typedef boost::shared_ptr<S5BProxyRequest> ref; + typedef boost::shared_ptr<S5BProxyRequest> ref; public: - struct StreamHost { - std::string host; - int port; - JID jid; - }; + struct StreamHost { + std::string host; + int port; + JID jid; + }; public: - const boost::optional<StreamHost>& getStreamHost() const { - return streamHost; - } + const boost::optional<StreamHost>& getStreamHost() const { + return streamHost; + } - void setStreamHost(const StreamHost& streamHost) { - this->streamHost = boost::optional<StreamHost>(streamHost); - } + void setStreamHost(const StreamHost& streamHost) { + this->streamHost = boost::optional<StreamHost>(streamHost); + } - const std::string& getSID() const { - return sid; - } + const std::string& getSID() const { + return sid; + } - void setSID(const std::string& sid) { - this->sid = sid; - } + void setSID(const std::string& sid) { + this->sid = sid; + } - const boost::optional<JID>& getActivate() const { - return activate; - } + const boost::optional<JID>& getActivate() const { + return activate; + } - void setActivate(const JID& activate) { - this->activate = activate; - } + void setActivate(const JID& activate) { + this->activate = activate; + } private: - boost::optional<StreamHost> streamHost; + boost::optional<StreamHost> streamHost; - std::string sid; - boost::optional<JID> activate; + std::string sid; + boost::optional<JID> activate; }; } diff --git a/Swiften/Elements/SearchPayload.h b/Swiften/Elements/SearchPayload.h index 2ca6888..6784291 100644 --- a/Swiften/Elements/SearchPayload.h +++ b/Swiften/Elements/SearchPayload.h @@ -16,81 +16,81 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - /** - * XEP-0055 search payload. - */ - class SWIFTEN_API SearchPayload : public Payload { - public: - typedef boost::shared_ptr<SearchPayload> ref; - - struct Item { - std::string first; - std::string last; - std::string nick; - std::string email; - JID jid; - }; - - SearchPayload() {} - - Form::ref getForm() const { return form; } - void setForm(Form::ref f) { form = f; } - - const boost::optional<std::string>& getInstructions() const { - return instructions; - } - - const boost::optional<std::string>& getNick() const { - return nick; - } - - const boost::optional<std::string>& getFirst() const { - return first; - } - - const boost::optional<std::string>& getLast() const { - return last; - } - - const boost::optional<std::string>& getEMail() const { - return email; - } - - void setInstructions(const std::string& v) { - this->instructions = v; - } - - void setNick(const std::string& v) { - this->nick = v; - } - - void setFirst(const std::string& v) { - this->first = v; - } - - void setLast(const std::string& v) { - this->last = v; - } - - void setEMail(const std::string& v) { - this->email = v; - } - - const std::vector<Item>& getItems() const { - return items; - } - - void addItem(const Item& item) { - items.push_back(item); - } - - private: - Form::ref form; - boost::optional<std::string> instructions; - boost::optional<std::string> nick; - boost::optional<std::string> first; - boost::optional<std::string> last; - boost::optional<std::string> email; - std::vector<Item> items; - }; + /** + * XEP-0055 search payload. + */ + class SWIFTEN_API SearchPayload : public Payload { + public: + typedef boost::shared_ptr<SearchPayload> ref; + + struct Item { + std::string first; + std::string last; + std::string nick; + std::string email; + JID jid; + }; + + SearchPayload() {} + + Form::ref getForm() const { return form; } + void setForm(Form::ref f) { form = f; } + + const boost::optional<std::string>& getInstructions() const { + return instructions; + } + + const boost::optional<std::string>& getNick() const { + return nick; + } + + const boost::optional<std::string>& getFirst() const { + return first; + } + + const boost::optional<std::string>& getLast() const { + return last; + } + + const boost::optional<std::string>& getEMail() const { + return email; + } + + void setInstructions(const std::string& v) { + this->instructions = v; + } + + void setNick(const std::string& v) { + this->nick = v; + } + + void setFirst(const std::string& v) { + this->first = v; + } + + void setLast(const std::string& v) { + this->last = v; + } + + void setEMail(const std::string& v) { + this->email = v; + } + + const std::vector<Item>& getItems() const { + return items; + } + + void addItem(const Item& item) { + items.push_back(item); + } + + private: + Form::ref form; + boost::optional<std::string> instructions; + boost::optional<std::string> nick; + boost::optional<std::string> first; + boost::optional<std::string> last; + boost::optional<std::string> email; + std::vector<Item> items; + }; } diff --git a/Swiften/Elements/SecurityLabel.h b/Swiften/Elements/SecurityLabel.h index b018620..748c65e 100644 --- a/Swiften/Elements/SecurityLabel.h +++ b/Swiften/Elements/SecurityLabel.h @@ -14,63 +14,63 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API SecurityLabel : public Payload { - public: - - SecurityLabel(); - - virtual ~SecurityLabel(); - - const std::vector< std::string >& getEquivalentLabels() const { - return equivalentLabels; - } - - void setEquivalentLabels(const std::vector< std::string >& value) { - this->equivalentLabels = value ; - } - - void addEquivalentLabel(const std::string& value) { - this->equivalentLabels.push_back(value); - } - - const std::string& getForegroundColor() const { - return foregroundColor; - } - - void setForegroundColor(const std::string& value) { - this->foregroundColor = value ; - } - - const std::string& getDisplayMarking() const { - return displayMarking; - } - - void setDisplayMarking(const std::string& value) { - this->displayMarking = value ; - } - - const std::string& getBackgroundColor() const { - return backgroundColor; - } - - void setBackgroundColor(const std::string& value) { - this->backgroundColor = value ; - } - - const std::string& getLabel() const { - return label; - } - - void setLabel(const std::string& value) { - this->label = value ; - } - - - private: - std::vector< std::string > equivalentLabels; - std::string foregroundColor; - std::string displayMarking; - std::string backgroundColor; - std::string label; - }; + class SWIFTEN_API SecurityLabel : public Payload { + public: + + SecurityLabel(); + + virtual ~SecurityLabel(); + + const std::vector< std::string >& getEquivalentLabels() const { + return equivalentLabels; + } + + void setEquivalentLabels(const std::vector< std::string >& value) { + this->equivalentLabels = value ; + } + + void addEquivalentLabel(const std::string& value) { + this->equivalentLabels.push_back(value); + } + + const std::string& getForegroundColor() const { + return foregroundColor; + } + + void setForegroundColor(const std::string& value) { + this->foregroundColor = value ; + } + + const std::string& getDisplayMarking() const { + return displayMarking; + } + + void setDisplayMarking(const std::string& value) { + this->displayMarking = value ; + } + + const std::string& getBackgroundColor() const { + return backgroundColor; + } + + void setBackgroundColor(const std::string& value) { + this->backgroundColor = value ; + } + + const std::string& getLabel() const { + return label; + } + + void setLabel(const std::string& value) { + this->label = value ; + } + + + private: + std::vector< std::string > equivalentLabels; + std::string foregroundColor; + std::string displayMarking; + std::string backgroundColor; + std::string label; + }; } diff --git a/Swiften/Elements/SecurityLabelsCatalog.h b/Swiften/Elements/SecurityLabelsCatalog.h index cdcfca3..8e6db64 100644 --- a/Swiften/Elements/SecurityLabelsCatalog.h +++ b/Swiften/Elements/SecurityLabelsCatalog.h @@ -17,74 +17,74 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API SecurityLabelsCatalog : public Payload { - public: - typedef boost::shared_ptr<SecurityLabelsCatalog> ref; - class Item { - public: - Item() : default_(false) {} - boost::shared_ptr<SecurityLabel> getLabel() const { - return label_; - } - - void setLabel(boost::shared_ptr<SecurityLabel> label) { - label_ = label; - } - - const std::string& getSelector() const { return selector_; } - - void setSelector(const std::string& selector) { - selector_ = selector; - } - - bool getIsDefault() const { return default_; } - - void setIsDefault(bool isDefault) { - default_ = isDefault; - } - private: - boost::shared_ptr<SecurityLabel> label_; - std::string selector_; - bool default_; - }; - SecurityLabelsCatalog(const JID& to = JID()) : to_(to) {} - - const std::vector<Item>& getItems() const { - return items_; - } - - void addItem(const Item& item) { - items_.push_back(item); - } - - const JID& getTo() const { - return to_; - } - - void setTo(const JID& to) { - to_ = to; - } - - const std::string& getName() const { - return name_; - } - - void setName(const std::string& name) { - name_ = name; - } - - const std::string& getDescription() const { - return description_; - } - - void setDescription(const std::string& description) { - description_ = description; - } - - private: - JID to_; - std::string name_; - std::string description_; - std::vector<Item> items_; - }; + class SWIFTEN_API SecurityLabelsCatalog : public Payload { + public: + typedef boost::shared_ptr<SecurityLabelsCatalog> ref; + class Item { + public: + Item() : default_(false) {} + boost::shared_ptr<SecurityLabel> getLabel() const { + return label_; + } + + void setLabel(boost::shared_ptr<SecurityLabel> label) { + label_ = label; + } + + const std::string& getSelector() const { return selector_; } + + void setSelector(const std::string& selector) { + selector_ = selector; + } + + bool getIsDefault() const { return default_; } + + void setIsDefault(bool isDefault) { + default_ = isDefault; + } + private: + boost::shared_ptr<SecurityLabel> label_; + std::string selector_; + bool default_; + }; + SecurityLabelsCatalog(const JID& to = JID()) : to_(to) {} + + const std::vector<Item>& getItems() const { + return items_; + } + + void addItem(const Item& item) { + items_.push_back(item); + } + + const JID& getTo() const { + return to_; + } + + void setTo(const JID& to) { + to_ = to; + } + + const std::string& getName() const { + return name_; + } + + void setName(const std::string& name) { + name_ = name; + } + + const std::string& getDescription() const { + return description_; + } + + void setDescription(const std::string& description) { + description_ = description; + } + + private: + JID to_; + std::string name_; + std::string description_; + std::vector<Item> items_; + }; } diff --git a/Swiften/Elements/SoftwareVersion.h b/Swiften/Elements/SoftwareVersion.h index f906223..57318b9 100644 --- a/Swiften/Elements/SoftwareVersion.h +++ b/Swiften/Elements/SoftwareVersion.h @@ -14,43 +14,43 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API SoftwareVersion : public Payload { - public: - typedef boost::shared_ptr<SoftwareVersion> ref; - - SoftwareVersion( - const std::string& name = "", - const std::string& version = "", - const std::string& os = "") : - name_(name), version_(version), os_(os) {} - - const std::string& getName() const { - return name_; - } - - void setName(const std::string& name) { - name_ = name; - } - - const std::string& getVersion() const { - return version_; - } - - void setVersion(const std::string& version) { - version_ = version; - } - - const std::string& getOS() const { - return os_; - } - - void setOS(const std::string& os) { - os_ = os; - } - - private: - std::string name_; - std::string version_; - std::string os_; - }; + class SWIFTEN_API SoftwareVersion : public Payload { + public: + typedef boost::shared_ptr<SoftwareVersion> ref; + + SoftwareVersion( + const std::string& name = "", + const std::string& version = "", + const std::string& os = "") : + name_(name), version_(version), os_(os) {} + + const std::string& getName() const { + return name_; + } + + void setName(const std::string& name) { + name_ = name; + } + + const std::string& getVersion() const { + return version_; + } + + void setVersion(const std::string& version) { + version_ = version; + } + + const std::string& getOS() const { + return os_; + } + + void setOS(const std::string& os) { + os_ = os; + } + + private: + std::string name_; + std::string version_; + std::string os_; + }; } diff --git a/Swiften/Elements/Stanza.cpp b/Swiften/Elements/Stanza.cpp index f385e1c..617be4e 100644 --- a/Swiften/Elements/Stanza.cpp +++ b/Swiften/Elements/Stanza.cpp @@ -17,53 +17,53 @@ namespace Swift { Stanza::Stanza() { } - + Stanza::~Stanza() { - payloads_.clear(); + payloads_.clear(); } void Stanza::updatePayload(boost::shared_ptr<Payload> payload) { - foreach (boost::shared_ptr<Payload>& i, payloads_) { - if (typeid(*i.get()) == typeid(*payload.get())) { - i = payload; - return; - } - } - addPayload(payload); + foreach (boost::shared_ptr<Payload>& i, payloads_) { + if (typeid(*i.get()) == typeid(*payload.get())) { + i = payload; + return; + } + } + addPayload(payload); } static bool sameType(boost::shared_ptr<Payload> a, boost::shared_ptr<Payload> b) { - return typeid(*a.get()) == typeid(*b.get()); + return typeid(*a.get()) == typeid(*b.get()); } void Stanza::removePayloadOfSameType(boost::shared_ptr<Payload> payload) { - payloads_.erase(std::remove_if(payloads_.begin(), payloads_.end(), - boost::bind<bool>(&sameType, payload, _1)), - payloads_.end()); + payloads_.erase(std::remove_if(payloads_.begin(), payloads_.end(), + boost::bind<bool>(&sameType, payload, _1)), + payloads_.end()); } boost::shared_ptr<Payload> Stanza::getPayloadOfSameType(boost::shared_ptr<Payload> payload) const { - foreach (const boost::shared_ptr<Payload>& i, payloads_) { - if (typeid(*i.get()) == typeid(*payload.get())) { - return i; - } - } - return boost::shared_ptr<Payload>(); + foreach (const boost::shared_ptr<Payload>& i, payloads_) { + if (typeid(*i.get()) == typeid(*payload.get())) { + return i; + } + } + return boost::shared_ptr<Payload>(); } boost::optional<boost::posix_time::ptime> Stanza::getTimestamp() const { - boost::shared_ptr<Delay> delay = getPayload<Delay>(); - return delay ? delay->getStamp() : boost::optional<boost::posix_time::ptime>(); + boost::shared_ptr<Delay> delay = getPayload<Delay>(); + return delay ? delay->getStamp() : boost::optional<boost::posix_time::ptime>(); } boost::optional<boost::posix_time::ptime> Stanza::getTimestampFrom(const JID& jid) const { - std::vector< boost::shared_ptr<Delay> > delays = getPayloads<Delay>(); - for (size_t i = 0; i < delays.size(); ++i) { - if (delays[i]->getFrom() == jid) { - return delays[i]->getStamp(); - } - } - return getTimestamp(); + std::vector< boost::shared_ptr<Delay> > delays = getPayloads<Delay>(); + for (size_t i = 0; i < delays.size(); ++i) { + if (delays[i]->getFrom() == jid) { + return delays[i]->getStamp(); + } + } + return getTimestamp(); } diff --git a/Swiften/Elements/Stanza.h b/Swiften/Elements/Stanza.h index 8da6280..765aca8 100644 --- a/Swiften/Elements/Stanza.h +++ b/Swiften/Elements/Stanza.h @@ -18,79 +18,79 @@ #include <Swiften/JID/JID.h> namespace Swift { - class Payload; - - class SWIFTEN_API Stanza : public ToplevelElement { - public: - typedef boost::shared_ptr<Stanza> ref; - - protected: - Stanza(); - - public: - virtual ~Stanza(); - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Stanza) - - template<typename T> - boost::shared_ptr<T> getPayload() const { - for (size_t i = 0; i < payloads_.size(); ++i) { - boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i])); - if (result) { - return result; - } - } - return boost::shared_ptr<T>(); - } - - template<typename T> - std::vector< boost::shared_ptr<T> > getPayloads() const { - std::vector< boost::shared_ptr<T> > results; - for (size_t i = 0; i < payloads_.size(); ++i) { - boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i])); - if (result) { - results.push_back(result); - } - } - return results; - } - - - const std::vector< boost::shared_ptr<Payload> >& getPayloads() const { - return payloads_; - } - - void addPayload(boost::shared_ptr<Payload> payload) { - payloads_.push_back(payload); - } - - template<typename InputIterator> - void addPayloads(InputIterator begin, InputIterator end) { - payloads_.insert(payloads_.end(), begin, end); - } - - void updatePayload(boost::shared_ptr<Payload> payload); - - void removePayloadOfSameType(boost::shared_ptr<Payload>); - boost::shared_ptr<Payload> getPayloadOfSameType(boost::shared_ptr<Payload>) const; - - const JID& getFrom() const { return from_; } - void setFrom(const JID& from) { from_ = from; } - - const JID& getTo() const { return to_; } - void setTo(const JID& to) { to_ = to; } - - const std::string& getID() const { return id_; } - void setID(const std::string& id) { id_ = id; } - - boost::optional<boost::posix_time::ptime> getTimestamp() const; - - // Falls back to any timestamp if no specific timestamp for the given JID is found. - boost::optional<boost::posix_time::ptime> getTimestampFrom(const JID& jid) const; - - private: - std::string id_; - JID from_; - JID to_; - std::vector< boost::shared_ptr<Payload> > payloads_; - }; + class Payload; + + class SWIFTEN_API Stanza : public ToplevelElement { + public: + typedef boost::shared_ptr<Stanza> ref; + + protected: + Stanza(); + + public: + virtual ~Stanza(); + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Stanza) + + template<typename T> + boost::shared_ptr<T> getPayload() const { + for (size_t i = 0; i < payloads_.size(); ++i) { + boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i])); + if (result) { + return result; + } + } + return boost::shared_ptr<T>(); + } + + template<typename T> + std::vector< boost::shared_ptr<T> > getPayloads() const { + std::vector< boost::shared_ptr<T> > results; + for (size_t i = 0; i < payloads_.size(); ++i) { + boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i])); + if (result) { + results.push_back(result); + } + } + return results; + } + + + const std::vector< boost::shared_ptr<Payload> >& getPayloads() const { + return payloads_; + } + + void addPayload(boost::shared_ptr<Payload> payload) { + payloads_.push_back(payload); + } + + template<typename InputIterator> + void addPayloads(InputIterator begin, InputIterator end) { + payloads_.insert(payloads_.end(), begin, end); + } + + void updatePayload(boost::shared_ptr<Payload> payload); + + void removePayloadOfSameType(boost::shared_ptr<Payload>); + boost::shared_ptr<Payload> getPayloadOfSameType(boost::shared_ptr<Payload>) const; + + const JID& getFrom() const { return from_; } + void setFrom(const JID& from) { from_ = from; } + + const JID& getTo() const { return to_; } + void setTo(const JID& to) { to_ = to; } + + const std::string& getID() const { return id_; } + void setID(const std::string& id) { id_ = id; } + + boost::optional<boost::posix_time::ptime> getTimestamp() const; + + // Falls back to any timestamp if no specific timestamp for the given JID is found. + boost::optional<boost::posix_time::ptime> getTimestampFrom(const JID& jid) const; + + private: + std::string id_; + JID from_; + JID to_; + std::vector< boost::shared_ptr<Payload> > payloads_; + }; } diff --git a/Swiften/Elements/StanzaAck.cpp b/Swiften/Elements/StanzaAck.cpp index 2dbff41..bd0b78d 100644 --- a/Swiften/Elements/StanzaAck.cpp +++ b/Swiften/Elements/StanzaAck.cpp @@ -14,6 +14,6 @@ StanzaAck::~StanzaAck() { } void StanzaAck::setHandledStanzasCount(int i) { - handledStanzasCount = boost::numeric_cast<unsigned int>(i); - valid = true; + handledStanzasCount = boost::numeric_cast<unsigned int>(i); + valid = true; } diff --git a/Swiften/Elements/StanzaAck.h b/Swiften/Elements/StanzaAck.h index d976802..45680c0 100644 --- a/Swiften/Elements/StanzaAck.h +++ b/Swiften/Elements/StanzaAck.h @@ -12,26 +12,26 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StanzaAck : public ToplevelElement { - public: - typedef boost::shared_ptr<StanzaAck> ref; + class SWIFTEN_API StanzaAck : public ToplevelElement { + public: + typedef boost::shared_ptr<StanzaAck> ref; - StanzaAck() : valid(false), handledStanzasCount(0) {} - StanzaAck(unsigned int handledStanzasCount) : valid(true), handledStanzasCount(handledStanzasCount) {} - virtual ~StanzaAck(); + StanzaAck() : valid(false), handledStanzasCount(0) {} + StanzaAck(unsigned int handledStanzasCount) : valid(true), handledStanzasCount(handledStanzasCount) {} + virtual ~StanzaAck(); - unsigned int getHandledStanzasCount() const { - return handledStanzasCount; - } + unsigned int getHandledStanzasCount() const { + return handledStanzasCount; + } - void setHandledStanzasCount(int i); + void setHandledStanzasCount(int i); - bool isValid() const { - return valid; - } + bool isValid() const { + return valid; + } - private: - bool valid; - unsigned int handledStanzasCount; - }; + private: + bool valid; + unsigned int handledStanzasCount; + }; } diff --git a/Swiften/Elements/StanzaAckRequest.h b/Swiften/Elements/StanzaAckRequest.h index dc3bf32..e9b95b5 100644 --- a/Swiften/Elements/StanzaAckRequest.h +++ b/Swiften/Elements/StanzaAckRequest.h @@ -10,6 +10,6 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StanzaAckRequest : public ToplevelElement { - }; + class SWIFTEN_API StanzaAckRequest : public ToplevelElement { + }; } diff --git a/Swiften/Elements/StartSession.h b/Swiften/Elements/StartSession.h index ea934da..a40865e 100644 --- a/Swiften/Elements/StartSession.h +++ b/Swiften/Elements/StartSession.h @@ -12,8 +12,8 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API StartSession : public Payload { - public: - StartSession() {} - }; + class SWIFTEN_API StartSession : public Payload { + public: + StartSession() {} + }; } diff --git a/Swiften/Elements/StartTLSFailure.h b/Swiften/Elements/StartTLSFailure.h index 1477962..5867e3f 100644 --- a/Swiften/Elements/StartTLSFailure.h +++ b/Swiften/Elements/StartTLSFailure.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StartTLSFailure : public ToplevelElement { - public: - StartTLSFailure() {} - }; + class SWIFTEN_API StartTLSFailure : public ToplevelElement { + public: + StartTLSFailure() {} + }; } diff --git a/Swiften/Elements/StartTLSRequest.h b/Swiften/Elements/StartTLSRequest.h index 648eef7..f47a21d 100644 --- a/Swiften/Elements/StartTLSRequest.h +++ b/Swiften/Elements/StartTLSRequest.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StartTLSRequest : public ToplevelElement { - public: - StartTLSRequest() {} - }; + class SWIFTEN_API StartTLSRequest : public ToplevelElement { + public: + StartTLSRequest() {} + }; } diff --git a/Swiften/Elements/Status.h b/Swiften/Elements/Status.h index 58e17d6..2fd2eff 100644 --- a/Swiften/Elements/Status.h +++ b/Swiften/Elements/Status.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Status : public Payload { - public: - Status(const std::string& text = "") : text_(text) { - } + class SWIFTEN_API Status : public Payload { + public: + Status(const std::string& text = "") : text_(text) { + } - void setText(const std::string& text) { - text_ = text; - } + void setText(const std::string& text) { + text_ = text; + } - const std::string& getText() const { - return text_; - } + const std::string& getText() const { + return text_; + } - private: - std::string text_; - }; + private: + std::string text_; + }; } diff --git a/Swiften/Elements/StatusShow.h b/Swiften/Elements/StatusShow.h index 84be286..b339fa1 100644 --- a/Swiften/Elements/StatusShow.h +++ b/Swiften/Elements/StatusShow.h @@ -12,38 +12,38 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API StatusShow : public Payload { - public: - enum Type { Online, Away, FFC, XA, DND, None }; - - StatusShow(const Type& type = Online); - - void setType(const Type& type) { - type_ = type; - } - - const Type& getType() const { - return type_; - } - - /** - * Can be used for rough ordering of Types. - * Greater magnitude = more available. - */ - static int typeToAvailabilityOrdering(Type type) { - switch (type) { - case Online: return 4; - case FFC: return 5; - case Away: return 2; - case XA: return 1; - case DND: return 3; - case None: return 0; - } - assert(false); - return 0; - } - - private: - Type type_; - }; + class SWIFTEN_API StatusShow : public Payload { + public: + enum Type { Online, Away, FFC, XA, DND, None }; + + StatusShow(const Type& type = Online); + + void setType(const Type& type) { + type_ = type; + } + + const Type& getType() const { + return type_; + } + + /** + * Can be used for rough ordering of Types. + * Greater magnitude = more available. + */ + static int typeToAvailabilityOrdering(Type type) { + switch (type) { + case Online: return 4; + case FFC: return 5; + case Away: return 2; + case XA: return 1; + case DND: return 3; + case None: return 0; + } + assert(false); + return 0; + } + + private: + Type type_; + }; } diff --git a/Swiften/Elements/Storage.h b/Swiften/Elements/Storage.h index 7de303d..87cfb39 100644 --- a/Swiften/Elements/Storage.h +++ b/Swiften/Elements/Storage.h @@ -17,51 +17,51 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API Storage : public Payload { - public: - struct Room { - Room() : autoJoin(false) {} - - std::string name; - JID jid; - bool autoJoin; - std::string nick; - boost::optional<std::string> password; - }; - - struct URL { - URL() {} - - std::string name; - std::string url; - }; - - Storage() { - } - - - void clearRooms() { - rooms.clear(); - } - - const std::vector<Room>& getRooms() const { - return rooms; - } - - void addRoom(const Room& room) { - rooms.push_back(room); - } - - const std::vector<URL>& getURLs() const { - return urls; - } - - void addURL(const URL& url) { - urls.push_back(url); - } - - private: - std::vector<Room> rooms; - std::vector<URL> urls; - }; + class SWIFTEN_API Storage : public Payload { + public: + struct Room { + Room() : autoJoin(false) {} + + std::string name; + JID jid; + bool autoJoin; + std::string nick; + boost::optional<std::string> password; + }; + + struct URL { + URL() {} + + std::string name; + std::string url; + }; + + Storage() { + } + + + void clearRooms() { + rooms.clear(); + } + + const std::vector<Room>& getRooms() const { + return rooms; + } + + void addRoom(const Room& room) { + rooms.push_back(room); + } + + const std::vector<URL>& getURLs() const { + return urls; + } + + void addURL(const URL& url) { + urls.push_back(url); + } + + private: + std::vector<Room> rooms; + std::vector<URL> urls; + }; } diff --git a/Swiften/Elements/StreamError.h b/Swiften/Elements/StreamError.h index e7e7309..ce57134 100644 --- a/Swiften/Elements/StreamError.h +++ b/Swiften/Elements/StreamError.h @@ -14,58 +14,58 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StreamError : public ToplevelElement { - public: - typedef boost::shared_ptr<StreamError> ref; + class SWIFTEN_API StreamError : public ToplevelElement { + public: + typedef boost::shared_ptr<StreamError> ref; - enum Type { - BadFormat, - BadNamespacePrefix, - Conflict, - ConnectionTimeout, - HostGone, - HostUnknown, - ImproperAddressing, - InternalServerError, - InvalidFrom, - InvalidID, - InvalidNamespace, - InvalidXML, - NotAuthorized, - NotWellFormed, - PolicyViolation, - RemoteConnectionFailed, - Reset, - ResourceConstraint, - RestrictedXML, - SeeOtherHost, - SystemShutdown, - UndefinedCondition, - UnsupportedEncoding, - UnsupportedStanzaType, - UnsupportedVersion - }; + enum Type { + BadFormat, + BadNamespacePrefix, + Conflict, + ConnectionTimeout, + HostGone, + HostUnknown, + ImproperAddressing, + InternalServerError, + InvalidFrom, + InvalidID, + InvalidNamespace, + InvalidXML, + NotAuthorized, + NotWellFormed, + PolicyViolation, + RemoteConnectionFailed, + Reset, + ResourceConstraint, + RestrictedXML, + SeeOtherHost, + SystemShutdown, + UndefinedCondition, + UnsupportedEncoding, + UnsupportedStanzaType, + UnsupportedVersion + }; - StreamError(Type type = UndefinedCondition, const std::string& text = std::string()) : type_(type), text_(text) { } + StreamError(Type type = UndefinedCondition, const std::string& text = std::string()) : type_(type), text_(text) { } - Type getType() const { - return type_; - } + Type getType() const { + return type_; + } - void setType(Type type) { - type_ = type; - } + void setType(Type type) { + type_ = type; + } - void setText(const std::string& text) { - text_ = text; - } + void setText(const std::string& text) { + text_ = text; + } - const std::string& getText() const { - return text_; - } + const std::string& getText() const { + return text_; + } - private: - Type type_; - std::string text_; - }; + private: + Type type_; + std::string text_; + }; } diff --git a/Swiften/Elements/StreamFeatures.cpp b/Swiften/Elements/StreamFeatures.cpp index 0acc417..77bafac 100644 --- a/Swiften/Elements/StreamFeatures.cpp +++ b/Swiften/Elements/StreamFeatures.cpp @@ -11,11 +11,11 @@ namespace Swift { bool StreamFeatures::hasCompressionMethod(const std::string& mechanism) const { - return std::find(compressionMethods_.begin(), compressionMethods_.end(), mechanism) != compressionMethods_.end(); + return std::find(compressionMethods_.begin(), compressionMethods_.end(), mechanism) != compressionMethods_.end(); } bool StreamFeatures::hasAuthenticationMechanism(const std::string& mechanism) const { - return std::find(authenticationMechanisms_.begin(), authenticationMechanisms_.end(), mechanism) != authenticationMechanisms_.end(); + return std::find(authenticationMechanisms_.begin(), authenticationMechanisms_.end(), mechanism) != authenticationMechanisms_.end(); } } diff --git a/Swiften/Elements/StreamFeatures.h b/Swiften/Elements/StreamFeatures.h index 7a9d936..1d07a16 100644 --- a/Swiften/Elements/StreamFeatures.h +++ b/Swiften/Elements/StreamFeatures.h @@ -16,92 +16,92 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StreamFeatures : public ToplevelElement { - public: - typedef boost::shared_ptr<StreamFeatures> ref; - - StreamFeatures() : hasStartTLS_(false), hasResourceBind_(false), hasSession_(false), hasStreamManagement_(false), hasRosterVersioning_(false) {} - - void setHasStartTLS() { - hasStartTLS_ = true; - } - - bool hasStartTLS() const { - return hasStartTLS_; - } - - void setHasSession() { - hasSession_ = true; - } - - bool hasSession() const { - return hasSession_; - } - - void setHasResourceBind() { - hasResourceBind_ = true; - } - - bool hasResourceBind() const { - return hasResourceBind_; - } - - const std::vector<std::string>& getCompressionMethods() const { - return compressionMethods_; - } - - void addCompressionMethod(const std::string& mechanism) { - compressionMethods_.push_back(mechanism); - } - - bool hasCompressionMethod(const std::string& mechanism) const; - - const std::vector<std::string>& getAuthenticationMechanisms() const { - return authenticationMechanisms_; - } - - void addAuthenticationMechanism(const std::string& mechanism) { - authenticationMechanisms_.push_back(mechanism); - } - - bool hasAuthenticationMechanism(const std::string& mechanism) const; - - bool hasAuthenticationMechanisms() const { - return !authenticationMechanisms_.empty(); - } - - const boost::optional<std::string> getAuthenticationHostname() const { - return authenticationHostname_; - } - - void setAuthenticationHostname(const boost::optional<std::string> authenticationHostname) { - authenticationHostname_ = authenticationHostname; - } - - bool hasStreamManagement() const { - return hasStreamManagement_; - } - - void setHasStreamManagement() { - hasStreamManagement_ = true; - } - - bool hasRosterVersioning() const { - return hasRosterVersioning_; - } - - void setHasRosterVersioning() { - hasRosterVersioning_ = true; - } - - private: - bool hasStartTLS_; - std::vector<std::string> compressionMethods_; - std::vector<std::string> authenticationMechanisms_; - bool hasResourceBind_; - bool hasSession_; - bool hasStreamManagement_; - bool hasRosterVersioning_; - boost::optional<std::string> authenticationHostname_; - }; + class SWIFTEN_API StreamFeatures : public ToplevelElement { + public: + typedef boost::shared_ptr<StreamFeatures> ref; + + StreamFeatures() : hasStartTLS_(false), hasResourceBind_(false), hasSession_(false), hasStreamManagement_(false), hasRosterVersioning_(false) {} + + void setHasStartTLS() { + hasStartTLS_ = true; + } + + bool hasStartTLS() const { + return hasStartTLS_; + } + + void setHasSession() { + hasSession_ = true; + } + + bool hasSession() const { + return hasSession_; + } + + void setHasResourceBind() { + hasResourceBind_ = true; + } + + bool hasResourceBind() const { + return hasResourceBind_; + } + + const std::vector<std::string>& getCompressionMethods() const { + return compressionMethods_; + } + + void addCompressionMethod(const std::string& mechanism) { + compressionMethods_.push_back(mechanism); + } + + bool hasCompressionMethod(const std::string& mechanism) const; + + const std::vector<std::string>& getAuthenticationMechanisms() const { + return authenticationMechanisms_; + } + + void addAuthenticationMechanism(const std::string& mechanism) { + authenticationMechanisms_.push_back(mechanism); + } + + bool hasAuthenticationMechanism(const std::string& mechanism) const; + + bool hasAuthenticationMechanisms() const { + return !authenticationMechanisms_.empty(); + } + + const boost::optional<std::string> getAuthenticationHostname() const { + return authenticationHostname_; + } + + void setAuthenticationHostname(const boost::optional<std::string> authenticationHostname) { + authenticationHostname_ = authenticationHostname; + } + + bool hasStreamManagement() const { + return hasStreamManagement_; + } + + void setHasStreamManagement() { + hasStreamManagement_ = true; + } + + bool hasRosterVersioning() const { + return hasRosterVersioning_; + } + + void setHasRosterVersioning() { + hasRosterVersioning_ = true; + } + + private: + bool hasStartTLS_; + std::vector<std::string> compressionMethods_; + std::vector<std::string> authenticationMechanisms_; + bool hasResourceBind_; + bool hasSession_; + bool hasStreamManagement_; + bool hasRosterVersioning_; + boost::optional<std::string> authenticationHostname_; + }; } diff --git a/Swiften/Elements/StreamInitiation.h b/Swiften/Elements/StreamInitiation.h index b56fadc..cd37974 100644 --- a/Swiften/Elements/StreamInitiation.h +++ b/Swiften/Elements/StreamInitiation.h @@ -17,57 +17,57 @@ #include <Swiften/Elements/StreamInitiationFileInfo.h> namespace Swift { - class SWIFTEN_API StreamInitiation : public Payload { - public: - typedef boost::shared_ptr<StreamInitiation> ref; - - StreamInitiation() : isFileTransfer(true) {} - - const std::string& getID() const { - return id; - } - - void setID(const std::string& id) { - this->id = id; - } - - const boost::optional<StreamInitiationFileInfo>& getFileInfo() const { - return fileInfo; - } - - void setFileInfo(const StreamInitiationFileInfo& info) { - fileInfo = info; - } - - const std::vector<std::string>& getProvidedMethods() const { - return providedMethods; - } - - void addProvidedMethod(const std::string& method) { - providedMethods.push_back(method); - } - - void setRequestedMethod(const std::string& method) { - requestedMethod = method; - } - - const std::string& getRequestedMethod() const { - return requestedMethod; - } - - bool getIsFileTransfer() const { - return isFileTransfer; - } - - void setIsFileTransfer(bool b) { - isFileTransfer = b; - } - - private: - bool isFileTransfer; - std::string id; - boost::optional<StreamInitiationFileInfo> fileInfo; - std::vector<std::string> providedMethods; - std::string requestedMethod; - }; + class SWIFTEN_API StreamInitiation : public Payload { + public: + typedef boost::shared_ptr<StreamInitiation> ref; + + StreamInitiation() : isFileTransfer(true) {} + + const std::string& getID() const { + return id; + } + + void setID(const std::string& id) { + this->id = id; + } + + const boost::optional<StreamInitiationFileInfo>& getFileInfo() const { + return fileInfo; + } + + void setFileInfo(const StreamInitiationFileInfo& info) { + fileInfo = info; + } + + const std::vector<std::string>& getProvidedMethods() const { + return providedMethods; + } + + void addProvidedMethod(const std::string& method) { + providedMethods.push_back(method); + } + + void setRequestedMethod(const std::string& method) { + requestedMethod = method; + } + + const std::string& getRequestedMethod() const { + return requestedMethod; + } + + bool getIsFileTransfer() const { + return isFileTransfer; + } + + void setIsFileTransfer(bool b) { + isFileTransfer = b; + } + + private: + bool isFileTransfer; + std::string id; + boost::optional<StreamInitiationFileInfo> fileInfo; + std::vector<std::string> providedMethods; + std::string requestedMethod; + }; } diff --git a/Swiften/Elements/StreamInitiationFileInfo.h b/Swiften/Elements/StreamInitiationFileInfo.h index 9c40d60..11bd4c5 100644 --- a/Swiften/Elements/StreamInitiationFileInfo.h +++ b/Swiften/Elements/StreamInitiationFileInfo.h @@ -18,87 +18,87 @@ namespace Swift { class SWIFTEN_API StreamInitiationFileInfo : public Payload { public: - typedef boost::shared_ptr<StreamInitiationFileInfo> ref; - + typedef boost::shared_ptr<StreamInitiationFileInfo> ref; + public: - StreamInitiationFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0, - const std::string& hash = "", const boost::posix_time::ptime &date = boost::posix_time::ptime(), const std::string& algo="md5") : - name(name), description(description), size(size), hash(hash), date(date), algo(algo), supportsRangeRequests(false), rangeOffset(0) {} - - void setName(const std::string& name) { - this->name = name;; - } - - const std::string& getName() const { - return this->name; - } - - void setDescription(const std::string& description) { - this->description = description; - } - - const std::string& getDescription() const { - return this->description; - } - - void setSize(const unsigned long long size) { - this->size = size; - } - - unsigned long long getSize() const { - return this->size; - } - - void setHash(const std::string& hash) { - this->hash = hash; - } - - const std::string& getHash() const { - return this->hash; - } - - void setDate(const boost::posix_time::ptime& date) { - this->date = date; - } - - const boost::posix_time::ptime& getDate() const { - return this->date; - } - - void setAlgo(const std::string& algo) { - this->algo = algo; - } - - const std::string& getAlgo() const { - return this->algo; - } - - void setSupportsRangeRequests(const bool supportsIt) { - supportsRangeRequests = supportsIt; - } - - bool getSupportsRangeRequests() const { - return supportsRangeRequests; - } - - void setRangeOffset(unsigned long long offset) { - supportsRangeRequests = true; - rangeOffset = offset; - } - - unsigned long long getRangeOffset() const { - return rangeOffset; - } + StreamInitiationFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0, + const std::string& hash = "", const boost::posix_time::ptime &date = boost::posix_time::ptime(), const std::string& algo="md5") : + name(name), description(description), size(size), hash(hash), date(date), algo(algo), supportsRangeRequests(false), rangeOffset(0) {} + + void setName(const std::string& name) { + this->name = name;; + } + + const std::string& getName() const { + return this->name; + } + + void setDescription(const std::string& description) { + this->description = description; + } + + const std::string& getDescription() const { + return this->description; + } + + void setSize(const unsigned long long size) { + this->size = size; + } + + unsigned long long getSize() const { + return this->size; + } + + void setHash(const std::string& hash) { + this->hash = hash; + } + + const std::string& getHash() const { + return this->hash; + } + + void setDate(const boost::posix_time::ptime& date) { + this->date = date; + } + + const boost::posix_time::ptime& getDate() const { + return this->date; + } + + void setAlgo(const std::string& algo) { + this->algo = algo; + } + + const std::string& getAlgo() const { + return this->algo; + } + + void setSupportsRangeRequests(const bool supportsIt) { + supportsRangeRequests = supportsIt; + } + + bool getSupportsRangeRequests() const { + return supportsRangeRequests; + } + + void setRangeOffset(unsigned long long offset) { + supportsRangeRequests = true; + rangeOffset = offset; + } + + unsigned long long getRangeOffset() const { + return rangeOffset; + } private: - std::string name; - std::string description; - unsigned long long size; - std::string hash; - boost::posix_time::ptime date; - std::string algo; - bool supportsRangeRequests; - unsigned long long rangeOffset; + std::string name; + std::string description; + unsigned long long size; + std::string hash; + boost::posix_time::ptime date; + std::string algo; + bool supportsRangeRequests; + unsigned long long rangeOffset; }; } diff --git a/Swiften/Elements/StreamManagementEnabled.h b/Swiften/Elements/StreamManagementEnabled.h index eaae189..7cb640d 100644 --- a/Swiften/Elements/StreamManagementEnabled.h +++ b/Swiften/Elements/StreamManagementEnabled.h @@ -12,29 +12,29 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StreamManagementEnabled : public ToplevelElement { - public: - StreamManagementEnabled(); - ~StreamManagementEnabled(); - - void setResumeSupported() { - resumeSupported = true; - } - - bool getResumeSupported() const { - return resumeSupported; - } - - void setResumeID(const std::string& id) { - resumeID = id; - } - - const std::string& getResumeID() const { - return resumeID; - } - - private: - bool resumeSupported; - std::string resumeID; - }; + class SWIFTEN_API StreamManagementEnabled : public ToplevelElement { + public: + StreamManagementEnabled(); + ~StreamManagementEnabled(); + + void setResumeSupported() { + resumeSupported = true; + } + + bool getResumeSupported() const { + return resumeSupported; + } + + void setResumeID(const std::string& id) { + resumeID = id; + } + + const std::string& getResumeID() const { + return resumeID; + } + + private: + bool resumeSupported; + std::string resumeID; + }; } diff --git a/Swiften/Elements/StreamManagementFailed.h b/Swiften/Elements/StreamManagementFailed.h index 70781d7..062d9bd 100644 --- a/Swiften/Elements/StreamManagementFailed.h +++ b/Swiften/Elements/StreamManagementFailed.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StreamManagementFailed : public ToplevelElement { - public: - StreamManagementFailed() {} - }; + class SWIFTEN_API StreamManagementFailed : public ToplevelElement { + public: + StreamManagementFailed() {} + }; } diff --git a/Swiften/Elements/StreamResume.h b/Swiften/Elements/StreamResume.h index 6876ead..0ded077 100644 --- a/Swiften/Elements/StreamResume.h +++ b/Swiften/Elements/StreamResume.h @@ -14,29 +14,29 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StreamResume : public ToplevelElement { - public: - StreamResume(); - ~StreamResume(); - - void setResumeID(const std::string& id) { - resumeID = id; - } - - const std::string& getResumeID() const { - return resumeID; - } - - const boost::optional<unsigned int> getHandledStanzasCount() const { - return handledStanzasCount; - } - - void setHandledStanzasCount(unsigned int i) { - handledStanzasCount = i; - } - - private: - std::string resumeID; - boost::optional<unsigned int> handledStanzasCount; - }; + class SWIFTEN_API StreamResume : public ToplevelElement { + public: + StreamResume(); + ~StreamResume(); + + void setResumeID(const std::string& id) { + resumeID = id; + } + + const std::string& getResumeID() const { + return resumeID; + } + + const boost::optional<unsigned int> getHandledStanzasCount() const { + return handledStanzasCount; + } + + void setHandledStanzasCount(unsigned int i) { + handledStanzasCount = i; + } + + private: + std::string resumeID; + boost::optional<unsigned int> handledStanzasCount; + }; } diff --git a/Swiften/Elements/StreamResumed.h b/Swiften/Elements/StreamResumed.h index 88779cc..e1c80d9 100644 --- a/Swiften/Elements/StreamResumed.h +++ b/Swiften/Elements/StreamResumed.h @@ -14,29 +14,29 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API StreamResumed : public ToplevelElement { - public: - StreamResumed(); - ~StreamResumed(); - - void setResumeID(const std::string& id) { - resumeID = id; - } - - const std::string& getResumeID() const { - return resumeID; - } - - const boost::optional<unsigned int> getHandledStanzasCount() const { - return handledStanzasCount; - } - - void setHandledStanzasCount(unsigned int i) { - handledStanzasCount = i; - } - - private: - std::string resumeID; - boost::optional<unsigned int> handledStanzasCount; - }; + class SWIFTEN_API StreamResumed : public ToplevelElement { + public: + StreamResumed(); + ~StreamResumed(); + + void setResumeID(const std::string& id) { + resumeID = id; + } + + const std::string& getResumeID() const { + return resumeID; + } + + const boost::optional<unsigned int> getHandledStanzasCount() const { + return handledStanzasCount; + } + + void setHandledStanzasCount(unsigned int i) { + handledStanzasCount = i; + } + + private: + std::string resumeID; + boost::optional<unsigned int> handledStanzasCount; + }; } diff --git a/Swiften/Elements/StreamType.h b/Swiften/Elements/StreamType.h index 0cd4133..d6b820e 100644 --- a/Swiften/Elements/StreamType.h +++ b/Swiften/Elements/StreamType.h @@ -7,9 +7,9 @@ #pragma once namespace Swift { - enum StreamType { - ClientStreamType, - ServerStreamType, - ComponentStreamType - }; + enum StreamType { + ClientStreamType, + ServerStreamType, + ComponentStreamType + }; } diff --git a/Swiften/Elements/Subject.h b/Swiften/Elements/Subject.h index 982ce3b..4f9444a 100644 --- a/Swiften/Elements/Subject.h +++ b/Swiften/Elements/Subject.h @@ -12,20 +12,20 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Subject : public Payload { - public: - Subject(const std::string& text = "") : text_(text) { - } + class SWIFTEN_API Subject : public Payload { + public: + Subject(const std::string& text = "") : text_(text) { + } - void setText(const std::string& text) { - text_ = text; - } + void setText(const std::string& text) { + text_ = text; + } - const std::string& getText() const { - return text_; - } + const std::string& getText() const { + return text_; + } - private: - std::string text_; - }; + private: + std::string text_; + }; } diff --git a/Swiften/Elements/TLSProceed.h b/Swiften/Elements/TLSProceed.h index 4e05511..3cd5360 100644 --- a/Swiften/Elements/TLSProceed.h +++ b/Swiften/Elements/TLSProceed.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API TLSProceed : public ToplevelElement { - public: - TLSProceed() {} - }; + class SWIFTEN_API TLSProceed : public ToplevelElement { + public: + TLSProceed() {} + }; } diff --git a/Swiften/Elements/Thread.cpp b/Swiften/Elements/Thread.cpp index dfd9029..5ac371b 100644 --- a/Swiften/Elements/Thread.cpp +++ b/Swiften/Elements/Thread.cpp @@ -8,27 +8,27 @@ namespace Swift { - Thread::Thread(const std::string& text, const std::string& parent) : text_(text), parent_(parent) { - - } + Thread::Thread(const std::string& text, const std::string& parent) : text_(text), parent_(parent) { - Thread::~Thread() { + } - } + Thread::~Thread() { - void Thread::setText(const std::string& text) { - text_ = text; - } + } - const std::string& Thread::getText() const { - return text_; - } + void Thread::setText(const std::string& text) { + text_ = text; + } - void Thread::setParent(const std::string& parent) { - parent_ = parent; - } + const std::string& Thread::getText() const { + return text_; + } - const std::string& Thread::getParent() const { - return parent_; - } + void Thread::setParent(const std::string& parent) { + parent_ = parent; + } + + const std::string& Thread::getParent() const { + return parent_; + } } diff --git a/Swiften/Elements/Thread.h b/Swiften/Elements/Thread.h index 8207851..e736e7f 100644 --- a/Swiften/Elements/Thread.h +++ b/Swiften/Elements/Thread.h @@ -12,17 +12,17 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Thread : public Payload { - public: - Thread(const std::string& text = "", const std::string& parent = ""); - virtual ~Thread(); - void setText(const std::string& text); - const std::string& getText() const; - void setParent(const std::string& parent); - const std::string& getParent() const; + class SWIFTEN_API Thread : public Payload { + public: + Thread(const std::string& text = "", const std::string& parent = ""); + virtual ~Thread(); + void setText(const std::string& text); + const std::string& getText() const; + void setParent(const std::string& parent); + const std::string& getParent() const; - private: - std::string text_; - std::string parent_; - }; + private: + std::string text_; + std::string parent_; + }; } diff --git a/Swiften/Elements/ToplevelElement.h b/Swiften/Elements/ToplevelElement.h index a9cc09c..55e055a 100644 --- a/Swiften/Elements/ToplevelElement.h +++ b/Swiften/Elements/ToplevelElement.h @@ -10,10 +10,10 @@ #include <Swiften/Elements/Element.h> namespace Swift { - class SWIFTEN_API ToplevelElement : public Element { - public: - ToplevelElement() {} - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(ToplevelElement) - virtual ~ToplevelElement(); - }; + class SWIFTEN_API ToplevelElement : public Element { + public: + ToplevelElement() {} + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(ToplevelElement) + virtual ~ToplevelElement(); + }; } diff --git a/Swiften/Elements/UnblockPayload.h b/Swiften/Elements/UnblockPayload.h index ddb42d8..7d6574d 100644 --- a/Swiften/Elements/UnblockPayload.h +++ b/Swiften/Elements/UnblockPayload.h @@ -13,20 +13,20 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API UnblockPayload : public Payload { - public: - UnblockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) { - } + class SWIFTEN_API UnblockPayload : public Payload { + public: + UnblockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) { + } - void addItem(const JID& item) { - items.push_back(item); - } + void addItem(const JID& item) { + items.push_back(item); + } - const std::vector<JID>& getItems() const { - return items; - } + const std::vector<JID>& getItems() const { + return items; + } - private: - std::vector<JID> items; - }; + private: + std::vector<JID> items; + }; } diff --git a/Swiften/Elements/UnitTest/FormTest.cpp b/Swiften/Elements/UnitTest/FormTest.cpp index ea680f9..9255fa8 100644 --- a/Swiften/Elements/UnitTest/FormTest.cpp +++ b/Swiften/Elements/UnitTest/FormTest.cpp @@ -15,44 +15,44 @@ using namespace Swift; class FormTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(FormTest); - CPPUNIT_TEST(testGetFormType); - CPPUNIT_TEST(testGetFormType_InvalidFormType); - CPPUNIT_TEST(testGetFormType_NoFormType); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(FormTest); + CPPUNIT_TEST(testGetFormType); + CPPUNIT_TEST(testGetFormType_InvalidFormType); + CPPUNIT_TEST(testGetFormType_NoFormType); + CPPUNIT_TEST_SUITE_END(); - public: - void testGetFormType() { - Form form; + public: + void testGetFormType() { + Form form; - form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo")); + form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo")); - FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:bot"); - field->setName("FORM_TYPE"); - form.addField(field); + FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:bot"); + field->setName("FORM_TYPE"); + form.addField(field); - form.addField(boost::make_shared<FormField>(FormField::FixedType, "Bar")); + form.addField(boost::make_shared<FormField>(FormField::FixedType, "Bar")); - CPPUNIT_ASSERT_EQUAL(std::string("jabber:bot"), form.getFormType()); - } + CPPUNIT_ASSERT_EQUAL(std::string("jabber:bot"), form.getFormType()); + } - void testGetFormType_InvalidFormType() { - Form form; + void testGetFormType_InvalidFormType() { + Form form; - FormField::ref field = boost::make_shared<FormField>(FormField::FixedType, "jabber:bot"); - field->setName("FORM_TYPE"); - form.addField(field); + FormField::ref field = boost::make_shared<FormField>(FormField::FixedType, "jabber:bot"); + field->setName("FORM_TYPE"); + form.addField(field); - CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType()); - } + CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType()); + } - void testGetFormType_NoFormType() { - Form form; + void testGetFormType_NoFormType() { + Form form; - form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo")); + form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo")); - CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType()); - } + CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType()); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(FormTest); diff --git a/Swiften/Elements/UnitTest/IQTest.cpp b/Swiften/Elements/UnitTest/IQTest.cpp index 7cc78c6..a88e2d6 100644 --- a/Swiften/Elements/UnitTest/IQTest.cpp +++ b/Swiften/Elements/UnitTest/IQTest.cpp @@ -16,43 +16,43 @@ using namespace Swift; class IQTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(IQTest); - CPPUNIT_TEST(testCreateResult); - CPPUNIT_TEST(testCreateResult_WithoutPayload); - CPPUNIT_TEST(testCreateError); - CPPUNIT_TEST_SUITE_END(); - - public: - IQTest() {} - - void testCreateResult() { - boost::shared_ptr<Payload> payload(new SoftwareVersion("myclient")); - boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid", payload)); - - CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo()); - CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID()); - CPPUNIT_ASSERT(iq->getPayload<SoftwareVersion>()); - CPPUNIT_ASSERT(payload == iq->getPayload<SoftwareVersion>()); - } - - void testCreateResult_WithoutPayload() { - boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid")); - - CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo()); - CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID()); - CPPUNIT_ASSERT(!iq->getPayload<SoftwareVersion>()); - } - - void testCreateError() { - boost::shared_ptr<IQ> iq(IQ::createError(JID("foo@bar/fum"), "myid", ErrorPayload::BadRequest, ErrorPayload::Modify)); - - CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo()); - CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID()); - boost::shared_ptr<ErrorPayload> error(iq->getPayload<ErrorPayload>()); - CPPUNIT_ASSERT(error); - CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, error->getCondition()); - CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, error->getType()); - } + CPPUNIT_TEST_SUITE(IQTest); + CPPUNIT_TEST(testCreateResult); + CPPUNIT_TEST(testCreateResult_WithoutPayload); + CPPUNIT_TEST(testCreateError); + CPPUNIT_TEST_SUITE_END(); + + public: + IQTest() {} + + void testCreateResult() { + boost::shared_ptr<Payload> payload(new SoftwareVersion("myclient")); + boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid", payload)); + + CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo()); + CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID()); + CPPUNIT_ASSERT(iq->getPayload<SoftwareVersion>()); + CPPUNIT_ASSERT(payload == iq->getPayload<SoftwareVersion>()); + } + + void testCreateResult_WithoutPayload() { + boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid")); + + CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo()); + CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID()); + CPPUNIT_ASSERT(!iq->getPayload<SoftwareVersion>()); + } + + void testCreateError() { + boost::shared_ptr<IQ> iq(IQ::createError(JID("foo@bar/fum"), "myid", ErrorPayload::BadRequest, ErrorPayload::Modify)); + + CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo()); + CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID()); + boost::shared_ptr<ErrorPayload> error(iq->getPayload<ErrorPayload>()); + CPPUNIT_ASSERT(error); + CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, error->getCondition()); + CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, error->getType()); + } }; diff --git a/Swiften/Elements/UnitTest/StanzaTest.cpp b/Swiften/Elements/UnitTest/StanzaTest.cpp index de5779c..13c038c 100644 --- a/Swiften/Elements/UnitTest/StanzaTest.cpp +++ b/Swiften/Elements/UnitTest/StanzaTest.cpp @@ -19,214 +19,214 @@ using namespace Swift; class StanzaTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(StanzaTest); - CPPUNIT_TEST(testConstructor_Copy); - CPPUNIT_TEST(testGetPayload); - CPPUNIT_TEST(testGetPayloads); - CPPUNIT_TEST(testGetPayload_NoSuchPayload); - CPPUNIT_TEST(testDestructor); - CPPUNIT_TEST(testDestructor_Copy); - CPPUNIT_TEST(testUpdatePayload_ExistingPayload); - CPPUNIT_TEST(testUpdatePayload_NewPayload); - CPPUNIT_TEST(testGetPayloadOfSameType); - CPPUNIT_TEST(testGetPayloadOfSameType_NoSuchPayload); - CPPUNIT_TEST(testGetTimestamp); - CPPUNIT_TEST(testGetTimestamp_TimestampWithFrom); - CPPUNIT_TEST(testGetTimestamp_NoDelay); - CPPUNIT_TEST(testGetTimestampFrom); - CPPUNIT_TEST(testGetTimestampFrom_Fallsback); - CPPUNIT_TEST_SUITE_END(); - - public: - class MyPayload1 : public Payload { - public: - MyPayload1() {} - }; - - class MyPayload2 : public Payload { - public: - MyPayload2(const std::string& s = "") : text_(s) {} - - std::string text_; - }; - - class MyPayload3 : public Payload { - public: - MyPayload3() {} - }; - - class DestroyingPayload : public Payload { - public: - DestroyingPayload(bool* alive) : alive_(alive) { - } - - ~DestroyingPayload() { - (*alive_) = false; - } - - private: - bool* alive_; - }; - - void testConstructor_Copy() { - Message m; - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(boost::make_shared<MyPayload2>()); - Message copy(m); - - CPPUNIT_ASSERT(copy.getPayload<MyPayload1>()); - CPPUNIT_ASSERT(copy.getPayload<MyPayload2>()); - } - - void testDestructor() { - bool payloadAlive = true; - { - Message m; - m.addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive)); - } - - CPPUNIT_ASSERT(!payloadAlive); - } - - void testDestructor_Copy() { - bool payloadAlive = true; - Message* m1 = new Message(); - m1->addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive)); - Message* m2 = new Message(*m1); - - delete m1; - CPPUNIT_ASSERT(payloadAlive); - - delete m2; - CPPUNIT_ASSERT(!payloadAlive); - } - - void testGetPayload() { - Message m; - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(boost::make_shared<MyPayload2>()); - m.addPayload(boost::make_shared<MyPayload3>()); - - boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); - CPPUNIT_ASSERT(p); - } - - void testGetPayload_NoSuchPayload() { - Message m; - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(boost::make_shared<MyPayload3>()); - - boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); - CPPUNIT_ASSERT(!p); - } - - void testGetPayloads() { - Message m; - boost::shared_ptr<MyPayload2> payload1(new MyPayload2()); - boost::shared_ptr<MyPayload2> payload2(new MyPayload2()); - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(payload1); - m.addPayload(boost::make_shared<MyPayload3>()); - m.addPayload(payload2); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), m.getPayloads<MyPayload2>().size()); - CPPUNIT_ASSERT_EQUAL(payload1, m.getPayloads<MyPayload2>()[0]); - CPPUNIT_ASSERT_EQUAL(payload2, m.getPayloads<MyPayload2>()[1]); - } - - - void testUpdatePayload_ExistingPayload() { - Message m; - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(boost::make_shared<MyPayload2>("foo")); - m.addPayload(boost::make_shared<MyPayload3>()); - - m.updatePayload(boost::make_shared<MyPayload2>("bar")); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size()); - boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_); - } - - void testUpdatePayload_NewPayload() { - Message m; - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(boost::make_shared<MyPayload3>()); - - m.updatePayload(boost::make_shared<MyPayload2>("bar")); - - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size()); - boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_); - } - - void testGetPayloadOfSameType() { - Message m; - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(boost::make_shared<MyPayload2>("foo")); - m.addPayload(boost::make_shared<MyPayload3>()); - - boost::shared_ptr<MyPayload2> payload(boost::dynamic_pointer_cast<MyPayload2>(m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar")))); - CPPUNIT_ASSERT(payload); - CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->text_); - } - - void testGetPayloadOfSameType_NoSuchPayload() { - Message m; - m.addPayload(boost::make_shared<MyPayload1>()); - m.addPayload(boost::make_shared<MyPayload3>()); - - CPPUNIT_ASSERT(!m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar"))); - } - - void testGetTimestamp() { - Message m; - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1))); - - boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp(); - - CPPUNIT_ASSERT(timestamp); - CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp)); - } - - void testGetTimestamp_TimestampWithFrom() { - Message m; - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo@bar.com"))); - - boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp(); - - CPPUNIT_ASSERT(timestamp); - CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp)); - } - - void testGetTimestamp_NoDelay() { - Message m; - CPPUNIT_ASSERT(!m.getTimestamp()); - } - - void testGetTimestampFrom() { - Message m; - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(0))); - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com"))); - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(2), JID("foo2@bar.com"))); - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com"))); - - boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com")); - - CPPUNIT_ASSERT(timestamp); - CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:02"), boost::posix_time::to_simple_string(*timestamp)); - } - - void testGetTimestampFrom_Fallsback() { - Message m; - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com"))); - m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com"))); - - boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com")); - - CPPUNIT_ASSERT(timestamp); - CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp)); - } + CPPUNIT_TEST_SUITE(StanzaTest); + CPPUNIT_TEST(testConstructor_Copy); + CPPUNIT_TEST(testGetPayload); + CPPUNIT_TEST(testGetPayloads); + CPPUNIT_TEST(testGetPayload_NoSuchPayload); + CPPUNIT_TEST(testDestructor); + CPPUNIT_TEST(testDestructor_Copy); + CPPUNIT_TEST(testUpdatePayload_ExistingPayload); + CPPUNIT_TEST(testUpdatePayload_NewPayload); + CPPUNIT_TEST(testGetPayloadOfSameType); + CPPUNIT_TEST(testGetPayloadOfSameType_NoSuchPayload); + CPPUNIT_TEST(testGetTimestamp); + CPPUNIT_TEST(testGetTimestamp_TimestampWithFrom); + CPPUNIT_TEST(testGetTimestamp_NoDelay); + CPPUNIT_TEST(testGetTimestampFrom); + CPPUNIT_TEST(testGetTimestampFrom_Fallsback); + CPPUNIT_TEST_SUITE_END(); + + public: + class MyPayload1 : public Payload { + public: + MyPayload1() {} + }; + + class MyPayload2 : public Payload { + public: + MyPayload2(const std::string& s = "") : text_(s) {} + + std::string text_; + }; + + class MyPayload3 : public Payload { + public: + MyPayload3() {} + }; + + class DestroyingPayload : public Payload { + public: + DestroyingPayload(bool* alive) : alive_(alive) { + } + + ~DestroyingPayload() { + (*alive_) = false; + } + + private: + bool* alive_; + }; + + void testConstructor_Copy() { + Message m; + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(boost::make_shared<MyPayload2>()); + Message copy(m); + + CPPUNIT_ASSERT(copy.getPayload<MyPayload1>()); + CPPUNIT_ASSERT(copy.getPayload<MyPayload2>()); + } + + void testDestructor() { + bool payloadAlive = true; + { + Message m; + m.addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive)); + } + + CPPUNIT_ASSERT(!payloadAlive); + } + + void testDestructor_Copy() { + bool payloadAlive = true; + Message* m1 = new Message(); + m1->addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive)); + Message* m2 = new Message(*m1); + + delete m1; + CPPUNIT_ASSERT(payloadAlive); + + delete m2; + CPPUNIT_ASSERT(!payloadAlive); + } + + void testGetPayload() { + Message m; + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(boost::make_shared<MyPayload2>()); + m.addPayload(boost::make_shared<MyPayload3>()); + + boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); + CPPUNIT_ASSERT(p); + } + + void testGetPayload_NoSuchPayload() { + Message m; + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(boost::make_shared<MyPayload3>()); + + boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); + CPPUNIT_ASSERT(!p); + } + + void testGetPayloads() { + Message m; + boost::shared_ptr<MyPayload2> payload1(new MyPayload2()); + boost::shared_ptr<MyPayload2> payload2(new MyPayload2()); + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(payload1); + m.addPayload(boost::make_shared<MyPayload3>()); + m.addPayload(payload2); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), m.getPayloads<MyPayload2>().size()); + CPPUNIT_ASSERT_EQUAL(payload1, m.getPayloads<MyPayload2>()[0]); + CPPUNIT_ASSERT_EQUAL(payload2, m.getPayloads<MyPayload2>()[1]); + } + + + void testUpdatePayload_ExistingPayload() { + Message m; + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(boost::make_shared<MyPayload2>("foo")); + m.addPayload(boost::make_shared<MyPayload3>()); + + m.updatePayload(boost::make_shared<MyPayload2>("bar")); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size()); + boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_); + } + + void testUpdatePayload_NewPayload() { + Message m; + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(boost::make_shared<MyPayload3>()); + + m.updatePayload(boost::make_shared<MyPayload2>("bar")); + + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size()); + boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_); + } + + void testGetPayloadOfSameType() { + Message m; + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(boost::make_shared<MyPayload2>("foo")); + m.addPayload(boost::make_shared<MyPayload3>()); + + boost::shared_ptr<MyPayload2> payload(boost::dynamic_pointer_cast<MyPayload2>(m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar")))); + CPPUNIT_ASSERT(payload); + CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->text_); + } + + void testGetPayloadOfSameType_NoSuchPayload() { + Message m; + m.addPayload(boost::make_shared<MyPayload1>()); + m.addPayload(boost::make_shared<MyPayload3>()); + + CPPUNIT_ASSERT(!m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar"))); + } + + void testGetTimestamp() { + Message m; + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1))); + + boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp(); + + CPPUNIT_ASSERT(timestamp); + CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp)); + } + + void testGetTimestamp_TimestampWithFrom() { + Message m; + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo@bar.com"))); + + boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp(); + + CPPUNIT_ASSERT(timestamp); + CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp)); + } + + void testGetTimestamp_NoDelay() { + Message m; + CPPUNIT_ASSERT(!m.getTimestamp()); + } + + void testGetTimestampFrom() { + Message m; + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(0))); + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com"))); + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(2), JID("foo2@bar.com"))); + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com"))); + + boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com")); + + CPPUNIT_ASSERT(timestamp); + CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:02"), boost::posix_time::to_simple_string(*timestamp)); + } + + void testGetTimestampFrom_Fallsback() { + Message m; + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com"))); + m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com"))); + + boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com")); + + CPPUNIT_ASSERT(timestamp); + CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp)); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(StanzaTest); diff --git a/Swiften/Elements/UnknownElement.h b/Swiften/Elements/UnknownElement.h index 1d71e6b..b6f8021 100644 --- a/Swiften/Elements/UnknownElement.h +++ b/Swiften/Elements/UnknownElement.h @@ -10,8 +10,8 @@ #include <Swiften/Elements/ToplevelElement.h> namespace Swift { - class SWIFTEN_API UnknownElement : public ToplevelElement { - public: - UnknownElement() {} - }; + class SWIFTEN_API UnknownElement : public ToplevelElement { + public: + UnknownElement() {} + }; } diff --git a/Swiften/Elements/UserLocation.h b/Swiften/Elements/UserLocation.h index 1a9dba3..7d07d6a 100644 --- a/Swiften/Elements/UserLocation.h +++ b/Swiften/Elements/UserLocation.h @@ -16,212 +16,212 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API UserLocation : public Payload { - public: - - UserLocation(); - - virtual ~UserLocation(); + class SWIFTEN_API UserLocation : public Payload { + public: - const boost::optional< std::string >& getArea() const { - return area; - } + UserLocation(); - void setArea(const boost::optional< std::string >& value) { - this->area = value ; - } + virtual ~UserLocation(); - const boost::optional< float >& getAltitude() const { - return altitude; - } + const boost::optional< std::string >& getArea() const { + return area; + } - void setAltitude(const boost::optional< float >& value) { - this->altitude = value ; - } + void setArea(const boost::optional< std::string >& value) { + this->area = value ; + } - const boost::optional< std::string >& getLocality() const { - return locality; - } + const boost::optional< float >& getAltitude() const { + return altitude; + } - void setLocality(const boost::optional< std::string >& value) { - this->locality = value ; - } + void setAltitude(const boost::optional< float >& value) { + this->altitude = value ; + } - const boost::optional< float >& getLatitude() const { - return latitude; - } + const boost::optional< std::string >& getLocality() const { + return locality; + } - void setLatitude(const boost::optional< float >& value) { - this->latitude = value ; - } + void setLocality(const boost::optional< std::string >& value) { + this->locality = value ; + } - const boost::optional< float >& getAccuracy() const { - return accuracy; - } + const boost::optional< float >& getLatitude() const { + return latitude; + } - void setAccuracy(const boost::optional< float >& value) { - this->accuracy = value ; - } + void setLatitude(const boost::optional< float >& value) { + this->latitude = value ; + } - const boost::optional< std::string >& getDescription() const { - return description; - } + const boost::optional< float >& getAccuracy() const { + return accuracy; + } - void setDescription(const boost::optional< std::string >& value) { - this->description = value ; - } + void setAccuracy(const boost::optional< float >& value) { + this->accuracy = value ; + } - const boost::optional< std::string >& getCountryCode() const { - return countryCode; - } + const boost::optional< std::string >& getDescription() const { + return description; + } - void setCountryCode(const boost::optional< std::string >& value) { - this->countryCode = value ; - } + void setDescription(const boost::optional< std::string >& value) { + this->description = value ; + } - const boost::optional< boost::posix_time::ptime >& getTimestamp() const { - return timestamp; - } + const boost::optional< std::string >& getCountryCode() const { + return countryCode; + } - void setTimestamp(const boost::optional< boost::posix_time::ptime >& value) { - this->timestamp = value ; - } + void setCountryCode(const boost::optional< std::string >& value) { + this->countryCode = value ; + } - const boost::optional< std::string >& getFloor() const { - return floor; - } + const boost::optional< boost::posix_time::ptime >& getTimestamp() const { + return timestamp; + } - void setFloor(const boost::optional< std::string >& value) { - this->floor = value ; - } + void setTimestamp(const boost::optional< boost::posix_time::ptime >& value) { + this->timestamp = value ; + } - const boost::optional< std::string >& getBuilding() const { - return building; - } + const boost::optional< std::string >& getFloor() const { + return floor; + } - void setBuilding(const boost::optional< std::string >& value) { - this->building = value ; - } + void setFloor(const boost::optional< std::string >& value) { + this->floor = value ; + } - const boost::optional< std::string >& getRoom() const { - return room; - } - - void setRoom(const boost::optional< std::string >& value) { - this->room = value ; - } - - const boost::optional< std::string >& getCountry() const { - return country; - } - - void setCountry(const boost::optional< std::string >& value) { - this->country = value ; - } - - const boost::optional< std::string >& getRegion() const { - return region; - } - - void setRegion(const boost::optional< std::string >& value) { - this->region = value ; - } - - const boost::optional< std::string >& getURI() const { - return uri; - } - - void setURI(const boost::optional< std::string >& value) { - this->uri = value ; - } - - const boost::optional< float >& getLongitude() const { - return longitude; - } - - void setLongitude(const boost::optional< float >& value) { - this->longitude = value ; - } - - const boost::optional< float >& getError() const { - return error; - } - - void setError(const boost::optional< float >& value) { - this->error = value ; - } - - const boost::optional< std::string >& getPostalCode() const { - return postalCode; - } - - void setPostalCode(const boost::optional< std::string >& value) { - this->postalCode = value ; - } - - const boost::optional< float >& getBearing() const { - return bearing; - } - - void setBearing(const boost::optional< float >& value) { - this->bearing = value ; - } - - const boost::optional< std::string >& getText() const { - return text; - } - - void setText(const boost::optional< std::string >& value) { - this->text = value ; - } - - const boost::optional< std::string >& getDatum() const { - return datum; - } - - void setDatum(const boost::optional< std::string >& value) { - this->datum = value ; - } - - const boost::optional< std::string >& getStreet() const { - return street; - } - - void setStreet(const boost::optional< std::string >& value) { - this->street = value ; - } - - const boost::optional< float >& getSpeed() const { - return speed; - } - - void setSpeed(const boost::optional< float >& value) { - this->speed = value ; - } - - - private: - boost::optional< std::string > area; - boost::optional< float > altitude; - boost::optional< std::string > locality; - boost::optional< float > latitude; - boost::optional< float > accuracy; - boost::optional< std::string > description; - boost::optional< std::string > countryCode; - boost::optional< boost::posix_time::ptime > timestamp; - boost::optional< std::string > floor; - boost::optional< std::string > building; - boost::optional< std::string > room; - boost::optional< std::string > country; - boost::optional< std::string > region; - boost::optional< std::string > uri; - boost::optional< float > longitude; - boost::optional< float > error; - boost::optional< std::string > postalCode; - boost::optional< float > bearing; - boost::optional< std::string > text; - boost::optional< std::string > datum; - boost::optional< std::string > street; - boost::optional< float > speed; - }; + const boost::optional< std::string >& getBuilding() const { + return building; + } + + void setBuilding(const boost::optional< std::string >& value) { + this->building = value ; + } + + const boost::optional< std::string >& getRoom() const { + return room; + } + + void setRoom(const boost::optional< std::string >& value) { + this->room = value ; + } + + const boost::optional< std::string >& getCountry() const { + return country; + } + + void setCountry(const boost::optional< std::string >& value) { + this->country = value ; + } + + const boost::optional< std::string >& getRegion() const { + return region; + } + + void setRegion(const boost::optional< std::string >& value) { + this->region = value ; + } + + const boost::optional< std::string >& getURI() const { + return uri; + } + + void setURI(const boost::optional< std::string >& value) { + this->uri = value ; + } + + const boost::optional< float >& getLongitude() const { + return longitude; + } + + void setLongitude(const boost::optional< float >& value) { + this->longitude = value ; + } + + const boost::optional< float >& getError() const { + return error; + } + + void setError(const boost::optional< float >& value) { + this->error = value ; + } + + const boost::optional< std::string >& getPostalCode() const { + return postalCode; + } + + void setPostalCode(const boost::optional< std::string >& value) { + this->postalCode = value ; + } + + const boost::optional< float >& getBearing() const { + return bearing; + } + + void setBearing(const boost::optional< float >& value) { + this->bearing = value ; + } + + const boost::optional< std::string >& getText() const { + return text; + } + + void setText(const boost::optional< std::string >& value) { + this->text = value ; + } + + const boost::optional< std::string >& getDatum() const { + return datum; + } + + void setDatum(const boost::optional< std::string >& value) { + this->datum = value ; + } + + const boost::optional< std::string >& getStreet() const { + return street; + } + + void setStreet(const boost::optional< std::string >& value) { + this->street = value ; + } + + const boost::optional< float >& getSpeed() const { + return speed; + } + + void setSpeed(const boost::optional< float >& value) { + this->speed = value ; + } + + + private: + boost::optional< std::string > area; + boost::optional< float > altitude; + boost::optional< std::string > locality; + boost::optional< float > latitude; + boost::optional< float > accuracy; + boost::optional< std::string > description; + boost::optional< std::string > countryCode; + boost::optional< boost::posix_time::ptime > timestamp; + boost::optional< std::string > floor; + boost::optional< std::string > building; + boost::optional< std::string > room; + boost::optional< std::string > country; + boost::optional< std::string > region; + boost::optional< std::string > uri; + boost::optional< float > longitude; + boost::optional< float > error; + boost::optional< std::string > postalCode; + boost::optional< float > bearing; + boost::optional< std::string > text; + boost::optional< std::string > datum; + boost::optional< std::string > street; + boost::optional< float > speed; + }; } diff --git a/Swiften/Elements/UserTune.h b/Swiften/Elements/UserTune.h index c500832..7def9b9 100644 --- a/Swiften/Elements/UserTune.h +++ b/Swiften/Elements/UserTune.h @@ -15,77 +15,77 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API UserTune : public Payload { - public: - - UserTune(); - - virtual ~UserTune(); - - const boost::optional< unsigned int >& getRating() const { - return rating; - } - - void setRating(const boost::optional< unsigned int >& value) { - this->rating = value ; - } - - const boost::optional< std::string >& getTitle() const { - return title; - } - - void setTitle(const boost::optional< std::string >& value) { - this->title = value ; - } - - const boost::optional< std::string >& getTrack() const { - return track; - } - - void setTrack(const boost::optional< std::string >& value) { - this->track = value ; - } - - const boost::optional< std::string >& getArtist() const { - return artist; - } - - void setArtist(const boost::optional< std::string >& value) { - this->artist = value ; - } - - const boost::optional< std::string >& getURI() const { - return uri; - } - - void setURI(const boost::optional< std::string >& value) { - this->uri = value ; - } - - const boost::optional< std::string >& getSource() const { - return source; - } - - void setSource(const boost::optional< std::string >& value) { - this->source = value ; - } - - const boost::optional< unsigned int >& getLength() const { - return length; - } - - void setLength(const boost::optional< unsigned int >& value) { - this->length = value ; - } - - - private: - boost::optional< unsigned int > rating; - boost::optional< std::string > title; - boost::optional< std::string > track; - boost::optional< std::string > artist; - boost::optional< std::string > uri; - boost::optional< std::string > source; - boost::optional< unsigned int > length; - }; + class SWIFTEN_API UserTune : public Payload { + public: + + UserTune(); + + virtual ~UserTune(); + + const boost::optional< unsigned int >& getRating() const { + return rating; + } + + void setRating(const boost::optional< unsigned int >& value) { + this->rating = value ; + } + + const boost::optional< std::string >& getTitle() const { + return title; + } + + void setTitle(const boost::optional< std::string >& value) { + this->title = value ; + } + + const boost::optional< std::string >& getTrack() const { + return track; + } + + void setTrack(const boost::optional< std::string >& value) { + this->track = value ; + } + + const boost::optional< std::string >& getArtist() const { + return artist; + } + + void setArtist(const boost::optional< std::string >& value) { + this->artist = value ; + } + + const boost::optional< std::string >& getURI() const { + return uri; + } + + void setURI(const boost::optional< std::string >& value) { + this->uri = value ; + } + + const boost::optional< std::string >& getSource() const { + return source; + } + + void setSource(const boost::optional< std::string >& value) { + this->source = value ; + } + + const boost::optional< unsigned int >& getLength() const { + return length; + } + + void setLength(const boost::optional< unsigned int >& value) { + this->length = value ; + } + + + private: + boost::optional< unsigned int > rating; + boost::optional< std::string > title; + boost::optional< std::string > track; + boost::optional< std::string > artist; + boost::optional< std::string > uri; + boost::optional< std::string > source; + boost::optional< unsigned int > length; + }; } diff --git a/Swiften/Elements/VCard.cpp b/Swiften/Elements/VCard.cpp index ffa90e7..f541d06 100644 --- a/Swiften/Elements/VCard.cpp +++ b/Swiften/Elements/VCard.cpp @@ -11,15 +11,15 @@ namespace Swift { VCard::EMailAddress VCard::getPreferredEMailAddress() const { - foreach(const EMailAddress& address, emailAddresses_) { - if (address.isPreferred) { - return address; - } - } - if (!emailAddresses_.empty()) { - return emailAddresses_[0]; - } - return EMailAddress(); + foreach(const EMailAddress& address, emailAddresses_) { + if (address.isPreferred) { + return address; + } + } + if (!emailAddresses_.empty()) { + return emailAddresses_[0]; + } + return EMailAddress(); } diff --git a/Swiften/Elements/VCard.h b/Swiften/Elements/VCard.h index ba9c39c..94cd029 100644 --- a/Swiften/Elements/VCard.h +++ b/Swiften/Elements/VCard.h @@ -17,287 +17,287 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API VCard : public Payload { - public: - typedef boost::shared_ptr<VCard> ref; - - struct EMailAddress { - EMailAddress() : isHome(false), isWork(false), isInternet(false), isPreferred(false), isX400(false) { - } - - bool isHome; - bool isWork; - bool isInternet; - bool isPreferred; - bool isX400; - std::string address; - }; - - struct Telephone { - Telephone() : isHome(false), isWork(false), isVoice(false), isFax(false), isPager(false), isMSG(false), isCell(false), - isVideo(false), isBBS(false), isModem(false), isISDN(false), isPCS(false), isPreferred(false) { - } - - bool isHome; - bool isWork; - bool isVoice; - bool isFax; - bool isPager; - bool isMSG; - bool isCell; - bool isVideo; - bool isBBS; - bool isModem; - bool isISDN; - bool isPCS; - bool isPreferred; - std::string number; - }; - - enum DeliveryType { - DomesticDelivery, - InternationalDelivery, - None - }; - - struct Address { - Address() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) { - } - - bool isHome; - bool isWork; - bool isPostal; - bool isParcel; - DeliveryType deliveryType; - bool isPreferred; - - std::string poBox; - std::string addressExtension; - std::string street; - std::string locality; - std::string region; - std::string postalCode; - std::string country; - }; - - struct AddressLabel { - AddressLabel() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) { - } - - bool isHome; - bool isWork; - bool isPostal; - bool isParcel; - DeliveryType deliveryType; - bool isPreferred; - std::vector<std::string> lines; - }; - - struct Organization { - std::string name; - std::vector<std::string> units; - }; - - VCard() {} - - void setVersion(const std::string& version) { version_ = version; } - const std::string& getVersion() const { return version_; } - - void setFullName(const std::string& fullName) { fullName_ = fullName; } - const std::string& getFullName() const { return fullName_; } - - void setFamilyName(const std::string& familyName) { familyName_ = familyName; } - const std::string& getFamilyName() const { return familyName_; } - - void setGivenName(const std::string& givenName) { givenName_ = givenName; } - const std::string& getGivenName() const { return givenName_; } - - void setMiddleName(const std::string& middleName) { middleName_ = middleName; } - const std::string& getMiddleName() const { return middleName_; } - - void setPrefix(const std::string& prefix) { prefix_ = prefix; } - const std::string& getPrefix() const { return prefix_; } - - void setSuffix(const std::string& suffix) { suffix_ = suffix; } - const std::string& getSuffix() const { return suffix_; } - - - //void setEMailAddress(const std::string& email) { email_ = email; } - //const std::string& getEMailAddress() const { return email_; } - - void setNickname(const std::string& nick) { nick_ = nick; } - const std::string& getNickname() const { return nick_; } - - void setPhoto(const ByteArray& photo) { photo_ = photo; } - const ByteArray& getPhoto() const { return photo_; } - - void setPhotoType(const std::string& photoType) { photoType_ = photoType; } - const std::string& getPhotoType() const { return photoType_; } - - const std::string& getUnknownContent() const { return unknownContent_; } - void addUnknownContent(const std::string& c) { - unknownContent_ += c; - } - - const std::vector<EMailAddress>& getEMailAddresses() const { - return emailAddresses_; - } - - void addEMailAddress(const EMailAddress& email) { - emailAddresses_.push_back(email); - } - - void clearEMailAddresses() { - emailAddresses_.clear(); - } + class SWIFTEN_API VCard : public Payload { + public: + typedef boost::shared_ptr<VCard> ref; + + struct EMailAddress { + EMailAddress() : isHome(false), isWork(false), isInternet(false), isPreferred(false), isX400(false) { + } + + bool isHome; + bool isWork; + bool isInternet; + bool isPreferred; + bool isX400; + std::string address; + }; + + struct Telephone { + Telephone() : isHome(false), isWork(false), isVoice(false), isFax(false), isPager(false), isMSG(false), isCell(false), + isVideo(false), isBBS(false), isModem(false), isISDN(false), isPCS(false), isPreferred(false) { + } + + bool isHome; + bool isWork; + bool isVoice; + bool isFax; + bool isPager; + bool isMSG; + bool isCell; + bool isVideo; + bool isBBS; + bool isModem; + bool isISDN; + bool isPCS; + bool isPreferred; + std::string number; + }; + + enum DeliveryType { + DomesticDelivery, + InternationalDelivery, + None + }; + + struct Address { + Address() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) { + } + + bool isHome; + bool isWork; + bool isPostal; + bool isParcel; + DeliveryType deliveryType; + bool isPreferred; + + std::string poBox; + std::string addressExtension; + std::string street; + std::string locality; + std::string region; + std::string postalCode; + std::string country; + }; + + struct AddressLabel { + AddressLabel() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) { + } + + bool isHome; + bool isWork; + bool isPostal; + bool isParcel; + DeliveryType deliveryType; + bool isPreferred; + std::vector<std::string> lines; + }; + + struct Organization { + std::string name; + std::vector<std::string> units; + }; + + VCard() {} + + void setVersion(const std::string& version) { version_ = version; } + const std::string& getVersion() const { return version_; } + + void setFullName(const std::string& fullName) { fullName_ = fullName; } + const std::string& getFullName() const { return fullName_; } + + void setFamilyName(const std::string& familyName) { familyName_ = familyName; } + const std::string& getFamilyName() const { return familyName_; } + + void setGivenName(const std::string& givenName) { givenName_ = givenName; } + const std::string& getGivenName() const { return givenName_; } + + void setMiddleName(const std::string& middleName) { middleName_ = middleName; } + const std::string& getMiddleName() const { return middleName_; } + + void setPrefix(const std::string& prefix) { prefix_ = prefix; } + const std::string& getPrefix() const { return prefix_; } + + void setSuffix(const std::string& suffix) { suffix_ = suffix; } + const std::string& getSuffix() const { return suffix_; } + + + //void setEMailAddress(const std::string& email) { email_ = email; } + //const std::string& getEMailAddress() const { return email_; } + + void setNickname(const std::string& nick) { nick_ = nick; } + const std::string& getNickname() const { return nick_; } + + void setPhoto(const ByteArray& photo) { photo_ = photo; } + const ByteArray& getPhoto() const { return photo_; } + + void setPhotoType(const std::string& photoType) { photoType_ = photoType; } + const std::string& getPhotoType() const { return photoType_; } + + const std::string& getUnknownContent() const { return unknownContent_; } + void addUnknownContent(const std::string& c) { + unknownContent_ += c; + } + + const std::vector<EMailAddress>& getEMailAddresses() const { + return emailAddresses_; + } + + void addEMailAddress(const EMailAddress& email) { + emailAddresses_.push_back(email); + } + + void clearEMailAddresses() { + emailAddresses_.clear(); + } - EMailAddress getPreferredEMailAddress() const; + EMailAddress getPreferredEMailAddress() const; - void setBirthday(const boost::posix_time::ptime& birthday) { - birthday_ = birthday; - } + void setBirthday(const boost::posix_time::ptime& birthday) { + birthday_ = birthday; + } - const boost::posix_time::ptime& getBirthday() const { - return birthday_; - } + const boost::posix_time::ptime& getBirthday() const { + return birthday_; + } - const std::vector<Telephone>& getTelephones() const { - return telephones_; - } + const std::vector<Telephone>& getTelephones() const { + return telephones_; + } - void addTelephone(const Telephone& phone) { - telephones_.push_back(phone); - } + void addTelephone(const Telephone& phone) { + telephones_.push_back(phone); + } - void clearTelephones() { - telephones_.clear(); - } + void clearTelephones() { + telephones_.clear(); + } - const std::vector<Address>& getAddresses() const { - return addresses_; - } + const std::vector<Address>& getAddresses() const { + return addresses_; + } - void addAddress(const Address& address) { - addresses_.push_back(address); - } + void addAddress(const Address& address) { + addresses_.push_back(address); + } - void clearAddresses() { - addresses_.clear(); - } - - const std::vector<AddressLabel>& getAddressLabels() const { - return addressLabels_; - } - - void addAddressLabel(const AddressLabel& addressLabel) { - addressLabels_.push_back(addressLabel); - } - - void clearAddressLabels() { - addressLabels_.clear(); - } - - const std::vector<JID>& getJIDs() const { - return jids_; - } - - void addJID(const JID& jid) { - jids_.push_back(jid); - } - - void clearJIDs() { - jids_.clear(); - } - - const std::string& getDescription() const { - return description_; - } - - void setDescription(const std::string& description) { - this->description_ = description; - } - - const std::vector<Organization>& getOrganizations() const { - return organizations_; - } - - void addOrganization(const Organization& organization) { - organizations_.push_back(organization); - } - - void clearOrganizations() { - organizations_.clear(); - } - - const std::vector<std::string>& getTitles() const { - return titles_; - } - - void addTitle(const std::string& title) { - titles_.push_back(title); - } - - void clearTitles() { - titles_.clear(); - } - - const std::vector<std::string>& getRoles() const { - return roles_; - } - - void addRole(const std::string& role) { - roles_.push_back(role); - } - - void clearRoles() { - roles_.clear(); - } - - const std::vector<std::string>& getURLs() const { - return urls_; - } - - void addURL(const std::string& url) { - urls_.push_back(url); - } - - void clearURLs() { - urls_.clear(); - } - - bool isEmpty() const { - bool empty = version_.empty() && fullName_.empty() && familyName_.empty() && givenName_.empty() && middleName_.empty() && prefix_.empty() && suffix_.empty(); - empty &= photo_.empty() && photoType_.empty() && nick_.empty(); - empty &= birthday_.is_not_a_date_time(); - empty &= unknownContent_.empty(); - empty &= emailAddresses_.empty() && telephones_.empty() && addresses_.empty() && addressLabels_.empty() && jids_.empty(); - empty &= description_.empty() && organizations_.empty() && titles_.empty() && roles_.empty() && urls_.empty(); - return empty; - } - - private: - std::string version_; - std::string fullName_; - std::string familyName_; - std::string givenName_; - std::string middleName_; - std::string prefix_; - std::string suffix_; - //std::string email_; - ByteArray photo_; - std::string photoType_; - std::string nick_; - boost::posix_time::ptime birthday_; - std::string unknownContent_; - std::vector<EMailAddress> emailAddresses_; - std::vector<Telephone> telephones_; - std::vector<Address> addresses_; - std::vector<AddressLabel> addressLabels_; - std::vector<JID> jids_; - std::string description_; - std::vector<Organization> organizations_; - std::vector<std::string> titles_; - std::vector<std::string> roles_; - std::vector<std::string> urls_; - }; + void clearAddresses() { + addresses_.clear(); + } + + const std::vector<AddressLabel>& getAddressLabels() const { + return addressLabels_; + } + + void addAddressLabel(const AddressLabel& addressLabel) { + addressLabels_.push_back(addressLabel); + } + + void clearAddressLabels() { + addressLabels_.clear(); + } + + const std::vector<JID>& getJIDs() const { + return jids_; + } + + void addJID(const JID& jid) { + jids_.push_back(jid); + } + + void clearJIDs() { + jids_.clear(); + } + + const std::string& getDescription() const { + return description_; + } + + void setDescription(const std::string& description) { + this->description_ = description; + } + + const std::vector<Organization>& getOrganizations() const { + return organizations_; + } + + void addOrganization(const Organization& organization) { + organizations_.push_back(organization); + } + + void clearOrganizations() { + organizations_.clear(); + } + + const std::vector<std::string>& getTitles() const { + return titles_; + } + + void addTitle(const std::string& title) { + titles_.push_back(title); + } + + void clearTitles() { + titles_.clear(); + } + + const std::vector<std::string>& getRoles() const { + return roles_; + } + + void addRole(const std::string& role) { + roles_.push_back(role); + } + + void clearRoles() { + roles_.clear(); + } + + const std::vector<std::string>& getURLs() const { + return urls_; + } + + void addURL(const std::string& url) { + urls_.push_back(url); + } + + void clearURLs() { + urls_.clear(); + } + + bool isEmpty() const { + bool empty = version_.empty() && fullName_.empty() && familyName_.empty() && givenName_.empty() && middleName_.empty() && prefix_.empty() && suffix_.empty(); + empty &= photo_.empty() && photoType_.empty() && nick_.empty(); + empty &= birthday_.is_not_a_date_time(); + empty &= unknownContent_.empty(); + empty &= emailAddresses_.empty() && telephones_.empty() && addresses_.empty() && addressLabels_.empty() && jids_.empty(); + empty &= description_.empty() && organizations_.empty() && titles_.empty() && roles_.empty() && urls_.empty(); + return empty; + } + + private: + std::string version_; + std::string fullName_; + std::string familyName_; + std::string givenName_; + std::string middleName_; + std::string prefix_; + std::string suffix_; + //std::string email_; + ByteArray photo_; + std::string photoType_; + std::string nick_; + boost::posix_time::ptime birthday_; + std::string unknownContent_; + std::vector<EMailAddress> emailAddresses_; + std::vector<Telephone> telephones_; + std::vector<Address> addresses_; + std::vector<AddressLabel> addressLabels_; + std::vector<JID> jids_; + std::string description_; + std::vector<Organization> organizations_; + std::vector<std::string> titles_; + std::vector<std::string> roles_; + std::vector<std::string> urls_; + }; } diff --git a/Swiften/Elements/VCardUpdate.h b/Swiften/Elements/VCardUpdate.h index ded26c9..e3b5377 100644 --- a/Swiften/Elements/VCardUpdate.h +++ b/Swiften/Elements/VCardUpdate.h @@ -12,14 +12,14 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API VCardUpdate : public Payload { - public: - VCardUpdate(const std::string& photoHash = "") : photoHash_(photoHash) {} + class SWIFTEN_API VCardUpdate : public Payload { + public: + VCardUpdate(const std::string& photoHash = "") : photoHash_(photoHash) {} - void setPhotoHash(const std::string& photoHash) { photoHash_ = photoHash; } - const std::string& getPhotoHash() const { return photoHash_; } + void setPhotoHash(const std::string& photoHash) { photoHash_ = photoHash; } + const std::string& getPhotoHash() const { return photoHash_; } - private: - std::string photoHash_; - }; + private: + std::string photoHash_; + }; } diff --git a/Swiften/Elements/Version.h b/Swiften/Elements/Version.h index b14dcf0..1d734be 100644 --- a/Swiften/Elements/Version.h +++ b/Swiften/Elements/Version.h @@ -12,17 +12,17 @@ #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API Version : public Payload { - public: - Version(const std::string& name = "", const std::string& version = "", const std::string& os = "") : name_(name), version_(version), os_(os) { } + class SWIFTEN_API Version : public Payload { + public: + Version(const std::string& name = "", const std::string& version = "", const std::string& os = "") : name_(name), version_(version), os_(os) { } - const std::string& getName() const { return name_; } - const std::string& getVersion() const { return version_; } - const std::string& getOS() const { return os_; } + const std::string& getName() const { return name_; } + const std::string& getVersion() const { return version_; } + const std::string& getOS() const { return os_; } - private: - std::string name_; - std::string version_; - std::string os_; - }; + private: + std::string name_; + std::string version_; + std::string os_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardColor.cpp b/Swiften/Elements/Whiteboard/WhiteboardColor.cpp index dcd6ad7..6bf7e03 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardColor.cpp +++ b/Swiften/Elements/Whiteboard/WhiteboardColor.cpp @@ -20,44 +20,44 @@ #include <Swiften/Base/String.h> namespace Swift { - WhiteboardColor::WhiteboardColor() : red_(0), green_(0), blue_(0), alpha_(255) { - } - - WhiteboardColor::WhiteboardColor(int red, int green, int blue, int alpha) : red_(red), green_(green), blue_(blue), alpha_(alpha) { - } - - WhiteboardColor::WhiteboardColor(const std::string& hex) : alpha_(255) { - int value = String::convertHexStringToInt(hex.substr(1)); - red_ = (value >> 16)&0xFF; - green_ = (value >> 8)&0xFF; - blue_ = value&0xFF; - } - - std::string WhiteboardColor::toHex() const { - std::string value = String::convertIntToHexString((red_ << 16) + (green_ << 8) + blue_); - while (value.size() < 6) { - value.insert(0, "0"); - } - return "#"+value; - } - - int WhiteboardColor::getRed() const { - return red_; - } - - int WhiteboardColor::getGreen() const { - return green_; - } - - int WhiteboardColor::getBlue() const { - return blue_; - } - - int WhiteboardColor::getAlpha() const { - return alpha_; - } - - void WhiteboardColor::setAlpha(int alpha) { - alpha_ = alpha; - } + WhiteboardColor::WhiteboardColor() : red_(0), green_(0), blue_(0), alpha_(255) { + } + + WhiteboardColor::WhiteboardColor(int red, int green, int blue, int alpha) : red_(red), green_(green), blue_(blue), alpha_(alpha) { + } + + WhiteboardColor::WhiteboardColor(const std::string& hex) : alpha_(255) { + int value = String::convertHexStringToInt(hex.substr(1)); + red_ = (value >> 16)&0xFF; + green_ = (value >> 8)&0xFF; + blue_ = value&0xFF; + } + + std::string WhiteboardColor::toHex() const { + std::string value = String::convertIntToHexString((red_ << 16) + (green_ << 8) + blue_); + while (value.size() < 6) { + value.insert(0, "0"); + } + return "#"+value; + } + + int WhiteboardColor::getRed() const { + return red_; + } + + int WhiteboardColor::getGreen() const { + return green_; + } + + int WhiteboardColor::getBlue() const { + return blue_; + } + + int WhiteboardColor::getAlpha() const { + return alpha_; + } + + void WhiteboardColor::setAlpha(int alpha) { + alpha_ = alpha; + } } diff --git a/Swiften/Elements/Whiteboard/WhiteboardColor.h b/Swiften/Elements/Whiteboard/WhiteboardColor.h index 3b3d93c..6402efd 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardColor.h +++ b/Swiften/Elements/Whiteboard/WhiteboardColor.h @@ -11,20 +11,20 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API WhiteboardColor { - public: - WhiteboardColor(); - WhiteboardColor(int red, int green, int blue, int alpha = 255); - WhiteboardColor(const std::string& hex); - std::string toHex() const; - int getRed() const; - int getGreen() const; - int getBlue() const; - int getAlpha() const; - void setAlpha(int alpha); + class SWIFTEN_API WhiteboardColor { + public: + WhiteboardColor(); + WhiteboardColor(int red, int green, int blue, int alpha = 255); + WhiteboardColor(const std::string& hex); + std::string toHex() const; + int getRed() const; + int getGreen() const; + int getBlue() const; + int getAlpha() const; + void setAlpha(int alpha); - private: - int red_, green_, blue_; - int alpha_; - }; + private: + int red_, green_, blue_; + int alpha_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h b/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h index d11fd8c..afecd0c 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h +++ b/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h @@ -17,19 +17,19 @@ #include <Swiften/Elements/Whiteboard/WhiteboardOperation.h> namespace Swift { - class SWIFTEN_API WhiteboardDeleteOperation : public WhiteboardOperation { - public: - typedef boost::shared_ptr<WhiteboardDeleteOperation> ref; - public: - std::string getElementID() const { - return elementID_; - } + class SWIFTEN_API WhiteboardDeleteOperation : public WhiteboardOperation { + public: + typedef boost::shared_ptr<WhiteboardDeleteOperation> ref; + public: + std::string getElementID() const { + return elementID_; + } - void setElementID(const std::string& elementID) { - elementID_ = elementID; - } + void setElementID(const std::string& elementID) { + elementID_ = elementID; + } - private: - std::string elementID_; - }; + private: + std::string elementID_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardElement.h b/Swiften/Elements/Whiteboard/WhiteboardElement.h index b01f31d..a4d1207 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardElement.h +++ b/Swiften/Elements/Whiteboard/WhiteboardElement.h @@ -17,23 +17,23 @@ #include <Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h> namespace Swift { - class WhiteboardElement { - public: - typedef boost::shared_ptr<WhiteboardElement> ref; + class WhiteboardElement { + public: + typedef boost::shared_ptr<WhiteboardElement> ref; - public: - virtual ~WhiteboardElement() {} - virtual void accept(WhiteboardElementVisitor& visitor) = 0; + public: + virtual ~WhiteboardElement() {} + virtual void accept(WhiteboardElementVisitor& visitor) = 0; - const std::string& getID() const { - return id_; - } + const std::string& getID() const { + return id_; + } - void setID(const std::string& id) { - id_ = id; - } + void setID(const std::string& id) { + id_ = id; + } - private: - std::string id_; - }; + private: + std::string id_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h b/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h index 413d6cf..090af56 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h +++ b/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h @@ -7,21 +7,21 @@ #pragma once namespace Swift { - class WhiteboardLineElement; - class WhiteboardFreehandPathElement; - class WhiteboardRectElement; - class WhiteboardPolygonElement; - class WhiteboardTextElement; - class WhiteboardEllipseElement; + class WhiteboardLineElement; + class WhiteboardFreehandPathElement; + class WhiteboardRectElement; + class WhiteboardPolygonElement; + class WhiteboardTextElement; + class WhiteboardEllipseElement; - class WhiteboardElementVisitor { - public: - virtual ~WhiteboardElementVisitor() {} - virtual void visit(WhiteboardLineElement& /*element*/) = 0; - virtual void visit(WhiteboardFreehandPathElement& /*element*/) = 0; - virtual void visit(WhiteboardRectElement& /*element*/) = 0; - virtual void visit(WhiteboardPolygonElement& /*element*/) = 0; - virtual void visit(WhiteboardTextElement& /*element*/) = 0; - virtual void visit(WhiteboardEllipseElement& /*element*/) = 0; - }; + class WhiteboardElementVisitor { + public: + virtual ~WhiteboardElementVisitor() {} + virtual void visit(WhiteboardLineElement& /*element*/) = 0; + virtual void visit(WhiteboardFreehandPathElement& /*element*/) = 0; + virtual void visit(WhiteboardRectElement& /*element*/) = 0; + virtual void visit(WhiteboardPolygonElement& /*element*/) = 0; + virtual void visit(WhiteboardTextElement& /*element*/) = 0; + virtual void visit(WhiteboardEllipseElement& /*element*/) = 0; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h b/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h index 040c8a3..15b50e4 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h +++ b/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h @@ -17,65 +17,65 @@ #include <Swiften/Elements/Whiteboard/WhiteboardElement.h> namespace Swift { - class SWIFTEN_API WhiteboardEllipseElement : public WhiteboardElement { - public: - typedef boost::shared_ptr<WhiteboardEllipseElement> ref; - public: - WhiteboardEllipseElement(int cx, int cy, int rx, int ry) { - cx_ = cx; - cy_ = cy; - rx_ = rx; - ry_ = ry; - } - - int getCX() const { - return cx_; - } - - int getCY() const { - return cy_; - } - - int getRX() const { - return rx_; - } - - int getRY() const { - return ry_; - } - - const WhiteboardColor& getPenColor() const { - return penColor_; - } - - void setPenColor(const WhiteboardColor& color) { - penColor_ = color; - } - - const WhiteboardColor& getBrushColor() const { - return brushColor_; - } - - void setBrushColor(const WhiteboardColor& color) { - brushColor_ = color; - } - - int getPenWidth() const { - return penWidth_; - } - - void setPenWidth(const int penWidth) { - penWidth_ = penWidth; - } - - void accept(WhiteboardElementVisitor& visitor) { - visitor.visit(*this); - } - - private: - int cx_, cy_, rx_, ry_; - WhiteboardColor penColor_; - WhiteboardColor brushColor_; - int penWidth_; - }; + class SWIFTEN_API WhiteboardEllipseElement : public WhiteboardElement { + public: + typedef boost::shared_ptr<WhiteboardEllipseElement> ref; + public: + WhiteboardEllipseElement(int cx, int cy, int rx, int ry) { + cx_ = cx; + cy_ = cy; + rx_ = rx; + ry_ = ry; + } + + int getCX() const { + return cx_; + } + + int getCY() const { + return cy_; + } + + int getRX() const { + return rx_; + } + + int getRY() const { + return ry_; + } + + const WhiteboardColor& getPenColor() const { + return penColor_; + } + + void setPenColor(const WhiteboardColor& color) { + penColor_ = color; + } + + const WhiteboardColor& getBrushColor() const { + return brushColor_; + } + + void setBrushColor(const WhiteboardColor& color) { + brushColor_ = color; + } + + int getPenWidth() const { + return penWidth_; + } + + void setPenWidth(const int penWidth) { + penWidth_ = penWidth; + } + + void accept(WhiteboardElementVisitor& visitor) { + visitor.visit(*this); + } + + private: + int cx_, cy_, rx_, ry_; + WhiteboardColor penColor_; + WhiteboardColor brushColor_; + int penWidth_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h b/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h index 5164ae9..7522b7b 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h +++ b/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h @@ -20,45 +20,45 @@ #include <Swiften/Elements/Whiteboard/WhiteboardElement.h> namespace Swift { - class SWIFTEN_API WhiteboardFreehandPathElement : public WhiteboardElement { - typedef std::pair<int, int> Point; - public: - typedef boost::shared_ptr<WhiteboardFreehandPathElement> ref; - public: - WhiteboardFreehandPathElement() { - } + class SWIFTEN_API WhiteboardFreehandPathElement : public WhiteboardElement { + typedef std::pair<int, int> Point; + public: + typedef boost::shared_ptr<WhiteboardFreehandPathElement> ref; + public: + WhiteboardFreehandPathElement() { + } - void setPoints(const std::vector<Point>& points) { - points_ = points; - } + void setPoints(const std::vector<Point>& points) { + points_ = points; + } - const std::vector<Point>& getPoints() const { - return points_; - } + const std::vector<Point>& getPoints() const { + return points_; + } - const WhiteboardColor& getColor() const { - return color_; - } + const WhiteboardColor& getColor() const { + return color_; + } - void setColor(const WhiteboardColor& color) { - color_ = color; - } + void setColor(const WhiteboardColor& color) { + color_ = color; + } - int getPenWidth() const { - return penWidth_; - } + int getPenWidth() const { + return penWidth_; + } - void setPenWidth(const int penWidth) { - penWidth_ = penWidth; - } + void setPenWidth(const int penWidth) { + penWidth_ = penWidth; + } - void accept(WhiteboardElementVisitor& visitor) { - visitor.visit(*this); - } + void accept(WhiteboardElementVisitor& visitor) { + visitor.visit(*this); + } - private: - std::vector<Point> points_; - WhiteboardColor color_; - int penWidth_; - }; + private: + std::vector<Point> points_; + WhiteboardColor color_; + int penWidth_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h b/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h index bbeaa12..855e502 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h +++ b/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h @@ -17,19 +17,19 @@ #include <Swiften/Elements/Whiteboard/WhiteboardOperation.h> namespace Swift { - class SWIFTEN_API WhiteboardInsertOperation : public WhiteboardOperation { - public: - typedef boost::shared_ptr<WhiteboardInsertOperation> ref; - public: - WhiteboardElement::ref getElement() const { - return element_; - } + class SWIFTEN_API WhiteboardInsertOperation : public WhiteboardOperation { + public: + typedef boost::shared_ptr<WhiteboardInsertOperation> ref; + public: + WhiteboardElement::ref getElement() const { + return element_; + } - void setElement(WhiteboardElement::ref element) { - element_ = element; - } + void setElement(WhiteboardElement::ref element) { + element_ = element; + } - private: - WhiteboardElement::ref element_; - }; + private: + WhiteboardElement::ref element_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardLineElement.h b/Swiften/Elements/Whiteboard/WhiteboardLineElement.h index dae207a..7fb8a77 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardLineElement.h +++ b/Swiften/Elements/Whiteboard/WhiteboardLineElement.h @@ -18,56 +18,56 @@ #include <Swiften/Elements/Whiteboard/WhiteboardElement.h> namespace Swift { - class SWIFTEN_API WhiteboardLineElement : public WhiteboardElement { - public: - typedef boost::shared_ptr<WhiteboardLineElement> ref; - public: - WhiteboardLineElement(int x1, int y1, int x2, int y2) : penWidth_(1) { - x1_ = x1; - y1_ = y1; - x2_ = x2; - y2_ = y2; - } + class SWIFTEN_API WhiteboardLineElement : public WhiteboardElement { + public: + typedef boost::shared_ptr<WhiteboardLineElement> ref; + public: + WhiteboardLineElement(int x1, int y1, int x2, int y2) : penWidth_(1) { + x1_ = x1; + y1_ = y1; + x2_ = x2; + y2_ = y2; + } - int x1() const { - return x1_; - } + int x1() const { + return x1_; + } - int y1() const { - return y1_; - } + int y1() const { + return y1_; + } - int x2() const { - return x2_; - } + int x2() const { + return x2_; + } - int y2() const { - return y2_; - } + int y2() const { + return y2_; + } - const WhiteboardColor& getColor() const { - return color_; - } + const WhiteboardColor& getColor() const { + return color_; + } - void setColor(const WhiteboardColor& color) { - color_ = color; - } + void setColor(const WhiteboardColor& color) { + color_ = color; + } - int getPenWidth() const { - return penWidth_; - } + int getPenWidth() const { + return penWidth_; + } - void setPenWidth(const int penWidth) { - penWidth_ = penWidth; - } + void setPenWidth(const int penWidth) { + penWidth_ = penWidth; + } - void accept(WhiteboardElementVisitor& visitor) { - visitor.visit(*this); - } + void accept(WhiteboardElementVisitor& visitor) { + visitor.visit(*this); + } - private: - int x1_, y1_, x2_, y2_; - WhiteboardColor color_; - int penWidth_; - }; + private: + int x1_, y1_, x2_, y2_; + WhiteboardColor color_; + int penWidth_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardOperation.h b/Swiften/Elements/Whiteboard/WhiteboardOperation.h index 79083a0..b657bd9 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardOperation.h +++ b/Swiften/Elements/Whiteboard/WhiteboardOperation.h @@ -19,41 +19,41 @@ #include <Swiften/Base/API.h> namespace Swift { - class WhiteboardOperation { - public: - typedef boost::shared_ptr<WhiteboardOperation> ref; - public: - WhiteboardOperation() {} - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(WhiteboardOperation) - virtual ~WhiteboardOperation(){} - - std::string getID() const { - return id_; - } - - void setID(const std::string& id) { - id_ = id; - } - - std::string getParentID() const { - return parentID_; - } - - void setParentID(const std::string& parentID) { - parentID_ = parentID; - } - - int getPos() const { - return pos_; - } - - void setPos(int pos) { - pos_ = pos; - } - - private: - std::string id_; - std::string parentID_; - int pos_; - }; + class WhiteboardOperation { + public: + typedef boost::shared_ptr<WhiteboardOperation> ref; + public: + WhiteboardOperation() {} + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(WhiteboardOperation) + virtual ~WhiteboardOperation(){} + + std::string getID() const { + return id_; + } + + void setID(const std::string& id) { + id_ = id; + } + + std::string getParentID() const { + return parentID_; + } + + void setParentID(const std::string& parentID) { + parentID_ = parentID; + } + + int getPos() const { + return pos_; + } + + void setPos(int pos) { + pos_ = pos; + } + + private: + std::string id_; + std::string parentID_; + int pos_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h b/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h index 38bc3e1..bd0b674 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h +++ b/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h @@ -19,54 +19,54 @@ #include <Swiften/Elements/Whiteboard/WhiteboardElement.h> namespace Swift { - class SWIFTEN_API WhiteboardPolygonElement : public WhiteboardElement { - typedef std::pair<int, int> Point; - public: - typedef boost::shared_ptr<WhiteboardPolygonElement> ref; - public: - WhiteboardPolygonElement() { - } + class SWIFTEN_API WhiteboardPolygonElement : public WhiteboardElement { + typedef std::pair<int, int> Point; + public: + typedef boost::shared_ptr<WhiteboardPolygonElement> ref; + public: + WhiteboardPolygonElement() { + } - const std::vector<Point>& getPoints() const { - return points_; - } + const std::vector<Point>& getPoints() const { + return points_; + } - void setPoints(const std::vector<Point>& points) { - points_ = points; - } + void setPoints(const std::vector<Point>& points) { + points_ = points; + } - const WhiteboardColor& getPenColor() const { - return penColor_; - } + const WhiteboardColor& getPenColor() const { + return penColor_; + } - void setPenColor(const WhiteboardColor& color) { - penColor_ = color; - } + void setPenColor(const WhiteboardColor& color) { + penColor_ = color; + } - const WhiteboardColor& getBrushColor() const { - return brushColor_; - } + const WhiteboardColor& getBrushColor() const { + return brushColor_; + } - void setBrushColor(const WhiteboardColor& color) { - brushColor_ = color; - } + void setBrushColor(const WhiteboardColor& color) { + brushColor_ = color; + } - int getPenWidth() const { - return penWidth_; - } + int getPenWidth() const { + return penWidth_; + } - void setPenWidth(const int penWidth) { - penWidth_ = penWidth; - } + void setPenWidth(const int penWidth) { + penWidth_ = penWidth; + } - void accept(WhiteboardElementVisitor& visitor) { - visitor.visit(*this); - } + void accept(WhiteboardElementVisitor& visitor) { + visitor.visit(*this); + } - private: - std::vector<Point> points_; - WhiteboardColor penColor_; - WhiteboardColor brushColor_; - int penWidth_; - }; + private: + std::vector<Point> points_; + WhiteboardColor penColor_; + WhiteboardColor brushColor_; + int penWidth_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardRectElement.h b/Swiften/Elements/Whiteboard/WhiteboardRectElement.h index 7d47ba0..c681e97 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardRectElement.h +++ b/Swiften/Elements/Whiteboard/WhiteboardRectElement.h @@ -17,65 +17,65 @@ #include <Swiften/Elements/Whiteboard/WhiteboardElement.h> namespace Swift { - class SWIFTEN_API WhiteboardRectElement : public WhiteboardElement { - public: - typedef boost::shared_ptr<WhiteboardRectElement> ref; - public: - WhiteboardRectElement(int x, int y, int width, int height) : penWidth_(1) { - x_ = x; - y_ = y; - width_ = width; - height_ = height; - } - - int getX() const { - return x_; - } - - int getY() const { - return y_; - } - - int getWidth() const { - return width_; - } - - int getHeight() const { - return height_; - } - - const WhiteboardColor& getPenColor() const { - return penColor_; - } - - void setPenColor(const WhiteboardColor& color) { - penColor_ = color; - } - - const WhiteboardColor& getBrushColor() const { - return brushColor_; - } - - void setBrushColor(const WhiteboardColor& color) { - brushColor_ = color; - } - - int getPenWidth() const { - return penWidth_; - } - - void setPenWidth(const int penWidth) { - penWidth_ = penWidth; - } - - void accept(WhiteboardElementVisitor& visitor) { - visitor.visit(*this); - } - - private: - int x_, y_, width_, height_; - WhiteboardColor penColor_; - WhiteboardColor brushColor_; - int penWidth_; - }; + class SWIFTEN_API WhiteboardRectElement : public WhiteboardElement { + public: + typedef boost::shared_ptr<WhiteboardRectElement> ref; + public: + WhiteboardRectElement(int x, int y, int width, int height) : penWidth_(1) { + x_ = x; + y_ = y; + width_ = width; + height_ = height; + } + + int getX() const { + return x_; + } + + int getY() const { + return y_; + } + + int getWidth() const { + return width_; + } + + int getHeight() const { + return height_; + } + + const WhiteboardColor& getPenColor() const { + return penColor_; + } + + void setPenColor(const WhiteboardColor& color) { + penColor_ = color; + } + + const WhiteboardColor& getBrushColor() const { + return brushColor_; + } + + void setBrushColor(const WhiteboardColor& color) { + brushColor_ = color; + } + + int getPenWidth() const { + return penWidth_; + } + + void setPenWidth(const int penWidth) { + penWidth_ = penWidth; + } + + void accept(WhiteboardElementVisitor& visitor) { + visitor.visit(*this); + } + + private: + int x_, y_, width_, height_; + WhiteboardColor penColor_; + WhiteboardColor brushColor_; + int penWidth_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardTextElement.h b/Swiften/Elements/Whiteboard/WhiteboardTextElement.h index 37ae2c5..df00bea 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardTextElement.h +++ b/Swiften/Elements/Whiteboard/WhiteboardTextElement.h @@ -17,55 +17,55 @@ #include <Swiften/Elements/Whiteboard/WhiteboardElement.h> namespace Swift { - class SWIFTEN_API WhiteboardTextElement : public WhiteboardElement { - public: - typedef boost::shared_ptr<WhiteboardTextElement> ref; - public: - WhiteboardTextElement(int x, int y) { - x_ = x; - y_ = y; - } + class SWIFTEN_API WhiteboardTextElement : public WhiteboardElement { + public: + typedef boost::shared_ptr<WhiteboardTextElement> ref; + public: + WhiteboardTextElement(int x, int y) { + x_ = x; + y_ = y; + } - void setText(const std::string text) { - text_ = text; - } + void setText(const std::string text) { + text_ = text; + } - const std::string& getText() const { - return text_; - } + const std::string& getText() const { + return text_; + } - int getX() const { - return x_; - } + int getX() const { + return x_; + } - int getY() const { - return y_; - } + int getY() const { + return y_; + } - const WhiteboardColor& getColor() const { - return color_; - } + const WhiteboardColor& getColor() const { + return color_; + } - void setColor(const WhiteboardColor& color) { - color_ = color; - } + void setColor(const WhiteboardColor& color) { + color_ = color; + } - int getSize() const { - return size_; - } + int getSize() const { + return size_; + } - void setSize(const int size) { - size_ = size; - } + void setSize(const int size) { + size_ = size; + } - void accept(WhiteboardElementVisitor& visitor) { - visitor.visit(*this); - } + void accept(WhiteboardElementVisitor& visitor) { + visitor.visit(*this); + } - private: - int x_, y_; - int size_; - std::string text_; - WhiteboardColor color_; - }; + private: + int x_, y_; + int size_; + std::string text_; + WhiteboardColor color_; + }; } diff --git a/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h b/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h index fe88fe7..5147999 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h +++ b/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h @@ -17,28 +17,28 @@ #include <Swiften/Elements/Whiteboard/WhiteboardOperation.h> namespace Swift { - class SWIFTEN_API WhiteboardUpdateOperation : public WhiteboardOperation { - public: - typedef boost::shared_ptr<WhiteboardUpdateOperation> ref; - public: - WhiteboardElement::ref getElement() const { - return element_; - } - - void setElement(WhiteboardElement::ref element) { - element_ = element; - } - - int getNewPos() const { - return newPos_; - } - - void setNewPos(int newPos) { - newPos_ = newPos; - } - - private: - WhiteboardElement::ref element_; - int newPos_; - }; + class SWIFTEN_API WhiteboardUpdateOperation : public WhiteboardOperation { + public: + typedef boost::shared_ptr<WhiteboardUpdateOperation> ref; + public: + WhiteboardElement::ref getElement() const { + return element_; + } + + void setElement(WhiteboardElement::ref element) { + element_ = element; + } + + int getNewPos() const { + return newPos_; + } + + void setNewPos(int newPos) { + newPos_ = newPos; + } + + private: + WhiteboardElement::ref element_; + int newPos_; + }; } diff --git a/Swiften/Elements/WhiteboardPayload.h b/Swiften/Elements/WhiteboardPayload.h index 3fcaa33..42e1375 100644 --- a/Swiften/Elements/WhiteboardPayload.h +++ b/Swiften/Elements/WhiteboardPayload.h @@ -20,52 +20,52 @@ #include <Swiften/Elements/Whiteboard/WhiteboardOperation.h> namespace Swift { - class SWIFTEN_API WhiteboardPayload : public Payload { - public: - typedef boost::shared_ptr<WhiteboardPayload> ref; - - public: - enum Type {UnknownType, Data, SessionRequest, SessionAccept, SessionTerminate}; - - WhiteboardPayload(Type type = WhiteboardPayload::Data) : type_(type) { - } - - void setData(const std::string &data) { - data_ = data; - } - - std::string getData() const { - return data_; - } - - Type getType() const { - return type_; - } - - void setType(Type type) { - type_ = type; - } - - WhiteboardElement::ref getElement() const { - return element_; - } - - void setElement(WhiteboardElement::ref element) { - element_ = element; - } - - WhiteboardOperation::ref getOperation() const { - return operation_; - } - - void setOperation(WhiteboardOperation::ref operation) { - operation_ = operation; - } - - private: - std::string data_; - Type type_; - WhiteboardElement::ref element_; - WhiteboardOperation::ref operation_; - }; + class SWIFTEN_API WhiteboardPayload : public Payload { + public: + typedef boost::shared_ptr<WhiteboardPayload> ref; + + public: + enum Type {UnknownType, Data, SessionRequest, SessionAccept, SessionTerminate}; + + WhiteboardPayload(Type type = WhiteboardPayload::Data) : type_(type) { + } + + void setData(const std::string &data) { + data_ = data; + } + + std::string getData() const { + return data_; + } + + Type getType() const { + return type_; + } + + void setType(Type type) { + type_ = type; + } + + WhiteboardElement::ref getElement() const { + return element_; + } + + void setElement(WhiteboardElement::ref element) { + element_ = element; + } + + WhiteboardOperation::ref getOperation() const { + return operation_; + } + + void setOperation(WhiteboardOperation::ref operation) { + operation_ = operation; + } + + private: + std::string data_; + Type type_; + WhiteboardElement::ref element_; + WhiteboardOperation::ref operation_; + }; } diff --git a/Swiften/Entity/Entity.cpp b/Swiften/Entity/Entity.cpp index af6f636..0875fb1 100644 --- a/Swiften/Entity/Entity.cpp +++ b/Swiften/Entity/Entity.cpp @@ -12,38 +12,38 @@ namespace Swift { Entity::Entity() { - payloadParserFactories = new FullPayloadParserFactoryCollection(); - payloadSerializers = new FullPayloadSerializerCollection(); + payloadParserFactories = new FullPayloadParserFactoryCollection(); + payloadSerializers = new FullPayloadSerializerCollection(); } Entity::~Entity() { - delete payloadSerializers; - delete payloadParserFactories; + delete payloadSerializers; + delete payloadParserFactories; } void Entity::addPayloadParserFactory(PayloadParserFactory* payloadParserFactory) { - payloadParserFactories->addFactory(payloadParserFactory); + payloadParserFactories->addFactory(payloadParserFactory); } void Entity::removePayloadParserFactory(PayloadParserFactory* payloadParserFactory) { - payloadParserFactories->removeFactory(payloadParserFactory); + payloadParserFactories->removeFactory(payloadParserFactory); } void Entity::addPayloadSerializer(PayloadSerializer* payloadSerializer) { - payloadSerializers->addSerializer(payloadSerializer); + payloadSerializers->addSerializer(payloadSerializer); } void Entity::removePayloadSerializer(PayloadSerializer* payloadSerializer) { - payloadSerializers->removeSerializer(payloadSerializer); + payloadSerializers->removeSerializer(payloadSerializer); } PayloadParserFactoryCollection* Entity::getPayloadParserFactories() { - return payloadParserFactories; + return payloadParserFactories; } PayloadSerializerCollection* Entity::getPayloadSerializers() { - return payloadSerializers; + return payloadSerializers; } } diff --git a/Swiften/Entity/Entity.h b/Swiften/Entity/Entity.h index d563c5e..a44c145 100644 --- a/Swiften/Entity/Entity.h +++ b/Swiften/Entity/Entity.h @@ -9,33 +9,33 @@ #include <Swiften/Base/API.h> namespace Swift { - class PayloadParserFactory; - class PayloadSerializer; - class FullPayloadParserFactoryCollection; - class FullPayloadSerializerCollection; - class PayloadParserFactoryCollection; - class PayloadSerializerCollection; - - /** - * The base class for XMPP entities (Clients, Components). - */ - class SWIFTEN_API Entity { - public: - Entity(); - virtual ~Entity(); - - void addPayloadParserFactory(PayloadParserFactory* payloadParserFactory); - void removePayloadParserFactory(PayloadParserFactory* payloadParserFactory); - - void addPayloadSerializer(PayloadSerializer* payloadSerializer); - void removePayloadSerializer(PayloadSerializer* payloadSerializer); - - protected: - PayloadParserFactoryCollection* getPayloadParserFactories(); - PayloadSerializerCollection* getPayloadSerializers(); - - private: - FullPayloadParserFactoryCollection* payloadParserFactories; - FullPayloadSerializerCollection* payloadSerializers; - }; + class PayloadParserFactory; + class PayloadSerializer; + class FullPayloadParserFactoryCollection; + class FullPayloadSerializerCollection; + class PayloadParserFactoryCollection; + class PayloadSerializerCollection; + + /** + * The base class for XMPP entities (Clients, Components). + */ + class SWIFTEN_API Entity { + public: + Entity(); + virtual ~Entity(); + + void addPayloadParserFactory(PayloadParserFactory* payloadParserFactory); + void removePayloadParserFactory(PayloadParserFactory* payloadParserFactory); + + void addPayloadSerializer(PayloadSerializer* payloadSerializer); + void removePayloadSerializer(PayloadSerializer* payloadSerializer); + + protected: + PayloadParserFactoryCollection* getPayloadParserFactories(); + PayloadSerializerCollection* getPayloadSerializers(); + + private: + FullPayloadParserFactoryCollection* payloadParserFactories; + FullPayloadSerializerCollection* payloadSerializers; + }; } diff --git a/Swiften/Entity/GenericPayloadPersister.h b/Swiften/Entity/GenericPayloadPersister.h index 6f07c3b..19afc61 100644 --- a/Swiften/Entity/GenericPayloadPersister.h +++ b/Swiften/Entity/GenericPayloadPersister.h @@ -11,27 +11,27 @@ #include <Swiften/Parser/GenericPayloadParserFactory.h> namespace Swift { - template<typename PAYLOAD, typename PARSER, typename SERIALIZER> - class SWIFTEN_API GenericPayloadPersister : public PayloadPersister { - public: - GenericPayloadPersister() { - } + template<typename PAYLOAD, typename PARSER, typename SERIALIZER> + class SWIFTEN_API GenericPayloadPersister : public PayloadPersister { + public: + GenericPayloadPersister() { + } - public: - boost::shared_ptr<PAYLOAD> loadPayloadGeneric(const boost::filesystem::path& path) { - return boost::dynamic_pointer_cast<PAYLOAD>(loadPayload(path)); - } + public: + boost::shared_ptr<PAYLOAD> loadPayloadGeneric(const boost::filesystem::path& path) { + return boost::dynamic_pointer_cast<PAYLOAD>(loadPayload(path)); + } - protected: - virtual const PayloadSerializer* getSerializer() const { - return &serializer; - } + protected: + virtual const PayloadSerializer* getSerializer() const { + return &serializer; + } - virtual PayloadParser* createParser() const { - return new PARSER(); - } + virtual PayloadParser* createParser() const { + return new PARSER(); + } - private: - SERIALIZER serializer; - }; + private: + SERIALIZER serializer; + }; } diff --git a/Swiften/Entity/PayloadPersister.cpp b/Swiften/Entity/PayloadPersister.cpp index 2ad8e09..7147615 100644 --- a/Swiften/Entity/PayloadPersister.cpp +++ b/Swiften/Entity/PayloadPersister.cpp @@ -26,32 +26,32 @@ PayloadPersister::~PayloadPersister() { } void PayloadPersister::savePayload(boost::shared_ptr<Payload> payload, const boost::filesystem::path& path) { - try { - if (!boost::filesystem::exists(path.parent_path())) { - boost::filesystem::create_directories(path.parent_path()); - } - boost::filesystem::ofstream file(path); - file << getSerializer()->serialize(payload); - file.close(); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } + try { + if (!boost::filesystem::exists(path.parent_path())) { + boost::filesystem::create_directories(path.parent_path()); + } + boost::filesystem::ofstream file(path); + file << getSerializer()->serialize(payload); + file.close(); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } } boost::shared_ptr<Payload> PayloadPersister::loadPayload(const boost::filesystem::path& path) { - try { - if (boost::filesystem::exists(path)) { - ByteArray data; - readByteArrayFromFile(data, path); - boost::shared_ptr<PayloadParser> parser(createParser()); - PayloadParserTester tester(parser.get()); - tester.parse(byteArrayToString(data)); - return parser->getPayload(); - } - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } - return boost::shared_ptr<Payload>(); + try { + if (boost::filesystem::exists(path)) { + ByteArray data; + readByteArrayFromFile(data, path); + boost::shared_ptr<PayloadParser> parser(createParser()); + PayloadParserTester tester(parser.get()); + tester.parse(byteArrayToString(data)); + return parser->getPayload(); + } + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } + return boost::shared_ptr<Payload>(); } diff --git a/Swiften/Entity/PayloadPersister.h b/Swiften/Entity/PayloadPersister.h index 44f400f..9102f4b 100644 --- a/Swiften/Entity/PayloadPersister.h +++ b/Swiften/Entity/PayloadPersister.h @@ -12,21 +12,21 @@ #include <Swiften/Base/API.h> namespace Swift { - class Payload; - class PayloadSerializer; - class PayloadParser; + class Payload; + class PayloadSerializer; + class PayloadParser; - class SWIFTEN_API PayloadPersister { - public: - PayloadPersister(); - virtual ~PayloadPersister(); + class SWIFTEN_API PayloadPersister { + public: + PayloadPersister(); + virtual ~PayloadPersister(); - void savePayload(boost::shared_ptr<Payload>, const boost::filesystem::path&); - boost::shared_ptr<Payload> loadPayload(const boost::filesystem::path&); + void savePayload(boost::shared_ptr<Payload>, const boost::filesystem::path&); + boost::shared_ptr<Payload> loadPayload(const boost::filesystem::path&); - protected: + protected: - virtual const PayloadSerializer* getSerializer() const = 0; - virtual PayloadParser* createParser() const = 0; - }; + virtual const PayloadSerializer* getSerializer() const = 0; + virtual PayloadParser* createParser() const = 0; + }; } diff --git a/Swiften/EventLoop/BoostASIOEventLoop.cpp b/Swiften/EventLoop/BoostASIOEventLoop.cpp index 1574434..a9d1440 100644 --- a/Swiften/EventLoop/BoostASIOEventLoop.cpp +++ b/Swiften/EventLoop/BoostASIOEventLoop.cpp @@ -19,19 +19,19 @@ BoostASIOEventLoop::~BoostASIOEventLoop() { } void BoostASIOEventLoop::handleASIOEvent() { - { - boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_); - isEventInASIOEventLoop_ = false; - } - handleNextEvents(); + { + boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_); + isEventInASIOEventLoop_ = false; + } + handleNextEvents(); } void BoostASIOEventLoop::eventPosted() { - boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_); - if (!isEventInASIOEventLoop_) { - isEventInASIOEventLoop_ = true; - ioService_->post(boost::bind(&BoostASIOEventLoop::handleASIOEvent, this)); - } + boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_); + if (!isEventInASIOEventLoop_) { + isEventInASIOEventLoop_ = true; + ioService_->post(boost::bind(&BoostASIOEventLoop::handleASIOEvent, this)); + } } } diff --git a/Swiften/EventLoop/BoostASIOEventLoop.h b/Swiften/EventLoop/BoostASIOEventLoop.h index a093199..c39aaf5 100644 --- a/Swiften/EventLoop/BoostASIOEventLoop.h +++ b/Swiften/EventLoop/BoostASIOEventLoop.h @@ -15,20 +15,20 @@ #include <Swiften/EventLoop/EventLoop.h> namespace Swift { - class SWIFTEN_API BoostASIOEventLoop : public EventLoop { - public: - BoostASIOEventLoop(boost::shared_ptr<boost::asio::io_service> ioService); - virtual ~BoostASIOEventLoop(); + class SWIFTEN_API BoostASIOEventLoop : public EventLoop { + public: + BoostASIOEventLoop(boost::shared_ptr<boost::asio::io_service> ioService); + virtual ~BoostASIOEventLoop(); - protected: - void handleASIOEvent(); + protected: + void handleASIOEvent(); - virtual void eventPosted(); + virtual void eventPosted(); - private: - boost::shared_ptr<boost::asio::io_service> ioService_; + private: + boost::shared_ptr<boost::asio::io_service> ioService_; - bool isEventInASIOEventLoop_; - boost::recursive_mutex isEventInASIOEventLoopMutex_; - }; + bool isEventInASIOEventLoop_; + boost::recursive_mutex isEventInASIOEventLoopMutex_; + }; } diff --git a/Swiften/EventLoop/Cocoa/CocoaEvent.h b/Swiften/EventLoop/Cocoa/CocoaEvent.h index 1e2c6f6..945056e 100644 --- a/Swiften/EventLoop/Cocoa/CocoaEvent.h +++ b/Swiften/EventLoop/Cocoa/CocoaEvent.h @@ -13,7 +13,7 @@ #undef check namespace Swift { - class CocoaEventLoop; + class CocoaEventLoop; } // Using deprecated declaration of instance vars in interface, because this @@ -22,7 +22,7 @@ namespace Swift { #pragma clang diagnostic ignored "-Wobjc-interface-ivars" @interface CocoaEvent : NSObject { - Swift::CocoaEventLoop* eventLoop; + Swift::CocoaEventLoop* eventLoop; } #pragma clang diagnostic pop diff --git a/Swiften/EventLoop/Cocoa/CocoaEvent.mm b/Swiften/EventLoop/Cocoa/CocoaEvent.mm index 8615b48..fc9695b 100644 --- a/Swiften/EventLoop/Cocoa/CocoaEvent.mm +++ b/Swiften/EventLoop/Cocoa/CocoaEvent.mm @@ -11,19 +11,19 @@ @implementation CocoaEvent - (id) init:(Swift::CocoaEventLoop*) el { - self = [super init]; - if (self != nil) { - eventLoop = el; - } - return self; + self = [super init]; + if (self != nil) { + eventLoop = el; + } + return self; } - (void) process { - eventLoop->handleNextCocoaEvent(); + eventLoop->handleNextCocoaEvent(); } - (void) dealloc { - [super dealloc]; + [super dealloc]; } @end diff --git a/Swiften/EventLoop/Cocoa/CocoaEventLoop.h b/Swiften/EventLoop/Cocoa/CocoaEventLoop.h index aad6b0a..bbe8390 100644 --- a/Swiften/EventLoop/Cocoa/CocoaEventLoop.h +++ b/Swiften/EventLoop/Cocoa/CocoaEventLoop.h @@ -11,18 +11,18 @@ #include <Swiften/EventLoop/EventLoop.h> namespace Swift { - class CocoaEventLoop : public EventLoop { - public: - CocoaEventLoop(); - virtual ~CocoaEventLoop(); + class CocoaEventLoop : public EventLoop { + public: + CocoaEventLoop(); + virtual ~CocoaEventLoop(); - void handleNextCocoaEvent(); - - protected: - virtual void eventPosted(); + void handleNextCocoaEvent(); - private: - bool isEventInCocoaEventLoop_; - boost::recursive_mutex isEventInCocoaEventLoopMutex_; - }; + protected: + virtual void eventPosted(); + + private: + bool isEventInCocoaEventLoop_; + boost::recursive_mutex isEventInCocoaEventLoopMutex_; + }; } diff --git a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm index 2d7c613..de7c1de 100644 --- a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm +++ b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm @@ -19,25 +19,25 @@ CocoaEventLoop::~CocoaEventLoop() { } void CocoaEventLoop::handleNextCocoaEvent() { - { - boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_); - isEventInCocoaEventLoop_ = false; - } - handleNextEvents(); + { + boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_); + isEventInCocoaEventLoop_ = false; + } + handleNextEvents(); } void CocoaEventLoop::eventPosted() { - boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_); - if (!isEventInCocoaEventLoop_) { - isEventInCocoaEventLoop_ = true; - - CocoaEvent* cocoaEvent = [[CocoaEvent alloc] init: this]; - [cocoaEvent - performSelectorOnMainThread:@selector(process) - withObject: nil - waitUntilDone: NO]; - [cocoaEvent release]; - } + boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_); + if (!isEventInCocoaEventLoop_) { + isEventInCocoaEventLoop_ = true; + + CocoaEvent* cocoaEvent = [[CocoaEvent alloc] init: this]; + [cocoaEvent + performSelectorOnMainThread:@selector(process) + withObject: nil + waitUntilDone: NO]; + [cocoaEvent release]; + } } } diff --git a/Swiften/EventLoop/DummyEventLoop.cpp b/Swiften/EventLoop/DummyEventLoop.cpp index 45e9af7..6eb730a 100644 --- a/Swiften/EventLoop/DummyEventLoop.cpp +++ b/Swiften/EventLoop/DummyEventLoop.cpp @@ -14,26 +14,26 @@ DummyEventLoop::DummyEventLoop() : hasEvents_(false) { } DummyEventLoop::~DummyEventLoop() { - if (hasEvents()) { - std::cerr << "DummyEventLoop: Unhandled events at destruction time" << std::endl; - } + if (hasEvents()) { + std::cerr << "DummyEventLoop: Unhandled events at destruction time" << std::endl; + } } void DummyEventLoop::processEvents() { - while(hasEvents()) { - hasEvents_ = false; - handleNextEvents(); - } + while(hasEvents()) { + hasEvents_ = false; + handleNextEvents(); + } } bool DummyEventLoop::hasEvents() { - boost::lock_guard<boost::mutex> lock(hasEventsMutex_); - return hasEvents_; + boost::lock_guard<boost::mutex> lock(hasEventsMutex_); + return hasEvents_; } void DummyEventLoop::eventPosted() { - boost::lock_guard<boost::mutex> lock(hasEventsMutex_); - hasEvents_ = true; + boost::lock_guard<boost::mutex> lock(hasEventsMutex_); + hasEvents_ = true; } } diff --git a/Swiften/EventLoop/DummyEventLoop.h b/Swiften/EventLoop/DummyEventLoop.h index b41cd09..b78c1a6 100644 --- a/Swiften/EventLoop/DummyEventLoop.h +++ b/Swiften/EventLoop/DummyEventLoop.h @@ -15,19 +15,19 @@ #include <Swiften/EventLoop/EventLoop.h> namespace Swift { - class SWIFTEN_API DummyEventLoop : public EventLoop { - public: - DummyEventLoop(); - virtual ~DummyEventLoop(); + class SWIFTEN_API DummyEventLoop : public EventLoop { + public: + DummyEventLoop(); + virtual ~DummyEventLoop(); - void processEvents(); + void processEvents(); - bool hasEvents(); + bool hasEvents(); - virtual void eventPosted(); + virtual void eventPosted(); - private: - bool hasEvents_; - boost::mutex hasEventsMutex_; - }; + private: + bool hasEvents_; + boost::mutex hasEventsMutex_; + }; } diff --git a/Swiften/EventLoop/Event.cpp b/Swiften/EventLoop/Event.cpp index f3ea228..15d7146 100644 --- a/Swiften/EventLoop/Event.cpp +++ b/Swiften/EventLoop/Event.cpp @@ -10,13 +10,13 @@ #include <typeinfo> std::ostream& operator<<(std::ostream& os, const Swift::Event& e) { - os << "Event(" << e.id << ","; - if (e.owner) { - os << typeid(*e.owner.get()).name(); - } - else { - os << "null"; - } - os << ")"; - return os; + os << "Event(" << e.id << ","; + if (e.owner) { + os << typeid(*e.owner.get()).name(); + } + else { + os << "null"; + } + os << ")"; + return os; } diff --git a/Swiften/EventLoop/Event.h b/Swiften/EventLoop/Event.h index 4585eb3..eecd896 100644 --- a/Swiften/EventLoop/Event.h +++ b/Swiften/EventLoop/Event.h @@ -12,19 +12,19 @@ #include <Swiften/EventLoop/EventOwner.h> namespace Swift { - class Event { - public: - Event(boost::shared_ptr<EventOwner> owner, const boost::function<void()>& callback) : id(~0U), owner(owner), callback(callback) { - } + class Event { + public: + Event(boost::shared_ptr<EventOwner> owner, const boost::function<void()>& callback) : id(~0U), owner(owner), callback(callback) { + } - bool operator==(const Event& o) const { - return o.id == id; - } + bool operator==(const Event& o) const { + return o.id == id; + } - unsigned int id; - boost::shared_ptr<EventOwner> owner; - boost::function<void()> callback; - }; + unsigned int id; + boost::shared_ptr<EventOwner> owner; + boost::function<void()> callback; + }; } std::ostream& operator<<(std::ostream& os, const Swift::Event& e); diff --git a/Swiften/EventLoop/EventLoop.cpp b/Swiften/EventLoop/EventLoop.cpp index 8e7add5..2434277 100644 --- a/Swiften/EventLoop/EventLoop.cpp +++ b/Swiften/EventLoop/EventLoop.cpp @@ -23,16 +23,16 @@ namespace lambda = boost::lambda; namespace Swift { inline void invokeCallback(const Event& event) { - try { - assert(!event.callback.empty()); - event.callback(); - } - catch (const std::exception& e) { - SWIFT_LOG(error) << "Uncaught exception in event loop: " << e.what() << std::endl; - } - catch (...) { - SWIFT_LOG(error) << "Uncaught non-exception in event loop" << std::endl; - } + try { + assert(!event.callback.empty()); + event.callback(); + } + catch (const std::exception& e) { + SWIFT_LOG(error) << "Uncaught exception in event loop: " << e.what() << std::endl; + } + catch (...) { + SWIFT_LOG(error) << "Uncaught non-exception in event loop" << std::endl; + } } EventLoop::EventLoop() : nextEventID_(0), handlingEvents_(false) { @@ -42,59 +42,59 @@ EventLoop::~EventLoop() { } void EventLoop::handleNextEvents() { - const int eventsBatched = 100; - // If handleNextEvents is already in progress, e.g. in case of a recursive call due to - // the event loop implementation, then do no handle further events. Instead call - // eventPosted() to continue event handling later. - bool callEventPosted = handlingEvents_; - if (!handlingEvents_) { - handlingEvents_ = true; - boost::recursive_mutex::scoped_lock lock(removeEventsMutex_); - { - std::vector<Event> nextEvents; - { - boost::recursive_mutex::scoped_lock lock(eventsMutex_); - for (int n = 0; ((n < eventsBatched) && !events_.empty()); n++) { - nextEvents.push_back(events_.front()); - events_.pop_front(); - } - callEventPosted = !events_.empty(); - } - if (!nextEvents.empty()) { - foreach (const Event& event, nextEvents) { - invokeCallback(event); - } - } - } - handlingEvents_ = false; - } - - if (callEventPosted) { - eventPosted(); - } + const int eventsBatched = 100; + // If handleNextEvents is already in progress, e.g. in case of a recursive call due to + // the event loop implementation, then do no handle further events. Instead call + // eventPosted() to continue event handling later. + bool callEventPosted = handlingEvents_; + if (!handlingEvents_) { + handlingEvents_ = true; + boost::recursive_mutex::scoped_lock lock(removeEventsMutex_); + { + std::vector<Event> nextEvents; + { + boost::recursive_mutex::scoped_lock lock(eventsMutex_); + for (int n = 0; ((n < eventsBatched) && !events_.empty()); n++) { + nextEvents.push_back(events_.front()); + events_.pop_front(); + } + callEventPosted = !events_.empty(); + } + if (!nextEvents.empty()) { + foreach (const Event& event, nextEvents) { + invokeCallback(event); + } + } + } + handlingEvents_ = false; + } + + if (callEventPosted) { + eventPosted(); + } } void EventLoop::postEvent(boost::function<void ()> callback, boost::shared_ptr<EventOwner> owner) { - Event event(owner, callback); - bool callEventPosted = false; - { - boost::recursive_mutex::scoped_lock lock(eventsMutex_); - - callEventPosted = events_.empty(); - - event.id = nextEventID_; - nextEventID_++; - events_.push_back(event); - } - if (callEventPosted) { - eventPosted(); - } + Event event(owner, callback); + bool callEventPosted = false; + { + boost::recursive_mutex::scoped_lock lock(eventsMutex_); + + callEventPosted = events_.empty(); + + event.id = nextEventID_; + nextEventID_++; + events_.push_back(event); + } + if (callEventPosted) { + eventPosted(); + } } void EventLoop::removeEventsFromOwner(boost::shared_ptr<EventOwner> owner) { - boost::recursive_mutex::scoped_lock removeLock(removeEventsMutex_); - boost::recursive_mutex::scoped_lock lock(eventsMutex_); - events_.remove_if(lambda::bind(&Event::owner, lambda::_1) == owner); + boost::recursive_mutex::scoped_lock removeLock(removeEventsMutex_); + boost::recursive_mutex::scoped_lock lock(eventsMutex_); + events_.remove_if(lambda::bind(&Event::owner, lambda::_1) == owner); } } diff --git a/Swiften/EventLoop/EventLoop.h b/Swiften/EventLoop/EventLoop.h index 2687501..84a3e9d 100644 --- a/Swiften/EventLoop/EventLoop.h +++ b/Swiften/EventLoop/EventLoop.h @@ -15,57 +15,57 @@ #include <Swiften/EventLoop/Event.h> namespace Swift { - class EventOwner; + class EventOwner; - /** - * The \ref EventLoop class provides the abstract interface for implementing event loops to use with Swiften. - * - * Events are added to the event queue using the \ref postEvent method and can be removed from the queue using - * the \ref removeEventsFromOwner method. - */ - class SWIFTEN_API EventLoop { - public: - EventLoop(); - virtual ~EventLoop(); + /** + * The \ref EventLoop class provides the abstract interface for implementing event loops to use with Swiften. + * + * Events are added to the event queue using the \ref postEvent method and can be removed from the queue using + * the \ref removeEventsFromOwner method. + */ + class SWIFTEN_API EventLoop { + public: + EventLoop(); + virtual ~EventLoop(); - /** - * The \ref postEvent method allows events to be added to the event queue of the \ref EventLoop. - * An optional \ref EventOwner can be passed, allowing later removal of events that have not yet been - * executed using the \ref removeEventsFromOwner method. - */ - void postEvent(boost::function<void ()> event, boost::shared_ptr<EventOwner> owner = boost::shared_ptr<EventOwner>()); + /** + * The \ref postEvent method allows events to be added to the event queue of the \ref EventLoop. + * An optional \ref EventOwner can be passed, allowing later removal of events that have not yet been + * executed using the \ref removeEventsFromOwner method. + */ + void postEvent(boost::function<void ()> event, boost::shared_ptr<EventOwner> owner = boost::shared_ptr<EventOwner>()); - /** - * The \ref removeEventsFromOwner method removes all events from the specified \ref owner from the - * event queue. - */ - void removeEventsFromOwner(boost::shared_ptr<EventOwner> owner); + /** + * The \ref removeEventsFromOwner method removes all events from the specified \ref owner from the + * event queue. + */ + void removeEventsFromOwner(boost::shared_ptr<EventOwner> owner); - protected: - /** - * The \ref handleNextEvents method is called by an implementation of the abstract \ref EventLoop class - * at any point after the virtual \ref eventPosted method has been called. - * This method does not block, except for short-time synchronization. - * It can process multiple events before it reutrns. - * If called recursively, the event queue is not further processed. Instead, \ref eventPosted - * is called to notify the implementing event loop of the non-empty event queue. - * It is recommended to not call \ref handleNextEvents inside an event posted to the event loop - * as this can lead to an infinite loop. - */ - void handleNextEvents(); + protected: + /** + * The \ref handleNextEvents method is called by an implementation of the abstract \ref EventLoop class + * at any point after the virtual \ref eventPosted method has been called. + * This method does not block, except for short-time synchronization. + * It can process multiple events before it reutrns. + * If called recursively, the event queue is not further processed. Instead, \ref eventPosted + * is called to notify the implementing event loop of the non-empty event queue. + * It is recommended to not call \ref handleNextEvents inside an event posted to the event loop + * as this can lead to an infinite loop. + */ + void handleNextEvents(); - /** - * The \ref eventPosted virtual method serves as notification for when events are still available in the queue. - * It is called after the first event is posted to an empty queue or after an event has been handled in - * \ref handleNextEvents and there are still remaining events in the queue. - */ - virtual void eventPosted() = 0; + /** + * The \ref eventPosted virtual method serves as notification for when events are still available in the queue. + * It is called after the first event is posted to an empty queue or after an event has been handled in + * \ref handleNextEvents and there are still remaining events in the queue. + */ + virtual void eventPosted() = 0; - private: - unsigned int nextEventID_; - std::list<Event> events_; - bool handlingEvents_; - boost::recursive_mutex eventsMutex_; - boost::recursive_mutex removeEventsMutex_; - }; + private: + unsigned int nextEventID_; + std::list<Event> events_; + bool handlingEvents_; + boost::recursive_mutex eventsMutex_; + boost::recursive_mutex removeEventsMutex_; + }; } diff --git a/Swiften/EventLoop/EventOwner.h b/Swiften/EventLoop/EventOwner.h index a62a778..cd4a80b 100644 --- a/Swiften/EventLoop/EventOwner.h +++ b/Swiften/EventLoop/EventOwner.h @@ -9,8 +9,8 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API EventOwner { - public: - virtual ~EventOwner(); - }; + class SWIFTEN_API EventOwner { + public: + virtual ~EventOwner(); + }; } diff --git a/Swiften/EventLoop/Qt/QtEventLoop.h b/Swiften/EventLoop/Qt/QtEventLoop.h index 123b6e8..3f5e93c 100644 --- a/Swiften/EventLoop/Qt/QtEventLoop.h +++ b/Swiften/EventLoop/Qt/QtEventLoop.h @@ -15,45 +15,45 @@ #include <Swiften/EventLoop/EventLoop.h> namespace Swift { - class QtEventLoop : public QObject, public EventLoop { - public: - QtEventLoop() : isEventInQtEventLoop_(false) {} - virtual ~QtEventLoop() { - QCoreApplication::removePostedEvents(this); - } - - protected: - virtual void eventPosted() { - boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_); - if (!isEventInQtEventLoop_) { - isEventInQtEventLoop_ = true; - QCoreApplication::postEvent(this, new Event()); - } - } - - virtual bool event(QEvent* qevent) { - Event* event = dynamic_cast<Event*>(qevent); - if (event) { - { - boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_); - isEventInQtEventLoop_ = false; - } - handleNextEvents(); - //event->deleteLater(); FIXME: Leak? - return true; - } - - return false; - } - - private: - struct Event : public QEvent { - Event() : - QEvent(QEvent::User) { - } - }; - - bool isEventInQtEventLoop_; - boost::recursive_mutex isEventInQtEventLoopMutex_; - }; + class QtEventLoop : public QObject, public EventLoop { + public: + QtEventLoop() : isEventInQtEventLoop_(false) {} + virtual ~QtEventLoop() { + QCoreApplication::removePostedEvents(this); + } + + protected: + virtual void eventPosted() { + boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_); + if (!isEventInQtEventLoop_) { + isEventInQtEventLoop_ = true; + QCoreApplication::postEvent(this, new Event()); + } + } + + virtual bool event(QEvent* qevent) { + Event* event = dynamic_cast<Event*>(qevent); + if (event) { + { + boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_); + isEventInQtEventLoop_ = false; + } + handleNextEvents(); + //event->deleteLater(); FIXME: Leak? + return true; + } + + return false; + } + + private: + struct Event : public QEvent { + Event() : + QEvent(QEvent::User) { + } + }; + + bool isEventInQtEventLoop_; + boost::recursive_mutex isEventInQtEventLoopMutex_; + }; } diff --git a/Swiften/EventLoop/SimpleEventLoop.cpp b/Swiften/EventLoop/SimpleEventLoop.cpp index 59e799f..37fecd9 100644 --- a/Swiften/EventLoop/SimpleEventLoop.cpp +++ b/Swiften/EventLoop/SimpleEventLoop.cpp @@ -19,40 +19,40 @@ SimpleEventLoop::~SimpleEventLoop() { } void SimpleEventLoop::doRun(bool breakAfterEvents) { - while (isRunning_) { - { - boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); - while (!eventAvailable_) { - eventAvailableCondition_.wait(lock); - } - - eventAvailable_ = false; - } - runOnce(); - if (breakAfterEvents) { - return; - } - } + while (isRunning_) { + { + boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); + while (!eventAvailable_) { + eventAvailableCondition_.wait(lock); + } + + eventAvailable_ = false; + } + runOnce(); + if (breakAfterEvents) { + return; + } + } } void SimpleEventLoop::runOnce() { - handleNextEvents(); + handleNextEvents(); } void SimpleEventLoop::stop() { - postEvent(boost::bind(&SimpleEventLoop::doStop, this)); + postEvent(boost::bind(&SimpleEventLoop::doStop, this)); } void SimpleEventLoop::doStop() { - isRunning_ = false; + isRunning_ = false; } void SimpleEventLoop::eventPosted() { - { - boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); - eventAvailable_ = true; - } - eventAvailableCondition_.notify_one(); + { + boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); + eventAvailable_ = true; + } + eventAvailableCondition_.notify_one(); } diff --git a/Swiften/EventLoop/SimpleEventLoop.h b/Swiften/EventLoop/SimpleEventLoop.h index 6374a8a..98b3554 100644 --- a/Swiften/EventLoop/SimpleEventLoop.h +++ b/Swiften/EventLoop/SimpleEventLoop.h @@ -13,35 +13,35 @@ #include <Swiften/EventLoop/EventLoop.h> namespace Swift { - class SWIFTEN_API SimpleEventLoop : public EventLoop { - public: - SimpleEventLoop(); - virtual ~SimpleEventLoop(); + class SWIFTEN_API SimpleEventLoop : public EventLoop { + public: + SimpleEventLoop(); + virtual ~SimpleEventLoop(); - void run() { - doRun(false); - } + void run() { + doRun(false); + } - void runUntilEvents() { - doRun(true); - } + void runUntilEvents() { + doRun(true); + } - void runOnce(); + void runOnce(); - void stop(); - - protected: - virtual void eventPosted(); + void stop(); - private: - void doRun(bool breakAfterEvents); - void doStop(); + protected: + virtual void eventPosted(); - private: - bool isRunning_; + private: + void doRun(bool breakAfterEvents); + void doStop(); - bool eventAvailable_; - boost::mutex eventAvailableMutex_; - boost::condition_variable eventAvailableCondition_; - }; + private: + bool isRunning_; + + bool eventAvailable_; + boost::mutex eventAvailableMutex_; + boost::condition_variable eventAvailableCondition_; + }; } diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.cpp b/Swiften/EventLoop/SingleThreadedEventLoop.cpp index c94b085..093b913 100644 --- a/Swiften/EventLoop/SingleThreadedEventLoop.cpp +++ b/Swiften/EventLoop/SingleThreadedEventLoop.cpp @@ -20,7 +20,7 @@ namespace Swift { -SingleThreadedEventLoop::SingleThreadedEventLoop() +SingleThreadedEventLoop::SingleThreadedEventLoop() : shouldShutDown_(false), eventAvailable_(false) { } @@ -30,33 +30,33 @@ SingleThreadedEventLoop::~SingleThreadedEventLoop() { } void SingleThreadedEventLoop::waitForEvents() { - boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); - while (!eventAvailable_ && !shouldShutDown_) { - eventAvailableCondition_.wait(lock); - } + boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); + while (!eventAvailable_ && !shouldShutDown_) { + eventAvailableCondition_.wait(lock); + } - if (shouldShutDown_) - throw EventLoopCanceledException(); + if (shouldShutDown_) + throw EventLoopCanceledException(); } void SingleThreadedEventLoop::handleEvents() { - { - boost::lock_guard<boost::mutex> lock(eventAvailableMutex_); - eventAvailable_ = false; - } - handleNextEvents(); + { + boost::lock_guard<boost::mutex> lock(eventAvailableMutex_); + eventAvailable_ = false; + } + handleNextEvents(); } void SingleThreadedEventLoop::stop() { - boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); - shouldShutDown_ = true; - eventAvailableCondition_.notify_one(); + boost::unique_lock<boost::mutex> lock(eventAvailableMutex_); + shouldShutDown_ = true; + eventAvailableCondition_.notify_one(); } void SingleThreadedEventLoop::eventPosted() { - boost::lock_guard<boost::mutex> lock(eventAvailableMutex_); - eventAvailable_ = true; - eventAvailableCondition_.notify_one(); + boost::lock_guard<boost::mutex> lock(eventAvailableMutex_); + eventAvailable_ = true; + eventAvailableCondition_.notify_one(); } } // namespace Swift diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.h b/Swiften/EventLoop/SingleThreadedEventLoop.h index 39f3fe3..eb897bf 100644 --- a/Swiften/EventLoop/SingleThreadedEventLoop.h +++ b/Swiften/EventLoop/SingleThreadedEventLoop.h @@ -29,39 +29,39 @@ // The SingleThreadedEventLoop class implements an event loop that can be used from such applications. // // USAGE: -// -// Spawn a new thread in the desired framework and call SingleThreadedEventLoop::waitForEvents(). The method +// +// Spawn a new thread in the desired framework and call SingleThreadedEventLoop::waitForEvents(). The method // blocks until a new event has arrived at which time it'll return, or until the wait is canceled -// at which time it throws EventLoopCanceledException. +// at which time it throws EventLoopCanceledException. // // When a new event has arrived and SingleThreadedEventLoop::waitForEvents() returns, the caller should then -// call SingleThreadedEventLoop::handleEvents() on the main GUI thread. For WPF applications, for instance, +// call SingleThreadedEventLoop::handleEvents() on the main GUI thread. For WPF applications, for instance, // the Dispatcher class can be used to execute the call on the GUI thread. // namespace Swift { - class SingleThreadedEventLoop : public EventLoop { - public: - class EventLoopCanceledException : public std::exception { }; + class SingleThreadedEventLoop : public EventLoop { + public: + class EventLoopCanceledException : public std::exception { }; + + public: + SingleThreadedEventLoop(); + virtual ~SingleThreadedEventLoop(); - public: - SingleThreadedEventLoop(); - virtual ~SingleThreadedEventLoop(); + // Blocks while waiting for new events and returns when new events are available. + // Throws EventLoopCanceledException when the wait is canceled. + void waitForEvents(); + void handleEvents(); + void stop(); - // Blocks while waiting for new events and returns when new events are available. - // Throws EventLoopCanceledException when the wait is canceled. - void waitForEvents(); - void handleEvents(); - void stop(); + protected: + virtual void eventPosted(); - protected: - virtual void eventPosted(); - - private: - bool shouldShutDown_; + private: + bool shouldShutDown_; - bool eventAvailable_; - boost::mutex eventAvailableMutex_; - boost::condition_variable eventAvailableCondition_; - }; + bool eventAvailable_; + boost::mutex eventAvailableMutex_; + boost::condition_variable eventAvailableCondition_; + }; } diff --git a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp index d1274e1..1028b7e 100644 --- a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp +++ b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp @@ -18,74 +18,74 @@ using namespace Swift; class EventLoopTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(EventLoopTest); - CPPUNIT_TEST(testPost); - CPPUNIT_TEST(testRemove); - CPPUNIT_TEST(testHandleEvent_Recursive); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - events_.clear(); - } - - void testPost() { - SimpleEventLoop testling; - - testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1)); - testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2)); - testling.stop(); - testling.run(); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size())); - CPPUNIT_ASSERT_EQUAL(1, events_[0]); - CPPUNIT_ASSERT_EQUAL(2, events_[1]); - } - - void testRemove() { - SimpleEventLoop testling; - boost::shared_ptr<MyEventOwner> eventOwner1(new MyEventOwner()); - boost::shared_ptr<MyEventOwner> eventOwner2(new MyEventOwner()); - - testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner1); - testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2), eventOwner2); - testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 3), eventOwner1); - testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 4), eventOwner2); - testling.removeEventsFromOwner(eventOwner2); - testling.stop(); - testling.run(); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size())); - CPPUNIT_ASSERT_EQUAL(1, events_[0]); - CPPUNIT_ASSERT_EQUAL(3, events_[1]); - } - - void testHandleEvent_Recursive() { - DummyEventLoop testling; - boost::shared_ptr<MyEventOwner> eventOwner(new MyEventOwner()); - - testling.postEvent(boost::bind(&EventLoopTest::runEventLoop, this, &testling, eventOwner), eventOwner); - testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 0), eventOwner); - testling.processEvents(); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size())); - CPPUNIT_ASSERT_EQUAL(0, events_[0]); - CPPUNIT_ASSERT_EQUAL(1, events_[1]); - } - - private: - struct MyEventOwner : public EventOwner {}; - void logEvent(int i) { - events_.push_back(i); - } - void runEventLoop(DummyEventLoop* loop, boost::shared_ptr<MyEventOwner> eventOwner) { - loop->processEvents(); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(events_.size())); - loop->postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner); - } - - private: - std::vector<int> events_; + CPPUNIT_TEST_SUITE(EventLoopTest); + CPPUNIT_TEST(testPost); + CPPUNIT_TEST(testRemove); + CPPUNIT_TEST(testHandleEvent_Recursive); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + events_.clear(); + } + + void testPost() { + SimpleEventLoop testling; + + testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1)); + testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2)); + testling.stop(); + testling.run(); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size())); + CPPUNIT_ASSERT_EQUAL(1, events_[0]); + CPPUNIT_ASSERT_EQUAL(2, events_[1]); + } + + void testRemove() { + SimpleEventLoop testling; + boost::shared_ptr<MyEventOwner> eventOwner1(new MyEventOwner()); + boost::shared_ptr<MyEventOwner> eventOwner2(new MyEventOwner()); + + testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner1); + testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2), eventOwner2); + testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 3), eventOwner1); + testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 4), eventOwner2); + testling.removeEventsFromOwner(eventOwner2); + testling.stop(); + testling.run(); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size())); + CPPUNIT_ASSERT_EQUAL(1, events_[0]); + CPPUNIT_ASSERT_EQUAL(3, events_[1]); + } + + void testHandleEvent_Recursive() { + DummyEventLoop testling; + boost::shared_ptr<MyEventOwner> eventOwner(new MyEventOwner()); + + testling.postEvent(boost::bind(&EventLoopTest::runEventLoop, this, &testling, eventOwner), eventOwner); + testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 0), eventOwner); + testling.processEvents(); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size())); + CPPUNIT_ASSERT_EQUAL(0, events_[0]); + CPPUNIT_ASSERT_EQUAL(1, events_[1]); + } + + private: + struct MyEventOwner : public EventOwner {}; + void logEvent(int i) { + events_.push_back(i); + } + void runEventLoop(DummyEventLoop* loop, boost::shared_ptr<MyEventOwner> eventOwner) { + loop->processEvents(); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(events_.size())); + loop->postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner); + } + + private: + std::vector<int> events_; }; CPPUNIT_TEST_SUITE_REGISTRATION(EventLoopTest); diff --git a/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp b/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp index 1748953..167fe45 100644 --- a/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp +++ b/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp @@ -16,53 +16,53 @@ using namespace Swift; class SimpleEventLoopTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SimpleEventLoopTest); - // FIXME: Temporarily disabling run, because it generates a "vector - // iterator not incrementable" on XP - //CPPUNIT_TEST(testRun); - CPPUNIT_TEST(testPostFromMainThread); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(SimpleEventLoopTest); + // FIXME: Temporarily disabling run, because it generates a "vector + // iterator not incrementable" on XP + //CPPUNIT_TEST(testRun); + CPPUNIT_TEST(testPostFromMainThread); + CPPUNIT_TEST_SUITE_END(); - public: - void setUp() { - counter_ = 0; - } + public: + void setUp() { + counter_ = 0; + } - void testRun() { - SimpleEventLoop testling; - boost::thread thread(boost::bind(&SimpleEventLoopTest::runIncrementingThread, this, &testling)); - testling.run(); + void testRun() { + SimpleEventLoop testling; + boost::thread thread(boost::bind(&SimpleEventLoopTest::runIncrementingThread, this, &testling)); + testling.run(); - CPPUNIT_ASSERT_EQUAL(10, counter_); - } + CPPUNIT_ASSERT_EQUAL(10, counter_); + } - void testPostFromMainThread() { - SimpleEventLoop testling; - testling.postEvent(boost::bind(&SimpleEventLoopTest::incrementCounterAndStop, this, &testling)); - testling.run(); + void testPostFromMainThread() { + SimpleEventLoop testling; + testling.postEvent(boost::bind(&SimpleEventLoopTest::incrementCounterAndStop, this, &testling)); + testling.run(); - CPPUNIT_ASSERT_EQUAL(1, counter_); - } + CPPUNIT_ASSERT_EQUAL(1, counter_); + } - private: - void runIncrementingThread(SimpleEventLoop* loop) { - for (unsigned int i = 0; i < 10; ++i) { - Swift::sleep(1); - loop->postEvent(boost::bind(&SimpleEventLoopTest::incrementCounter, this)); - } - loop->stop(); - } + private: + void runIncrementingThread(SimpleEventLoop* loop) { + for (unsigned int i = 0; i < 10; ++i) { + Swift::sleep(1); + loop->postEvent(boost::bind(&SimpleEventLoopTest::incrementCounter, this)); + } + loop->stop(); + } - void incrementCounter() { - counter_++; - } + void incrementCounter() { + counter_++; + } - void incrementCounterAndStop(SimpleEventLoop* loop) { - counter_++; - loop->stop(); - } + void incrementCounterAndStop(SimpleEventLoop* loop) { + counter_++; + loop->stop(); + } - int counter_; + int counter_; }; CPPUNIT_TEST_SUITE_REGISTRATION(SimpleEventLoopTest); diff --git a/Swiften/Examples/BenchTool/BenchTool.cpp b/Swiften/Examples/BenchTool/BenchTool.cpp index 49ecd92..f7337b9 100644 --- a/Swiften/Examples/BenchTool/BenchTool.cpp +++ b/Swiften/Examples/BenchTool/BenchTool.cpp @@ -28,40 +28,40 @@ static int numberOfInstances = 100; static void handleConnected() { - numberOfConnectedClients++; - std::cout << "Connected " << numberOfConnectedClients << std::endl; + numberOfConnectedClients++; + std::cout << "Connected " << numberOfConnectedClients << std::endl; } int main(int, char**) { - char* jid = getenv("SWIFT_BENCHTOOL_JID"); - if (!jid) { - std::cerr << "Please set the SWIFT_BENCHTOOL_JID environment variable" << std::endl; - return -1; - } - char* pass = getenv("SWIFT_BENCHTOOL_PASS"); - if (!pass) { - std::cerr << "Please set the SWIFT_BENCHTOOL_PASS environment variable" << std::endl; - return -1; - } + char* jid = getenv("SWIFT_BENCHTOOL_JID"); + if (!jid) { + std::cerr << "Please set the SWIFT_BENCHTOOL_JID environment variable" << std::endl; + return -1; + } + char* pass = getenv("SWIFT_BENCHTOOL_PASS"); + if (!pass) { + std::cerr << "Please set the SWIFT_BENCHTOOL_PASS environment variable" << std::endl; + return -1; + } - BlindCertificateTrustChecker trustChecker; - std::vector<CoreClient*> clients; - for (int i = 0; i < numberOfInstances; ++i) { - CoreClient* client = new Swift::CoreClient(JID(jid), createSafeByteArray(std::string(pass)), &networkFactories); - client->setCertificateTrustChecker(&trustChecker); - client->onConnected.connect(&handleConnected); - clients.push_back(client); - } - - for (size_t i = 0; i < clients.size(); ++i) { - clients[i]->connect(); - } + BlindCertificateTrustChecker trustChecker; + std::vector<CoreClient*> clients; + for (int i = 0; i < numberOfInstances; ++i) { + CoreClient* client = new Swift::CoreClient(JID(jid), createSafeByteArray(std::string(pass)), &networkFactories); + client->setCertificateTrustChecker(&trustChecker); + client->onConnected.connect(&handleConnected); + clients.push_back(client); + } - eventLoop.run(); + for (size_t i = 0; i < clients.size(); ++i) { + clients[i]->connect(); + } - for (size_t i = 0; i < clients.size(); ++i) { - delete clients[i]; - } + eventLoop.run(); - return 0; + for (size_t i = 0; i < clients.size(); ++i) { + delete clients[i]; + } + + return 0; } diff --git a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp index 8d1da38..50f857c 100644 --- a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp +++ b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp @@ -31,72 +31,72 @@ static int exitCode = CANNOT_CONNECT; static boost::bsignals::connection errorConnection; static void handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> /*info*/, ErrorPayload::ref error) { - if (!error) { - errorConnection.disconnect(); - client->disconnect(); - eventLoop.stop(); - exitCode = OK; - } else { - errorConnection.disconnect(); - exitCode = DISCO_ERROR; - } + if (!error) { + errorConnection.disconnect(); + client->disconnect(); + eventLoop.stop(); + exitCode = OK; + } else { + errorConnection.disconnect(); + exitCode = DISCO_ERROR; + } } static void handleConnected() { - exitCode = NO_RESPONSE; - GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(), client->getIQRouter()); - discoInfoRequest->onResponse.connect(&handleServerDiscoInfoResponse); - discoInfoRequest->send(); + exitCode = NO_RESPONSE; + GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(), client->getIQRouter()); + discoInfoRequest->onResponse.connect(&handleServerDiscoInfoResponse); + discoInfoRequest->send(); } static void handleDisconnected(const boost::optional<ClientError>&) { - exitCode = CANNOT_AUTH; - eventLoop.stop(); + exitCode = CANNOT_AUTH; + eventLoop.stop(); } int main(int argc, char* argv[]) { - if (argc < 4 || argc > 5) { - std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>] <password> <timeout_seconds>" << std::endl; - return -1; - } - - int argi = 1; - - std::string jid = argv[argi++]; - std::string connectHost = ""; - if (argc == 5) { - connectHost = argv[argi++]; - } - - client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories); - char* timeoutChar = argv[argi++]; - int timeout = atoi(timeoutChar); - timeout = (timeout ? timeout : 30) * 1000; - ClientXMLTracer* tracer = new ClientXMLTracer(client); - client->onConnected.connect(&handleConnected); - errorConnection = client->onDisconnected.connect(&handleDisconnected); - std::cout << "Connecting to JID " << jid << " with timeout " << timeout << "ms on host: "; ; - if (!connectHost.empty()) { - std::cout << connectHost << std::endl; - ClientOptions options; - options.manualHostname = connectHost; - client->connect(options); - } else { - std::cout << " Default" << std::endl; - client->connect(); - } - - { - Timer::ref timer = networkFactories.getTimerFactory()->createTimer(timeout); - timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); - timer->start(); - - eventLoop.run(); - } - - delete tracer; - delete client; - return exitCode; + if (argc < 4 || argc > 5) { + std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>] <password> <timeout_seconds>" << std::endl; + return -1; + } + + int argi = 1; + + std::string jid = argv[argi++]; + std::string connectHost = ""; + if (argc == 5) { + connectHost = argv[argi++]; + } + + client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories); + char* timeoutChar = argv[argi++]; + int timeout = atoi(timeoutChar); + timeout = (timeout ? timeout : 30) * 1000; + ClientXMLTracer* tracer = new ClientXMLTracer(client); + client->onConnected.connect(&handleConnected); + errorConnection = client->onDisconnected.connect(&handleDisconnected); + std::cout << "Connecting to JID " << jid << " with timeout " << timeout << "ms on host: "; ; + if (!connectHost.empty()) { + std::cout << connectHost << std::endl; + ClientOptions options; + options.manualHostname = connectHost; + client->connect(options); + } else { + std::cout << " Default" << std::endl; + client->connect(); + } + + { + Timer::ref timer = networkFactories.getTimerFactory()->createTimer(timeout); + timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); + timer->start(); + + eventLoop.run(); + } + + delete tracer; + delete client; + return exitCode; } diff --git a/Swiften/Examples/LinkLocalTool/main.cpp b/Swiften/Examples/LinkLocalTool/main.cpp index dabce57..37804fb 100644 --- a/Swiften/Examples/LinkLocalTool/main.cpp +++ b/Swiften/Examples/LinkLocalTool/main.cpp @@ -17,33 +17,33 @@ using namespace Swift; int main(int argc, char* argv[]) { - if (argc < 2) { - std::cerr << "Invalid parameters" << std::endl; - return -1; - } - - SimpleEventLoop eventLoop; - PlatformDNSSDQuerierFactory factory(&eventLoop); - boost::shared_ptr<DNSSDQuerier> querier = factory.createQuerier(); - querier->start(); - - if (std::string(argv[1]) == "browse") { - boost::shared_ptr<DNSSDBrowseQuery> browseQuery = querier->createBrowseQuery(); - browseQuery->startBrowsing(); - eventLoop.run(); - browseQuery->stopBrowsing(); - } - else if (std::string(argv[1]) == "resolve-service") { - if (argc < 5) { - std::cerr << "Invalid parameters" << std::endl; - return -1; - } - boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(DNSSDServiceID(argv[2], argv[3], argv[4])); - resolveQuery->start(); - eventLoop.run(); - std::cerr << "Done running" << std::endl; - resolveQuery->stop(); - } - - querier->stop(); + if (argc < 2) { + std::cerr << "Invalid parameters" << std::endl; + return -1; + } + + SimpleEventLoop eventLoop; + PlatformDNSSDQuerierFactory factory(&eventLoop); + boost::shared_ptr<DNSSDQuerier> querier = factory.createQuerier(); + querier->start(); + + if (std::string(argv[1]) == "browse") { + boost::shared_ptr<DNSSDBrowseQuery> browseQuery = querier->createBrowseQuery(); + browseQuery->startBrowsing(); + eventLoop.run(); + browseQuery->stopBrowsing(); + } + else if (std::string(argv[1]) == "resolve-service") { + if (argc < 5) { + std::cerr << "Invalid parameters" << std::endl; + return -1; + } + boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(DNSSDServiceID(argv[2], argv[3], argv[4])); + resolveQuery->start(); + eventLoop.run(); + std::cerr << "Done running" << std::endl; + resolveQuery->stop(); + } + + querier->stop(); } diff --git a/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp b/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp index 216d16d..1aaebac 100644 --- a/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp +++ b/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp @@ -33,88 +33,88 @@ static JID mucJID; static JID roomJID; static void joinMUC() { - cout << "Joining " << roomJID.toString() << endl; + cout << "Joining " << roomJID.toString() << endl; - muc = client->getMUCManager()->createMUC(roomJID); - muc->joinAs("SwiftExample"); + muc = client->getMUCManager()->createMUC(roomJID); + muc->joinAs("SwiftExample"); } static void handleRoomsItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error) { - if (error) { - cout << "Error fetching list of rooms." << endl; - return; - } - - int roomCount = 0; - cout << "List of rooms at " << mucJID.toString() << endl; - foreach (DiscoItems::Item item, items->getItems()) { - roomCount++; - cout << "\t" << roomCount << ". " << item.getJID().getNode() << " - " << item.getName() << std::endl; - if (roomCount == 1) { - roomJID = item.getJID(); - } - } - cout << endl; - joinMUC(); + if (error) { + cout << "Error fetching list of rooms." << endl; + return; + } + + int roomCount = 0; + cout << "List of rooms at " << mucJID.toString() << endl; + foreach (DiscoItems::Item item, items->getItems()) { + roomCount++; + cout << "\t" << roomCount << ". " << item.getJID().getNode() << " - " << item.getName() << std::endl; + if (roomCount == 1) { + roomJID = item.getJID(); + } + } + cout << endl; + joinMUC(); } static void handleConnected() { - cout << "Connected." << endl; - // search for MUC rooms + cout << "Connected." << endl; + // search for MUC rooms - GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(mucJID, client->getIQRouter()); - discoItemsRequest->onResponse.connect(&handleRoomsItemsResponse); + GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(mucJID, client->getIQRouter()); + discoItemsRequest->onResponse.connect(&handleRoomsItemsResponse); - cout << "Request list of rooms." << endl; - discoItemsRequest->send(); + cout << "Request list of rooms." << endl; + discoItemsRequest->send(); } static void handleDisconnected(const boost::optional<ClientError>&) { - cout << "Disconnected." << endl; + cout << "Disconnected." << endl; } static void handleIncomingMessage(boost::shared_ptr<Message> message) { - if (message->getFrom().toBare() == roomJID) { - cout << "[ " << roomJID << " ] " << message->getFrom().getResource() << ": " << message->getBody().get_value_or("") << endl; - } + if (message->getFrom().toBare() == roomJID) { + cout << "[ " << roomJID << " ] " << message->getFrom().getResource() << ": " << message->getBody().get_value_or("") << endl; + } } /* * Usage: ./MUCListAndJoin <jid> <password> <muc_domain> */ int main(int argc, char* argv[]) { - int ret = 0; - - if (argc != 4) { - cout << "Usage: ./" << argv[0] << " <jid> <password> <muc_domain>" << endl; - ret = -1; - } - else { - mucJID = JID(argv[3]); - client = boost::make_shared<Client>(JID(argv[1]), string(argv[2]), &networkFactories); - client->setAlwaysTrustCertificates(); - - // Enable the following line for detailed XML logging - // ClientXMLTracer* tracer = new ClientXMLTracer(client.get()); - - client->onConnected.connect(&handleConnected); - client->onDisconnected.connect(&handleDisconnected); - client->onMessageReceived.connect(&handleIncomingMessage); - - cout << "Connecting..." << flush; - client->connect(); - { - Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000); - timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); - - Timer::ref disconnectTimer = networkFactories.getTimerFactory()->createTimer(25000); - disconnectTimer->onTick.connect(boost::bind(&Client::disconnect, client.get())); - - timer->start(); - disconnectTimer->start(); - - eventLoop.run(); - } - } - return ret; + int ret = 0; + + if (argc != 4) { + cout << "Usage: ./" << argv[0] << " <jid> <password> <muc_domain>" << endl; + ret = -1; + } + else { + mucJID = JID(argv[3]); + client = boost::make_shared<Client>(JID(argv[1]), string(argv[2]), &networkFactories); + client->setAlwaysTrustCertificates(); + + // Enable the following line for detailed XML logging + // ClientXMLTracer* tracer = new ClientXMLTracer(client.get()); + + client->onConnected.connect(&handleConnected); + client->onDisconnected.connect(&handleDisconnected); + client->onMessageReceived.connect(&handleIncomingMessage); + + cout << "Connecting..." << flush; + client->connect(); + { + Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000); + timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); + + Timer::ref disconnectTimer = networkFactories.getTimerFactory()->createTimer(25000); + disconnectTimer->onTick.connect(boost::bind(&Client::disconnect, client.get())); + + timer->start(); + disconnectTimer->start(); + + eventLoop.run(); + } + } + return ret; } diff --git a/Swiften/Examples/NetworkTool/main.cpp b/Swiften/Examples/NetworkTool/main.cpp index c3f95e8..0cedfa7 100644 --- a/Swiften/Examples/NetworkTool/main.cpp +++ b/Swiften/Examples/NetworkTool/main.cpp @@ -20,67 +20,67 @@ using namespace Swift; static SimpleEventLoop eventLoop; static void handleGetPublicIPRequestResponse(const boost::optional<HostAddress>& result) { - if (result) { - std::cerr << "Result: " << result->toString() << std::endl;; - } - else { - std::cerr << "No result" << std::endl; - } - eventLoop.stop(); + if (result) { + std::cerr << "Result: " << result->toString() << std::endl;; + } + else { + std::cerr << "No result" << std::endl; + } + eventLoop.stop(); } static void handleGetForwardPortRequestResponse(const boost::optional<NATPortMapping>& result) { - if (result) { - std::cerr << "Result: " << result->getPublicPort() << " -> " << result->getLocalPort() << std::endl;; - } - else { - std::cerr << "No result" << std::endl; - } - eventLoop.stop(); + if (result) { + std::cerr << "Result: " << result->getPublicPort() << " -> " << result->getLocalPort() << std::endl;; + } + else { + std::cerr << "No result" << std::endl; + } + eventLoop.stop(); } static void handleRemovePortForwardingRequestResponse(const boost::optional<bool> result) { - if (result && result.get()) { - std::cerr << "Result: OK" << std::endl; - } - else { - std::cerr << "Result: ERROR" << std::endl; - } - eventLoop.stop(); + if (result && result.get()) { + std::cerr << "Result: OK" << std::endl; + } + else { + std::cerr << "Result: ERROR" << std::endl; + } + eventLoop.stop(); } int main(int argc, char* argv[]) { - if (argc < 2) { - std::cerr << "Invalid parameters" << std::endl; - return -1; - } + if (argc < 2) { + std::cerr << "Invalid parameters" << std::endl; + return -1; + } - PlatformNATTraversalWorker natTraverser(&eventLoop); - if (std::string(argv[1]) == "get-public-ip") { - boost::shared_ptr<NATTraversalGetPublicIPRequest> query = natTraverser.createGetPublicIPRequest(); - query->onResult.connect(boost::bind(&handleGetPublicIPRequestResponse, _1)); - query->start(); - eventLoop.run(); - } - else if (std::string(argv[1]) == "add-port-forward") { - if (argc < 4) { - std::cerr << "Invalid parameters" << std::endl; - } - boost::shared_ptr<NATTraversalForwardPortRequest> query = natTraverser.createForwardPortRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3])); - query->onResult.connect(boost::bind(&handleGetForwardPortRequestResponse, _1)); - query->start(); - eventLoop.run(); - } - else if (std::string(argv[1]) == "remove-port-forward") { - if (argc < 4) { - std::cerr << "Invalid parameters" << std::endl; - } - boost::shared_ptr<NATTraversalRemovePortForwardingRequest> query = natTraverser.createRemovePortForwardingRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3])); - query->onResult.connect(boost::bind(&handleRemovePortForwardingRequestResponse, _1)); - query->start(); - eventLoop.run(); - } - else if (std::string(argv[1]) == "get-local-ip") { - std::cout << PlatformNetworkEnvironment().getLocalAddress().toString() << std::endl; - } + PlatformNATTraversalWorker natTraverser(&eventLoop); + if (std::string(argv[1]) == "get-public-ip") { + boost::shared_ptr<NATTraversalGetPublicIPRequest> query = natTraverser.createGetPublicIPRequest(); + query->onResult.connect(boost::bind(&handleGetPublicIPRequestResponse, _1)); + query->start(); + eventLoop.run(); + } + else if (std::string(argv[1]) == "add-port-forward") { + if (argc < 4) { + std::cerr << "Invalid parameters" << std::endl; + } + boost::shared_ptr<NATTraversalForwardPortRequest> query = natTraverser.createForwardPortRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3])); + query->onResult.connect(boost::bind(&handleGetForwardPortRequestResponse, _1)); + query->start(); + eventLoop.run(); + } + else if (std::string(argv[1]) == "remove-port-forward") { + if (argc < 4) { + std::cerr << "Invalid parameters" << std::endl; + } + boost::shared_ptr<NATTraversalRemovePortForwardingRequest> query = natTraverser.createRemovePortForwardingRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3])); + query->onResult.connect(boost::bind(&handleRemovePortForwardingRequestResponse, _1)); + query->start(); + eventLoop.run(); + } + else if (std::string(argv[1]) == "get-local-ip") { + std::cout << PlatformNetworkEnvironment().getLocalAddress().toString() << std::endl; + } } diff --git a/Swiften/Examples/ParserTester/ParserTester.cpp b/Swiften/Examples/ParserTester/ParserTester.cpp index 25963a6..af79ece 100644 --- a/Swiften/Examples/ParserTester/ParserTester.cpp +++ b/Swiften/Examples/ParserTester/ParserTester.cpp @@ -18,44 +18,44 @@ using namespace Swift; class MyXMPPParserClient : public XMPPParserClient { - public: - virtual void handleStreamStart(const ProtocolHeader&) { - std::cout << "-> Stream start" << std::endl; - } - virtual void handleElement(boost::shared_ptr<ToplevelElement> element) { - std::cout << "-> Element " << typeid(*element.get()).name() << std::endl; - } - virtual void handleStreamEnd() { - std::cout << "-> Stream end" << std::endl; - } + public: + virtual void handleStreamStart(const ProtocolHeader&) { + std::cout << "-> Stream start" << std::endl; + } + virtual void handleElement(boost::shared_ptr<ToplevelElement> element) { + std::cout << "-> Element " << typeid(*element.get()).name() << std::endl; + } + virtual void handleStreamEnd() { + std::cout << "-> Stream end" << std::endl; + } }; int main(int argc, char* argv[]) { - if (argc != 2) { - std::cerr << "Usage: " << argv[0] << " file" << std::endl; - return 0; - } - FullPayloadParserFactoryCollection factories; - MyXMPPParserClient parserClient; - PlatformXMLParserFactory xmlParserFactory; - XMPPParser parser(&parserClient, &factories, &xmlParserFactory); - ParserTester<XMLParserClient> tester(&parser); + if (argc != 2) { + std::cerr << "Usage: " << argv[0] << " file" << std::endl; + return 0; + } + FullPayloadParserFactoryCollection factories; + MyXMPPParserClient parserClient; + PlatformXMLParserFactory xmlParserFactory; + XMPPParser parser(&parserClient, &factories, &xmlParserFactory); + ParserTester<XMLParserClient> tester(&parser); - std::string line; - std::ifstream myfile (argv[1]); - if (myfile.is_open()) { - while (!myfile.eof()) { - getline (myfile,line); - std::cout << "Parsing: " << line << std::endl; - if (!tester.parse(line)) { - std::cerr << "PARSE ERROR" << std::endl; - return -1; - } - } - myfile.close(); - } - else { - std::cerr << "Unable to open file " << argv[1] << std::endl; - } - return 0; + std::string line; + std::ifstream myfile (argv[1]); + if (myfile.is_open()) { + while (!myfile.eof()) { + getline (myfile,line); + std::cout << "Parsing: " << line << std::endl; + if (!tester.parse(line)) { + std::cerr << "PARSE ERROR" << std::endl; + return -1; + } + } + myfile.close(); + } + else { + std::cerr << "Unable to open file " << argv[1] << std::endl; + } + return 0; } diff --git a/Swiften/Examples/SendFile/ReceiveFile.cpp b/Swiften/Examples/SendFile/ReceiveFile.cpp index bfda44f..c6e75e8 100644 --- a/Swiften/Examples/SendFile/ReceiveFile.cpp +++ b/Swiften/Examples/SendFile/ReceiveFile.cpp @@ -36,101 +36,101 @@ static const std::string CLIENT_NAME = "Swiften FT Test"; static const std::string CLIENT_NODE = "http://swift.im"; class FileReceiver { - public: - FileReceiver(const JID& jid, const std::string& password) : jid(jid), password(password) { - client = new Swift::Client(jid, password, &networkFactories); - client->onConnected.connect(boost::bind(&FileReceiver::handleConnected, this)); - client->onDisconnected.connect(boost::bind(&FileReceiver::handleDisconnected, this, _1)); - tracer = new ClientXMLTracer(client); - } - - ~FileReceiver() { - delete tracer; - client->onDisconnected.disconnect(boost::bind(&FileReceiver::handleDisconnected, this, _1)); - client->onConnected.disconnect(boost::bind(&FileReceiver::handleConnected, this)); - delete client; - } - - void start() { - client->connect(); - } - - void stop() { - foreach(const IncomingFileTransfer::ref transfer, incomingFileTransfers) { - //transfer->stop(); - } - client->disconnect(); - } - - private: - void handleConnected() { - Log::setLogLevel(Log::debug); - client->getFileTransferManager()->onIncomingFileTransfer.connect(boost::bind(&FileReceiver::handleIncomingFileTransfer, this, _1)); - - DiscoInfo discoInfo; - discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc")); - discoInfo.addFeature(DiscoInfo::JingleFeature); - discoInfo.addFeature(DiscoInfo::JingleFTFeature); - discoInfo.addFeature(DiscoInfo::Bytestream); - discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature); - discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature); - client->getDiscoManager()->setCapsNode(CLIENT_NODE); - client->getDiscoManager()->setDiscoInfo(discoInfo); - client->getPresenceSender()->sendPresence(Presence::create()); - } - - void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) { - SWIFT_LOG(debug) << "foo" << std::endl; - incomingFileTransfers.push_back(transfer); - boost::shared_ptr<FileWriteBytestream> out = boost::make_shared<FileWriteBytestream>("out"); - transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1, out)); - transfer->accept(out); - } - - void handleDisconnected(const boost::optional<ClientError>&) { - std::cerr << "Error!" << std::endl; - exit(-1); - } - - void handleFileTransferFinished( - const boost::optional<FileTransferError>& error, - boost::shared_ptr<FileWriteBytestream> out) { - std::cout << "File transfer finished" << std::endl; - out->close(); - if (error) { - exit(-1); - } - else { - exit(0); - } - } - - void exit(int code) { - exitCode = code; - stop(); - eventLoop.stop(); - } - - private: - JID jid; - std::string password; - Client* client; - ClientXMLTracer* tracer; - std::vector<IncomingFileTransfer::ref> incomingFileTransfers; + public: + FileReceiver(const JID& jid, const std::string& password) : jid(jid), password(password) { + client = new Swift::Client(jid, password, &networkFactories); + client->onConnected.connect(boost::bind(&FileReceiver::handleConnected, this)); + client->onDisconnected.connect(boost::bind(&FileReceiver::handleDisconnected, this, _1)); + tracer = new ClientXMLTracer(client); + } + + ~FileReceiver() { + delete tracer; + client->onDisconnected.disconnect(boost::bind(&FileReceiver::handleDisconnected, this, _1)); + client->onConnected.disconnect(boost::bind(&FileReceiver::handleConnected, this)); + delete client; + } + + void start() { + client->connect(); + } + + void stop() { + foreach(const IncomingFileTransfer::ref transfer, incomingFileTransfers) { + //transfer->stop(); + } + client->disconnect(); + } + + private: + void handleConnected() { + Log::setLogLevel(Log::debug); + client->getFileTransferManager()->onIncomingFileTransfer.connect(boost::bind(&FileReceiver::handleIncomingFileTransfer, this, _1)); + + DiscoInfo discoInfo; + discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc")); + discoInfo.addFeature(DiscoInfo::JingleFeature); + discoInfo.addFeature(DiscoInfo::JingleFTFeature); + discoInfo.addFeature(DiscoInfo::Bytestream); + discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature); + discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature); + client->getDiscoManager()->setCapsNode(CLIENT_NODE); + client->getDiscoManager()->setDiscoInfo(discoInfo); + client->getPresenceSender()->sendPresence(Presence::create()); + } + + void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) { + SWIFT_LOG(debug) << "foo" << std::endl; + incomingFileTransfers.push_back(transfer); + boost::shared_ptr<FileWriteBytestream> out = boost::make_shared<FileWriteBytestream>("out"); + transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1, out)); + transfer->accept(out); + } + + void handleDisconnected(const boost::optional<ClientError>&) { + std::cerr << "Error!" << std::endl; + exit(-1); + } + + void handleFileTransferFinished( + const boost::optional<FileTransferError>& error, + boost::shared_ptr<FileWriteBytestream> out) { + std::cout << "File transfer finished" << std::endl; + out->close(); + if (error) { + exit(-1); + } + else { + exit(0); + } + } + + void exit(int code) { + exitCode = code; + stop(); + eventLoop.stop(); + } + + private: + JID jid; + std::string password; + Client* client; + ClientXMLTracer* tracer; + std::vector<IncomingFileTransfer::ref> incomingFileTransfers; }; int main(int argc, char* argv[]) { - if (argc != 3) { - std::cerr << "Usage: " << argv[0] << " <jid> <password>" << std::endl; - return -1; - } + if (argc != 3) { + std::cerr << "Usage: " << argv[0] << " <jid> <password>" << std::endl; + return -1; + } - JID jid(argv[1]); - FileReceiver fileReceiver(jid, std::string(argv[2])); - fileReceiver.start(); + JID jid(argv[1]); + FileReceiver fileReceiver(jid, std::string(argv[2])); + fileReceiver.start(); - eventLoop.run(); + eventLoop.run(); - return exitCode; + return exitCode; } diff --git a/Swiften/Examples/SendFile/SendFile.cpp b/Swiften/Examples/SendFile/SendFile.cpp index 5f2403a..bed6512 100644 --- a/Swiften/Examples/SendFile/SendFile.cpp +++ b/Swiften/Examples/SendFile/SendFile.cpp @@ -38,110 +38,110 @@ static BoostNetworkFactories networkFactories(&eventLoop); static int exitCode = 2; class FileSender { - public: - FileSender(const JID& jid, const std::string& password, const JID& recipient, const boost::filesystem::path& file) : jid(jid), password(password), recipient(recipient), file(file), tracer(NULL) { - client = new Swift::Client(jid, password, &networkFactories); - client->onConnected.connect(boost::bind(&FileSender::handleConnected, this)); - client->onDisconnected.connect(boost::bind(&FileSender::handleDisconnected, this, _1)); - //tracer = new ClientXMLTracer(client); - client->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileSender::handleCapsChanged, this, _1)); - } - - ~FileSender() { - delete tracer; - client->onDisconnected.disconnect(boost::bind(&FileSender::handleDisconnected, this, _1)); - client->onConnected.disconnect(boost::bind(&FileSender::handleConnected, this)); - delete client; - } - - void start() { - client->connect(); - } - - private: - void handleConnected() { - std::cout << "Connected. Awaiting presence from receipient." << std::endl; - client->sendPresence(Presence::create()); - } - - void handleCapsChanged(JID jid) { - if (jid.toBare() == recipient) { - // create ReadBytestream from file - boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(file); - - outgoingFileTransfer = client->getFileTransferManager()->createOutgoingFileTransfer(recipient, file, "Some File!", fileStream); - - if (outgoingFileTransfer) { - outgoingFileTransfer->onFinished.connect(boost::bind(&FileSender::handleFileTransferFinished, this, _1)); - std::cout << "Starting file-transfer to " << recipient.toString() << "." << std::endl; - outgoingFileTransfer->start(); - // TODO: getting notified about FT status and end - } else { - std::cout << recipient << " doesn't support any kind of file transfer!" << std::endl; - client->disconnect(); - } - } - } - - void handleDisconnected(const boost::optional<ClientError>& err) { - if (err) { - std::cout << "Disconnected due to error ( " << err.get().getType() << " )." << std::endl; - exit(-1); - } - else { - std::cout << "Successfully disconnected." << std::endl; - } - } - - void handleFileTransferFinished(const boost::optional<FileTransferError>& error) { - std::cout << "File transfer finished." << std::endl; - outgoingFileTransfer.reset(); - if (error) { - client->disconnect(); - exit(-1); - } - else { - client->disconnect(); - exit(0); - } - } - - void exit(int code) { - exitCode = code; - eventLoop.stop(); - } - - private: - BoostConnectionServer::ref connectionServer; - OutgoingFileTransfer::ref outgoingFileTransfer; - JID jid; - std::string password; - JID recipient; - boost::filesystem::path file; - Client* client; - ClientXMLTracer* tracer; + public: + FileSender(const JID& jid, const std::string& password, const JID& recipient, const boost::filesystem::path& file) : jid(jid), password(password), recipient(recipient), file(file), tracer(NULL) { + client = new Swift::Client(jid, password, &networkFactories); + client->onConnected.connect(boost::bind(&FileSender::handleConnected, this)); + client->onDisconnected.connect(boost::bind(&FileSender::handleDisconnected, this, _1)); + //tracer = new ClientXMLTracer(client); + client->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileSender::handleCapsChanged, this, _1)); + } + + ~FileSender() { + delete tracer; + client->onDisconnected.disconnect(boost::bind(&FileSender::handleDisconnected, this, _1)); + client->onConnected.disconnect(boost::bind(&FileSender::handleConnected, this)); + delete client; + } + + void start() { + client->connect(); + } + + private: + void handleConnected() { + std::cout << "Connected. Awaiting presence from receipient." << std::endl; + client->sendPresence(Presence::create()); + } + + void handleCapsChanged(JID jid) { + if (jid.toBare() == recipient) { + // create ReadBytestream from file + boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(file); + + outgoingFileTransfer = client->getFileTransferManager()->createOutgoingFileTransfer(recipient, file, "Some File!", fileStream); + + if (outgoingFileTransfer) { + outgoingFileTransfer->onFinished.connect(boost::bind(&FileSender::handleFileTransferFinished, this, _1)); + std::cout << "Starting file-transfer to " << recipient.toString() << "." << std::endl; + outgoingFileTransfer->start(); + // TODO: getting notified about FT status and end + } else { + std::cout << recipient << " doesn't support any kind of file transfer!" << std::endl; + client->disconnect(); + } + } + } + + void handleDisconnected(const boost::optional<ClientError>& err) { + if (err) { + std::cout << "Disconnected due to error ( " << err.get().getType() << " )." << std::endl; + exit(-1); + } + else { + std::cout << "Successfully disconnected." << std::endl; + } + } + + void handleFileTransferFinished(const boost::optional<FileTransferError>& error) { + std::cout << "File transfer finished." << std::endl; + outgoingFileTransfer.reset(); + if (error) { + client->disconnect(); + exit(-1); + } + else { + client->disconnect(); + exit(0); + } + } + + void exit(int code) { + exitCode = code; + eventLoop.stop(); + } + + private: + BoostConnectionServer::ref connectionServer; + OutgoingFileTransfer::ref outgoingFileTransfer; + JID jid; + std::string password; + JID recipient; + boost::filesystem::path file; + Client* client; + ClientXMLTracer* tracer; }; int main(int argc, char* argv[]) { - if (argc != 5) { - std::cerr << "Usage: " << argv[0] << " <jid> <password> <recipient> <file>" << std::endl; - return -1; - } - - //Log::setLogLevel(Log::debug); - - JID sender(argv[1]); - JID recipient(argv[3]); - FileSender fileSender(sender, std::string(argv[2]), recipient, boost::filesystem::path(argv[4])); - fileSender.start(); - { - Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000); - timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); - timer->start(); - - eventLoop.run(); - } - - return exitCode; + if (argc != 5) { + std::cerr << "Usage: " << argv[0] << " <jid> <password> <recipient> <file>" << std::endl; + return -1; + } + + //Log::setLogLevel(Log::debug); + + JID sender(argv[1]); + JID recipient(argv[3]); + FileSender fileSender(sender, std::string(argv[2]), recipient, boost::filesystem::path(argv[4])); + fileSender.start(); + { + Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000); + timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); + timer->start(); + + eventLoop.run(); + } + + return exitCode; } diff --git a/Swiften/Examples/SendMessage/SendMessage.cpp b/Swiften/Examples/SendMessage/SendMessage.cpp index 5f13903..973cda5 100644 --- a/Swiften/Examples/SendMessage/SendMessage.cpp +++ b/Swiften/Examples/SendMessage/SendMessage.cpp @@ -30,62 +30,62 @@ static boost::bsignals::connection errorConnection; static void handleConnected() { - boost::shared_ptr<Message> message(new Message()); - message->setBody(messageBody); - message->setTo(recipient); - client->sendMessage(message); - exitCode = 0; - errorConnection.disconnect(); - client->disconnect(); - eventLoop.stop(); + boost::shared_ptr<Message> message(new Message()); + message->setBody(messageBody); + message->setTo(recipient); + client->sendMessage(message); + exitCode = 0; + errorConnection.disconnect(); + client->disconnect(); + eventLoop.stop(); } static void handleDisconnected(const boost::optional<ClientError>&) { - std::cerr << "Error!" << std::endl; - exitCode = 1; - eventLoop.stop(); + std::cerr << "Error!" << std::endl; + exitCode = 1; + eventLoop.stop(); } int main(int argc, char* argv[]) { - if (argc < 5 || argc > 6) { - std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>]<password> <recipient> <message>" << std::endl; - return -1; - } - - int argi = 1; - - std::string jid = argv[argi++]; - std::string connectHost = ""; - if (argc == 6) { - connectHost = argv[argi++]; - } - - client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories); - client->setAlwaysTrustCertificates(); - - recipient = JID(argv[argi++]); - messageBody = std::string(argv[argi++]); - - ClientXMLTracer* tracer = new ClientXMLTracer(client); - client->onConnected.connect(&handleConnected); - errorConnection = client->onDisconnected.connect(&handleDisconnected); - if (!connectHost.empty()) { - ClientOptions options; - options.manualHostname = connectHost; - client->connect(options); - } else { - client->connect(); - } - - { - Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000); - timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); - timer->start(); - - eventLoop.run(); - } - - delete tracer; - delete client; - return exitCode; + if (argc < 5 || argc > 6) { + std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>]<password> <recipient> <message>" << std::endl; + return -1; + } + + int argi = 1; + + std::string jid = argv[argi++]; + std::string connectHost = ""; + if (argc == 6) { + connectHost = argv[argi++]; + } + + client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories); + client->setAlwaysTrustCertificates(); + + recipient = JID(argv[argi++]); + messageBody = std::string(argv[argi++]); + + ClientXMLTracer* tracer = new ClientXMLTracer(client); + client->onConnected.connect(&handleConnected); + errorConnection = client->onDisconnected.connect(&handleDisconnected); + if (!connectHost.empty()) { + ClientOptions options; + options.manualHostname = connectHost; + client->connect(options); + } else { + client->connect(); + } + + { + Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000); + timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop)); + timer->start(); + + eventLoop.run(); + } + + delete tracer; + delete client; + return exitCode; } diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp index d1b0db3..c1fadee 100644 --- a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp +++ b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp @@ -14,20 +14,20 @@ using namespace Swift; boost::shared_ptr<ByteArray> ByteArrayReadBytestream::read(size_t size) { - size_t readSize = size; - if (position + readSize > data.size()) { - readSize = data.size() - position; - } - boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>( - data.begin() + boost::numeric_cast<long long>(position), - data.begin() + boost::numeric_cast<long long>(position) + boost::numeric_cast<long long>(readSize)); + size_t readSize = size; + if (position + readSize > data.size()) { + readSize = data.size() - position; + } + boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>( + data.begin() + boost::numeric_cast<long long>(position), + data.begin() + boost::numeric_cast<long long>(position) + boost::numeric_cast<long long>(readSize)); - onRead(*result); - position += readSize; - return result; + onRead(*result); + position += readSize; + return result; } void ByteArrayReadBytestream::addData(const std::vector<unsigned char>& moreData) { - append(data, moreData); - onDataAvailable(); + append(data, moreData); + onDataAvailable(); } diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.h b/Swiften/FileTransfer/ByteArrayReadBytestream.h index eefa80a..a711acb 100644 --- a/Swiften/FileTransfer/ByteArrayReadBytestream.h +++ b/Swiften/FileTransfer/ByteArrayReadBytestream.h @@ -13,26 +13,26 @@ #include <Swiften/FileTransfer/ReadBytestream.h> namespace Swift { - class SWIFTEN_API ByteArrayReadBytestream : public ReadBytestream { - public: - ByteArrayReadBytestream(const std::vector<unsigned char>& data) : data(data), position(0), dataComplete(true) { - } + class SWIFTEN_API ByteArrayReadBytestream : public ReadBytestream { + public: + ByteArrayReadBytestream(const std::vector<unsigned char>& data) : data(data), position(0), dataComplete(true) { + } - virtual boost::shared_ptr<ByteArray> read(size_t size); + virtual boost::shared_ptr<ByteArray> read(size_t size); - virtual bool isFinished() const { - return position >= data.size() && dataComplete; - } + virtual bool isFinished() const { + return position >= data.size() && dataComplete; + } - virtual void setDataComplete(bool b) { - dataComplete = b; - } + virtual void setDataComplete(bool b) { + dataComplete = b; + } - void addData(const std::vector<unsigned char>& moreData); + void addData(const std::vector<unsigned char>& moreData); - private: - std::vector<unsigned char> data; - size_t position; - bool dataComplete; - }; + private: + std::vector<unsigned char> data; + size_t position; + bool dataComplete; + }; } diff --git a/Swiften/FileTransfer/ByteArrayWriteBytestream.h b/Swiften/FileTransfer/ByteArrayWriteBytestream.h index 08c4d4b..ec9d101 100644 --- a/Swiften/FileTransfer/ByteArrayWriteBytestream.h +++ b/Swiften/FileTransfer/ByteArrayWriteBytestream.h @@ -10,22 +10,22 @@ #include <Swiften/FileTransfer/WriteBytestream.h> namespace Swift { - class SWIFTEN_API ByteArrayWriteBytestream : public WriteBytestream { - public: - ByteArrayWriteBytestream() { - } + class SWIFTEN_API ByteArrayWriteBytestream : public WriteBytestream { + public: + ByteArrayWriteBytestream() { + } - virtual bool write(const std::vector<unsigned char>& bytes) { - data.insert(data.end(), bytes.begin(), bytes.end()); - onWrite(bytes); - return true; - } + virtual bool write(const std::vector<unsigned char>& bytes) { + data.insert(data.end(), bytes.begin(), bytes.end()); + onWrite(bytes); + return true; + } - const std::vector<unsigned char>& getData() const { - return data; - } + const std::vector<unsigned char>& getData() const { + return data; + } - private: - std::vector<unsigned char> data; - }; + private: + std::vector<unsigned char> data; + }; } diff --git a/Swiften/FileTransfer/BytestreamException.h b/Swiften/FileTransfer/BytestreamException.h index 202315e..02d1e98 100644 --- a/Swiften/FileTransfer/BytestreamException.h +++ b/Swiften/FileTransfer/BytestreamException.h @@ -11,9 +11,9 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API BytestreamException : public std::exception { - public: - BytestreamException() { - } - }; + class SWIFTEN_API BytestreamException : public std::exception { + public: + BytestreamException() { + } + }; } diff --git a/Swiften/FileTransfer/BytestreamsRequest.h b/Swiften/FileTransfer/BytestreamsRequest.h index 447f743..7fa3660 100644 --- a/Swiften/FileTransfer/BytestreamsRequest.h +++ b/Swiften/FileTransfer/BytestreamsRequest.h @@ -13,23 +13,23 @@ #include <Swiften/Queries/GenericRequest.h> namespace Swift { - class SWIFTEN_API BytestreamsRequest : public GenericRequest<Bytestreams> { - public: - typedef boost::shared_ptr<BytestreamsRequest> ref; + class SWIFTEN_API BytestreamsRequest : public GenericRequest<Bytestreams> { + public: + typedef boost::shared_ptr<BytestreamsRequest> ref; - static ref create(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) { - return ref(new BytestreamsRequest(jid, payload, router)); - } + static ref create(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) { + return ref(new BytestreamsRequest(jid, payload, router)); + } - static ref create(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) { - return ref(new BytestreamsRequest(from, to, payload, router)); - } + static ref create(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) { + return ref(new BytestreamsRequest(from, to, payload, router)); + } - private: - BytestreamsRequest(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, jid, payload, router) { - } + private: + BytestreamsRequest(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, jid, payload, router) { + } - BytestreamsRequest(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, from, to, payload, router) { - } - }; + BytestreamsRequest(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, from, to, payload, router) { + } + }; } diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp index 1e68bc6..b54f1c1 100644 --- a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp +++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp @@ -33,268 +33,268 @@ using namespace Swift; DefaultFileTransferTransporter::DefaultFileTransferTransporter( - const JID& initiator, - const JID& responder, - Role role, - SOCKS5BytestreamRegistry* s5bRegistry, - SOCKS5BytestreamServerManager* s5bServerManager, - SOCKS5BytestreamProxiesManager* s5bProxy, - IDGenerator* idGenerator, - ConnectionFactory* connectionFactory, - TimerFactory* timerFactory, - CryptoProvider* crypto, - IQRouter* router, - const FileTransferOptions& options) : - initiator(initiator), - responder(responder), - role(role), - s5bRegistry(s5bRegistry), - s5bServerManager(s5bServerManager), - s5bProxy(s5bProxy), - crypto(crypto), - router(router) { - - localCandidateGenerator = new LocalJingleTransportCandidateGenerator( - s5bServerManager, - s5bProxy, - role == Initiator ? initiator : responder, - idGenerator, - options); - localCandidateGenerator->onLocalTransportCandidatesGenerated.connect( - boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1)); - - remoteCandidateSelector = new RemoteJingleTransportCandidateSelector( - connectionFactory, - timerFactory, - options); - remoteCandidateSelector->onCandidateSelectFinished.connect( - boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2)); + const JID& initiator, + const JID& responder, + Role role, + SOCKS5BytestreamRegistry* s5bRegistry, + SOCKS5BytestreamServerManager* s5bServerManager, + SOCKS5BytestreamProxiesManager* s5bProxy, + IDGenerator* idGenerator, + ConnectionFactory* connectionFactory, + TimerFactory* timerFactory, + CryptoProvider* crypto, + IQRouter* router, + const FileTransferOptions& options) : + initiator(initiator), + responder(responder), + role(role), + s5bRegistry(s5bRegistry), + s5bServerManager(s5bServerManager), + s5bProxy(s5bProxy), + crypto(crypto), + router(router) { + + localCandidateGenerator = new LocalJingleTransportCandidateGenerator( + s5bServerManager, + s5bProxy, + role == Initiator ? initiator : responder, + idGenerator, + options); + localCandidateGenerator->onLocalTransportCandidatesGenerated.connect( + boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1)); + + remoteCandidateSelector = new RemoteJingleTransportCandidateSelector( + connectionFactory, + timerFactory, + options); + remoteCandidateSelector->onCandidateSelectFinished.connect( + boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2)); } DefaultFileTransferTransporter::~DefaultFileTransferTransporter() { - DefaultFileTransferTransporter::stopGeneratingLocalCandidates(); - remoteCandidateSelector->onCandidateSelectFinished.disconnect( - boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2)); - delete remoteCandidateSelector; - - localCandidateGenerator->onLocalTransportCandidatesGenerated.disconnect( - boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1)); - delete localCandidateGenerator; + DefaultFileTransferTransporter::stopGeneratingLocalCandidates(); + remoteCandidateSelector->onCandidateSelectFinished.disconnect( + boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2)); + delete remoteCandidateSelector; + + localCandidateGenerator->onLocalTransportCandidatesGenerated.disconnect( + boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1)); + delete localCandidateGenerator; } void DefaultFileTransferTransporter::initialize() { - s5bSessionID = s5bRegistry->generateSessionID(); + s5bSessionID = s5bRegistry->generateSessionID(); } void DefaultFileTransferTransporter::initialize(const std::string& s5bSessionID) { - this->s5bSessionID = s5bSessionID; + this->s5bSessionID = s5bSessionID; } void DefaultFileTransferTransporter::startGeneratingLocalCandidates() { - localCandidateGenerator->start(); + localCandidateGenerator->start(); } void DefaultFileTransferTransporter::stopGeneratingLocalCandidates() { - localCandidateGenerator->stop(); + localCandidateGenerator->stop(); } - + void DefaultFileTransferTransporter::handleLocalCandidatesGenerated( - const std::vector<JingleS5BTransportPayload::Candidate>& candidates) { - s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), true); - s5bProxy->connectToProxies(getSOCKS5DstAddr()); - onLocalCandidatesGenerated(s5bSessionID, candidates, getSOCKS5DstAddr()); + const std::vector<JingleS5BTransportPayload::Candidate>& candidates) { + s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), true); + s5bProxy->connectToProxies(getSOCKS5DstAddr()); + onLocalCandidatesGenerated(s5bSessionID, candidates, getSOCKS5DstAddr()); } void DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished( - const boost::optional<JingleS5BTransportPayload::Candidate>& candidate, - boost::shared_ptr<SOCKS5BytestreamClientSession> session) { - remoteS5BClientSession = session; - onRemoteCandidateSelectFinished(s5bSessionID, candidate); + const boost::optional<JingleS5BTransportPayload::Candidate>& candidate, + boost::shared_ptr<SOCKS5BytestreamClientSession> session) { + remoteS5BClientSession = session; + onRemoteCandidateSelectFinished(s5bSessionID, candidate); } void DefaultFileTransferTransporter::addRemoteCandidates( - const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) { - remoteCandidateSelector->setSOCKS5DstAddr(dstAddr.empty() ? getRemoteCandidateSOCKS5DstAddr() : dstAddr); - remoteCandidateSelector->addCandidates(candidates); + const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) { + remoteCandidateSelector->setSOCKS5DstAddr(dstAddr.empty() ? getRemoteCandidateSOCKS5DstAddr() : dstAddr); + remoteCandidateSelector->addCandidates(candidates); } void DefaultFileTransferTransporter::startTryingRemoteCandidates() { - remoteCandidateSelector->startSelectingCandidate(); + remoteCandidateSelector->startSelectingCandidate(); } void DefaultFileTransferTransporter::stopTryingRemoteCandidates() { - remoteCandidateSelector->stopSelectingCandidate(); + remoteCandidateSelector->stopSelectingCandidate(); } void DefaultFileTransferTransporter::handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error) { - onProxyActivated(sessionID, error); + onProxyActivated(sessionID, error); } void DefaultFileTransferTransporter::startActivatingProxy(const JID& proxyServiceJID) { - // activate proxy - SWIFT_LOG(debug) << "Start activating proxy " << proxyServiceJID.toString() << " with sid = " << s5bSessionID << "." << std::endl; - S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>(); - proxyRequest->setSID(s5bSessionID); - proxyRequest->setActivate(role == Initiator ? responder : initiator); - - boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Set, proxyServiceJID, proxyRequest, router); - request->onResponse.connect(boost::bind(&DefaultFileTransferTransporter::handleActivateProxySessionResult, this, s5bSessionID, _2)); - request->send(); + // activate proxy + SWIFT_LOG(debug) << "Start activating proxy " << proxyServiceJID.toString() << " with sid = " << s5bSessionID << "." << std::endl; + S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>(); + proxyRequest->setSID(s5bSessionID); + proxyRequest->setActivate(role == Initiator ? responder : initiator); + + boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Set, proxyServiceJID, proxyRequest, router); + request->onResponse.connect(boost::bind(&DefaultFileTransferTransporter::handleActivateProxySessionResult, this, s5bSessionID, _2)); + request->send(); } void DefaultFileTransferTransporter::stopActivatingProxy() { - // TODO - assert(false); + // TODO + assert(false); } boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createIBBSendSession( - const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) { - if (s5bServerManager->getServer()) { - closeLocalSession(); - } - closeRemoteSession(); - boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>( - sessionID, initiator, responder, stream, router); - ibbSession->setBlockSize(blockSize); - return boost::make_shared<IBBSendTransportSession>(ibbSession); + const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) { + if (s5bServerManager->getServer()) { + closeLocalSession(); + } + closeRemoteSession(); + boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>( + sessionID, initiator, responder, stream, router); + ibbSession->setBlockSize(blockSize); + return boost::make_shared<IBBSendTransportSession>(ibbSession); } boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createIBBReceiveSession( - const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) { - if (s5bServerManager->getServer()) { - closeLocalSession(); - } - closeRemoteSession(); - boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>( - sessionID, initiator, responder, size, stream, router); - return boost::make_shared<IBBReceiveTransportSession>(ibbSession); + const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) { + if (s5bServerManager->getServer()) { + closeLocalSession(); + } + closeRemoteSession(); + boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>( + sessionID, initiator, responder, size, stream, router); + return boost::make_shared<IBBReceiveTransportSession>(ibbSession); } boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createRemoteCandidateSession( - boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) { - closeLocalSession(); - return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >( - remoteS5BClientSession, stream); + boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) { + closeLocalSession(); + return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >( + remoteS5BClientSession, stream); } boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createRemoteCandidateSession( - boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) { - closeLocalSession(); - return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >( - remoteS5BClientSession, stream); + boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) { + closeLocalSession(); + return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >( + remoteS5BClientSession, stream); } boost::shared_ptr<SOCKS5BytestreamServerSession> DefaultFileTransferTransporter::getServerSession() { - s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false); - std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = - s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr()); - while (serverSessions.size() > 1) { - boost::shared_ptr<SOCKS5BytestreamServerSession> session = serverSessions.back(); - serverSessions.pop_back(); - session->stop(); - } - return !serverSessions.empty() ? serverSessions.front() : boost::shared_ptr<SOCKS5BytestreamServerSession>(); + s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false); + std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = + s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr()); + while (serverSessions.size() > 1) { + boost::shared_ptr<SOCKS5BytestreamServerSession> session = serverSessions.back(); + serverSessions.pop_back(); + session->stop(); + } + return !serverSessions.empty() ? serverSessions.front() : boost::shared_ptr<SOCKS5BytestreamServerSession>(); } boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCandidateSession( - boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) { - closeRemoteSession(); - boost::shared_ptr<TransportSession> transportSession; - if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) { - SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr()); - assert(proxySession); - transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream); - } - - if (!transportSession) { - boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession(); - if (serverSession) { - transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream); - } - } - - if (!transportSession) { - transportSession = boost::make_shared<FailingTransportSession>(); - } - return transportSession; + boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) { + closeRemoteSession(); + boost::shared_ptr<TransportSession> transportSession; + if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) { + SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr()); + assert(proxySession); + transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream); + } + + if (!transportSession) { + boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession(); + if (serverSession) { + transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream); + } + } + + if (!transportSession) { + transportSession = boost::make_shared<FailingTransportSession>(); + } + return transportSession; } boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCandidateSession( - boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) { - closeRemoteSession(); - boost::shared_ptr<TransportSession> transportSession; - if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) { - SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr()); - assert(proxySession); - transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream); - } - - if (!transportSession) { - boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession(); - if (serverSession) { - transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream); - } - } - - if (!transportSession) { - transportSession = boost::make_shared<FailingTransportSession>(); - } - return transportSession; + boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) { + closeRemoteSession(); + boost::shared_ptr<TransportSession> transportSession; + if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) { + SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr()); + assert(proxySession); + transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream); + } + + if (!transportSession) { + boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession(); + if (serverSession) { + transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream); + } + } + + if (!transportSession) { + transportSession = boost::make_shared<FailingTransportSession>(); + } + return transportSession; } std::string DefaultFileTransferTransporter::getSOCKS5DstAddr() const { - std::string result; - if (role == Initiator) { - result = getInitiatorCandidateSOCKS5DstAddr(); - SWIFT_LOG(debug) << "Initiator S5B DST.ADDR = " << s5bSessionID << " + " << initiator.toString() << " + " << responder.toString() << " : " << result << std::endl; - } - else { - result = getResponderCandidateSOCKS5DstAddr(); - SWIFT_LOG(debug) << "Responder S5B DST.ADDR = " << s5bSessionID << " + " << responder.toString() << " + " << initiator.toString() << " : " << result << std::endl; - } - return result; + std::string result; + if (role == Initiator) { + result = getInitiatorCandidateSOCKS5DstAddr(); + SWIFT_LOG(debug) << "Initiator S5B DST.ADDR = " << s5bSessionID << " + " << initiator.toString() << " + " << responder.toString() << " : " << result << std::endl; + } + else { + result = getResponderCandidateSOCKS5DstAddr(); + SWIFT_LOG(debug) << "Responder S5B DST.ADDR = " << s5bSessionID << " + " << responder.toString() << " + " << initiator.toString() << " : " << result << std::endl; + } + return result; } std::string DefaultFileTransferTransporter::getInitiatorCandidateSOCKS5DstAddr() const { - return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + initiator.toString() + responder.toString()))); + return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + initiator.toString() + responder.toString()))); } std::string DefaultFileTransferTransporter::getResponderCandidateSOCKS5DstAddr() const { - return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + responder.toString() + initiator.toString()))); + return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + responder.toString() + initiator.toString()))); } std::string DefaultFileTransferTransporter::getRemoteCandidateSOCKS5DstAddr() const { - if (role == Initiator) { - return getResponderCandidateSOCKS5DstAddr(); - } - else { - return getInitiatorCandidateSOCKS5DstAddr(); - } + if (role == Initiator) { + return getResponderCandidateSOCKS5DstAddr(); + } + else { + return getInitiatorCandidateSOCKS5DstAddr(); + } } std::string DefaultFileTransferTransporter::getLocalCandidateSOCKS5DstAddr() const { - if (role == Responder) { - return getResponderCandidateSOCKS5DstAddr(); - } - else { - return getInitiatorCandidateSOCKS5DstAddr(); - } + if (role == Responder) { + return getResponderCandidateSOCKS5DstAddr(); + } + else { + return getInitiatorCandidateSOCKS5DstAddr(); + } } void DefaultFileTransferTransporter::closeLocalSession() { - s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false); - if (s5bServerManager->getServer()) { - std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr()); - foreach(boost::shared_ptr<SOCKS5BytestreamServerSession> session, serverSessions) { - session->stop(); - } - } + s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false); + if (s5bServerManager->getServer()) { + std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr()); + foreach(boost::shared_ptr<SOCKS5BytestreamServerSession> session, serverSessions) { + session->stop(); + } + } } void DefaultFileTransferTransporter::closeRemoteSession() { - if (remoteS5BClientSession) { - remoteS5BClientSession->stop(); - remoteS5BClientSession.reset(); - } + if (remoteS5BClientSession) { + remoteS5BClientSession->stop(); + remoteS5BClientSession.reset(); + } } diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporter.h b/Swiften/FileTransfer/DefaultFileTransferTransporter.h index 026b834..7ec6a12 100644 --- a/Swiften/FileTransfer/DefaultFileTransferTransporter.h +++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.h @@ -12,101 +12,101 @@ #include <Swiften/FileTransfer/FileTransferTransporter.h> namespace Swift { - class LocalJingleTransportCandidateGenerator; - class RemoteJingleTransportCandidateSelector; - class SOCKS5BytestreamRegistry; - class SOCKS5BytestreamServerManager; - class SOCKS5BytestreamProxiesManager; - class SOCKS5BytestreamClientSession; - class SOCKS5BytestreamServerSession; - class IDGenerator; - class IQRouter; - class ReadBytestream; - class WriteBytestream; - class ConnectionFactory; - class TimerFactory; - class CryptoProvider; - class FileTransferOptions; + class LocalJingleTransportCandidateGenerator; + class RemoteJingleTransportCandidateSelector; + class SOCKS5BytestreamRegistry; + class SOCKS5BytestreamServerManager; + class SOCKS5BytestreamProxiesManager; + class SOCKS5BytestreamClientSession; + class SOCKS5BytestreamServerSession; + class IDGenerator; + class IQRouter; + class ReadBytestream; + class WriteBytestream; + class ConnectionFactory; + class TimerFactory; + class CryptoProvider; + class FileTransferOptions; - class SWIFTEN_API DefaultFileTransferTransporter : public FileTransferTransporter { - public: - enum Role { - Initiator, - Responder - }; + class SWIFTEN_API DefaultFileTransferTransporter : public FileTransferTransporter { + public: + enum Role { + Initiator, + Responder + }; - DefaultFileTransferTransporter( - const JID& initiator, - const JID& responder, - Role role, - SOCKS5BytestreamRegistry*, - SOCKS5BytestreamServerManager* s5bServerManager, - SOCKS5BytestreamProxiesManager* s5bProxy, - IDGenerator* idGenerator, - ConnectionFactory*, - TimerFactory*, - CryptoProvider*, - IQRouter*, - const FileTransferOptions&); - virtual ~DefaultFileTransferTransporter(); + DefaultFileTransferTransporter( + const JID& initiator, + const JID& responder, + Role role, + SOCKS5BytestreamRegistry*, + SOCKS5BytestreamServerManager* s5bServerManager, + SOCKS5BytestreamProxiesManager* s5bProxy, + IDGenerator* idGenerator, + ConnectionFactory*, + TimerFactory*, + CryptoProvider*, + IQRouter*, + const FileTransferOptions&); + virtual ~DefaultFileTransferTransporter(); - - virtual void initialize(); - virtual void initialize(const std::string& s5bSessionID); - virtual void startGeneratingLocalCandidates() SWIFTEN_OVERRIDE; - virtual void stopGeneratingLocalCandidates() SWIFTEN_OVERRIDE; + virtual void initialize(); + virtual void initialize(const std::string& s5bSessionID); - virtual void addRemoteCandidates( - const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) SWIFTEN_OVERRIDE; - virtual void startTryingRemoteCandidates() SWIFTEN_OVERRIDE; - virtual void stopTryingRemoteCandidates() SWIFTEN_OVERRIDE; + virtual void startGeneratingLocalCandidates() SWIFTEN_OVERRIDE; + virtual void stopGeneratingLocalCandidates() SWIFTEN_OVERRIDE; - virtual void startActivatingProxy(const JID& jid) SWIFTEN_OVERRIDE; - virtual void stopActivatingProxy() SWIFTEN_OVERRIDE; + virtual void addRemoteCandidates( + const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) SWIFTEN_OVERRIDE; + virtual void startTryingRemoteCandidates() SWIFTEN_OVERRIDE; + virtual void stopTryingRemoteCandidates() SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createIBBSendSession( - const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createIBBReceiveSession( - const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( - boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( - boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( - boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( - boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + virtual void startActivatingProxy(const JID& jid) SWIFTEN_OVERRIDE; + virtual void stopActivatingProxy() SWIFTEN_OVERRIDE; - private: - void handleLocalCandidatesGenerated(const std::vector<JingleS5BTransportPayload::Candidate>&); - void handleRemoteCandidateSelectFinished( - const boost::optional<JingleS5BTransportPayload::Candidate>&, - boost::shared_ptr<SOCKS5BytestreamClientSession>); - void handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error); - void closeLocalSession(); - void closeRemoteSession(); - boost::shared_ptr<SOCKS5BytestreamServerSession> getServerSession(); + virtual boost::shared_ptr<TransportSession> createIBBSendSession( + const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createIBBReceiveSession( + const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( + boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( + boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( + boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( + boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; - std::string getSOCKS5DstAddr() const; - std::string getInitiatorCandidateSOCKS5DstAddr() const; - std::string getResponderCandidateSOCKS5DstAddr() const; - std::string getRemoteCandidateSOCKS5DstAddr() const; - std::string getLocalCandidateSOCKS5DstAddr() const; + private: + void handleLocalCandidatesGenerated(const std::vector<JingleS5BTransportPayload::Candidate>&); + void handleRemoteCandidateSelectFinished( + const boost::optional<JingleS5BTransportPayload::Candidate>&, + boost::shared_ptr<SOCKS5BytestreamClientSession>); + void handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error); + void closeLocalSession(); + void closeRemoteSession(); + boost::shared_ptr<SOCKS5BytestreamServerSession> getServerSession(); - private: - JID initiator; - JID responder; - Role role; - SOCKS5BytestreamRegistry* s5bRegistry; - SOCKS5BytestreamServerManager* s5bServerManager; - SOCKS5BytestreamProxiesManager* s5bProxy; - CryptoProvider* crypto; - IQRouter* router; - LocalJingleTransportCandidateGenerator* localCandidateGenerator; - RemoteJingleTransportCandidateSelector* remoteCandidateSelector; - std::string s5bSessionID; - boost::shared_ptr<SOCKS5BytestreamClientSession> remoteS5BClientSession; - }; + std::string getSOCKS5DstAddr() const; + std::string getInitiatorCandidateSOCKS5DstAddr() const; + std::string getResponderCandidateSOCKS5DstAddr() const; + std::string getRemoteCandidateSOCKS5DstAddr() const; + std::string getLocalCandidateSOCKS5DstAddr() const; + + private: + JID initiator; + JID responder; + Role role; + SOCKS5BytestreamRegistry* s5bRegistry; + SOCKS5BytestreamServerManager* s5bServerManager; + SOCKS5BytestreamProxiesManager* s5bProxy; + CryptoProvider* crypto; + IQRouter* router; + LocalJingleTransportCandidateGenerator* localCandidateGenerator; + RemoteJingleTransportCandidateSelector* remoteCandidateSelector; + std::string s5bSessionID; + boost::shared_ptr<SOCKS5BytestreamClientSession> remoteS5BClientSession; + }; } diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp index ffa0a12..3af2cad 100644 --- a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp +++ b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp @@ -11,22 +11,22 @@ using namespace Swift; DefaultFileTransferTransporterFactory::DefaultFileTransferTransporterFactory( - SOCKS5BytestreamRegistry* s5bRegistry, - SOCKS5BytestreamServerManager* s5bServerManager, - SOCKS5BytestreamProxiesManager* s5bProxiesManager, - IDGenerator* idGenerator, - ConnectionFactory* connectionFactory, - TimerFactory* timerFactory, - CryptoProvider* cryptoProvider, - IQRouter* iqRouter) : - s5bRegistry(s5bRegistry), - s5bServerManager(s5bServerManager), - s5bProxiesManager(s5bProxiesManager), - idGenerator(idGenerator), - connectionFactory(connectionFactory), - timerFactory(timerFactory), - cryptoProvider(cryptoProvider), - iqRouter(iqRouter) + SOCKS5BytestreamRegistry* s5bRegistry, + SOCKS5BytestreamServerManager* s5bServerManager, + SOCKS5BytestreamProxiesManager* s5bProxiesManager, + IDGenerator* idGenerator, + ConnectionFactory* connectionFactory, + TimerFactory* timerFactory, + CryptoProvider* cryptoProvider, + IQRouter* iqRouter) : + s5bRegistry(s5bRegistry), + s5bServerManager(s5bServerManager), + s5bProxiesManager(s5bProxiesManager), + idGenerator(idGenerator), + connectionFactory(connectionFactory), + timerFactory(timerFactory), + cryptoProvider(cryptoProvider), + iqRouter(iqRouter) { } @@ -34,39 +34,39 @@ DefaultFileTransferTransporterFactory::~DefaultFileTransferTransporterFactory() } FileTransferTransporter* DefaultFileTransferTransporterFactory::createInitiatorTransporter( - const JID& initiator, const JID& responder, const FileTransferOptions& options) { - DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter( - initiator, - responder, - DefaultFileTransferTransporter::Initiator, - s5bRegistry, - s5bServerManager, - s5bProxiesManager, - idGenerator, - connectionFactory, - timerFactory, - cryptoProvider, - iqRouter, - options); - transporter->initialize(); - return transporter; + const JID& initiator, const JID& responder, const FileTransferOptions& options) { + DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter( + initiator, + responder, + DefaultFileTransferTransporter::Initiator, + s5bRegistry, + s5bServerManager, + s5bProxiesManager, + idGenerator, + connectionFactory, + timerFactory, + cryptoProvider, + iqRouter, + options); + transporter->initialize(); + return transporter; } FileTransferTransporter* DefaultFileTransferTransporterFactory::createResponderTransporter( - const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions& options) { - DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter( - initiator, - responder, - DefaultFileTransferTransporter::Responder, - s5bRegistry, - s5bServerManager, - s5bProxiesManager, - idGenerator, - connectionFactory, - timerFactory, - cryptoProvider, - iqRouter, - options); - transporter->initialize(s5bSessionID); - return transporter; + const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions& options) { + DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter( + initiator, + responder, + DefaultFileTransferTransporter::Responder, + s5bRegistry, + s5bServerManager, + s5bProxiesManager, + idGenerator, + connectionFactory, + timerFactory, + cryptoProvider, + iqRouter, + options); + transporter->initialize(s5bSessionID); + return transporter; } diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h index 33ed05e..3cc3455 100644 --- a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h +++ b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h @@ -11,41 +11,41 @@ #include <Swiften/FileTransfer/FileTransferTransporterFactory.h> namespace Swift { - class SOCKS5BytestreamRegistry; - class SOCKS5BytestreamServerManager; - class SOCKS5BytestreamProxiesManager; - class IDGenerator; - class ConnectionFactory; - class TimerFactory; - class CryptoProvider; - class IQRouter; + class SOCKS5BytestreamRegistry; + class SOCKS5BytestreamServerManager; + class SOCKS5BytestreamProxiesManager; + class IDGenerator; + class ConnectionFactory; + class TimerFactory; + class CryptoProvider; + class IQRouter; - class SWIFTEN_API DefaultFileTransferTransporterFactory : public FileTransferTransporterFactory { - public: - DefaultFileTransferTransporterFactory( - SOCKS5BytestreamRegistry*, - SOCKS5BytestreamServerManager* s5bServerManager, - SOCKS5BytestreamProxiesManager* s5bProxy, - IDGenerator* idGenerator, - ConnectionFactory*, - TimerFactory*, - CryptoProvider*, - IQRouter*); - virtual ~DefaultFileTransferTransporterFactory(); + class SWIFTEN_API DefaultFileTransferTransporterFactory : public FileTransferTransporterFactory { + public: + DefaultFileTransferTransporterFactory( + SOCKS5BytestreamRegistry*, + SOCKS5BytestreamServerManager* s5bServerManager, + SOCKS5BytestreamProxiesManager* s5bProxy, + IDGenerator* idGenerator, + ConnectionFactory*, + TimerFactory*, + CryptoProvider*, + IQRouter*); + virtual ~DefaultFileTransferTransporterFactory(); - virtual FileTransferTransporter* createInitiatorTransporter( - const JID& initiator, const JID& responder, const FileTransferOptions&) SWIFTEN_OVERRIDE; - virtual FileTransferTransporter* createResponderTransporter( - const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions&) SWIFTEN_OVERRIDE; + virtual FileTransferTransporter* createInitiatorTransporter( + const JID& initiator, const JID& responder, const FileTransferOptions&) SWIFTEN_OVERRIDE; + virtual FileTransferTransporter* createResponderTransporter( + const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions&) SWIFTEN_OVERRIDE; - private: - SOCKS5BytestreamRegistry* s5bRegistry; - SOCKS5BytestreamServerManager* s5bServerManager; - SOCKS5BytestreamProxiesManager* s5bProxiesManager; - IDGenerator* idGenerator; - ConnectionFactory* connectionFactory; - TimerFactory* timerFactory; - CryptoProvider* cryptoProvider; - IQRouter* iqRouter; - }; + private: + SOCKS5BytestreamRegistry* s5bRegistry; + SOCKS5BytestreamServerManager* s5bServerManager; + SOCKS5BytestreamProxiesManager* s5bProxiesManager; + IDGenerator* idGenerator; + ConnectionFactory* connectionFactory; + TimerFactory* timerFactory; + CryptoProvider* cryptoProvider; + IQRouter* iqRouter; + }; } diff --git a/Swiften/FileTransfer/FailingTransportSession.h b/Swiften/FileTransfer/FailingTransportSession.h index c197052..f0f21eb 100644 --- a/Swiften/FileTransfer/FailingTransportSession.h +++ b/Swiften/FileTransfer/FailingTransportSession.h @@ -12,17 +12,17 @@ namespace Swift { class SWIFTEN_API FailingTransportSession : public TransportSession { - public: - virtual ~FailingTransportSession() { - } + public: + virtual ~FailingTransportSession() { + } - virtual void start() SWIFTEN_OVERRIDE { - assert(false); - onFinished(FileTransferError(FileTransferError::PeerError)); - } + virtual void start() SWIFTEN_OVERRIDE { + assert(false); + onFinished(FileTransferError(FileTransferError::PeerError)); + } - virtual void stop() SWIFTEN_OVERRIDE { - } + virtual void stop() SWIFTEN_OVERRIDE { + } }; } diff --git a/Swiften/FileTransfer/FileReadBytestream.cpp b/Swiften/FileTransfer/FileReadBytestream.cpp index 4700a9c..7b7127a 100644 --- a/Swiften/FileTransfer/FileReadBytestream.cpp +++ b/Swiften/FileTransfer/FileReadBytestream.cpp @@ -20,28 +20,28 @@ FileReadBytestream::FileReadBytestream(const boost::filesystem::path& file) : fi } FileReadBytestream::~FileReadBytestream() { - if (stream) { - stream->close(); - delete stream; - stream = NULL; - } + if (stream) { + stream->close(); + delete stream; + stream = NULL; + } } boost::shared_ptr<ByteArray> FileReadBytestream::read(size_t size) { - if (!stream) { - stream = new boost::filesystem::ifstream(file, std::ios_base::in|std::ios_base::binary); - } - boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>(); - result->resize(size); - assert(stream->good()); - stream->read(reinterpret_cast<char*>(vecptr(*result)), boost::numeric_cast<std::streamsize>(size)); - result->resize(boost::numeric_cast<size_t>(stream->gcount())); - onRead(*result); - return result; + if (!stream) { + stream = new boost::filesystem::ifstream(file, std::ios_base::in|std::ios_base::binary); + } + boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>(); + result->resize(size); + assert(stream->good()); + stream->read(reinterpret_cast<char*>(vecptr(*result)), boost::numeric_cast<std::streamsize>(size)); + result->resize(boost::numeric_cast<size_t>(stream->gcount())); + onRead(*result); + return result; } bool FileReadBytestream::isFinished() const { - return stream && !stream->good(); + return stream && !stream->good(); } } diff --git a/Swiften/FileTransfer/FileReadBytestream.h b/Swiften/FileTransfer/FileReadBytestream.h index 5ea197e..24cfbae 100644 --- a/Swiften/FileTransfer/FileReadBytestream.h +++ b/Swiften/FileTransfer/FileReadBytestream.h @@ -13,16 +13,16 @@ #include <Swiften/FileTransfer/ReadBytestream.h> namespace Swift { - class SWIFTEN_API FileReadBytestream : public ReadBytestream { - public: - FileReadBytestream(const boost::filesystem::path& file); - virtual ~FileReadBytestream(); + class SWIFTEN_API FileReadBytestream : public ReadBytestream { + public: + FileReadBytestream(const boost::filesystem::path& file); + virtual ~FileReadBytestream(); - virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size); - virtual bool isFinished() const; + virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size); + virtual bool isFinished() const; - private: - boost::filesystem::path file; - boost::filesystem::ifstream* stream; - }; + private: + boost::filesystem::path file; + boost::filesystem::ifstream* stream; + }; } diff --git a/Swiften/FileTransfer/FileTransfer.cpp b/Swiften/FileTransfer/FileTransfer.cpp index 4782d39..32c9f53 100644 --- a/Swiften/FileTransfer/FileTransfer.cpp +++ b/Swiften/FileTransfer/FileTransfer.cpp @@ -15,12 +15,12 @@ FileTransfer::~FileTransfer() { } void FileTransfer::setState(const State& state) { - state_ = state; - onStateChanged(state); + state_ = state; + onStateChanged(state); } void FileTransfer::setFileInfo(const std::string& name, boost::uintmax_t size, const std::string& description) { - filename_ = name; - fileSizeInBytes_ = size; - description_ = description; + filename_ = name; + fileSizeInBytes_ = size; + description_ = description; } diff --git a/Swiften/FileTransfer/FileTransfer.h b/Swiften/FileTransfer/FileTransfer.h index ab8e806..b585ab9 100644 --- a/Swiften/FileTransfer/FileTransfer.h +++ b/Swiften/FileTransfer/FileTransfer.h @@ -21,68 +21,68 @@ #include <Swiften/FileTransfer/FileTransferError.h> namespace Swift { - /** - * The FileTransfer class provides a general interface for file-transfer - * implmenetations. Currently, only Jingle File Transfer based on XEP-0234 is - * implementated in the \ref OutgoingJingleFileTransfer and - * \ref IncomingJingleFileTransfer classes. - */ - class SWIFTEN_API FileTransfer { - public: - struct State { - enum Type { - Initial, - WaitingForStart, - Negotiating, - WaitingForAccept, - Transferring, - Canceled, - Failed, - Finished - }; - - State(Type type, const std::string& message = "") : type(type), message(message) {} - - Type type; - std::string message; - }; - typedef boost::shared_ptr<FileTransfer> ref; - - public: - FileTransfer(); - virtual ~FileTransfer(); - - virtual void cancel() = 0; - - const std::string& getFileName() const { - return filename_; - } - - boost::uintmax_t getFileSizeInBytes() const { - return fileSizeInBytes_; - } - - const State& getState() const { - return state_; - } - - const std::string& getDescription() const { - return description_; - } - - public: - boost::signal<void (size_t /* proccessedBytes */)> onProcessedBytes; - boost::signal<void (const State&)> onStateChanged; - boost::signal<void (boost::optional<FileTransferError>)> onFinished; - - protected: - void setState(const State& state); - void setFileInfo(const std::string& name, boost::uintmax_t size, const std::string& description); - - private: - boost::uintmax_t fileSizeInBytes_; - std::string filename_; - std::string description_; - State state_; - }; + /** + * The FileTransfer class provides a general interface for file-transfer + * implmenetations. Currently, only Jingle File Transfer based on XEP-0234 is + * implementated in the \ref OutgoingJingleFileTransfer and + * \ref IncomingJingleFileTransfer classes. + */ + class SWIFTEN_API FileTransfer { + public: + struct State { + enum Type { + Initial, + WaitingForStart, + Negotiating, + WaitingForAccept, + Transferring, + Canceled, + Failed, + Finished + }; + + State(Type type, const std::string& message = "") : type(type), message(message) {} + + Type type; + std::string message; + }; + typedef boost::shared_ptr<FileTransfer> ref; + + public: + FileTransfer(); + virtual ~FileTransfer(); + + virtual void cancel() = 0; + + const std::string& getFileName() const { + return filename_; + } + + boost::uintmax_t getFileSizeInBytes() const { + return fileSizeInBytes_; + } + + const State& getState() const { + return state_; + } + + const std::string& getDescription() const { + return description_; + } + + public: + boost::signal<void (size_t /* proccessedBytes */)> onProcessedBytes; + boost::signal<void (const State&)> onStateChanged; + boost::signal<void (boost::optional<FileTransferError>)> onFinished; + + protected: + void setState(const State& state); + void setFileInfo(const std::string& name, boost::uintmax_t size, const std::string& description); + + private: + boost::uintmax_t fileSizeInBytes_; + std::string filename_; + std::string description_; + State state_; + }; } diff --git a/Swiften/FileTransfer/FileTransferError.h b/Swiften/FileTransfer/FileTransferError.h index eff8ca9..e94ee7a 100644 --- a/Swiften/FileTransfer/FileTransferError.h +++ b/Swiften/FileTransfer/FileTransferError.h @@ -9,23 +9,23 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API FileTransferError { - public: - enum Type { - UnknownError, - PeerError, - ReadError, - WriteError, - ClosedError - }; + class SWIFTEN_API FileTransferError { + public: + enum Type { + UnknownError, + PeerError, + ReadError, + WriteError, + ClosedError + }; - FileTransferError(Type type = UnknownError) : type(type) {} + FileTransferError(Type type = UnknownError) : type(type) {} - Type getType() const { - return type; - } + Type getType() const { + return type; + } - private: - Type type; - }; + private: + Type type; + }; } diff --git a/Swiften/FileTransfer/FileTransferManager.cpp b/Swiften/FileTransfer/FileTransferManager.cpp index 0c7d894..94f4ab7 100644 --- a/Swiften/FileTransfer/FileTransferManager.cpp +++ b/Swiften/FileTransfer/FileTransferManager.cpp @@ -12,12 +12,12 @@ FileTransferManager::~FileTransferManager() { } bool FileTransferManager::isSupportedBy(const DiscoInfo::ref info) { - if (info) { - return info->hasFeature(DiscoInfo::JingleFeature) - && info->hasFeature(DiscoInfo::JingleFTFeature) - && (info->hasFeature(DiscoInfo::JingleTransportsIBBFeature) || info->hasFeature(DiscoInfo::JingleTransportsS5BFeature)); - } - return false; + if (info) { + return info->hasFeature(DiscoInfo::JingleFeature) + && info->hasFeature(DiscoInfo::JingleFTFeature) + && (info->hasFeature(DiscoInfo::JingleTransportsIBBFeature) || info->hasFeature(DiscoInfo::JingleTransportsS5BFeature)); + } + return false; } } diff --git a/Swiften/FileTransfer/FileTransferManager.h b/Swiften/FileTransfer/FileTransferManager.h index ec568e8..be2902a 100644 --- a/Swiften/FileTransfer/FileTransferManager.h +++ b/Swiften/FileTransfer/FileTransferManager.h @@ -26,29 +26,29 @@ #include <Swiften/JID/JID.h> namespace Swift { - class ReadBytestream; - - class SWIFTEN_API FileTransferManager { - public: - virtual ~FileTransferManager(); - - virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( - const JID& to, - const boost::filesystem::path& filepath, - const std::string& description, - boost::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions& = FileTransferOptions()) = 0; - virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( - const JID& to, - const std::string& filename, - const std::string& description, - const boost::uintmax_t sizeInBytes, - const boost::posix_time::ptime& lastModified, - boost::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions& = FileTransferOptions()) = 0; - - static bool isSupportedBy(const DiscoInfo::ref info); - - boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer; - }; + class ReadBytestream; + + class SWIFTEN_API FileTransferManager { + public: + virtual ~FileTransferManager(); + + virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( + const JID& to, + const boost::filesystem::path& filepath, + const std::string& description, + boost::shared_ptr<ReadBytestream> bytestream, + const FileTransferOptions& = FileTransferOptions()) = 0; + virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( + const JID& to, + const std::string& filename, + const std::string& description, + const boost::uintmax_t sizeInBytes, + const boost::posix_time::ptime& lastModified, + boost::shared_ptr<ReadBytestream> bytestream, + const FileTransferOptions& = FileTransferOptions()) = 0; + + static bool isSupportedBy(const DiscoInfo::ref info); + + boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer; + }; } diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.cpp b/Swiften/FileTransfer/FileTransferManagerImpl.cpp index 2bd6a04..80993ef 100644 --- a/Swiften/FileTransfer/FileTransferManagerImpl.cpp +++ b/Swiften/FileTransfer/FileTransferManagerImpl.cpp @@ -40,147 +40,147 @@ namespace Swift { FileTransferManagerImpl::FileTransferManagerImpl( - const JID& ownJID, - JingleSessionManager* jingleSessionManager, - IQRouter* router, - EntityCapsProvider* capsProvider, - PresenceOracle* presOracle, - ConnectionFactory* connectionFactory, - ConnectionServerFactory* connectionServerFactory, - TimerFactory* timerFactory, - DomainNameResolver* domainNameResolver, - NetworkEnvironment* networkEnvironment, - NATTraverser* natTraverser, - CryptoProvider* crypto) : - iqRouter(router), - capsProvider(capsProvider), - presenceOracle(presOracle) { - bytestreamRegistry = new SOCKS5BytestreamRegistry(); - s5bServerManager = new SOCKS5BytestreamServerManager( - bytestreamRegistry, connectionServerFactory, networkEnvironment, natTraverser); - bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, domainNameResolver, iqRouter, JID(ownJID.getDomain())); - - transporterFactory = new DefaultFileTransferTransporterFactory( - bytestreamRegistry, - s5bServerManager, - bytestreamProxy, - &idGenerator, - connectionFactory, - timerFactory, - crypto, - iqRouter); - outgoingFTManager = new OutgoingFileTransferManager( - jingleSessionManager, - iqRouter, - transporterFactory, - timerFactory, - crypto); - incomingFTManager = new IncomingFileTransferManager( - jingleSessionManager, - transporterFactory, - timerFactory, - crypto); - incomingFTManager->onIncomingFileTransfer.connect(onIncomingFileTransfer); + const JID& ownJID, + JingleSessionManager* jingleSessionManager, + IQRouter* router, + EntityCapsProvider* capsProvider, + PresenceOracle* presOracle, + ConnectionFactory* connectionFactory, + ConnectionServerFactory* connectionServerFactory, + TimerFactory* timerFactory, + DomainNameResolver* domainNameResolver, + NetworkEnvironment* networkEnvironment, + NATTraverser* natTraverser, + CryptoProvider* crypto) : + iqRouter(router), + capsProvider(capsProvider), + presenceOracle(presOracle) { + bytestreamRegistry = new SOCKS5BytestreamRegistry(); + s5bServerManager = new SOCKS5BytestreamServerManager( + bytestreamRegistry, connectionServerFactory, networkEnvironment, natTraverser); + bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, domainNameResolver, iqRouter, JID(ownJID.getDomain())); + + transporterFactory = new DefaultFileTransferTransporterFactory( + bytestreamRegistry, + s5bServerManager, + bytestreamProxy, + &idGenerator, + connectionFactory, + timerFactory, + crypto, + iqRouter); + outgoingFTManager = new OutgoingFileTransferManager( + jingleSessionManager, + iqRouter, + transporterFactory, + timerFactory, + crypto); + incomingFTManager = new IncomingFileTransferManager( + jingleSessionManager, + transporterFactory, + timerFactory, + crypto); + incomingFTManager->onIncomingFileTransfer.connect(onIncomingFileTransfer); } FileTransferManagerImpl::~FileTransferManagerImpl() { - delete incomingFTManager; - delete outgoingFTManager; - delete transporterFactory; - delete bytestreamProxy; - delete s5bServerManager; - delete bytestreamRegistry; + delete incomingFTManager; + delete outgoingFTManager; + delete transporterFactory; + delete bytestreamProxy; + delete s5bServerManager; + delete bytestreamRegistry; } void FileTransferManagerImpl::start() { } void FileTransferManagerImpl::stop() { - s5bServerManager->stop(); + s5bServerManager->stop(); } boost::optional<JID> FileTransferManagerImpl::highestPriorityJIDSupportingFileTransfer(const JID& bareJID) { - JID fullReceipientJID; - int priority = INT_MIN; - - //getAllPresence(bareJID) gives you all presences for the bare JID (i.e. all resources) Isode Limited. @ 11:11 - std::vector<Presence::ref> presences = presenceOracle->getAllPresence(bareJID); - - //iterate over them - foreach(Presence::ref pres, presences) { - if (pres->getPriority() > priority) { - // look up caps from the jid - DiscoInfo::ref info = capsProvider->getCaps(pres->getFrom()); - if (isSupportedBy(info)) { - priority = pres->getPriority(); - fullReceipientJID = pres->getFrom(); - } - } - } - - return fullReceipientJID.isValid() ? boost::optional<JID>(fullReceipientJID) : boost::optional<JID>(); + JID fullReceipientJID; + int priority = INT_MIN; + + //getAllPresence(bareJID) gives you all presences for the bare JID (i.e. all resources) Isode Limited. @ 11:11 + std::vector<Presence::ref> presences = presenceOracle->getAllPresence(bareJID); + + //iterate over them + foreach(Presence::ref pres, presences) { + if (pres->getPriority() > priority) { + // look up caps from the jid + DiscoInfo::ref info = capsProvider->getCaps(pres->getFrom()); + if (isSupportedBy(info)) { + priority = pres->getPriority(); + fullReceipientJID = pres->getFrom(); + } + } + } + + return fullReceipientJID.isValid() ? boost::optional<JID>(fullReceipientJID) : boost::optional<JID>(); } OutgoingFileTransfer::ref FileTransferManagerImpl::createOutgoingFileTransfer( - const JID& to, - const boost::filesystem::path& filepath, - const std::string& description, - boost::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions& config) { + const JID& to, + const boost::filesystem::path& filepath, + const std::string& description, + boost::shared_ptr<ReadBytestream> bytestream, + const FileTransferOptions& config) { #if BOOST_FILESYSTEM_VERSION == 2 // TODO: Delete this when boost 1.44 becomes a minimum requirement, and we no longer need v2 - std::string filename = filepath.filename(); + std::string filename = filepath.filename(); #else - std::string filename = pathToString(filepath.filename()); + std::string filename = pathToString(filepath.filename()); #endif - boost::uintmax_t sizeInBytes = boost::filesystem::file_size(filepath); - boost::posix_time::ptime lastModified = boost::posix_time::from_time_t(boost::filesystem::last_write_time(filepath)); - return createOutgoingFileTransfer(to, filename, description, sizeInBytes, lastModified, bytestream, config); + boost::uintmax_t sizeInBytes = boost::filesystem::file_size(filepath); + boost::posix_time::ptime lastModified = boost::posix_time::from_time_t(boost::filesystem::last_write_time(filepath)); + return createOutgoingFileTransfer(to, filename, description, sizeInBytes, lastModified, bytestream, config); } OutgoingFileTransfer::ref FileTransferManagerImpl::createOutgoingFileTransfer( - const JID& to, - const std::string& filename, - const std::string& description, - const boost::uintmax_t sizeInBytes, - const boost::posix_time::ptime& lastModified, - boost::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions& config) { - JingleFileTransferFileInfo fileInfo; - fileInfo.setDate(lastModified); - fileInfo.setSize(sizeInBytes); - fileInfo.setName(filename); - fileInfo.setDescription(description); - - JID receipient = to; - - if(receipient.isBare()) { - boost::optional<JID> fullJID = highestPriorityJIDSupportingFileTransfer(receipient); - if (fullJID.is_initialized()) { - receipient = fullJID.get(); - } else { - return OutgoingFileTransfer::ref(); - } - } - - assert(!iqRouter->getJID().isBare()); - - DiscoInfo::ref capabilities = capsProvider->getCaps(receipient); - - FileTransferOptions options = config; - if (capabilities) { - if (!capabilities->hasFeature(DiscoInfo::JingleTransportsS5BFeature)) { - options = options.withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false); - } - if (!capabilities->hasFeature(DiscoInfo::JingleTransportsIBBFeature)) { - options = options.withInBandAllowed(false); - } - } - else { - SWIFT_LOG(warning) << "No entity capabilities information for " << receipient.toString() << std::endl; - } - - return outgoingFTManager->createOutgoingFileTransfer(iqRouter->getJID(), receipient, bytestream, fileInfo, options); + const JID& to, + const std::string& filename, + const std::string& description, + const boost::uintmax_t sizeInBytes, + const boost::posix_time::ptime& lastModified, + boost::shared_ptr<ReadBytestream> bytestream, + const FileTransferOptions& config) { + JingleFileTransferFileInfo fileInfo; + fileInfo.setDate(lastModified); + fileInfo.setSize(sizeInBytes); + fileInfo.setName(filename); + fileInfo.setDescription(description); + + JID receipient = to; + + if(receipient.isBare()) { + boost::optional<JID> fullJID = highestPriorityJIDSupportingFileTransfer(receipient); + if (fullJID.is_initialized()) { + receipient = fullJID.get(); + } else { + return OutgoingFileTransfer::ref(); + } + } + + assert(!iqRouter->getJID().isBare()); + + DiscoInfo::ref capabilities = capsProvider->getCaps(receipient); + + FileTransferOptions options = config; + if (capabilities) { + if (!capabilities->hasFeature(DiscoInfo::JingleTransportsS5BFeature)) { + options = options.withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false); + } + if (!capabilities->hasFeature(DiscoInfo::JingleTransportsIBBFeature)) { + options = options.withInBandAllowed(false); + } + } + else { + SWIFT_LOG(warning) << "No entity capabilities information for " << receipient.toString() << std::endl; + } + + return outgoingFTManager->createOutgoingFileTransfer(iqRouter->getJID(), receipient, bytestream, fileInfo, options); } } diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.h b/Swiften/FileTransfer/FileTransferManagerImpl.h index 49490c8..a939ace 100644 --- a/Swiften/FileTransfer/FileTransferManagerImpl.h +++ b/Swiften/FileTransfer/FileTransferManagerImpl.h @@ -30,74 +30,74 @@ #include <Swiften/FileTransfer/OutgoingFileTransfer.h> namespace Swift { - class ConnectionFactory; - class ConnectionServerFactory; - class CryptoProvider; - class DomainNameResolver; - class EntityCapsProvider; - class FileTransferTransporterFactory; - class IQRouter; - class IncomingFileTransferManager; - class JID; - class JingleSessionManager; - class NATTraverser; - class NetworkEnvironment; - class OutgoingFileTransferManager; - class PresenceOracle; - class ReadBytestream; - class SOCKS5BytestreamProxiesManager; - class SOCKS5BytestreamRegistry; - class SOCKS5BytestreamServerManager; - class TimerFactory; + class ConnectionFactory; + class ConnectionServerFactory; + class CryptoProvider; + class DomainNameResolver; + class EntityCapsProvider; + class FileTransferTransporterFactory; + class IQRouter; + class IncomingFileTransferManager; + class JID; + class JingleSessionManager; + class NATTraverser; + class NetworkEnvironment; + class OutgoingFileTransferManager; + class PresenceOracle; + class ReadBytestream; + class SOCKS5BytestreamProxiesManager; + class SOCKS5BytestreamRegistry; + class SOCKS5BytestreamServerManager; + class TimerFactory; - class SWIFTEN_API FileTransferManagerImpl : public FileTransferManager { - public: - FileTransferManagerImpl( - const JID& ownFullJID, - JingleSessionManager* jingleSessionManager, - IQRouter* router, - EntityCapsProvider* capsProvider, - PresenceOracle* presOracle, - ConnectionFactory* connectionFactory, - ConnectionServerFactory* connectionServerFactory, - TimerFactory* timerFactory, - DomainNameResolver* domainNameResolver, - NetworkEnvironment* networkEnvironment, - NATTraverser* natTraverser, - CryptoProvider* crypto); - virtual ~FileTransferManagerImpl(); - - OutgoingFileTransfer::ref createOutgoingFileTransfer( - const JID& to, - const boost::filesystem::path& filepath, - const std::string& description, - boost::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions&) SWIFTEN_OVERRIDE; - OutgoingFileTransfer::ref createOutgoingFileTransfer( - const JID& to, - const std::string& filename, - const std::string& description, - const boost::uintmax_t sizeInBytes, - const boost::posix_time::ptime& lastModified, - boost::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions&) SWIFTEN_OVERRIDE; + class SWIFTEN_API FileTransferManagerImpl : public FileTransferManager { + public: + FileTransferManagerImpl( + const JID& ownFullJID, + JingleSessionManager* jingleSessionManager, + IQRouter* router, + EntityCapsProvider* capsProvider, + PresenceOracle* presOracle, + ConnectionFactory* connectionFactory, + ConnectionServerFactory* connectionServerFactory, + TimerFactory* timerFactory, + DomainNameResolver* domainNameResolver, + NetworkEnvironment* networkEnvironment, + NATTraverser* natTraverser, + CryptoProvider* crypto); + virtual ~FileTransferManagerImpl(); - void start(); - void stop(); - - private: - boost::optional<JID> highestPriorityJIDSupportingFileTransfer(const JID& bareJID); - - private: - OutgoingFileTransferManager* outgoingFTManager; - IncomingFileTransferManager* incomingFTManager; - FileTransferTransporterFactory* transporterFactory; - IQRouter* iqRouter; - EntityCapsProvider* capsProvider; - PresenceOracle* presenceOracle; - IDGenerator idGenerator; - SOCKS5BytestreamRegistry* bytestreamRegistry; - SOCKS5BytestreamProxiesManager* bytestreamProxy; - SOCKS5BytestreamServerManager* s5bServerManager; - }; + OutgoingFileTransfer::ref createOutgoingFileTransfer( + const JID& to, + const boost::filesystem::path& filepath, + const std::string& description, + boost::shared_ptr<ReadBytestream> bytestream, + const FileTransferOptions&) SWIFTEN_OVERRIDE; + OutgoingFileTransfer::ref createOutgoingFileTransfer( + const JID& to, + const std::string& filename, + const std::string& description, + const boost::uintmax_t sizeInBytes, + const boost::posix_time::ptime& lastModified, + boost::shared_ptr<ReadBytestream> bytestream, + const FileTransferOptions&) SWIFTEN_OVERRIDE; + + void start(); + void stop(); + + private: + boost::optional<JID> highestPriorityJIDSupportingFileTransfer(const JID& bareJID); + + private: + OutgoingFileTransferManager* outgoingFTManager; + IncomingFileTransferManager* incomingFTManager; + FileTransferTransporterFactory* transporterFactory; + IQRouter* iqRouter; + EntityCapsProvider* capsProvider; + PresenceOracle* presenceOracle; + IDGenerator idGenerator; + SOCKS5BytestreamRegistry* bytestreamRegistry; + SOCKS5BytestreamProxiesManager* bytestreamProxy; + SOCKS5BytestreamServerManager* s5bServerManager; + }; } diff --git a/Swiften/FileTransfer/FileTransferOptions.h b/Swiften/FileTransfer/FileTransferOptions.h index 77c6a8b..2bc4ee1 100644 --- a/Swiften/FileTransfer/FileTransferOptions.h +++ b/Swiften/FileTransfer/FileTransferOptions.h @@ -10,57 +10,57 @@ #include <Swiften/Base/Override.h> namespace Swift { - class SWIFTEN_API FileTransferOptions { - public: - FileTransferOptions() : allowInBand_(true), allowAssisted_(true), allowProxied_(true), allowDirect_(true) { - } - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(FileTransferOptions) - ~FileTransferOptions(); + class SWIFTEN_API FileTransferOptions { + public: + FileTransferOptions() : allowInBand_(true), allowAssisted_(true), allowProxied_(true), allowDirect_(true) { + } + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(FileTransferOptions) + ~FileTransferOptions(); - FileTransferOptions& withInBandAllowed(bool b) { - allowInBand_ = b; - return *this; - } + FileTransferOptions& withInBandAllowed(bool b) { + allowInBand_ = b; + return *this; + } - bool isInBandAllowed() const { - return allowInBand_; - } + bool isInBandAllowed() const { + return allowInBand_; + } - FileTransferOptions& withAssistedAllowed(bool b) { - allowAssisted_ = b; - return *this; - } + FileTransferOptions& withAssistedAllowed(bool b) { + allowAssisted_ = b; + return *this; + } - bool isAssistedAllowed() const { - return allowAssisted_; - } + bool isAssistedAllowed() const { + return allowAssisted_; + } - FileTransferOptions& withProxiedAllowed(bool b) { - allowProxied_ = b; - return *this; - } + FileTransferOptions& withProxiedAllowed(bool b) { + allowProxied_ = b; + return *this; + } - bool isProxiedAllowed() const { - return allowProxied_; - } + bool isProxiedAllowed() const { + return allowProxied_; + } - FileTransferOptions& withDirectAllowed(bool b) { - allowDirect_ = b; - return *this; - } + FileTransferOptions& withDirectAllowed(bool b) { + allowDirect_ = b; + return *this; + } - bool isDirectAllowed() const { - return allowDirect_; - } + bool isDirectAllowed() const { + return allowDirect_; + } - SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(FileTransferOptions) + SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(FileTransferOptions) - private: - bool allowInBand_; - bool allowAssisted_; - bool allowProxied_; - bool allowDirect_; - }; + private: + bool allowInBand_; + bool allowAssisted_; + bool allowProxied_; + bool allowDirect_; + }; } diff --git a/Swiften/FileTransfer/FileTransferTransporter.h b/Swiften/FileTransfer/FileTransferTransporter.h index fe401f0..dc12b0e 100644 --- a/Swiften/FileTransfer/FileTransferTransporter.h +++ b/Swiften/FileTransfer/FileTransferTransporter.h @@ -15,46 +15,46 @@ #include <Swiften/Elements/JingleS5BTransportPayload.h> namespace Swift { - class TransportSession; - class ErrorPayload; - class ReadBytestream; - class WriteBytestream; - - /** - * @brief The FileTransferTransporter class is an abstract factory definition - * to generate SOCKS5 bytestream transports or IBB bytestreams for use in file - * transfers. - */ - class SWIFTEN_API FileTransferTransporter { - public: - virtual ~FileTransferTransporter(); - - virtual void startGeneratingLocalCandidates() = 0; - virtual void stopGeneratingLocalCandidates() = 0; - - virtual void addRemoteCandidates( - const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) = 0; - virtual void startTryingRemoteCandidates() = 0; - virtual void stopTryingRemoteCandidates() = 0; - - virtual void startActivatingProxy(const JID& proxy) = 0; - virtual void stopActivatingProxy() = 0; - - virtual boost::shared_ptr<TransportSession> createIBBSendSession( - const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) = 0; - virtual boost::shared_ptr<TransportSession> createIBBReceiveSession( - const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) = 0; - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( - boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( - boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( - boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( - boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; - - boost::signal<void (const std::string& /* sessionID */, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& /* dstAddr */)> onLocalCandidatesGenerated; - boost::signal<void (const std::string& /* sessionID */, const boost::optional<JingleS5BTransportPayload::Candidate>&)> onRemoteCandidateSelectFinished; - boost::signal<void (const std::string& /* sessionID */, boost::shared_ptr<ErrorPayload>)> onProxyActivated; - }; + class TransportSession; + class ErrorPayload; + class ReadBytestream; + class WriteBytestream; + + /** + * @brief The FileTransferTransporter class is an abstract factory definition + * to generate SOCKS5 bytestream transports or IBB bytestreams for use in file + * transfers. + */ + class SWIFTEN_API FileTransferTransporter { + public: + virtual ~FileTransferTransporter(); + + virtual void startGeneratingLocalCandidates() = 0; + virtual void stopGeneratingLocalCandidates() = 0; + + virtual void addRemoteCandidates( + const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) = 0; + virtual void startTryingRemoteCandidates() = 0; + virtual void stopTryingRemoteCandidates() = 0; + + virtual void startActivatingProxy(const JID& proxy) = 0; + virtual void stopActivatingProxy() = 0; + + virtual boost::shared_ptr<TransportSession> createIBBSendSession( + const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) = 0; + virtual boost::shared_ptr<TransportSession> createIBBReceiveSession( + const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) = 0; + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( + boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( + boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( + boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( + boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0; + + boost::signal<void (const std::string& /* sessionID */, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& /* dstAddr */)> onLocalCandidatesGenerated; + boost::signal<void (const std::string& /* sessionID */, const boost::optional<JingleS5BTransportPayload::Candidate>&)> onRemoteCandidateSelectFinished; + boost::signal<void (const std::string& /* sessionID */, boost::shared_ptr<ErrorPayload>)> onProxyActivated; + }; } diff --git a/Swiften/FileTransfer/FileTransferTransporterFactory.h b/Swiften/FileTransfer/FileTransferTransporterFactory.h index a1af4af..4adf32e 100644 --- a/Swiften/FileTransfer/FileTransferTransporterFactory.h +++ b/Swiften/FileTransfer/FileTransferTransporterFactory.h @@ -11,22 +11,22 @@ #include <Swiften/Base/API.h> namespace Swift { - class JID; - class FileTransferTransporter; - class FileTransferOptions; + class JID; + class FileTransferTransporter; + class FileTransferOptions; - class SWIFTEN_API FileTransferTransporterFactory { - public: - virtual ~FileTransferTransporterFactory(); + class SWIFTEN_API FileTransferTransporterFactory { + public: + virtual ~FileTransferTransporterFactory(); - virtual FileTransferTransporter* createInitiatorTransporter( - const JID& initiator, - const JID& responder, - const FileTransferOptions& options) = 0; - virtual FileTransferTransporter* createResponderTransporter( - const JID& initiator, - const JID& responder, - const std::string& s5bSessionID, - const FileTransferOptions& options) = 0; - }; + virtual FileTransferTransporter* createInitiatorTransporter( + const JID& initiator, + const JID& responder, + const FileTransferOptions& options) = 0; + virtual FileTransferTransporter* createResponderTransporter( + const JID& initiator, + const JID& responder, + const std::string& s5bSessionID, + const FileTransferOptions& options) = 0; + }; } diff --git a/Swiften/FileTransfer/FileWriteBytestream.cpp b/Swiften/FileTransfer/FileWriteBytestream.cpp index c39d63a..b07f444 100644 --- a/Swiften/FileTransfer/FileWriteBytestream.cpp +++ b/Swiften/FileTransfer/FileWriteBytestream.cpp @@ -17,36 +17,36 @@ FileWriteBytestream::FileWriteBytestream(const boost::filesystem::path& file) : } FileWriteBytestream::~FileWriteBytestream() { - if (stream) { - stream->close(); - delete stream; - stream = NULL; - } + if (stream) { + stream->close(); + delete stream; + stream = NULL; + } } bool FileWriteBytestream::write(const std::vector<unsigned char>& data) { - if (data.empty()) { - return true; - } - if (!stream) { - stream = new boost::filesystem::ofstream(file, std::ios_base::out|std::ios_base::binary); - } - if (stream->good()) { - stream->write(reinterpret_cast<const char*>(&data[0]), boost::numeric_cast<std::streamsize>(data.size())); - if (stream->good()) { - onWrite(data); - return true; - } - } - return false; + if (data.empty()) { + return true; + } + if (!stream) { + stream = new boost::filesystem::ofstream(file, std::ios_base::out|std::ios_base::binary); + } + if (stream->good()) { + stream->write(reinterpret_cast<const char*>(&data[0]), boost::numeric_cast<std::streamsize>(data.size())); + if (stream->good()) { + onWrite(data); + return true; + } + } + return false; } void FileWriteBytestream::close() { - if (stream) { - stream->close(); - delete stream; - stream = NULL; - } + if (stream) { + stream->close(); + delete stream; + stream = NULL; + } } } diff --git a/Swiften/FileTransfer/FileWriteBytestream.h b/Swiften/FileTransfer/FileWriteBytestream.h index 02e1b46..c563789 100644 --- a/Swiften/FileTransfer/FileWriteBytestream.h +++ b/Swiften/FileTransfer/FileWriteBytestream.h @@ -13,16 +13,16 @@ #include <Swiften/FileTransfer/WriteBytestream.h> namespace Swift { - class SWIFTEN_API FileWriteBytestream : public WriteBytestream { - public: - FileWriteBytestream(const boost::filesystem::path& file); - virtual ~FileWriteBytestream(); + class SWIFTEN_API FileWriteBytestream : public WriteBytestream { + public: + FileWriteBytestream(const boost::filesystem::path& file); + virtual ~FileWriteBytestream(); - virtual bool write(const std::vector<unsigned char>&); - void close(); + virtual bool write(const std::vector<unsigned char>&); + void close(); - private: - boost::filesystem::path file; - boost::filesystem::ofstream* stream; - }; + private: + boost::filesystem::path file; + boost::filesystem::ofstream* stream; + }; } diff --git a/Swiften/FileTransfer/IBBReceiveSession.cpp b/Swiften/FileTransfer/IBBReceiveSession.cpp index cce263b..5a29ccb 100644 --- a/Swiften/FileTransfer/IBBReceiveSession.cpp +++ b/Swiften/FileTransfer/IBBReceiveSession.cpp @@ -19,100 +19,100 @@ namespace Swift { class IBBReceiveSession::IBBResponder : public SetResponder<IBB> { - public: - IBBResponder(IBBReceiveSession* session, IQRouter* router) : SetResponder<IBB>(router), session(session), sequenceNumber(0), receivedSize(0) { - setFinal(false); - } + public: + IBBResponder(IBBReceiveSession* session, IQRouter* router) : SetResponder<IBB>(router), session(session), sequenceNumber(0), receivedSize(0) { + setFinal(false); + } - virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, IBB::ref ibb) { - if (from == session->from && ibb->getStreamID() == session->id) { - if (ibb->getAction() == IBB::Data) { - if (sequenceNumber == ibb->getSequenceNumber()) { - session->bytestream->write(ibb->getData()); - receivedSize += ibb->getData().size(); - sequenceNumber++; - sendResponse(from, id, IBB::ref()); - if (receivedSize >= session->size) { - if (receivedSize > session->size) { - SWIFT_LOG(warning) << "Received more data than expected"; - } - session->finish(boost::optional<FileTransferError>()); - } - } - else { - SWIFT_LOG(warning) << "Received data out of order"; - sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel); - session->finish(FileTransferError(FileTransferError::ClosedError)); - } - } - else if (ibb->getAction() == IBB::Open) { - SWIFT_LOG(debug) << "IBB open received"; - sendResponse(from, id, IBB::ref()); - } - else if (ibb->getAction() == IBB::Close) { - SWIFT_LOG(debug) << "IBB close received"; - sendResponse(from, id, IBB::ref()); - session->finish(FileTransferError(FileTransferError::ClosedError)); - } - return true; - } - SWIFT_LOG(debug) << "wrong from/sessionID: " << from << " == " << session->from << " / " <<ibb->getStreamID() << " == " << session->id; - return false; - } + virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, IBB::ref ibb) { + if (from == session->from && ibb->getStreamID() == session->id) { + if (ibb->getAction() == IBB::Data) { + if (sequenceNumber == ibb->getSequenceNumber()) { + session->bytestream->write(ibb->getData()); + receivedSize += ibb->getData().size(); + sequenceNumber++; + sendResponse(from, id, IBB::ref()); + if (receivedSize >= session->size) { + if (receivedSize > session->size) { + SWIFT_LOG(warning) << "Received more data than expected"; + } + session->finish(boost::optional<FileTransferError>()); + } + } + else { + SWIFT_LOG(warning) << "Received data out of order"; + sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel); + session->finish(FileTransferError(FileTransferError::ClosedError)); + } + } + else if (ibb->getAction() == IBB::Open) { + SWIFT_LOG(debug) << "IBB open received"; + sendResponse(from, id, IBB::ref()); + } + else if (ibb->getAction() == IBB::Close) { + SWIFT_LOG(debug) << "IBB close received"; + sendResponse(from, id, IBB::ref()); + session->finish(FileTransferError(FileTransferError::ClosedError)); + } + return true; + } + SWIFT_LOG(debug) << "wrong from/sessionID: " << from << " == " << session->from << " / " <<ibb->getStreamID() << " == " << session->id; + return false; + } - private: - IBBReceiveSession* session; - int sequenceNumber; - unsigned long long receivedSize; + private: + IBBReceiveSession* session; + int sequenceNumber; + unsigned long long receivedSize; }; IBBReceiveSession::IBBReceiveSession( - const std::string& id, - const JID& from, - const JID& to, - unsigned long long size, - boost::shared_ptr<WriteBytestream> bytestream, - IQRouter* router) : - id(id), - from(from), - to(to), - size(size), - bytestream(bytestream), - router(router), - active(false) { - assert(!id.empty()); - assert(from.isValid()); - responder = new IBBResponder(this, router); + const std::string& id, + const JID& from, + const JID& to, + unsigned long long size, + boost::shared_ptr<WriteBytestream> bytestream, + IQRouter* router) : + id(id), + from(from), + to(to), + size(size), + bytestream(bytestream), + router(router), + active(false) { + assert(!id.empty()); + assert(from.isValid()); + responder = new IBBResponder(this, router); } IBBReceiveSession::~IBBReceiveSession() { - if (active) { - SWIFT_LOG(warning) << "Session still active"; - } - delete responder; + if (active) { + SWIFT_LOG(warning) << "Session still active"; + } + delete responder; } void IBBReceiveSession::start() { - SWIFT_LOG(debug) << "receive session started"; - active = true; - responder->start(); + SWIFT_LOG(debug) << "receive session started"; + active = true; + responder->start(); } void IBBReceiveSession::stop() { - SWIFT_LOG(debug) << "receive session stopped"; - responder->stop(); - if (active) { - if (router->isAvailable()) { - IBBRequest::create(to, from, IBB::createIBBClose(id), router)->send(); - } - finish(boost::optional<FileTransferError>()); - } + SWIFT_LOG(debug) << "receive session stopped"; + responder->stop(); + if (active) { + if (router->isAvailable()) { + IBBRequest::create(to, from, IBB::createIBBClose(id), router)->send(); + } + finish(boost::optional<FileTransferError>()); + } } void IBBReceiveSession::finish(boost::optional<FileTransferError> error) { - active = false; - onFinished(error); + active = false; + onFinished(error); } } diff --git a/Swiften/FileTransfer/IBBReceiveSession.h b/Swiften/FileTransfer/IBBReceiveSession.h index c6f7211..3eec96e 100644 --- a/Swiften/FileTransfer/IBBReceiveSession.h +++ b/Swiften/FileTransfer/IBBReceiveSession.h @@ -17,47 +17,47 @@ #include <Swiften/JID/JID.h> namespace Swift { - class IQRouter; - - class SWIFTEN_API IBBReceiveSession { - public: - IBBReceiveSession( - const std::string& id, - const JID& from, - const JID& to, - unsigned long long size, - boost::shared_ptr<WriteBytestream> bytestream, - IQRouter* router); - ~IBBReceiveSession(); - - void start(); - void stop(); - - const JID& getSender() const { - return from; - } - - const JID& getReceiver() const { - return to; - } - - boost::signal<void (boost::optional<FileTransferError>)> onFinished; - - private: - bool handleSetRequest(const JID& from, const JID& to, const std::string& id, IBB::ref payload); - void finish(boost::optional<FileTransferError>); - - private: - class IBBResponder; - friend class IBBResponder; - - std::string id; - JID from; - JID to; - unsigned long long size; - boost::shared_ptr<WriteBytestream> bytestream; - IQRouter* router; - IBBResponder* responder; - bool active; - }; + class IQRouter; + + class SWIFTEN_API IBBReceiveSession { + public: + IBBReceiveSession( + const std::string& id, + const JID& from, + const JID& to, + unsigned long long size, + boost::shared_ptr<WriteBytestream> bytestream, + IQRouter* router); + ~IBBReceiveSession(); + + void start(); + void stop(); + + const JID& getSender() const { + return from; + } + + const JID& getReceiver() const { + return to; + } + + boost::signal<void (boost::optional<FileTransferError>)> onFinished; + + private: + bool handleSetRequest(const JID& from, const JID& to, const std::string& id, IBB::ref payload); + void finish(boost::optional<FileTransferError>); + + private: + class IBBResponder; + friend class IBBResponder; + + std::string id; + JID from; + JID to; + unsigned long long size; + boost::shared_ptr<WriteBytestream> bytestream; + IQRouter* router; + IBBResponder* responder; + bool active; + }; } diff --git a/Swiften/FileTransfer/IBBReceiveTransportSession.cpp b/Swiften/FileTransfer/IBBReceiveTransportSession.cpp index ba56728..2e19b75 100644 --- a/Swiften/FileTransfer/IBBReceiveTransportSession.cpp +++ b/Swiften/FileTransfer/IBBReceiveTransportSession.cpp @@ -11,18 +11,18 @@ namespace Swift { IBBReceiveTransportSession::IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session) : session(session) { - finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1)); + finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1)); } IBBReceiveTransportSession::~IBBReceiveTransportSession() { } void IBBReceiveTransportSession::start() { - session->start(); + session->start(); } void IBBReceiveTransportSession::stop() { - session->stop(); + session->stop(); } } diff --git a/Swiften/FileTransfer/IBBReceiveTransportSession.h b/Swiften/FileTransfer/IBBReceiveTransportSession.h index 8a7c620..f66731b 100644 --- a/Swiften/FileTransfer/IBBReceiveTransportSession.h +++ b/Swiften/FileTransfer/IBBReceiveTransportSession.h @@ -14,17 +14,17 @@ namespace Swift { class SWIFTEN_API IBBReceiveTransportSession : public TransportSession { - public: - IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session); - virtual ~IBBReceiveTransportSession(); + public: + IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session); + virtual ~IBBReceiveTransportSession(); - virtual void start() SWIFTEN_OVERRIDE; - virtual void stop() SWIFTEN_OVERRIDE; + virtual void start() SWIFTEN_OVERRIDE; + virtual void stop() SWIFTEN_OVERRIDE; - private: - boost::shared_ptr<IBBReceiveSession> session; - boost::bsignals::scoped_connection finishedConnection; - boost::bsignals::scoped_connection bytesSentConnection; + private: + boost::shared_ptr<IBBReceiveSession> session; + boost::bsignals::scoped_connection finishedConnection; + boost::bsignals::scoped_connection bytesSentConnection; }; } diff --git a/Swiften/FileTransfer/IBBRequest.h b/Swiften/FileTransfer/IBBRequest.h index dc63b90..165dd21 100644 --- a/Swiften/FileTransfer/IBBRequest.h +++ b/Swiften/FileTransfer/IBBRequest.h @@ -11,16 +11,16 @@ #include <Swiften/Queries/GenericRequest.h> namespace Swift { - class SWIFTEN_API IBBRequest : public GenericRequest<IBB> { - public: - typedef boost::shared_ptr<IBBRequest> ref; + class SWIFTEN_API IBBRequest : public GenericRequest<IBB> { + public: + typedef boost::shared_ptr<IBBRequest> ref; - static ref create(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) { - return ref(new IBBRequest(from, to, payload, router)); - } + static ref create(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) { + return ref(new IBBRequest(from, to, payload, router)); + } - private: - IBBRequest(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) : GenericRequest<IBB>(IQ::Set, from, to, payload, router) { - } - }; + private: + IBBRequest(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) : GenericRequest<IBB>(IQ::Set, from, to, payload, router) { + } + }; } diff --git a/Swiften/FileTransfer/IBBSendSession.cpp b/Swiften/FileTransfer/IBBSendSession.cpp index 9f41532..10a36a9 100644 --- a/Swiften/FileTransfer/IBBSendSession.cpp +++ b/Swiften/FileTransfer/IBBSendSession.cpp @@ -17,92 +17,92 @@ namespace Swift { IBBSendSession::IBBSendSession( - const std::string& id, - const JID& from, - const JID& to, - boost::shared_ptr<ReadBytestream> bytestream, - IQRouter* router) : - id(id), - from(from), - to(to), - bytestream(bytestream), - router(router), - blockSize(4096), - sequenceNumber(0), - active(false), - waitingForData(false) { - bytestream->onDataAvailable.connect(boost::bind(&IBBSendSession::handleDataAvailable, this)); + const std::string& id, + const JID& from, + const JID& to, + boost::shared_ptr<ReadBytestream> bytestream, + IQRouter* router) : + id(id), + from(from), + to(to), + bytestream(bytestream), + router(router), + blockSize(4096), + sequenceNumber(0), + active(false), + waitingForData(false) { + bytestream->onDataAvailable.connect(boost::bind(&IBBSendSession::handleDataAvailable, this)); } IBBSendSession::~IBBSendSession() { - bytestream->onDataAvailable.disconnect(boost::bind(&IBBSendSession::handleDataAvailable, this)); + bytestream->onDataAvailable.disconnect(boost::bind(&IBBSendSession::handleDataAvailable, this)); } void IBBSendSession::start() { - IBBRequest::ref request = IBBRequest::create( - from, to, IBB::createIBBOpen(id, boost::numeric_cast<int>(blockSize)), router); - request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2)); - active = true; - request->send(); - currentRequest = request; + IBBRequest::ref request = IBBRequest::create( + from, to, IBB::createIBBOpen(id, boost::numeric_cast<int>(blockSize)), router); + request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2)); + active = true; + request->send(); + currentRequest = request; } void IBBSendSession::stop() { - if (active && router->isAvailable()) { - IBBRequest::create(from, to, IBB::createIBBClose(id), router)->send(); - } - if (currentRequest) { - currentRequest->onResponse.disconnect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2)); - } - finish(boost::optional<FileTransferError>()); + if (active && router->isAvailable()) { + IBBRequest::create(from, to, IBB::createIBBClose(id), router)->send(); + } + if (currentRequest) { + currentRequest->onResponse.disconnect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2)); + } + finish(boost::optional<FileTransferError>()); } void IBBSendSession::handleIBBResponse(IBB::ref, ErrorPayload::ref error) { - currentRequest.reset(); + currentRequest.reset(); - if (!error && active) { - if (!bytestream->isFinished()) { - sendMoreData(); - } - else { - finish(boost::optional<FileTransferError>()); - } - } - else { - finish(FileTransferError(FileTransferError::PeerError)); - } + if (!error && active) { + if (!bytestream->isFinished()) { + sendMoreData(); + } + else { + finish(boost::optional<FileTransferError>()); + } + } + else { + finish(FileTransferError(FileTransferError::PeerError)); + } } void IBBSendSession::sendMoreData() { - try { - boost::shared_ptr<ByteArray> data = bytestream->read(blockSize); - if (!data->empty()) { - waitingForData = false; - IBBRequest::ref request = IBBRequest::create(from, to, IBB::createIBBData(id, sequenceNumber, *data), router); - sequenceNumber++; - request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2)); - request->send(); - currentRequest = request; - onBytesSent(data->size()); - } - else { - waitingForData = true; - } - } - catch (const BytestreamException&) { - finish(FileTransferError(FileTransferError::ReadError)); - } + try { + boost::shared_ptr<ByteArray> data = bytestream->read(blockSize); + if (!data->empty()) { + waitingForData = false; + IBBRequest::ref request = IBBRequest::create(from, to, IBB::createIBBData(id, sequenceNumber, *data), router); + sequenceNumber++; + request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2)); + request->send(); + currentRequest = request; + onBytesSent(data->size()); + } + else { + waitingForData = true; + } + } + catch (const BytestreamException&) { + finish(FileTransferError(FileTransferError::ReadError)); + } } void IBBSendSession::finish(boost::optional<FileTransferError> error) { - active = false; - onFinished(error); + active = false; + onFinished(error); } void IBBSendSession::handleDataAvailable() { - if (waitingForData) { - sendMoreData(); - } + if (waitingForData) { + sendMoreData(); + } } } diff --git a/Swiften/FileTransfer/IBBSendSession.h b/Swiften/FileTransfer/IBBSendSession.h index af8cc12..e62ef79 100644 --- a/Swiften/FileTransfer/IBBSendSession.h +++ b/Swiften/FileTransfer/IBBSendSession.h @@ -18,53 +18,53 @@ #include <Swiften/JID/JID.h> namespace Swift { - class IQRouter; - class IBBRequest; + class IQRouter; + class IBBRequest; - class SWIFTEN_API IBBSendSession { - public: - IBBSendSession( - const std::string& id, - const JID& from, - const JID& to, - boost::shared_ptr<ReadBytestream> bytestream, - IQRouter* router); - ~IBBSendSession(); + class SWIFTEN_API IBBSendSession { + public: + IBBSendSession( + const std::string& id, + const JID& from, + const JID& to, + boost::shared_ptr<ReadBytestream> bytestream, + IQRouter* router); + ~IBBSendSession(); - void start(); - void stop(); + void start(); + void stop(); - const JID& getSender() const { - return from; - } + const JID& getSender() const { + return from; + } - const JID& getReceiver() const { - return to; - } + const JID& getReceiver() const { + return to; + } - void setBlockSize(unsigned int blockSize) { - this->blockSize = blockSize; - } + void setBlockSize(unsigned int blockSize) { + this->blockSize = blockSize; + } - boost::signal<void (boost::optional<FileTransferError>)> onFinished; - boost::signal<void (size_t)> onBytesSent; + boost::signal<void (boost::optional<FileTransferError>)> onFinished; + boost::signal<void (size_t)> onBytesSent; - private: - void handleIBBResponse(IBB::ref, ErrorPayload::ref); - void finish(boost::optional<FileTransferError>); - void sendMoreData(); - void handleDataAvailable(); + private: + void handleIBBResponse(IBB::ref, ErrorPayload::ref); + void finish(boost::optional<FileTransferError>); + void sendMoreData(); + void handleDataAvailable(); - private: - std::string id; - JID from; - JID to; - boost::shared_ptr<ReadBytestream> bytestream; - IQRouter* router; - unsigned int blockSize; - int sequenceNumber; - bool active; - bool waitingForData; - boost::shared_ptr<IBBRequest> currentRequest; - }; + private: + std::string id; + JID from; + JID to; + boost::shared_ptr<ReadBytestream> bytestream; + IQRouter* router; + unsigned int blockSize; + int sequenceNumber; + bool active; + bool waitingForData; + boost::shared_ptr<IBBRequest> currentRequest; + }; } diff --git a/Swiften/FileTransfer/IBBSendTransportSession.cpp b/Swiften/FileTransfer/IBBSendTransportSession.cpp index a023dde..fd2d8e6 100644 --- a/Swiften/FileTransfer/IBBSendTransportSession.cpp +++ b/Swiften/FileTransfer/IBBSendTransportSession.cpp @@ -11,19 +11,19 @@ namespace Swift { IBBSendTransportSession::IBBSendTransportSession(boost::shared_ptr<IBBSendSession> session) : session(session) { - finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1)); - bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1)); + finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1)); + bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1)); } IBBSendTransportSession::~IBBSendTransportSession() { } void IBBSendTransportSession::start() { - session->start(); + session->start(); } void IBBSendTransportSession::stop() { - session->stop(); + session->stop(); } } diff --git a/Swiften/FileTransfer/IBBSendTransportSession.h b/Swiften/FileTransfer/IBBSendTransportSession.h index 20700b4..812c42e 100644 --- a/Swiften/FileTransfer/IBBSendTransportSession.h +++ b/Swiften/FileTransfer/IBBSendTransportSession.h @@ -14,17 +14,17 @@ namespace Swift { class SWIFTEN_API IBBSendTransportSession : public TransportSession { - public: - IBBSendTransportSession(boost::shared_ptr<IBBSendSession> session); - virtual ~IBBSendTransportSession(); + public: + IBBSendTransportSession(boost::shared_ptr<IBBSendSession> session); + virtual ~IBBSendTransportSession(); - virtual void start() SWIFTEN_OVERRIDE; - virtual void stop() SWIFTEN_OVERRIDE; + virtual void start() SWIFTEN_OVERRIDE; + virtual void stop() SWIFTEN_OVERRIDE; - private: - boost::shared_ptr<IBBSendSession> session; - boost::bsignals::scoped_connection finishedConnection; - boost::bsignals::scoped_connection bytesSentConnection; + private: + boost::shared_ptr<IBBSendSession> session; + boost::bsignals::scoped_connection finishedConnection; + boost::bsignals::scoped_connection bytesSentConnection; }; } diff --git a/Swiften/FileTransfer/IncomingFileTransfer.h b/Swiften/FileTransfer/IncomingFileTransfer.h index 16905b8..4cb18e8 100644 --- a/Swiften/FileTransfer/IncomingFileTransfer.h +++ b/Swiften/FileTransfer/IncomingFileTransfer.h @@ -14,24 +14,24 @@ #include <Swiften/FileTransfer/FileTransferOptions.h> namespace Swift { - class WriteBytestream; - class JID; - - /** - * @brief The IncomingFileTransfer abstract class is the general interface in Swiften - * for incoming file transfers. - */ - class SWIFTEN_API IncomingFileTransfer : public FileTransfer { - public: - typedef boost::shared_ptr<IncomingFileTransfer> ref; - - virtual ~IncomingFileTransfer(); - - virtual void accept( - boost::shared_ptr<WriteBytestream>, - const FileTransferOptions& = FileTransferOptions()) = 0; - - virtual const JID& getSender() const = 0; - virtual const JID& getRecipient() const = 0; - }; + class WriteBytestream; + class JID; + + /** + * @brief The IncomingFileTransfer abstract class is the general interface in Swiften + * for incoming file transfers. + */ + class SWIFTEN_API IncomingFileTransfer : public FileTransfer { + public: + typedef boost::shared_ptr<IncomingFileTransfer> ref; + + virtual ~IncomingFileTransfer(); + + virtual void accept( + boost::shared_ptr<WriteBytestream>, + const FileTransferOptions& = FileTransferOptions()) = 0; + + virtual const JID& getSender() const = 0; + virtual const JID& getRecipient() const = 0; + }; } diff --git a/Swiften/FileTransfer/IncomingFileTransferManager.cpp b/Swiften/FileTransfer/IncomingFileTransferManager.cpp index f5b95ec..b0b4d49 100644 --- a/Swiften/FileTransfer/IncomingFileTransferManager.cpp +++ b/Swiften/FileTransfer/IncomingFileTransferManager.cpp @@ -20,46 +20,46 @@ namespace Swift { IncomingFileTransferManager::IncomingFileTransferManager( - JingleSessionManager* jingleSessionManager, - FileTransferTransporterFactory* transporterFactory, - TimerFactory* timerFactory, - CryptoProvider* crypto) : - jingleSessionManager(jingleSessionManager), - transporterFactory(transporterFactory), - timerFactory(timerFactory), - crypto(crypto) { - jingleSessionManager->addIncomingSessionHandler(this); + JingleSessionManager* jingleSessionManager, + FileTransferTransporterFactory* transporterFactory, + TimerFactory* timerFactory, + CryptoProvider* crypto) : + jingleSessionManager(jingleSessionManager), + transporterFactory(transporterFactory), + timerFactory(timerFactory), + crypto(crypto) { + jingleSessionManager->addIncomingSessionHandler(this); } IncomingFileTransferManager::~IncomingFileTransferManager() { - jingleSessionManager->removeIncomingSessionHandler(this); + jingleSessionManager->removeIncomingSessionHandler(this); } bool IncomingFileTransferManager::handleIncomingJingleSession( - JingleSession::ref session, - const std::vector<JingleContentPayload::ref>& contents, - const JID& recipient) { - if (JingleContentPayload::ref content = Jingle::getContentWithDescription<JingleFileTransferDescription>(contents)) { - if (content->getTransport<JingleS5BTransportPayload>() || content->getTransport<JingleIBBTransportPayload>()) { - JingleFileTransferDescription::ref description = content->getDescription<JingleFileTransferDescription>(); - if (description) { - IncomingJingleFileTransfer::ref transfer = boost::make_shared<IncomingJingleFileTransfer>( - recipient, session, content, transporterFactory, timerFactory, crypto); - onIncomingFileTransfer(transfer); - } - else { - SWIFT_LOG(warning) << "Received a file-transfer request with no file description."; - session->sendTerminate(JinglePayload::Reason::FailedApplication); - } - } - else { - session->sendTerminate(JinglePayload::Reason::UnsupportedTransports); - } - return true; - } - else { - return false; - } + JingleSession::ref session, + const std::vector<JingleContentPayload::ref>& contents, + const JID& recipient) { + if (JingleContentPayload::ref content = Jingle::getContentWithDescription<JingleFileTransferDescription>(contents)) { + if (content->getTransport<JingleS5BTransportPayload>() || content->getTransport<JingleIBBTransportPayload>()) { + JingleFileTransferDescription::ref description = content->getDescription<JingleFileTransferDescription>(); + if (description) { + IncomingJingleFileTransfer::ref transfer = boost::make_shared<IncomingJingleFileTransfer>( + recipient, session, content, transporterFactory, timerFactory, crypto); + onIncomingFileTransfer(transfer); + } + else { + SWIFT_LOG(warning) << "Received a file-transfer request with no file description."; + session->sendTerminate(JinglePayload::Reason::FailedApplication); + } + } + else { + session->sendTerminate(JinglePayload::Reason::UnsupportedTransports); + } + return true; + } + else { + return false; + } } diff --git a/Swiften/FileTransfer/IncomingFileTransferManager.h b/Swiften/FileTransfer/IncomingFileTransferManager.h index 285ff3f..7a34b2a 100644 --- a/Swiften/FileTransfer/IncomingFileTransferManager.h +++ b/Swiften/FileTransfer/IncomingFileTransferManager.h @@ -14,32 +14,32 @@ #include <Swiften/Jingle/IncomingJingleSessionHandler.h> namespace Swift { - class JingleSessionManager; - class FileTransferTransporterFactory; - class TimerFactory; - class CryptoProvider; - - class SWIFTEN_API IncomingFileTransferManager : public IncomingJingleSessionHandler { - public: - IncomingFileTransferManager( - JingleSessionManager* jingleSessionManager, - FileTransferTransporterFactory* transporterFactory, - TimerFactory* timerFactory, - CryptoProvider* crypto); - virtual ~IncomingFileTransferManager(); - - boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer; - - private: - bool handleIncomingJingleSession( - JingleSession::ref session, - const std::vector<JingleContentPayload::ref>& contents, - const JID& recipient); - - private: - JingleSessionManager* jingleSessionManager; - FileTransferTransporterFactory* transporterFactory; - TimerFactory* timerFactory; - CryptoProvider* crypto; - }; + class JingleSessionManager; + class FileTransferTransporterFactory; + class TimerFactory; + class CryptoProvider; + + class SWIFTEN_API IncomingFileTransferManager : public IncomingJingleSessionHandler { + public: + IncomingFileTransferManager( + JingleSessionManager* jingleSessionManager, + FileTransferTransporterFactory* transporterFactory, + TimerFactory* timerFactory, + CryptoProvider* crypto); + virtual ~IncomingFileTransferManager(); + + boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer; + + private: + bool handleIncomingJingleSession( + JingleSession::ref session, + const std::vector<JingleContentPayload::ref>& contents, + const JID& recipient); + + private: + JingleSessionManager* jingleSessionManager; + FileTransferTransporterFactory* transporterFactory; + TimerFactory* timerFactory; + CryptoProvider* crypto; + }; } diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp index db17620..40f952e 100644 --- a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp +++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp @@ -33,388 +33,388 @@ using namespace Swift; // TODO: ALlow terminate when already terminated. IncomingJingleFileTransfer::IncomingJingleFileTransfer( - const JID& toJID, - JingleSession::ref session, - JingleContentPayload::ref content, - FileTransferTransporterFactory* transporterFactory, - TimerFactory* timerFactory, - CryptoProvider* crypto) : - JingleFileTransfer(session, toJID, transporterFactory), - initialContent(content), - crypto(crypto), - state(Initial), - receivedBytes(0), - hashCalculator(NULL) { - description = initialContent->getDescription<JingleFileTransferDescription>(); - assert(description); - JingleFileTransferFileInfo fileInfo = description->getFileInfo(); - setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription()); - hashes = fileInfo.getHashes(); - - waitOnHashTimer = timerFactory->createTimer(5000); - waitOnHashTimerTickedConnection = waitOnHashTimer->onTick.connect( - boost::bind(&IncomingJingleFileTransfer::handleWaitOnHashTimerTicked, this)); + const JID& toJID, + JingleSession::ref session, + JingleContentPayload::ref content, + FileTransferTransporterFactory* transporterFactory, + TimerFactory* timerFactory, + CryptoProvider* crypto) : + JingleFileTransfer(session, toJID, transporterFactory), + initialContent(content), + crypto(crypto), + state(Initial), + receivedBytes(0), + hashCalculator(NULL) { + description = initialContent->getDescription<JingleFileTransferDescription>(); + assert(description); + JingleFileTransferFileInfo fileInfo = description->getFileInfo(); + setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription()); + hashes = fileInfo.getHashes(); + + waitOnHashTimer = timerFactory->createTimer(5000); + waitOnHashTimerTickedConnection = waitOnHashTimer->onTick.connect( + boost::bind(&IncomingJingleFileTransfer::handleWaitOnHashTimerTicked, this)); } IncomingJingleFileTransfer::~IncomingJingleFileTransfer() { - if (waitOnHashTimer) { - waitOnHashTimer->stop(); - } + if (waitOnHashTimer) { + waitOnHashTimer->stop(); + } - delete hashCalculator; - hashCalculator = NULL; + delete hashCalculator; + hashCalculator = NULL; } void IncomingJingleFileTransfer::accept( - boost::shared_ptr<WriteBytestream> stream, - const FileTransferOptions& options) { - SWIFT_LOG(debug) << std::endl; - if (state != Initial) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - - assert(!this->stream); - this->stream = stream; - this->options = options; - - assert(!hashCalculator); - - hashCalculator = new IncrementalBytestreamHashCalculator( - hashes.find("md5") != hashes.end(), hashes.find("sha-1") != hashes.end(), crypto); - - writeStreamDataReceivedConnection = stream->onWrite.connect( - boost::bind(&IncomingJingleFileTransfer::handleWriteStreamDataReceived, this, _1)); - - JingleS5BTransportPayload::ref s5bTransport = initialContent->getTransport<JingleS5BTransportPayload>(); - JingleIBBTransportPayload::ref ibbTransport = initialContent->getTransport<JingleIBBTransportPayload>(); - if (s5bTransport) { - SWIFT_LOG(debug) << "Got S5B transport as initial payload." << std::endl; - setTransporter(transporterFactory->createResponderTransporter( - getInitiator(), getResponder(), s5bTransport->getSessionID(), options)); - transporter->addRemoteCandidates(s5bTransport->getCandidates(), s5bTransport->getDstAddr()); - setState(GeneratingInitialLocalCandidates); - transporter->startGeneratingLocalCandidates(); - } - else if (ibbTransport && options.isInBandAllowed()) { - SWIFT_LOG(debug) << "Got IBB transport as initial payload." << std::endl; - setTransporter(transporterFactory->createResponderTransporter( - getInitiator(), getResponder(), ibbTransport->getSessionID(), options)); - - startTransferring(transporter->createIBBReceiveSession( - ibbTransport->getSessionID(), - description->getFileInfo().getSize(), - stream)); - - session->sendAccept(getContentID(), initialContent->getDescriptions()[0], ibbTransport); - } - else { - // This might happen on incoming transfer which only list transport methods we are not allowed to use due to file-transfer options. - session->sendTerminate(JinglePayload::Reason::UnsupportedTransports); - setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError)); - } + boost::shared_ptr<WriteBytestream> stream, + const FileTransferOptions& options) { + SWIFT_LOG(debug) << std::endl; + if (state != Initial) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + + assert(!this->stream); + this->stream = stream; + this->options = options; + + assert(!hashCalculator); + + hashCalculator = new IncrementalBytestreamHashCalculator( + hashes.find("md5") != hashes.end(), hashes.find("sha-1") != hashes.end(), crypto); + + writeStreamDataReceivedConnection = stream->onWrite.connect( + boost::bind(&IncomingJingleFileTransfer::handleWriteStreamDataReceived, this, _1)); + + JingleS5BTransportPayload::ref s5bTransport = initialContent->getTransport<JingleS5BTransportPayload>(); + JingleIBBTransportPayload::ref ibbTransport = initialContent->getTransport<JingleIBBTransportPayload>(); + if (s5bTransport) { + SWIFT_LOG(debug) << "Got S5B transport as initial payload." << std::endl; + setTransporter(transporterFactory->createResponderTransporter( + getInitiator(), getResponder(), s5bTransport->getSessionID(), options)); + transporter->addRemoteCandidates(s5bTransport->getCandidates(), s5bTransport->getDstAddr()); + setState(GeneratingInitialLocalCandidates); + transporter->startGeneratingLocalCandidates(); + } + else if (ibbTransport && options.isInBandAllowed()) { + SWIFT_LOG(debug) << "Got IBB transport as initial payload." << std::endl; + setTransporter(transporterFactory->createResponderTransporter( + getInitiator(), getResponder(), ibbTransport->getSessionID(), options)); + + startTransferring(transporter->createIBBReceiveSession( + ibbTransport->getSessionID(), + description->getFileInfo().getSize(), + stream)); + + session->sendAccept(getContentID(), initialContent->getDescriptions()[0], ibbTransport); + } + else { + // This might happen on incoming transfer which only list transport methods we are not allowed to use due to file-transfer options. + session->sendTerminate(JinglePayload::Reason::UnsupportedTransports); + setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError)); + } } void IncomingJingleFileTransfer::cancel() { - SWIFT_LOG(debug) << std::endl; - terminate(state == Initial ? JinglePayload::Reason::Decline : JinglePayload::Reason::Cancel); + SWIFT_LOG(debug) << std::endl; + terminate(state == Initial ? JinglePayload::Reason::Decline : JinglePayload::Reason::Cancel); } void IncomingJingleFileTransfer::handleLocalTransportCandidatesGenerated( - const std::string& s5bSessionID, - const std::vector<JingleS5BTransportPayload::Candidate>& candidates, - const std::string& dstAddr) { - SWIFT_LOG(debug) << std::endl; - if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + const std::string& s5bSessionID, + const std::vector<JingleS5BTransportPayload::Candidate>& candidates, + const std::string& dstAddr) { + SWIFT_LOG(debug) << std::endl; + if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - fillCandidateMap(localCandidates, candidates); + fillCandidateMap(localCandidates, candidates); - JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>(); - transport->setSessionID(s5bSessionID); - transport->setMode(JingleS5BTransportPayload::TCPMode); - transport->setDstAddr(dstAddr); - foreach(JingleS5BTransportPayload::Candidate candidate, candidates) { - transport->addCandidate(candidate); - } - session->sendAccept(getContentID(), initialContent->getDescriptions()[0], transport); + JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>(); + transport->setSessionID(s5bSessionID); + transport->setMode(JingleS5BTransportPayload::TCPMode); + transport->setDstAddr(dstAddr); + foreach(JingleS5BTransportPayload::Candidate candidate, candidates) { + transport->addCandidate(candidate); + } + session->sendAccept(getContentID(), initialContent->getDescriptions()[0], transport); - setState(TryingCandidates); - transporter->startTryingRemoteCandidates(); + setState(TryingCandidates); + transporter->startTryingRemoteCandidates(); } void IncomingJingleFileTransfer::handleSessionInfoReceived(JinglePayload::ref jinglePayload) { - SWIFT_LOG(debug) << std::endl; - - JingleFileTransferHash::ref transferHash = jinglePayload->getPayload<JingleFileTransferHash>(); - if (transferHash) { - SWIFT_LOG(debug) << "Received hash information." << std::endl; - waitOnHashTimer->stop(); - if (transferHash->getFileInfo().getHashes().find("sha-1") != transferHash->getFileInfo().getHashes().end()) { - hashes["sha-1"] = transferHash->getFileInfo().getHash("sha-1").get(); - } - if (transferHash->getFileInfo().getHashes().find("md5") != transferHash->getFileInfo().getHashes().end()) { - hashes["md5"] = transferHash->getFileInfo().getHash("md5").get(); - } - if (state == WaitingForHash) { - checkHashAndTerminate(); - } - } - else { - SWIFT_LOG(debug) << "Ignoring unknown session info" << std::endl; - } + SWIFT_LOG(debug) << std::endl; + + JingleFileTransferHash::ref transferHash = jinglePayload->getPayload<JingleFileTransferHash>(); + if (transferHash) { + SWIFT_LOG(debug) << "Received hash information." << std::endl; + waitOnHashTimer->stop(); + if (transferHash->getFileInfo().getHashes().find("sha-1") != transferHash->getFileInfo().getHashes().end()) { + hashes["sha-1"] = transferHash->getFileInfo().getHash("sha-1").get(); + } + if (transferHash->getFileInfo().getHashes().find("md5") != transferHash->getFileInfo().getHashes().end()) { + hashes["md5"] = transferHash->getFileInfo().getHash("md5").get(); + } + if (state == WaitingForHash) { + checkHashAndTerminate(); + } + } + else { + SWIFT_LOG(debug) << "Ignoring unknown session info" << std::endl; + } } void IncomingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) { - SWIFT_LOG(debug) << std::endl; - if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - - if (state == Finished) { - SWIFT_LOG(debug) << "Already terminated" << std::endl; - return; - } - - stopAll(); - if (reason && reason->type == JinglePayload::Reason::Cancel) { - setFinishedState(FileTransfer::State::Canceled, FileTransferError(FileTransferError::PeerError)); - } - else if (reason && reason->type == JinglePayload::Reason::Success) { - setFinishedState(FileTransfer::State::Finished, boost::optional<FileTransferError>()); - } - else { - setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError)); - } + SWIFT_LOG(debug) << std::endl; + if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + + if (state == Finished) { + SWIFT_LOG(debug) << "Already terminated" << std::endl; + return; + } + + stopAll(); + if (reason && reason->type == JinglePayload::Reason::Cancel) { + setFinishedState(FileTransfer::State::Canceled, FileTransferError(FileTransferError::PeerError)); + } + else if (reason && reason->type == JinglePayload::Reason::Success) { + setFinishedState(FileTransfer::State::Finished, boost::optional<FileTransferError>()); + } + else { + setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError)); + } } void IncomingJingleFileTransfer::checkHashAndTerminate() { - if (verifyData()) { - terminate(JinglePayload::Reason::Success); - } - else { - SWIFT_LOG(warning) << "Hash verification failed" << std::endl; - terminate(JinglePayload::Reason::MediaError); - } + if (verifyData()) { + terminate(JinglePayload::Reason::Success); + } + else { + SWIFT_LOG(warning) << "Hash verification failed" << std::endl; + terminate(JinglePayload::Reason::MediaError); + } } void IncomingJingleFileTransfer::checkIfAllDataReceived() { - if (receivedBytes == getFileSizeInBytes()) { - SWIFT_LOG(debug) << "All data received." << std::endl; - bool hashInfoAvailable = false; - foreach(const JingleFileTransferFileInfo::HashElementMap::value_type& hashElement, hashes) { - hashInfoAvailable |= !hashElement.second.empty(); - } - - if (!hashInfoAvailable) { - SWIFT_LOG(debug) << "No hash information yet. Waiting a while on hash info." << std::endl; - setState(WaitingForHash); - waitOnHashTimer->start(); - } - else { - checkHashAndTerminate(); - } - } - else if (receivedBytes > getFileSizeInBytes()) { - SWIFT_LOG(debug) << "We got more than we could handle!" << std::endl; - terminate(JinglePayload::Reason::MediaError); - } + if (receivedBytes == getFileSizeInBytes()) { + SWIFT_LOG(debug) << "All data received." << std::endl; + bool hashInfoAvailable = false; + foreach(const JingleFileTransferFileInfo::HashElementMap::value_type& hashElement, hashes) { + hashInfoAvailable |= !hashElement.second.empty(); + } + + if (!hashInfoAvailable) { + SWIFT_LOG(debug) << "No hash information yet. Waiting a while on hash info." << std::endl; + setState(WaitingForHash); + waitOnHashTimer->start(); + } + else { + checkHashAndTerminate(); + } + } + else if (receivedBytes > getFileSizeInBytes()) { + SWIFT_LOG(debug) << "We got more than we could handle!" << std::endl; + terminate(JinglePayload::Reason::MediaError); + } } void IncomingJingleFileTransfer::handleWriteStreamDataReceived( - const std::vector<unsigned char>& data) { - hashCalculator->feedData(data); - receivedBytes += data.size(); - onProcessedBytes(data.size()); - checkIfAllDataReceived(); + const std::vector<unsigned char>& data) { + hashCalculator->feedData(data); + receivedBytes += data.size(); + onProcessedBytes(data.size()); + checkIfAllDataReceived(); } void IncomingJingleFileTransfer::handleTransportReplaceReceived( - const JingleContentID& content, JingleTransportPayload::ref transport) { - SWIFT_LOG(debug) << std::endl; - if (state != WaitingForFallbackOrTerminate) { - SWIFT_LOG(warning) << "Incorrect state" << std::endl; - return; - } - - JingleIBBTransportPayload::ref ibbTransport; - if (options.isInBandAllowed() && (ibbTransport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) { - SWIFT_LOG(debug) << "transport replaced with IBB" << std::endl; - - startTransferring(transporter->createIBBReceiveSession( - ibbTransport->getSessionID(), - description->getFileInfo().getSize(), - stream)); - session->sendTransportAccept(content, ibbTransport); - } - else { - SWIFT_LOG(debug) << "Unknown replace transport" << std::endl; - session->sendTransportReject(content, transport); - } + const JingleContentID& content, JingleTransportPayload::ref transport) { + SWIFT_LOG(debug) << std::endl; + if (state != WaitingForFallbackOrTerminate) { + SWIFT_LOG(warning) << "Incorrect state" << std::endl; + return; + } + + JingleIBBTransportPayload::ref ibbTransport; + if (options.isInBandAllowed() && (ibbTransport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) { + SWIFT_LOG(debug) << "transport replaced with IBB" << std::endl; + + startTransferring(transporter->createIBBReceiveSession( + ibbTransport->getSessionID(), + description->getFileInfo().getSize(), + stream)); + session->sendTransportAccept(content, ibbTransport); + } + else { + SWIFT_LOG(debug) << "Unknown replace transport" << std::endl; + session->sendTransportReject(content, transport); + } } JingleContentID IncomingJingleFileTransfer::getContentID() const { - return JingleContentID(initialContent->getName(), initialContent->getCreator()); + return JingleContentID(initialContent->getName(), initialContent->getCreator()); } bool IncomingJingleFileTransfer::verifyData() { - if (hashes.empty()) { - SWIFT_LOG(debug) << "no verification possible, skipping" << std::endl; - return true; - } - if (hashes.find("sha-1") != hashes.end()) { - SWIFT_LOG(debug) << "Verify SHA-1 hash: " << (hashes["sha-1"] == hashCalculator->getSHA1Hash()) << std::endl; - return hashes["sha-1"] == hashCalculator->getSHA1Hash(); - } - else if (hashes.find("md5") != hashes.end()) { - SWIFT_LOG(debug) << "Verify MD5 hash: " << (hashes["md5"] == hashCalculator->getMD5Hash()) << std::endl; - return hashes["md5"] == hashCalculator->getMD5Hash(); - } - else { - SWIFT_LOG(debug) << "Unknown hash, skipping" << std::endl; - return true; - } + if (hashes.empty()) { + SWIFT_LOG(debug) << "no verification possible, skipping" << std::endl; + return true; + } + if (hashes.find("sha-1") != hashes.end()) { + SWIFT_LOG(debug) << "Verify SHA-1 hash: " << (hashes["sha-1"] == hashCalculator->getSHA1Hash()) << std::endl; + return hashes["sha-1"] == hashCalculator->getSHA1Hash(); + } + else if (hashes.find("md5") != hashes.end()) { + SWIFT_LOG(debug) << "Verify MD5 hash: " << (hashes["md5"] == hashCalculator->getMD5Hash()) << std::endl; + return hashes["md5"] == hashCalculator->getMD5Hash(); + } + else { + SWIFT_LOG(debug) << "Unknown hash, skipping" << std::endl; + return true; + } } void IncomingJingleFileTransfer::handleWaitOnHashTimerTicked() { - SWIFT_LOG(debug) << std::endl; - waitOnHashTimer->stop(); - terminate(JinglePayload::Reason::Success); + SWIFT_LOG(debug) << std::endl; + waitOnHashTimer->stop(); + terminate(JinglePayload::Reason::Success); } const JID& IncomingJingleFileTransfer::getSender() const { - return getInitiator(); + return getInitiator(); } const JID& IncomingJingleFileTransfer::getRecipient() const { - return getResponder(); + return getResponder(); } void IncomingJingleFileTransfer::setState(State state) { - SWIFT_LOG(debug) << state << std::endl; - this->state = state; - onStateChanged(FileTransfer::State(getExternalState(state))); + SWIFT_LOG(debug) << state << std::endl; + this->state = state; + onStateChanged(FileTransfer::State(getExternalState(state))); } void IncomingJingleFileTransfer::setFinishedState( - FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) { - SWIFT_LOG(debug) << std::endl; - this->state = Finished; - onStateChanged(type); - onFinished(error); + FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) { + SWIFT_LOG(debug) << std::endl; + this->state = Finished; + onStateChanged(type); + onFinished(error); } void IncomingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) { - if (error && state != WaitingForHash) { - terminate(JinglePayload::Reason::MediaError); - } + if (error && state != WaitingForHash) { + terminate(JinglePayload::Reason::MediaError); + } } FileTransfer::State::Type IncomingJingleFileTransfer::getExternalState(State state) { - switch (state) { - case Initial: return FileTransfer::State::Initial; - case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart; - case TryingCandidates: return FileTransfer::State::Negotiating; - case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating; - case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating; - case WaitingForFallbackOrTerminate: return FileTransfer::State::Negotiating; - case Transferring: return FileTransfer::State::Transferring; - case WaitingForHash: return FileTransfer::State::Transferring; - case Finished: return FileTransfer::State::Finished; - } - assert(false); - return FileTransfer::State::Initial; + switch (state) { + case Initial: return FileTransfer::State::Initial; + case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart; + case TryingCandidates: return FileTransfer::State::Negotiating; + case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating; + case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating; + case WaitingForFallbackOrTerminate: return FileTransfer::State::Negotiating; + case Transferring: return FileTransfer::State::Transferring; + case WaitingForHash: return FileTransfer::State::Transferring; + case Finished: return FileTransfer::State::Finished; + } + assert(false); + return FileTransfer::State::Initial; } void IncomingJingleFileTransfer::stopAll() { - if (state != Initial) { - writeStreamDataReceivedConnection.disconnect(); - delete hashCalculator; - hashCalculator = NULL; - } - switch (state) { - case Initial: break; - case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break; - case TryingCandidates: transporter->stopTryingRemoteCandidates(); break; - case WaitingForFallbackOrTerminate: break; - case WaitingForPeerProxyActivate: break; - case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break; - case WaitingForHash: // Fallthrough - case Transferring: - assert(transportSession); - transferFinishedConnection.disconnect(); - transportSession->stop(); - transportSession.reset(); - break; - case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break; - } - if (state != Initial) { - removeTransporter(); - } + if (state != Initial) { + writeStreamDataReceivedConnection.disconnect(); + delete hashCalculator; + hashCalculator = NULL; + } + switch (state) { + case Initial: break; + case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break; + case TryingCandidates: transporter->stopTryingRemoteCandidates(); break; + case WaitingForFallbackOrTerminate: break; + case WaitingForPeerProxyActivate: break; + case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break; + case WaitingForHash: // Fallthrough + case Transferring: + assert(transportSession); + transferFinishedConnection.disconnect(); + transportSession->stop(); + transportSession.reset(); + break; + case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break; + } + if (state != Initial) { + removeTransporter(); + } } bool IncomingJingleFileTransfer::hasPriorityOnCandidateTie() const { - return false; + return false; } void IncomingJingleFileTransfer::fallback() { - setState(WaitingForFallbackOrTerminate); + setState(WaitingForFallbackOrTerminate); } void IncomingJingleFileTransfer::startTransferViaRemoteCandidate() { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug) << std::endl; - if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { - setState(WaitingForPeerProxyActivate); - } - else { - startTransferring(createRemoteCandidateSession()); - } + if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { + setState(WaitingForPeerProxyActivate); + } + else { + startTransferring(createRemoteCandidateSession()); + } } void IncomingJingleFileTransfer::startTransferViaLocalCandidate() { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug) << std::endl; - if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { - setState(WaitingForLocalProxyActivate); - transporter->startActivatingProxy(theirCandidateChoice->jid); - } - else { - startTransferring(createLocalCandidateSession()); - } + if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { + setState(WaitingForLocalProxyActivate); + transporter->startActivatingProxy(theirCandidateChoice->jid); + } + else { + startTransferring(createLocalCandidateSession()); + } } void IncomingJingleFileTransfer::startTransferring(boost::shared_ptr<TransportSession> transportSession) { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug) << std::endl; - this->transportSession = transportSession; - transferFinishedConnection = transportSession->onFinished.connect( - boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1)); - setState(Transferring); - transportSession->start(); + this->transportSession = transportSession; + transferFinishedConnection = transportSession->onFinished.connect( + boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1)); + setState(Transferring); + transportSession->start(); } bool IncomingJingleFileTransfer::isWaitingForPeerProxyActivate() const { - return state == WaitingForPeerProxyActivate; + return state == WaitingForPeerProxyActivate; } bool IncomingJingleFileTransfer::isWaitingForLocalProxyActivate() const { - return state == WaitingForLocalProxyActivate; + return state == WaitingForLocalProxyActivate; } bool IncomingJingleFileTransfer::isTryingCandidates() const { - return state == TryingCandidates; + return state == TryingCandidates; } boost::shared_ptr<TransportSession> IncomingJingleFileTransfer::createLocalCandidateSession() { - return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get()); + return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get()); } boost::shared_ptr<TransportSession> IncomingJingleFileTransfer::createRemoteCandidateSession() { - return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get()); + return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get()); } void IncomingJingleFileTransfer::terminate(JinglePayload::Reason::Type reason) { - SWIFT_LOG(debug) << reason << std::endl; + SWIFT_LOG(debug) << reason << std::endl; - if (state != Finished) { - session->sendTerminate(reason); - } - stopAll(); - setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason)); + if (state != Finished) { + session->sendTerminate(reason); + } + stopAll(); + setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason)); } diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.h b/Swiften/FileTransfer/IncomingJingleFileTransfer.h index 57e2bcc..d3cc331 100644 --- a/Swiften/FileTransfer/IncomingJingleFileTransfer.h +++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.h @@ -21,109 +21,109 @@ #include <Swiften/Jingle/JingleContentID.h> namespace Swift { - class JID; - class JingleSession; - class JingleContentPayload; - class FileTransferTransporter; - class FileTransferTransporterFactory; - class TimerFactory; - class Timer; - class CryptoProvider; - class IncrementalBytestreamHashCalculator; - class JingleFileTransferDescription; - class HashElement; - - /** - * @brief The IncomingJingleFileTransfer class contains the business logic for managing incoming - * Jingle file transfers. - * - * Calling IncomingJingleFileTransfer::accept will start to negotiate possible transfer - * methods and after a working method has been decided among peers the trasnfer is started. - */ - class SWIFTEN_API IncomingJingleFileTransfer : public IncomingFileTransfer, public JingleFileTransfer { - public: - typedef boost::shared_ptr<IncomingJingleFileTransfer> ref; - - IncomingJingleFileTransfer( - const JID& recipient, - boost::shared_ptr<JingleSession>, - boost::shared_ptr<JingleContentPayload> content, - FileTransferTransporterFactory*, - TimerFactory*, - CryptoProvider*); - virtual ~IncomingJingleFileTransfer(); - - virtual void accept(boost::shared_ptr<WriteBytestream>, const FileTransferOptions& = FileTransferOptions()) SWIFTEN_OVERRIDE; - virtual void cancel() SWIFTEN_OVERRIDE; - - private: - enum State { - Initial, - GeneratingInitialLocalCandidates, - TryingCandidates, - WaitingForPeerProxyActivate, - WaitingForLocalProxyActivate, - WaitingForFallbackOrTerminate, - Transferring, - WaitingForHash, - Finished - }; - - virtual void handleSessionTerminateReceived( - boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE; - virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportReplaceReceived( - const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - - virtual void handleLocalTransportCandidatesGenerated( - const std::string& s5bSessionID, - const std::vector<JingleS5BTransportPayload::Candidate>&, - const std::string& dstAddr) SWIFTEN_OVERRIDE; - - void handleWriteStreamDataReceived(const std::vector<unsigned char>& data); - void stopActiveTransport(); - void checkCandidateSelected(); - virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE; - void checkIfAllDataReceived(); - bool verifyData(); - void handleWaitOnHashTimerTicked(); - void handleTransferFinished(boost::optional<FileTransferError>); - - private: - virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE; - virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE; - void checkHashAndTerminate(); - void stopAll(); - void setState(State state); - void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error); - const JID& getSender() const SWIFTEN_OVERRIDE; - const JID& getRecipient() const SWIFTEN_OVERRIDE; - static FileTransfer::State::Type getExternalState(State state); - virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE; - virtual void fallback() SWIFTEN_OVERRIDE; - virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE; - virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE; - virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; - - - private: - boost::shared_ptr<JingleContentPayload> initialContent; - CryptoProvider* crypto; - State state; - boost::shared_ptr<JingleFileTransferDescription> description; - boost::shared_ptr<WriteBytestream> stream; - boost::uintmax_t receivedBytes; - IncrementalBytestreamHashCalculator* hashCalculator; - boost::shared_ptr<Timer> waitOnHashTimer; - std::map<std::string, ByteArray> hashes; - FileTransferOptions options; - - boost::bsignals::scoped_connection writeStreamDataReceivedConnection; - boost::bsignals::scoped_connection waitOnHashTimerTickedConnection; - boost::bsignals::connection transferFinishedConnection; - }; + class JID; + class JingleSession; + class JingleContentPayload; + class FileTransferTransporter; + class FileTransferTransporterFactory; + class TimerFactory; + class Timer; + class CryptoProvider; + class IncrementalBytestreamHashCalculator; + class JingleFileTransferDescription; + class HashElement; + + /** + * @brief The IncomingJingleFileTransfer class contains the business logic for managing incoming + * Jingle file transfers. + * + * Calling IncomingJingleFileTransfer::accept will start to negotiate possible transfer + * methods and after a working method has been decided among peers the trasnfer is started. + */ + class SWIFTEN_API IncomingJingleFileTransfer : public IncomingFileTransfer, public JingleFileTransfer { + public: + typedef boost::shared_ptr<IncomingJingleFileTransfer> ref; + + IncomingJingleFileTransfer( + const JID& recipient, + boost::shared_ptr<JingleSession>, + boost::shared_ptr<JingleContentPayload> content, + FileTransferTransporterFactory*, + TimerFactory*, + CryptoProvider*); + virtual ~IncomingJingleFileTransfer(); + + virtual void accept(boost::shared_ptr<WriteBytestream>, const FileTransferOptions& = FileTransferOptions()) SWIFTEN_OVERRIDE; + virtual void cancel() SWIFTEN_OVERRIDE; + + private: + enum State { + Initial, + GeneratingInitialLocalCandidates, + TryingCandidates, + WaitingForPeerProxyActivate, + WaitingForLocalProxyActivate, + WaitingForFallbackOrTerminate, + Transferring, + WaitingForHash, + Finished + }; + + virtual void handleSessionTerminateReceived( + boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE; + virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE; + virtual void handleTransportReplaceReceived( + const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + + virtual void handleLocalTransportCandidatesGenerated( + const std::string& s5bSessionID, + const std::vector<JingleS5BTransportPayload::Candidate>&, + const std::string& dstAddr) SWIFTEN_OVERRIDE; + + void handleWriteStreamDataReceived(const std::vector<unsigned char>& data); + void stopActiveTransport(); + void checkCandidateSelected(); + virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE; + void checkIfAllDataReceived(); + bool verifyData(); + void handleWaitOnHashTimerTicked(); + void handleTransferFinished(boost::optional<FileTransferError>); + + private: + virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE; + virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE; + void checkHashAndTerminate(); + void stopAll(); + void setState(State state); + void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error); + const JID& getSender() const SWIFTEN_OVERRIDE; + const JID& getRecipient() const SWIFTEN_OVERRIDE; + static FileTransfer::State::Type getExternalState(State state); + virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE; + virtual void fallback() SWIFTEN_OVERRIDE; + virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE; + virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE; + virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE; + virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE; + virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; + + + private: + boost::shared_ptr<JingleContentPayload> initialContent; + CryptoProvider* crypto; + State state; + boost::shared_ptr<JingleFileTransferDescription> description; + boost::shared_ptr<WriteBytestream> stream; + boost::uintmax_t receivedBytes; + IncrementalBytestreamHashCalculator* hashCalculator; + boost::shared_ptr<Timer> waitOnHashTimer; + std::map<std::string, ByteArray> hashes; + FileTransferOptions options; + + boost::bsignals::scoped_connection writeStreamDataReceivedConnection; + boost::bsignals::scoped_connection waitOnHashTimerTickedConnection; + boost::bsignals::connection transferFinishedConnection; + }; } diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp index 483270c..f657192 100644 --- a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp +++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp @@ -19,57 +19,57 @@ namespace Swift { IncrementalBytestreamHashCalculator::IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1, CryptoProvider* crypto) { - md5Hasher = doMD5 ? crypto->createMD5() : NULL; - sha1Hasher = doSHA1 ? crypto->createSHA1() : NULL; + md5Hasher = doMD5 ? crypto->createMD5() : NULL; + sha1Hasher = doSHA1 ? crypto->createSHA1() : NULL; } IncrementalBytestreamHashCalculator::~IncrementalBytestreamHashCalculator() { - delete md5Hasher; - delete sha1Hasher; + delete md5Hasher; + delete sha1Hasher; } void IncrementalBytestreamHashCalculator::feedData(const ByteArray& data) { - if (md5Hasher) { - md5Hasher->update(data); - } - if (sha1Hasher) { - sha1Hasher->update(data); - } + if (md5Hasher) { + md5Hasher->update(data); + } + if (sha1Hasher) { + sha1Hasher->update(data); + } } /* void IncrementalBytestreamHashCalculator::feedData(const SafeByteArray& data) { - if (md5Hasher) { - md5Hasher->update(createByteArray(data.data(), data.size())); - } - if (sha1Hasher) { - sha1Hasher->update(createByteArray(data.data(), data.size())); - } + if (md5Hasher) { + md5Hasher->update(createByteArray(data.data(), data.size())); + } + if (sha1Hasher) { + sha1Hasher->update(createByteArray(data.data(), data.size())); + } }*/ ByteArray IncrementalBytestreamHashCalculator::getSHA1Hash() { - assert(sha1Hasher); - if (!sha1Hash) { - sha1Hash = sha1Hasher->getHash(); - } - return *sha1Hash; + assert(sha1Hasher); + if (!sha1Hash) { + sha1Hash = sha1Hasher->getHash(); + } + return *sha1Hash; } ByteArray IncrementalBytestreamHashCalculator::getMD5Hash() { - assert(md5Hasher); - if (!md5Hash) { - md5Hash = md5Hasher->getHash(); - } - return *md5Hash; + assert(md5Hasher); + if (!md5Hash) { + md5Hash = md5Hasher->getHash(); + } + return *md5Hash; } std::string IncrementalBytestreamHashCalculator::getSHA1String() { - assert(sha1Hasher); - return Hexify::hexify(getSHA1Hash());; + assert(sha1Hasher); + return Hexify::hexify(getSHA1Hash());; } std::string IncrementalBytestreamHashCalculator::getMD5String() { - assert(md5Hasher); - return Hexify::hexify(getMD5Hash());; + assert(md5Hasher); + return Hexify::hexify(getMD5Hash());; } } diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h index ba3c0e1..4477ec1 100644 --- a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h +++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h @@ -20,28 +20,28 @@ #include <Swiften/Base/SafeByteArray.h> namespace Swift { - class Hash; - class CryptoProvider; + class Hash; + class CryptoProvider; - class IncrementalBytestreamHashCalculator { - public: - IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1, CryptoProvider* crypto); - ~IncrementalBytestreamHashCalculator(); + class IncrementalBytestreamHashCalculator { + public: + IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1, CryptoProvider* crypto); + ~IncrementalBytestreamHashCalculator(); - void feedData(const ByteArray& data); - //void feedData(const SafeByteArray& data); + void feedData(const ByteArray& data); + //void feedData(const SafeByteArray& data); - ByteArray getSHA1Hash(); - ByteArray getMD5Hash(); + ByteArray getSHA1Hash(); + ByteArray getMD5Hash(); - std::string getSHA1String(); - std::string getMD5String(); + std::string getSHA1String(); + std::string getMD5String(); - private: - Hash* md5Hasher; - Hash* sha1Hasher; - boost::optional<ByteArray> md5Hash; - boost::optional<ByteArray> sha1Hash; - }; + private: + Hash* md5Hasher; + Hash* sha1Hasher; + boost::optional<ByteArray> md5Hash; + boost::optional<ByteArray> sha1Hash; + }; } diff --git a/Swiften/FileTransfer/JingleFileTransfer.cpp b/Swiften/FileTransfer/JingleFileTransfer.cpp index cf67a67..55296f9 100644 --- a/Swiften/FileTransfer/JingleFileTransfer.cpp +++ b/Swiften/FileTransfer/JingleFileTransfer.cpp @@ -19,217 +19,217 @@ using namespace Swift; JingleFileTransfer::JingleFileTransfer( - boost::shared_ptr<JingleSession> session, - const JID& target, - FileTransferTransporterFactory* transporterFactory) : - session(session), - target(target), - transporterFactory(transporterFactory), - transporter(NULL), - ourCandidateSelectFinished(false), - theirCandidateSelectFinished(false) { - - session->addListener(this); + boost::shared_ptr<JingleSession> session, + const JID& target, + FileTransferTransporterFactory* transporterFactory) : + session(session), + target(target), + transporterFactory(transporterFactory), + transporter(NULL), + ourCandidateSelectFinished(false), + theirCandidateSelectFinished(false) { + + session->addListener(this); } JingleFileTransfer::~JingleFileTransfer() { - session->removeListener(this); + session->removeListener(this); } void JingleFileTransfer::fillCandidateMap(CandidateMap& map, const std::vector<JingleS5BTransportPayload::Candidate>& candidates) { - map.clear(); - foreach (JingleS5BTransportPayload::Candidate candidate, candidates) { - map[candidate.cid] = candidate; - } + map.clear(); + foreach (JingleS5BTransportPayload::Candidate candidate, candidates) { + map[candidate.cid] = candidate; + } } /* std::string JingleFileTransfer::getS5BDstAddr(const JID& requester, const JID& target) const { - return Hexify::hexify(crypto->getSHA1Hash( - createSafeByteArray(s5bSessionID + requester.toString() + target.toString()))); + return Hexify::hexify(crypto->getSHA1Hash( + createSafeByteArray(s5bSessionID + requester.toString() + target.toString()))); } */ const JID& JingleFileTransfer::getInitiator() const { - return session->getInitiator(); + return session->getInitiator(); } const JID& JingleFileTransfer::getResponder() const { - return target; + return target; } FileTransfer::State::Type JingleFileTransfer::getExternalFinishedState(JinglePayload::Reason::Type reason) { - if (reason == JinglePayload::Reason::Cancel || reason == JinglePayload::Reason::Decline) { - return FileTransfer::State::Canceled; - } - else if (reason == JinglePayload::Reason::Success) { - return FileTransfer::State::Finished; - } - else { - return FileTransfer::State::Failed; - } + if (reason == JinglePayload::Reason::Cancel || reason == JinglePayload::Reason::Decline) { + return FileTransfer::State::Canceled; + } + else if (reason == JinglePayload::Reason::Success) { + return FileTransfer::State::Finished; + } + else { + return FileTransfer::State::Failed; + } } boost::optional<FileTransferError> JingleFileTransfer::getFileTransferError(JinglePayload::Reason::Type reason) { - if (reason == JinglePayload::Reason::Success) { - return boost::optional<FileTransferError>(); - } - else { - return boost::optional<FileTransferError>(FileTransferError::UnknownError); - } + if (reason == JinglePayload::Reason::Success) { + return boost::optional<FileTransferError>(); + } + else { + return boost::optional<FileTransferError>(FileTransferError::UnknownError); + } } void JingleFileTransfer::handleRemoteTransportCandidateSelectFinished( - const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>& candidate) { - SWIFT_LOG(debug) << std::endl; - - ourCandidateChoice = candidate; - ourCandidateSelectFinished = true; - - JingleS5BTransportPayload::ref s5bPayload = boost::make_shared<JingleS5BTransportPayload>(); - s5bPayload->setSessionID(s5bSessionID); - if (candidate) { - s5bPayload->setCandidateUsed(candidate->cid); - } - else { - s5bPayload->setCandidateError(true); - } - candidateSelectRequestID = session->sendTransportInfo(getContentID(), s5bPayload); - - decideOnCandidates(); + const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>& candidate) { + SWIFT_LOG(debug) << std::endl; + + ourCandidateChoice = candidate; + ourCandidateSelectFinished = true; + + JingleS5BTransportPayload::ref s5bPayload = boost::make_shared<JingleS5BTransportPayload>(); + s5bPayload->setSessionID(s5bSessionID); + if (candidate) { + s5bPayload->setCandidateUsed(candidate->cid); + } + else { + s5bPayload->setCandidateError(true); + } + candidateSelectRequestID = session->sendTransportInfo(getContentID(), s5bPayload); + + decideOnCandidates(); } // decide on candidates according to http://xmpp.org/extensions/xep-0260.html#complete void JingleFileTransfer::decideOnCandidates() { - SWIFT_LOG(debug) << std::endl; - if (!ourCandidateSelectFinished || !theirCandidateSelectFinished) { - SWIFT_LOG(debug) << "Can't make a decision yet!" << std::endl; - return; - } - if (!ourCandidateChoice && !theirCandidateChoice) { - SWIFT_LOG(debug) << "No candidates succeeded." << std::endl; - fallback(); - } - else if (ourCandidateChoice && !theirCandidateChoice) { - SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl; - startTransferViaRemoteCandidate(); - } - else if (theirCandidateChoice && !ourCandidateChoice) { - SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << "." << std::endl; - startTransferViaLocalCandidate(); - } - else { - SWIFT_LOG(debug) << "Choosing between candidates " - << ourCandidateChoice->cid << "(" << ourCandidateChoice->priority << ")" << " and " - << theirCandidateChoice->cid << "(" << theirCandidateChoice->priority << ")" << std::endl; - if (ourCandidateChoice->priority > theirCandidateChoice->priority) { - SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl; - startTransferViaRemoteCandidate(); - } - else if (ourCandidateChoice->priority < theirCandidateChoice->priority) { - SWIFT_LOG(debug) << "Start transfer using local candidate:" << theirCandidateChoice.get().cid << "." << std::endl; - startTransferViaLocalCandidate(); - } - else { - if (hasPriorityOnCandidateTie()) { - SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << std::endl; - startTransferViaRemoteCandidate(); - } - else { - SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << std::endl; - startTransferViaLocalCandidate(); - } - } - } + SWIFT_LOG(debug) << std::endl; + if (!ourCandidateSelectFinished || !theirCandidateSelectFinished) { + SWIFT_LOG(debug) << "Can't make a decision yet!" << std::endl; + return; + } + if (!ourCandidateChoice && !theirCandidateChoice) { + SWIFT_LOG(debug) << "No candidates succeeded." << std::endl; + fallback(); + } + else if (ourCandidateChoice && !theirCandidateChoice) { + SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl; + startTransferViaRemoteCandidate(); + } + else if (theirCandidateChoice && !ourCandidateChoice) { + SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << "." << std::endl; + startTransferViaLocalCandidate(); + } + else { + SWIFT_LOG(debug) << "Choosing between candidates " + << ourCandidateChoice->cid << "(" << ourCandidateChoice->priority << ")" << " and " + << theirCandidateChoice->cid << "(" << theirCandidateChoice->priority << ")" << std::endl; + if (ourCandidateChoice->priority > theirCandidateChoice->priority) { + SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl; + startTransferViaRemoteCandidate(); + } + else if (ourCandidateChoice->priority < theirCandidateChoice->priority) { + SWIFT_LOG(debug) << "Start transfer using local candidate:" << theirCandidateChoice.get().cid << "." << std::endl; + startTransferViaLocalCandidate(); + } + else { + if (hasPriorityOnCandidateTie()) { + SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << std::endl; + startTransferViaRemoteCandidate(); + } + else { + SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << std::endl; + startTransferViaLocalCandidate(); + } + } + } } void JingleFileTransfer::handleProxyActivateFinished( - const std::string& s5bSessionID, ErrorPayload::ref error) { - SWIFT_LOG(debug) << std::endl; - if (!isWaitingForLocalProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - - if (error) { - SWIFT_LOG(debug) << "Error activating proxy" << std::endl; - JingleS5BTransportPayload::ref proxyError = boost::make_shared<JingleS5BTransportPayload>(); - proxyError->setSessionID(s5bSessionID); - proxyError->setProxyError(true); - session->sendTransportInfo(getContentID(), proxyError); - fallback(); - } - else { - JingleS5BTransportPayload::ref proxyActivate = boost::make_shared<JingleS5BTransportPayload>(); - proxyActivate->setSessionID(s5bSessionID); - proxyActivate->setActivated(theirCandidateChoice->cid); - session->sendTransportInfo(getContentID(), proxyActivate); - startTransferring(createLocalCandidateSession()); - } + const std::string& s5bSessionID, ErrorPayload::ref error) { + SWIFT_LOG(debug) << std::endl; + if (!isWaitingForLocalProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + + if (error) { + SWIFT_LOG(debug) << "Error activating proxy" << std::endl; + JingleS5BTransportPayload::ref proxyError = boost::make_shared<JingleS5BTransportPayload>(); + proxyError->setSessionID(s5bSessionID); + proxyError->setProxyError(true); + session->sendTransportInfo(getContentID(), proxyError); + fallback(); + } + else { + JingleS5BTransportPayload::ref proxyActivate = boost::make_shared<JingleS5BTransportPayload>(); + proxyActivate->setSessionID(s5bSessionID); + proxyActivate->setActivated(theirCandidateChoice->cid); + session->sendTransportInfo(getContentID(), proxyActivate); + startTransferring(createLocalCandidateSession()); + } } void JingleFileTransfer::handleTransportInfoReceived( - const JingleContentID& /* contentID */, JingleTransportPayload::ref transport) { - SWIFT_LOG(debug) << std::endl; - - if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) { - if (s5bPayload->hasCandidateError() || !s5bPayload->getCandidateUsed().empty()) { - SWIFT_LOG(debug) << "Received candidate decision from peer" << std::endl; - if (!isTryingCandidates()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - - theirCandidateSelectFinished = true; - if (!s5bPayload->hasCandidateError()) { - BOOST_AUTO(theirCandidate, localCandidates.find(s5bPayload->getCandidateUsed())); - if (theirCandidate == localCandidates.end()) { - SWIFT_LOG(warning) << "Got invalid candidate" << std::endl; - terminate(JinglePayload::Reason::GeneralError); - return; - } - theirCandidateChoice = theirCandidate->second; - } - decideOnCandidates(); - } - else if (!s5bPayload->getActivated().empty()) { - SWIFT_LOG(debug) << "Received peer activate from peer" << std::endl; - if (!isWaitingForPeerProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - - if (ourCandidateChoice->cid == s5bPayload->getActivated()) { - startTransferring(createRemoteCandidateSession()); - } - else { - SWIFT_LOG(warning) << "ourCandidateChoice doesn't match activated proxy candidate!" << std::endl; - terminate(JinglePayload::Reason::GeneralError); - } - } - else if (s5bPayload->hasProxyError()) { - SWIFT_LOG(debug) << "Received proxy error. Trying to fall back to IBB." << std::endl; - fallback(); - } - else { - SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl; - } - } - else { - SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl; - } + const JingleContentID& /* contentID */, JingleTransportPayload::ref transport) { + SWIFT_LOG(debug) << std::endl; + + if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) { + if (s5bPayload->hasCandidateError() || !s5bPayload->getCandidateUsed().empty()) { + SWIFT_LOG(debug) << "Received candidate decision from peer" << std::endl; + if (!isTryingCandidates()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + + theirCandidateSelectFinished = true; + if (!s5bPayload->hasCandidateError()) { + BOOST_AUTO(theirCandidate, localCandidates.find(s5bPayload->getCandidateUsed())); + if (theirCandidate == localCandidates.end()) { + SWIFT_LOG(warning) << "Got invalid candidate" << std::endl; + terminate(JinglePayload::Reason::GeneralError); + return; + } + theirCandidateChoice = theirCandidate->second; + } + decideOnCandidates(); + } + else if (!s5bPayload->getActivated().empty()) { + SWIFT_LOG(debug) << "Received peer activate from peer" << std::endl; + if (!isWaitingForPeerProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + + if (ourCandidateChoice->cid == s5bPayload->getActivated()) { + startTransferring(createRemoteCandidateSession()); + } + else { + SWIFT_LOG(warning) << "ourCandidateChoice doesn't match activated proxy candidate!" << std::endl; + terminate(JinglePayload::Reason::GeneralError); + } + } + else if (s5bPayload->hasProxyError()) { + SWIFT_LOG(debug) << "Received proxy error. Trying to fall back to IBB." << std::endl; + fallback(); + } + else { + SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl; + } + } + else { + SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl; + } } void JingleFileTransfer::setTransporter(FileTransferTransporter* transporter) { - SWIFT_LOG_ASSERT(!this->transporter, error); - this->transporter = transporter; - localTransportCandidatesGeneratedConnection = transporter->onLocalCandidatesGenerated.connect( - boost::bind(&JingleFileTransfer::handleLocalTransportCandidatesGenerated, this, _1, _2, _3)); - remoteTransportCandidateSelectFinishedConnection = transporter->onRemoteCandidateSelectFinished.connect( - boost::bind(&JingleFileTransfer::handleRemoteTransportCandidateSelectFinished, this, _1, _2)); - proxyActivatedConnection = transporter->onProxyActivated.connect( - boost::bind(&JingleFileTransfer::handleProxyActivateFinished, this, _1, _2)); + SWIFT_LOG_ASSERT(!this->transporter, error); + this->transporter = transporter; + localTransportCandidatesGeneratedConnection = transporter->onLocalCandidatesGenerated.connect( + boost::bind(&JingleFileTransfer::handleLocalTransportCandidatesGenerated, this, _1, _2, _3)); + remoteTransportCandidateSelectFinishedConnection = transporter->onRemoteCandidateSelectFinished.connect( + boost::bind(&JingleFileTransfer::handleRemoteTransportCandidateSelectFinished, this, _1, _2)); + proxyActivatedConnection = transporter->onProxyActivated.connect( + boost::bind(&JingleFileTransfer::handleProxyActivateFinished, this, _1, _2)); } void JingleFileTransfer::removeTransporter() { - if (transporter) { - localTransportCandidatesGeneratedConnection.release(); - remoteTransportCandidateSelectFinishedConnection.release(); - proxyActivatedConnection.release(); - delete transporter; - transporter = NULL; - } + if (transporter) { + localTransportCandidatesGeneratedConnection.release(); + remoteTransportCandidateSelectFinishedConnection.release(); + proxyActivatedConnection.release(); + delete transporter; + transporter = NULL; + } } diff --git a/Swiften/FileTransfer/JingleFileTransfer.h b/Swiften/FileTransfer/JingleFileTransfer.h index 16a55c6..6862ba2 100644 --- a/Swiften/FileTransfer/JingleFileTransfer.h +++ b/Swiften/FileTransfer/JingleFileTransfer.h @@ -19,78 +19,78 @@ #include <Swiften/Jingle/JingleContentID.h> namespace Swift { - class CryptoProvider; - class IQRouter; - class RemoteJingleTransportCandidateSelector; - class LocalJingleTransportCandidateGenerator; - class JingleSession; - class FileTransferTransporter; - class FileTransferTransporterFactory; - class TransportSession; + class CryptoProvider; + class IQRouter; + class RemoteJingleTransportCandidateSelector; + class LocalJingleTransportCandidateGenerator; + class JingleSession; + class FileTransferTransporter; + class FileTransferTransporterFactory; + class TransportSession; - class SWIFTEN_API JingleFileTransfer : public AbstractJingleSessionListener { - public: - JingleFileTransfer( - boost::shared_ptr<JingleSession>, - const JID& target, - FileTransferTransporterFactory*); - virtual ~JingleFileTransfer(); + class SWIFTEN_API JingleFileTransfer : public AbstractJingleSessionListener { + public: + JingleFileTransfer( + boost::shared_ptr<JingleSession>, + const JID& target, + FileTransferTransporterFactory*); + virtual ~JingleFileTransfer(); - protected: - virtual void handleTransportInfoReceived(const JingleContentID&, JingleTransportPayload::ref); - virtual void handleLocalTransportCandidatesGenerated( - const std::string& s5bSessionID, - const std::vector<JingleS5BTransportPayload::Candidate>&, - const std::string& dstAddr) = 0; - virtual void handleProxyActivateFinished( - const std::string& s5bSessionID, - ErrorPayload::ref error); - virtual void decideOnCandidates(); - void handleRemoteTransportCandidateSelectFinished( - const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>&); - virtual JingleContentID getContentID() const = 0; - virtual void startTransferring(boost::shared_ptr<TransportSession>) = 0; - virtual void terminate(JinglePayload::Reason::Type reason) = 0; - virtual void fallback() = 0; - virtual bool hasPriorityOnCandidateTie() const = 0; - virtual bool isWaitingForPeerProxyActivate() const = 0; - virtual bool isWaitingForLocalProxyActivate() const = 0; - virtual bool isTryingCandidates() const = 0; - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() = 0; - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() = 0; - virtual void startTransferViaLocalCandidate() = 0; - virtual void startTransferViaRemoteCandidate() = 0; + protected: + virtual void handleTransportInfoReceived(const JingleContentID&, JingleTransportPayload::ref); + virtual void handleLocalTransportCandidatesGenerated( + const std::string& s5bSessionID, + const std::vector<JingleS5BTransportPayload::Candidate>&, + const std::string& dstAddr) = 0; + virtual void handleProxyActivateFinished( + const std::string& s5bSessionID, + ErrorPayload::ref error); + virtual void decideOnCandidates(); + void handleRemoteTransportCandidateSelectFinished( + const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>&); + virtual JingleContentID getContentID() const = 0; + virtual void startTransferring(boost::shared_ptr<TransportSession>) = 0; + virtual void terminate(JinglePayload::Reason::Type reason) = 0; + virtual void fallback() = 0; + virtual bool hasPriorityOnCandidateTie() const = 0; + virtual bool isWaitingForPeerProxyActivate() const = 0; + virtual bool isWaitingForLocalProxyActivate() const = 0; + virtual bool isTryingCandidates() const = 0; + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() = 0; + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() = 0; + virtual void startTransferViaLocalCandidate() = 0; + virtual void startTransferViaRemoteCandidate() = 0; - protected: - typedef std::map<std::string, JingleS5BTransportPayload::Candidate> CandidateMap; + protected: + typedef std::map<std::string, JingleS5BTransportPayload::Candidate> CandidateMap; - void setTransporter(FileTransferTransporter* transporter); - void removeTransporter(); - void fillCandidateMap( - CandidateMap& map, - const std::vector<JingleS5BTransportPayload::Candidate>&); - const JID& getInitiator() const; - const JID& getResponder() const; + void setTransporter(FileTransferTransporter* transporter); + void removeTransporter(); + void fillCandidateMap( + CandidateMap& map, + const std::vector<JingleS5BTransportPayload::Candidate>&); + const JID& getInitiator() const; + const JID& getResponder() const; - static FileTransfer::State::Type getExternalFinishedState(JinglePayload::Reason::Type); - static boost::optional<FileTransferError> getFileTransferError(JinglePayload::Reason::Type); + static FileTransfer::State::Type getExternalFinishedState(JinglePayload::Reason::Type); + static boost::optional<FileTransferError> getFileTransferError(JinglePayload::Reason::Type); - boost::shared_ptr<JingleSession> session; - JID target; - FileTransferTransporterFactory* transporterFactory; - FileTransferTransporter* transporter; + boost::shared_ptr<JingleSession> session; + JID target; + FileTransferTransporterFactory* transporterFactory; + FileTransferTransporter* transporter; - std::string candidateSelectRequestID; - bool ourCandidateSelectFinished; - boost::optional<JingleS5BTransportPayload::Candidate> ourCandidateChoice; - bool theirCandidateSelectFinished; - boost::optional<JingleS5BTransportPayload::Candidate> theirCandidateChoice; - CandidateMap localCandidates; + std::string candidateSelectRequestID; + bool ourCandidateSelectFinished; + boost::optional<JingleS5BTransportPayload::Candidate> ourCandidateChoice; + bool theirCandidateSelectFinished; + boost::optional<JingleS5BTransportPayload::Candidate> theirCandidateChoice; + CandidateMap localCandidates; - boost::shared_ptr<TransportSession> transportSession; + boost::shared_ptr<TransportSession> transportSession; - boost::bsignals::scoped_connection localTransportCandidatesGeneratedConnection; - boost::bsignals::scoped_connection remoteTransportCandidateSelectFinishedConnection; - boost::bsignals::scoped_connection proxyActivatedConnection; - }; + boost::bsignals::scoped_connection localTransportCandidatesGeneratedConnection; + boost::bsignals::scoped_connection remoteTransportCandidateSelectFinishedConnection; + boost::bsignals::scoped_connection proxyActivatedConnection; + }; } diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp index f6e6963..3703ba1 100644 --- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp +++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp @@ -31,162 +31,162 @@ static const unsigned int LOCAL_PREFERENCE = 0; namespace Swift { LocalJingleTransportCandidateGenerator::LocalJingleTransportCandidateGenerator( - SOCKS5BytestreamServerManager* s5bServerManager, - SOCKS5BytestreamProxiesManager* s5bProxy, - const JID& ownJID, - IDGenerator* idGenerator, - const FileTransferOptions& options) : - s5bServerManager(s5bServerManager), - s5bProxy(s5bProxy), - ownJID(ownJID), - idGenerator(idGenerator), - triedServerInit_(false), - triedForwarding_(false), - triedProxyDiscovery_(false), - options_(options) { + SOCKS5BytestreamServerManager* s5bServerManager, + SOCKS5BytestreamProxiesManager* s5bProxy, + const JID& ownJID, + IDGenerator* idGenerator, + const FileTransferOptions& options) : + s5bServerManager(s5bServerManager), + s5bProxy(s5bProxy), + ownJID(ownJID), + idGenerator(idGenerator), + triedServerInit_(false), + triedForwarding_(false), + triedProxyDiscovery_(false), + options_(options) { } LocalJingleTransportCandidateGenerator::~LocalJingleTransportCandidateGenerator() { - SWIFT_LOG_ASSERT(!s5bServerInitializeRequest, warning) << std::endl; + SWIFT_LOG_ASSERT(!s5bServerInitializeRequest, warning) << std::endl; } void LocalJingleTransportCandidateGenerator::start() { - assert(!s5bServerInitializeRequest); - if (options_.isDirectAllowed() || options_.isAssistedAllowed()) { - s5bServerResourceUser_ = s5bServerManager->aquireResourceUser(); - if (s5bServerResourceUser_->isInitialized()) { - handleS5BServerInitialized(true); - } - else { - s5bServerResourceUser_->onSuccessfulInitialized.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); - } - } else { - handleS5BServerInitialized(false); - } - - if (options_.isProxiedAllowed()) { - s5bProxy->onDiscoveredProxiesChanged.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this)); - if (s5bProxy->getOrDiscoverS5BProxies().is_initialized()) { - handleDiscoveredProxiesChanged(); - } - } + assert(!s5bServerInitializeRequest); + if (options_.isDirectAllowed() || options_.isAssistedAllowed()) { + s5bServerResourceUser_ = s5bServerManager->aquireResourceUser(); + if (s5bServerResourceUser_->isInitialized()) { + handleS5BServerInitialized(true); + } + else { + s5bServerResourceUser_->onSuccessfulInitialized.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); + } + } else { + handleS5BServerInitialized(false); + } + + if (options_.isProxiedAllowed()) { + s5bProxy->onDiscoveredProxiesChanged.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this)); + if (s5bProxy->getOrDiscoverS5BProxies().is_initialized()) { + handleDiscoveredProxiesChanged(); + } + } } void LocalJingleTransportCandidateGenerator::stop() { - s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this)); - if (s5bServerPortForwardingUser_) { - s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1)); - s5bServerPortForwardingUser_.reset(); - } - if (s5bServerResourceUser_) { - s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); - s5bServerResourceUser_.reset(); - } + s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this)); + if (s5bServerPortForwardingUser_) { + s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1)); + s5bServerPortForwardingUser_.reset(); + } + if (s5bServerResourceUser_) { + s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); + s5bServerResourceUser_.reset(); + } } void LocalJingleTransportCandidateGenerator::handleS5BServerInitialized(bool success) { - if (s5bServerResourceUser_) { - s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); - } - triedServerInit_ = true; - if (success) { - if (options_.isAssistedAllowed()) { - // try to setup port forwarding - s5bServerPortForwardingUser_ = s5bServerManager->aquirePortForwardingUser(); - s5bServerPortForwardingUser_->onSetup.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1)); - if (s5bServerPortForwardingUser_->isForwardingSetup()) { - handlePortForwardingSetup(true); - } - } - } - else { - SWIFT_LOG(warning) << "Unable to start SOCKS5 server" << std::endl; - if (s5bServerResourceUser_) { - s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); - } - s5bServerResourceUser_.reset(); - handlePortForwardingSetup(false); - } - checkS5BCandidatesReady(); + if (s5bServerResourceUser_) { + s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); + } + triedServerInit_ = true; + if (success) { + if (options_.isAssistedAllowed()) { + // try to setup port forwarding + s5bServerPortForwardingUser_ = s5bServerManager->aquirePortForwardingUser(); + s5bServerPortForwardingUser_->onSetup.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1)); + if (s5bServerPortForwardingUser_->isForwardingSetup()) { + handlePortForwardingSetup(true); + } + } + } + else { + SWIFT_LOG(warning) << "Unable to start SOCKS5 server" << std::endl; + if (s5bServerResourceUser_) { + s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1)); + } + s5bServerResourceUser_.reset(); + handlePortForwardingSetup(false); + } + checkS5BCandidatesReady(); } void LocalJingleTransportCandidateGenerator::handlePortForwardingSetup(bool /* success */) { - if (s5bServerPortForwardingUser_) { - s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1)); - } - triedForwarding_ = true; - checkS5BCandidatesReady(); + if (s5bServerPortForwardingUser_) { + s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1)); + } + triedForwarding_ = true; + checkS5BCandidatesReady(); } void LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged() { - if (s5bProxy) { - s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this)); - } - triedProxyDiscovery_ = true; - checkS5BCandidatesReady(); + if (s5bProxy) { + s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this)); + } + triedProxyDiscovery_ = true; + checkS5BCandidatesReady(); } void LocalJingleTransportCandidateGenerator::checkS5BCandidatesReady() { - if ((!options_.isDirectAllowed() || (options_.isDirectAllowed() && triedServerInit_)) && - (!options_.isProxiedAllowed() || (options_.isProxiedAllowed() && triedProxyDiscovery_)) && - (!options_.isAssistedAllowed() || (options_.isAssistedAllowed() && triedForwarding_))) { - emitOnLocalTransportCandidatesGenerated(); - } + if ((!options_.isDirectAllowed() || (options_.isDirectAllowed() && triedServerInit_)) && + (!options_.isProxiedAllowed() || (options_.isProxiedAllowed() && triedProxyDiscovery_)) && + (!options_.isAssistedAllowed() || (options_.isAssistedAllowed() && triedForwarding_))) { + emitOnLocalTransportCandidatesGenerated(); + } } void LocalJingleTransportCandidateGenerator::emitOnLocalTransportCandidatesGenerated() { - std::vector<JingleS5BTransportPayload::Candidate> candidates; - - if (options_.isDirectAllowed()) { - // get direct candidates - std::vector<HostAddressPort> directCandidates = s5bServerManager->getHostAddressPorts(); - foreach(HostAddressPort addressPort, directCandidates) { - if (addressPort.getAddress().getRawAddress().is_v6() && - addressPort.getAddress().getRawAddress().to_v6().is_link_local()) { - continue; - } - JingleS5BTransportPayload::Candidate candidate; - candidate.type = JingleS5BTransportPayload::Candidate::DirectType; - candidate.jid = ownJID; - candidate.hostPort = addressPort; - candidate.priority = 65536 * 126 + LOCAL_PREFERENCE; - candidate.cid = idGenerator->generateID(); - candidates.push_back(candidate); - } - } - - if (options_.isAssistedAllowed()) { - // get assissted candidates - std::vector<HostAddressPort> assisstedCandidates = s5bServerManager->getAssistedHostAddressPorts(); - foreach(HostAddressPort addressPort, assisstedCandidates) { - JingleS5BTransportPayload::Candidate candidate; - candidate.type = JingleS5BTransportPayload::Candidate::AssistedType; - candidate.jid = ownJID; - candidate.hostPort = addressPort; - candidate.priority = 65536 * 120 + LOCAL_PREFERENCE; - candidate.cid = idGenerator->generateID(); - candidates.push_back(candidate); - } - } - - if (options_.isProxiedAllowed() && s5bProxy->getOrDiscoverS5BProxies().is_initialized()) { - foreach(S5BProxyRequest::ref proxy, s5bProxy->getOrDiscoverS5BProxies().get()) { - if (proxy->getStreamHost()) { // FIXME: Added this test, because there were cases where this wasn't initialized. Investigate this. (Remko) - JingleS5BTransportPayload::Candidate candidate; - candidate.type = JingleS5BTransportPayload::Candidate::ProxyType; - candidate.jid = (*proxy->getStreamHost()).jid; - HostAddress address = (*proxy->getStreamHost()).host; - assert(address.isValid()); - candidate.hostPort = HostAddressPort(address, (*proxy->getStreamHost()).port); - candidate.priority = 65536 * 10 + LOCAL_PREFERENCE; - candidate.cid = idGenerator->generateID(); - candidates.push_back(candidate); - } - } - } - - onLocalTransportCandidatesGenerated(candidates); + std::vector<JingleS5BTransportPayload::Candidate> candidates; + + if (options_.isDirectAllowed()) { + // get direct candidates + std::vector<HostAddressPort> directCandidates = s5bServerManager->getHostAddressPorts(); + foreach(HostAddressPort addressPort, directCandidates) { + if (addressPort.getAddress().getRawAddress().is_v6() && + addressPort.getAddress().getRawAddress().to_v6().is_link_local()) { + continue; + } + JingleS5BTransportPayload::Candidate candidate; + candidate.type = JingleS5BTransportPayload::Candidate::DirectType; + candidate.jid = ownJID; + candidate.hostPort = addressPort; + candidate.priority = 65536 * 126 + LOCAL_PREFERENCE; + candidate.cid = idGenerator->generateID(); + candidates.push_back(candidate); + } + } + + if (options_.isAssistedAllowed()) { + // get assissted candidates + std::vector<HostAddressPort> assisstedCandidates = s5bServerManager->getAssistedHostAddressPorts(); + foreach(HostAddressPort addressPort, assisstedCandidates) { + JingleS5BTransportPayload::Candidate candidate; + candidate.type = JingleS5BTransportPayload::Candidate::AssistedType; + candidate.jid = ownJID; + candidate.hostPort = addressPort; + candidate.priority = 65536 * 120 + LOCAL_PREFERENCE; + candidate.cid = idGenerator->generateID(); + candidates.push_back(candidate); + } + } + + if (options_.isProxiedAllowed() && s5bProxy->getOrDiscoverS5BProxies().is_initialized()) { + foreach(S5BProxyRequest::ref proxy, s5bProxy->getOrDiscoverS5BProxies().get()) { + if (proxy->getStreamHost()) { // FIXME: Added this test, because there were cases where this wasn't initialized. Investigate this. (Remko) + JingleS5BTransportPayload::Candidate candidate; + candidate.type = JingleS5BTransportPayload::Candidate::ProxyType; + candidate.jid = (*proxy->getStreamHost()).jid; + HostAddress address = (*proxy->getStreamHost()).host; + assert(address.isValid()); + candidate.hostPort = HostAddressPort(address, (*proxy->getStreamHost()).port); + candidate.priority = 65536 * 10 + LOCAL_PREFERENCE; + candidate.cid = idGenerator->generateID(); + candidates.push_back(candidate); + } + } + } + + onLocalTransportCandidatesGenerated(candidates); } } diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h index d08a85e..74c6bfb 100644 --- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h +++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h @@ -23,47 +23,47 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SOCKS5BytestreamServerManager; - class SOCKS5BytestreamProxiesManager; - class SOCKS5BytestreamServerInitializeRequest; - class SOCKS5BytestreamServerResourceUser; - class SOCKS5BytestreamServerPortForwardingUser; - class JingleS5BTransportPayload; + class SOCKS5BytestreamServerManager; + class SOCKS5BytestreamProxiesManager; + class SOCKS5BytestreamServerInitializeRequest; + class SOCKS5BytestreamServerResourceUser; + class SOCKS5BytestreamServerPortForwardingUser; + class JingleS5BTransportPayload; - class LocalJingleTransportCandidateGenerator { - public: - LocalJingleTransportCandidateGenerator( - SOCKS5BytestreamServerManager* s5bServerManager, - SOCKS5BytestreamProxiesManager* s5bProxy, - const JID& ownJID, - IDGenerator* idGenerator, - const FileTransferOptions& options); - virtual ~LocalJingleTransportCandidateGenerator(); + class LocalJingleTransportCandidateGenerator { + public: + LocalJingleTransportCandidateGenerator( + SOCKS5BytestreamServerManager* s5bServerManager, + SOCKS5BytestreamProxiesManager* s5bProxy, + const JID& ownJID, + IDGenerator* idGenerator, + const FileTransferOptions& options); + virtual ~LocalJingleTransportCandidateGenerator(); - virtual void start(); - virtual void stop(); + virtual void start(); + virtual void stop(); - boost::signal<void (const std::vector<JingleS5BTransportPayload::Candidate>&)> onLocalTransportCandidatesGenerated; + boost::signal<void (const std::vector<JingleS5BTransportPayload::Candidate>&)> onLocalTransportCandidatesGenerated; - private: - void handleS5BServerInitialized(bool success); - void handlePortForwardingSetup(bool success); - void handleDiscoveredProxiesChanged(); + private: + void handleS5BServerInitialized(bool success); + void handlePortForwardingSetup(bool success); + void handleDiscoveredProxiesChanged(); - void checkS5BCandidatesReady(); - void emitOnLocalTransportCandidatesGenerated(); + void checkS5BCandidatesReady(); + void emitOnLocalTransportCandidatesGenerated(); - private: - SOCKS5BytestreamServerManager* s5bServerManager; - SOCKS5BytestreamProxiesManager* s5bProxy; - JID ownJID; - IDGenerator* idGenerator; - boost::shared_ptr<SOCKS5BytestreamServerInitializeRequest> s5bServerInitializeRequest; - boost::shared_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_; - boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_; - bool triedServerInit_; - bool triedForwarding_; - bool triedProxyDiscovery_; - FileTransferOptions options_; - }; + private: + SOCKS5BytestreamServerManager* s5bServerManager; + SOCKS5BytestreamProxiesManager* s5bProxy; + JID ownJID; + IDGenerator* idGenerator; + boost::shared_ptr<SOCKS5BytestreamServerInitializeRequest> s5bServerInitializeRequest; + boost::shared_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_; + boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_; + bool triedServerInit_; + bool triedForwarding_; + bool triedProxyDiscovery_; + FileTransferOptions options_; + }; } diff --git a/Swiften/FileTransfer/OutgoingFileTransfer.h b/Swiften/FileTransfer/OutgoingFileTransfer.h index 358cc2f..e83a893 100644 --- a/Swiften/FileTransfer/OutgoingFileTransfer.h +++ b/Swiften/FileTransfer/OutgoingFileTransfer.h @@ -12,12 +12,12 @@ #include <Swiften/FileTransfer/FileTransfer.h> namespace Swift { - class SWIFTEN_API OutgoingFileTransfer : public FileTransfer { - public: - typedef boost::shared_ptr<OutgoingFileTransfer> ref; - public: - virtual ~OutgoingFileTransfer(); + class SWIFTEN_API OutgoingFileTransfer : public FileTransfer { + public: + typedef boost::shared_ptr<OutgoingFileTransfer> ref; + public: + virtual ~OutgoingFileTransfer(); - virtual void start() = 0; - }; + virtual void start() = 0; + }; } diff --git a/Swiften/FileTransfer/OutgoingFileTransferManager.cpp b/Swiften/FileTransfer/OutgoingFileTransferManager.cpp index f34c449..f6d216e 100644 --- a/Swiften/FileTransfer/OutgoingFileTransferManager.cpp +++ b/Swiften/FileTransfer/OutgoingFileTransferManager.cpp @@ -24,42 +24,42 @@ namespace Swift { OutgoingFileTransferManager::OutgoingFileTransferManager( - JingleSessionManager* jingleSessionManager, - IQRouter* router, - FileTransferTransporterFactory* transporterFactory, - TimerFactory* timerFactory, - CryptoProvider* crypto) : - jingleSessionManager(jingleSessionManager), - iqRouter(router), - transporterFactory(transporterFactory), - timerFactory(timerFactory), - crypto(crypto) { - idGenerator = new IDGenerator(); + JingleSessionManager* jingleSessionManager, + IQRouter* router, + FileTransferTransporterFactory* transporterFactory, + TimerFactory* timerFactory, + CryptoProvider* crypto) : + jingleSessionManager(jingleSessionManager), + iqRouter(router), + transporterFactory(transporterFactory), + timerFactory(timerFactory), + crypto(crypto) { + idGenerator = new IDGenerator(); } OutgoingFileTransferManager::~OutgoingFileTransferManager() { - delete idGenerator; + delete idGenerator; } boost::shared_ptr<OutgoingFileTransfer> OutgoingFileTransferManager::createOutgoingFileTransfer( - const JID& from, - const JID& recipient, - boost::shared_ptr<ReadBytestream> readBytestream, - const JingleFileTransferFileInfo& fileInfo, - const FileTransferOptions& config) { - JingleSessionImpl::ref jingleSession = boost::make_shared<JingleSessionImpl>( - from, recipient, idGenerator->generateID(), iqRouter); - jingleSessionManager->registerOutgoingSession(from, jingleSession); - return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer( - recipient, - jingleSession, - readBytestream, - transporterFactory, - timerFactory, - idGenerator, - fileInfo, - config, - crypto)); + const JID& from, + const JID& recipient, + boost::shared_ptr<ReadBytestream> readBytestream, + const JingleFileTransferFileInfo& fileInfo, + const FileTransferOptions& config) { + JingleSessionImpl::ref jingleSession = boost::make_shared<JingleSessionImpl>( + from, recipient, idGenerator->generateID(), iqRouter); + jingleSessionManager->registerOutgoingSession(from, jingleSession); + return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer( + recipient, + jingleSession, + readBytestream, + transporterFactory, + timerFactory, + idGenerator, + fileInfo, + config, + crypto)); } } diff --git a/Swiften/FileTransfer/OutgoingFileTransferManager.h b/Swiften/FileTransfer/OutgoingFileTransferManager.h index 1ad992e..3981005 100644 --- a/Swiften/FileTransfer/OutgoingFileTransferManager.h +++ b/Swiften/FileTransfer/OutgoingFileTransferManager.h @@ -17,41 +17,41 @@ #include <Swiften/Base/API.h> namespace Swift { - class JingleSessionManager; - class IQRouter; - class FileTransferTransporterFactory; - class OutgoingFileTransfer; - class JID; - class IDGenerator; - class ReadBytestream; - class JingleFileTransferFileInfo; - class CryptoProvider; - class FileTransferOptions; - class TimerFactory; - - class SWIFTEN_API OutgoingFileTransferManager { - public: - OutgoingFileTransferManager( - JingleSessionManager* jingleSessionManager, - IQRouter* router, - FileTransferTransporterFactory* transporterFactory, - TimerFactory* timerFactory, - CryptoProvider* crypto); - ~OutgoingFileTransferManager(); - - boost::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer( - const JID& from, - const JID& to, - boost::shared_ptr<ReadBytestream>, - const JingleFileTransferFileInfo&, - const FileTransferOptions&); - - private: - JingleSessionManager* jingleSessionManager; - IQRouter* iqRouter; - FileTransferTransporterFactory* transporterFactory; - TimerFactory* timerFactory; - IDGenerator* idGenerator; - CryptoProvider* crypto; - }; + class JingleSessionManager; + class IQRouter; + class FileTransferTransporterFactory; + class OutgoingFileTransfer; + class JID; + class IDGenerator; + class ReadBytestream; + class JingleFileTransferFileInfo; + class CryptoProvider; + class FileTransferOptions; + class TimerFactory; + + class SWIFTEN_API OutgoingFileTransferManager { + public: + OutgoingFileTransferManager( + JingleSessionManager* jingleSessionManager, + IQRouter* router, + FileTransferTransporterFactory* transporterFactory, + TimerFactory* timerFactory, + CryptoProvider* crypto); + ~OutgoingFileTransferManager(); + + boost::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer( + const JID& from, + const JID& to, + boost::shared_ptr<ReadBytestream>, + const JingleFileTransferFileInfo&, + const FileTransferOptions&); + + private: + JingleSessionManager* jingleSessionManager; + IQRouter* iqRouter; + FileTransferTransporterFactory* transporterFactory; + TimerFactory* timerFactory; + IDGenerator* idGenerator; + CryptoProvider* crypto; + }; } diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp index 2c43766..a5a84eb 100644 --- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp +++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp @@ -10,7 +10,7 @@ * See the COPYING file for more information. */ -// TODO: +// TODO: // - We should handle incoming terminates after we have terminated, so the other // side can warn that he didn't receive all bytes correctly. // - Should the proby stuff also wait for candidate used acknowledgement? @@ -44,364 +44,364 @@ using namespace Swift; static const int DEFAULT_BLOCK_SIZE = 4096; OutgoingJingleFileTransfer::OutgoingJingleFileTransfer( - const JID& toJID, - JingleSession::ref session, - boost::shared_ptr<ReadBytestream> stream, - FileTransferTransporterFactory* transporterFactory, - TimerFactory* timerFactory, - IDGenerator* idGenerator, - const JingleFileTransferFileInfo& fileInfo, - const FileTransferOptions& options, - CryptoProvider* crypto) : - JingleFileTransfer(session, toJID, transporterFactory), - idGenerator(idGenerator), - stream(stream), - fileInfo(fileInfo), - options(options), - contentID(idGenerator->generateID(), JingleContentPayload::InitiatorCreator), - state(Initial), - candidateAcknowledged(false) { - - setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription()); - - // calculate both, MD5 and SHA-1 since we don't know which one the other side supports - hashCalculator = new IncrementalBytestreamHashCalculator(true, true, crypto); - stream->onRead.connect( - boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1)); - - waitForRemoteTermination = timerFactory->createTimer(5000); - waitForRemoteTermination->onTick.connect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this)); + const JID& toJID, + JingleSession::ref session, + boost::shared_ptr<ReadBytestream> stream, + FileTransferTransporterFactory* transporterFactory, + TimerFactory* timerFactory, + IDGenerator* idGenerator, + const JingleFileTransferFileInfo& fileInfo, + const FileTransferOptions& options, + CryptoProvider* crypto) : + JingleFileTransfer(session, toJID, transporterFactory), + idGenerator(idGenerator), + stream(stream), + fileInfo(fileInfo), + options(options), + contentID(idGenerator->generateID(), JingleContentPayload::InitiatorCreator), + state(Initial), + candidateAcknowledged(false) { + + setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription()); + + // calculate both, MD5 and SHA-1 since we don't know which one the other side supports + hashCalculator = new IncrementalBytestreamHashCalculator(true, true, crypto); + stream->onRead.connect( + boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1)); + + waitForRemoteTermination = timerFactory->createTimer(5000); + waitForRemoteTermination->onTick.connect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this)); } OutgoingJingleFileTransfer::~OutgoingJingleFileTransfer() { - if (waitForRemoteTermination) { - waitForRemoteTermination->onTick.disconnect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this)); - waitForRemoteTermination->stop(); - } - - stream->onRead.disconnect( - boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1)); - delete hashCalculator; - hashCalculator = NULL; - removeTransporter(); + if (waitForRemoteTermination) { + waitForRemoteTermination->onTick.disconnect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this)); + waitForRemoteTermination->stop(); + } + + stream->onRead.disconnect( + boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1)); + delete hashCalculator; + hashCalculator = NULL; + removeTransporter(); } - + void OutgoingJingleFileTransfer::start() { - SWIFT_LOG(debug) << std::endl; - if (state != Initial) { - SWIFT_LOG(warning) << "Incorrect state" << std::endl; - return; - } - - if (!options.isInBandAllowed() && !options.isDirectAllowed() && !options.isAssistedAllowed() && !options.isProxiedAllowed()) { - // Started outgoing file transfer while not supporting transport methods. - setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::UnknownError)); - } - else { - setTransporter(transporterFactory->createInitiatorTransporter(getInitiator(), getResponder(), options)); - setInternalState(GeneratingInitialLocalCandidates); - transporter->startGeneratingLocalCandidates(); - } + SWIFT_LOG(debug) << std::endl; + if (state != Initial) { + SWIFT_LOG(warning) << "Incorrect state" << std::endl; + return; + } + + if (!options.isInBandAllowed() && !options.isDirectAllowed() && !options.isAssistedAllowed() && !options.isProxiedAllowed()) { + // Started outgoing file transfer while not supporting transport methods. + setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::UnknownError)); + } + else { + setTransporter(transporterFactory->createInitiatorTransporter(getInitiator(), getResponder(), options)); + setInternalState(GeneratingInitialLocalCandidates); + transporter->startGeneratingLocalCandidates(); + } } void OutgoingJingleFileTransfer::cancel() { - terminate(JinglePayload::Reason::Cancel); + terminate(JinglePayload::Reason::Cancel); } void OutgoingJingleFileTransfer::terminate(JinglePayload::Reason::Type reason) { - SWIFT_LOG(debug) << reason << std::endl; + SWIFT_LOG(debug) << reason << std::endl; - if (state != Initial && state != GeneratingInitialLocalCandidates && state != Finished) { - session->sendTerminate(reason); - } - stopAll(); - setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason)); + if (state != Initial && state != GeneratingInitialLocalCandidates && state != Finished) { + session->sendTerminate(reason); + } + stopAll(); + setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason)); } void OutgoingJingleFileTransfer::handleSessionAcceptReceived( - const JingleContentID&, - JingleDescription::ref, - JingleTransportPayload::ref transportPayload) { - SWIFT_LOG(debug) << std::endl; - if (state != WaitingForAccept) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - - if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload)) { - transporter->addRemoteCandidates(s5bPayload->getCandidates(), s5bPayload->getDstAddr()); - setInternalState(TryingCandidates); - transporter->startTryingRemoteCandidates(); - } - else if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transportPayload)) { - startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream)); - } - else { - SWIFT_LOG(debug) << "Unknown transport payload. Falling back." << std::endl; - fallback(); - } + const JingleContentID&, + JingleDescription::ref, + JingleTransportPayload::ref transportPayload) { + SWIFT_LOG(debug) << std::endl; + if (state != WaitingForAccept) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + + if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload)) { + transporter->addRemoteCandidates(s5bPayload->getCandidates(), s5bPayload->getDstAddr()); + setInternalState(TryingCandidates); + transporter->startTryingRemoteCandidates(); + } + else if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transportPayload)) { + startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream)); + } + else { + SWIFT_LOG(debug) << "Unknown transport payload. Falling back." << std::endl; + fallback(); + } } void OutgoingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) { - SWIFT_LOG(debug) << std::endl; - if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; } - - stopAll(); - if (state == WaitForTermination) { - waitForRemoteTermination->stop(); - } - if (reason && reason->type == JinglePayload::Reason::Cancel) { - setFinishedState(FileTransfer::State::Canceled, FileTransferError(FileTransferError::PeerError)); - } - else if (reason && reason->type == JinglePayload::Reason::Decline) { - setFinishedState(FileTransfer::State::Canceled, boost::optional<FileTransferError>()); - } - else if (reason && reason->type == JinglePayload::Reason::Success) { - setFinishedState(FileTransfer::State::Finished, boost::optional<FileTransferError>()); - } - else { - setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError)); - } + SWIFT_LOG(debug) << std::endl; + if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; } + + stopAll(); + if (state == WaitForTermination) { + waitForRemoteTermination->stop(); + } + if (reason && reason->type == JinglePayload::Reason::Cancel) { + setFinishedState(FileTransfer::State::Canceled, FileTransferError(FileTransferError::PeerError)); + } + else if (reason && reason->type == JinglePayload::Reason::Decline) { + setFinishedState(FileTransfer::State::Canceled, boost::optional<FileTransferError>()); + } + else if (reason && reason->type == JinglePayload::Reason::Success) { + setFinishedState(FileTransfer::State::Finished, boost::optional<FileTransferError>()); + } + else { + setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError)); + } } void OutgoingJingleFileTransfer::handleTransportAcceptReceived(const JingleContentID&, JingleTransportPayload::ref transport) { - SWIFT_LOG(debug) << std::endl; - if (state != FallbackRequested) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } - - if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport)) { - startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream)); - } - else { - SWIFT_LOG(debug) << "Unknown transport replacement" << std::endl; - terminate(JinglePayload::Reason::FailedTransport); - } + SWIFT_LOG(debug) << std::endl; + if (state != FallbackRequested) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } + + if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport)) { + startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream)); + } + else { + SWIFT_LOG(debug) << "Unknown transport replacement" << std::endl; + terminate(JinglePayload::Reason::FailedTransport); + } } void OutgoingJingleFileTransfer::handleTransportRejectReceived(const JingleContentID &, boost::shared_ptr<JingleTransportPayload>) { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug) << std::endl; - terminate(JinglePayload::Reason::UnsupportedTransports); + terminate(JinglePayload::Reason::UnsupportedTransports); } void OutgoingJingleFileTransfer::sendSessionInfoHash() { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug) << std::endl; - JingleFileTransferHash::ref hashElement = boost::make_shared<JingleFileTransferHash>(); - hashElement->getFileInfo().addHash(HashElement("sha-1", hashCalculator->getSHA1Hash())); - hashElement->getFileInfo().addHash(HashElement("md5", hashCalculator->getMD5Hash())); - session->sendInfo(hashElement); + JingleFileTransferHash::ref hashElement = boost::make_shared<JingleFileTransferHash>(); + hashElement->getFileInfo().addHash(HashElement("sha-1", hashCalculator->getSHA1Hash())); + hashElement->getFileInfo().addHash(HashElement("md5", hashCalculator->getMD5Hash())); + session->sendInfo(hashElement); } void OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated( - const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) { - SWIFT_LOG(debug) << std::endl; - if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; } - - fillCandidateMap(localCandidates, candidates); - - JingleFileTransferDescription::ref description = boost::make_shared<JingleFileTransferDescription>(); - fileInfo.addHash(HashElement("sha-1", ByteArray())); - fileInfo.addHash(HashElement("md5", ByteArray())); - description->setFileInfo(fileInfo); - - JingleTransportPayload::ref transport; - if (candidates.empty()) { - SWIFT_LOG(debug) << "no S5B candidates generated. Send IBB transport candidate." << std::endl; - JingleIBBTransportPayload::ref ibbTransport = boost::make_shared<JingleIBBTransportPayload>(); - ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE); - ibbTransport->setSessionID(idGenerator->generateID()); - transport = ibbTransport; - } - else { - JingleS5BTransportPayload::ref s5bTransport = boost::make_shared<JingleS5BTransportPayload>(); - s5bTransport->setSessionID(s5bSessionID); - s5bTransport->setMode(JingleS5BTransportPayload::TCPMode); - s5bTransport->setDstAddr(dstAddr); - foreach(JingleS5BTransportPayload::Candidate candidate, candidates) { - s5bTransport->addCandidate(candidate); - SWIFT_LOG(debug) << "\t" << "S5B candidate: " << candidate.hostPort.toString() << std::endl; - } - transport = s5bTransport; - } - setInternalState(WaitingForAccept); - session->sendInitiate(contentID, description, transport); + const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) { + SWIFT_LOG(debug) << std::endl; + if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; } + + fillCandidateMap(localCandidates, candidates); + + JingleFileTransferDescription::ref description = boost::make_shared<JingleFileTransferDescription>(); + fileInfo.addHash(HashElement("sha-1", ByteArray())); + fileInfo.addHash(HashElement("md5", ByteArray())); + description->setFileInfo(fileInfo); + + JingleTransportPayload::ref transport; + if (candidates.empty()) { + SWIFT_LOG(debug) << "no S5B candidates generated. Send IBB transport candidate." << std::endl; + JingleIBBTransportPayload::ref ibbTransport = boost::make_shared<JingleIBBTransportPayload>(); + ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE); + ibbTransport->setSessionID(idGenerator->generateID()); + transport = ibbTransport; + } + else { + JingleS5BTransportPayload::ref s5bTransport = boost::make_shared<JingleS5BTransportPayload>(); + s5bTransport->setSessionID(s5bSessionID); + s5bTransport->setMode(JingleS5BTransportPayload::TCPMode); + s5bTransport->setDstAddr(dstAddr); + foreach(JingleS5BTransportPayload::Candidate candidate, candidates) { + s5bTransport->addCandidate(candidate); + SWIFT_LOG(debug) << "\t" << "S5B candidate: " << candidate.hostPort.toString() << std::endl; + } + transport = s5bTransport; + } + setInternalState(WaitingForAccept); + session->sendInitiate(contentID, description, transport); } void OutgoingJingleFileTransfer::fallback() { - if (options.isInBandAllowed()) { - SWIFT_LOG(debug) << "Trying to fallback to IBB transport." << std::endl; - JingleIBBTransportPayload::ref ibbTransport = boost::make_shared<JingleIBBTransportPayload>(); - ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE); - ibbTransport->setSessionID(idGenerator->generateID()); - setInternalState(FallbackRequested); - session->sendTransportReplace(contentID, ibbTransport); - } - else { - SWIFT_LOG(debug) << "Fallback to IBB transport not allowed." << std::endl; - terminate(JinglePayload::Reason::ConnectivityError); - } + if (options.isInBandAllowed()) { + SWIFT_LOG(debug) << "Trying to fallback to IBB transport." << std::endl; + JingleIBBTransportPayload::ref ibbTransport = boost::make_shared<JingleIBBTransportPayload>(); + ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE); + ibbTransport->setSessionID(idGenerator->generateID()); + setInternalState(FallbackRequested); + session->sendTransportReplace(contentID, ibbTransport); + } + else { + SWIFT_LOG(debug) << "Fallback to IBB transport not allowed." << std::endl; + terminate(JinglePayload::Reason::ConnectivityError); + } } void OutgoingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) { - SWIFT_LOG(debug) << std::endl; - if (state != Transferring) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; } - - if (error) { - terminate(JinglePayload::Reason::ConnectivityError); - } - else { - sendSessionInfoHash(); - - // wait for other party to terminate session after they have verified the hash - setInternalState(WaitForTermination); - waitForRemoteTermination->start(); - } + SWIFT_LOG(debug) << std::endl; + if (state != Transferring) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; } + + if (error) { + terminate(JinglePayload::Reason::ConnectivityError); + } + else { + sendSessionInfoHash(); + + // wait for other party to terminate session after they have verified the hash + setInternalState(WaitForTermination); + waitForRemoteTermination->start(); + } } void OutgoingJingleFileTransfer::startTransferring(boost::shared_ptr<TransportSession> transportSession) { - SWIFT_LOG(debug) << std::endl; - - this->transportSession = transportSession; - processedBytesConnection = transportSession->onBytesSent.connect( - boost::bind(boost::ref(onProcessedBytes), _1)); - transferFinishedConnection = transportSession->onFinished.connect( - boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1)); - setInternalState(Transferring); - transportSession->start(); + SWIFT_LOG(debug) << std::endl; + + this->transportSession = transportSession; + processedBytesConnection = transportSession->onBytesSent.connect( + boost::bind(boost::ref(onProcessedBytes), _1)); + transferFinishedConnection = transportSession->onFinished.connect( + boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1)); + setInternalState(Transferring); + transportSession->start(); } void OutgoingJingleFileTransfer::setInternalState(State state) { - SWIFT_LOG(debug) << state << std::endl; - this->state = state; - setState(FileTransfer::State(getExternalState(state))); + SWIFT_LOG(debug) << state << std::endl; + this->state = state; + setState(FileTransfer::State(getExternalState(state))); } void OutgoingJingleFileTransfer::setFinishedState( - FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) { - SWIFT_LOG(debug) << std::endl; - this->state = Finished; - onStateChanged(type); - onFinished(error); + FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) { + SWIFT_LOG(debug) << std::endl; + this->state = Finished; + onStateChanged(type); + onFinished(error); } FileTransfer::State::Type OutgoingJingleFileTransfer::getExternalState(State state) { - switch (state) { - case Initial: return FileTransfer::State::Initial; - case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart; - case WaitingForAccept: return FileTransfer::State::WaitingForAccept; - case TryingCandidates: return FileTransfer::State::Negotiating; - case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating; - case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating; - case WaitingForCandidateAcknowledge: return FileTransfer::State::Negotiating; - case FallbackRequested: return FileTransfer::State::Negotiating; - case Transferring: return FileTransfer::State::Transferring; - case WaitForTermination: return FileTransfer::State::Transferring; - case Finished: return FileTransfer::State::Finished; - } - assert(false); - return FileTransfer::State::Initial; + switch (state) { + case Initial: return FileTransfer::State::Initial; + case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart; + case WaitingForAccept: return FileTransfer::State::WaitingForAccept; + case TryingCandidates: return FileTransfer::State::Negotiating; + case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating; + case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating; + case WaitingForCandidateAcknowledge: return FileTransfer::State::Negotiating; + case FallbackRequested: return FileTransfer::State::Negotiating; + case Transferring: return FileTransfer::State::Transferring; + case WaitForTermination: return FileTransfer::State::Transferring; + case Finished: return FileTransfer::State::Finished; + } + assert(false); + return FileTransfer::State::Initial; } void OutgoingJingleFileTransfer::stopAll() { - SWIFT_LOG(debug) << state << std::endl; - switch (state) { - case Initial: SWIFT_LOG(warning) << "Not yet started" << std::endl; break; - case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break; - case WaitingForAccept: break; - case TryingCandidates: transporter->stopTryingRemoteCandidates(); break; - case FallbackRequested: break; - case WaitingForPeerProxyActivate: break; - case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break; - case WaitingForCandidateAcknowledge: // Fallthrough - case Transferring: - assert(transportSession); - processedBytesConnection.disconnect(); - transferFinishedConnection.disconnect(); - transportSession->stop(); - transportSession.reset(); - break; - case WaitForTermination: - break; - case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break; - } - if (state != Initial) { - removeTransporter(); - } + SWIFT_LOG(debug) << state << std::endl; + switch (state) { + case Initial: SWIFT_LOG(warning) << "Not yet started" << std::endl; break; + case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break; + case WaitingForAccept: break; + case TryingCandidates: transporter->stopTryingRemoteCandidates(); break; + case FallbackRequested: break; + case WaitingForPeerProxyActivate: break; + case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break; + case WaitingForCandidateAcknowledge: // Fallthrough + case Transferring: + assert(transportSession); + processedBytesConnection.disconnect(); + transferFinishedConnection.disconnect(); + transportSession->stop(); + transportSession.reset(); + break; + case WaitForTermination: + break; + case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break; + } + if (state != Initial) { + removeTransporter(); + } } void OutgoingJingleFileTransfer::startTransferViaRemoteCandidate() { - SWIFT_LOG(debug) << std::endl; - - if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { - setInternalState(WaitingForPeerProxyActivate); - } - else { - transportSession = createRemoteCandidateSession(); - startTransferringIfCandidateAcknowledged(); - } + SWIFT_LOG(debug) << std::endl; + + if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { + setInternalState(WaitingForPeerProxyActivate); + } + else { + transportSession = createRemoteCandidateSession(); + startTransferringIfCandidateAcknowledged(); + } } void OutgoingJingleFileTransfer::startTransferViaLocalCandidate() { - SWIFT_LOG(debug) << std::endl; - - if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { - setInternalState(WaitingForLocalProxyActivate); - transporter->startActivatingProxy(theirCandidateChoice->jid); - } - else { - transportSession = createLocalCandidateSession(); - startTransferringIfCandidateAcknowledged(); - } + SWIFT_LOG(debug) << std::endl; + + if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) { + setInternalState(WaitingForLocalProxyActivate); + transporter->startActivatingProxy(theirCandidateChoice->jid); + } + else { + transportSession = createLocalCandidateSession(); + startTransferringIfCandidateAcknowledged(); + } } void OutgoingJingleFileTransfer::startTransferringIfCandidateAcknowledged() { - if (candidateAcknowledged) { - startTransferring(transportSession); - } - else { - setInternalState(WaitingForCandidateAcknowledge); - } + if (candidateAcknowledged) { + startTransferring(transportSession); + } + else { + setInternalState(WaitingForCandidateAcknowledge); + } } void OutgoingJingleFileTransfer::handleTransportInfoAcknowledged(const std::string& id) { - if (id == candidateSelectRequestID) { - candidateAcknowledged = true; - } - if (state == WaitingForCandidateAcknowledge) { - startTransferring(transportSession); - } + if (id == candidateSelectRequestID) { + candidateAcknowledged = true; + } + if (state == WaitingForCandidateAcknowledge) { + startTransferring(transportSession); + } } JingleContentID OutgoingJingleFileTransfer::getContentID() const { - return contentID; + return contentID; } bool OutgoingJingleFileTransfer::hasPriorityOnCandidateTie() const { - return true; + return true; } bool OutgoingJingleFileTransfer::isWaitingForPeerProxyActivate() const { - return state == WaitingForPeerProxyActivate; + return state == WaitingForPeerProxyActivate; } bool OutgoingJingleFileTransfer::isWaitingForLocalProxyActivate() const { - return state == WaitingForLocalProxyActivate; + return state == WaitingForLocalProxyActivate; } bool OutgoingJingleFileTransfer::isTryingCandidates() const { - return state == TryingCandidates; + return state == TryingCandidates; } boost::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createLocalCandidateSession() { - return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get()); + return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get()); } boost::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createRemoteCandidateSession() { - return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get()); + return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get()); } void OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout() { - assert(state == WaitForTermination); - SWIFT_LOG(warning) << "Other party did not terminate session. Terminate it now." << std::endl; - waitForRemoteTermination->stop(); - terminate(JinglePayload::Reason::MediaError); + assert(state == WaitForTermination); + SWIFT_LOG(warning) << "Other party did not terminate session. Terminate it now." << std::endl; + waitForRemoteTermination->stop(); + terminate(JinglePayload::Reason::MediaError); } diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h index 96b465b..a8dad1e 100644 --- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h +++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h @@ -25,98 +25,98 @@ #include <Swiften/Network/Timer.h> namespace Swift { - class CryptoProvider; - class FileTransferTransporter; - class FileTransferTransporterFactory; - class IDGenerator; - class IncrementalBytestreamHashCalculator; - class ReadBytestream; - class TimerFactory; - class TransportSession; - - class SWIFTEN_API OutgoingJingleFileTransfer : public OutgoingFileTransfer, public JingleFileTransfer { - public: - OutgoingJingleFileTransfer( - const JID& to, - boost::shared_ptr<JingleSession>, - boost::shared_ptr<ReadBytestream>, - FileTransferTransporterFactory*, - TimerFactory*, - IDGenerator*, - const JingleFileTransferFileInfo&, - const FileTransferOptions&, - CryptoProvider*); - virtual ~OutgoingJingleFileTransfer(); - - virtual void start() SWIFTEN_OVERRIDE; - virtual void cancel() SWIFTEN_OVERRIDE; - - private: - enum State { - Initial, - GeneratingInitialLocalCandidates, - WaitingForAccept, - TryingCandidates, - WaitingForPeerProxyActivate, - WaitingForLocalProxyActivate, - WaitingForCandidateAcknowledge, - FallbackRequested, - Transferring, - WaitForTermination, - Finished - }; - - virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE; - virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportRejectReceived(const JingleContentID &, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE; - virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE; - void startTransferringIfCandidateAcknowledged(); - - virtual void handleLocalTransportCandidatesGenerated(const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& dstAddr) SWIFTEN_OVERRIDE; - virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE; - - virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE; - - virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; - - virtual void fallback() SWIFTEN_OVERRIDE; - void handleTransferFinished(boost::optional<FileTransferError>); - - void sendSessionInfoHash(); - - virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE; - - virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE; - virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE; - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE; - - void handleWaitForRemoteTerminationTimeout(); - - void stopAll(); - void setInternalState(State state); - void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error); - - static FileTransfer::State::Type getExternalState(State state); - - private: - IDGenerator* idGenerator; - boost::shared_ptr<ReadBytestream> stream; - JingleFileTransferFileInfo fileInfo; - FileTransferOptions options; - JingleContentID contentID; - IncrementalBytestreamHashCalculator* hashCalculator; - State state; - bool candidateAcknowledged; - - Timer::ref waitForRemoteTermination; - - boost::bsignals::connection processedBytesConnection; - boost::bsignals::connection transferFinishedConnection; - }; + class CryptoProvider; + class FileTransferTransporter; + class FileTransferTransporterFactory; + class IDGenerator; + class IncrementalBytestreamHashCalculator; + class ReadBytestream; + class TimerFactory; + class TransportSession; + + class SWIFTEN_API OutgoingJingleFileTransfer : public OutgoingFileTransfer, public JingleFileTransfer { + public: + OutgoingJingleFileTransfer( + const JID& to, + boost::shared_ptr<JingleSession>, + boost::shared_ptr<ReadBytestream>, + FileTransferTransporterFactory*, + TimerFactory*, + IDGenerator*, + const JingleFileTransferFileInfo&, + const FileTransferOptions&, + CryptoProvider*); + virtual ~OutgoingJingleFileTransfer(); + + virtual void start() SWIFTEN_OVERRIDE; + virtual void cancel() SWIFTEN_OVERRIDE; + + private: + enum State { + Initial, + GeneratingInitialLocalCandidates, + WaitingForAccept, + TryingCandidates, + WaitingForPeerProxyActivate, + WaitingForLocalProxyActivate, + WaitingForCandidateAcknowledge, + FallbackRequested, + Transferring, + WaitForTermination, + Finished + }; + + virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE; + virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void handleTransportRejectReceived(const JingleContentID &, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE; + virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE; + void startTransferringIfCandidateAcknowledged(); + + virtual void handleLocalTransportCandidatesGenerated(const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& dstAddr) SWIFTEN_OVERRIDE; + virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE; + + virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE; + + virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; + + virtual void fallback() SWIFTEN_OVERRIDE; + void handleTransferFinished(boost::optional<FileTransferError>); + + void sendSessionInfoHash(); + + virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE; + + virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE; + virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE; + virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE; + virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE; + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE; + + void handleWaitForRemoteTerminationTimeout(); + + void stopAll(); + void setInternalState(State state); + void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error); + + static FileTransfer::State::Type getExternalState(State state); + + private: + IDGenerator* idGenerator; + boost::shared_ptr<ReadBytestream> stream; + JingleFileTransferFileInfo fileInfo; + FileTransferOptions options; + JingleContentID contentID; + IncrementalBytestreamHashCalculator* hashCalculator; + State state; + bool candidateAcknowledged; + + Timer::ref waitForRemoteTermination; + + boost::bsignals::connection processedBytesConnection; + boost::bsignals::connection transferFinishedConnection; + }; } diff --git a/Swiften/FileTransfer/ReadBytestream.h b/Swiften/FileTransfer/ReadBytestream.h index 1ba8417..e967c53 100644 --- a/Swiften/FileTransfer/ReadBytestream.h +++ b/Swiften/FileTransfer/ReadBytestream.h @@ -14,20 +14,20 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - class SWIFTEN_API ReadBytestream { - public: - virtual ~ReadBytestream(); - - /** - * Return an empty vector if no more data is available. - * Use onDataAvailable signal for signaling there is data available again. - */ - virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size) = 0; - - virtual bool isFinished() const = 0; - - public: - boost::signal<void ()> onDataAvailable; - boost::signal<void (const std::vector<unsigned char>&)> onRead; - }; + class SWIFTEN_API ReadBytestream { + public: + virtual ~ReadBytestream(); + + /** + * Return an empty vector if no more data is available. + * Use onDataAvailable signal for signaling there is data available again. + */ + virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size) = 0; + + virtual bool isFinished() const = 0; + + public: + boost::signal<void ()> onDataAvailable; + boost::signal<void (const std::vector<unsigned char>&)> onRead; + }; } diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp index 97e2706..296723e 100644 --- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp +++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp @@ -25,73 +25,73 @@ using namespace Swift; RemoteJingleTransportCandidateSelector::RemoteJingleTransportCandidateSelector( - ConnectionFactory* connectionFactory, - TimerFactory* timerFactory, - const FileTransferOptions& options) : - connectionFactory(connectionFactory), - timerFactory(timerFactory), - options(options) { + ConnectionFactory* connectionFactory, + TimerFactory* timerFactory, + const FileTransferOptions& options) : + connectionFactory(connectionFactory), + timerFactory(timerFactory), + options(options) { } RemoteJingleTransportCandidateSelector::~RemoteJingleTransportCandidateSelector() { } void RemoteJingleTransportCandidateSelector::addCandidates( - const std::vector<JingleS5BTransportPayload::Candidate>& candidates) { - foreach(JingleS5BTransportPayload::Candidate c, candidates) { - this->candidates.push(c); - } + const std::vector<JingleS5BTransportPayload::Candidate>& candidates) { + foreach(JingleS5BTransportPayload::Candidate c, candidates) { + this->candidates.push(c); + } } void RemoteJingleTransportCandidateSelector::startSelectingCandidate() { - tryNextCandidate(); + tryNextCandidate(); } void RemoteJingleTransportCandidateSelector::stopSelectingCandidate() { - if (s5bSession) { - sessionReadyConnection.disconnect(); - s5bSession->stop(); - } + if (s5bSession) { + sessionReadyConnection.disconnect(); + s5bSession->stop(); + } } void RemoteJingleTransportCandidateSelector::tryNextCandidate() { - if (candidates.empty()) { - SWIFT_LOG(debug) << "No more candidates" << std::endl; - onCandidateSelectFinished( - boost::optional<JingleS5BTransportPayload::Candidate>(), boost::shared_ptr<SOCKS5BytestreamClientSession>()); - } - else { - lastCandidate = candidates.top(); - candidates.pop(); - SWIFT_LOG(debug) << "Trying candidate " << lastCandidate.cid << std::endl; - if ((lastCandidate.type == JingleS5BTransportPayload::Candidate::DirectType && options.isDirectAllowed()) || - (lastCandidate.type == JingleS5BTransportPayload::Candidate::AssistedType && options.isAssistedAllowed()) || - (lastCandidate.type == JingleS5BTransportPayload::Candidate::ProxyType && options.isProxiedAllowed())) { - boost::shared_ptr<Connection> connection = connectionFactory->createConnection(); - s5bSession = boost::make_shared<SOCKS5BytestreamClientSession>( - connection, lastCandidate.hostPort, socks5DstAddr, timerFactory); - sessionReadyConnection = s5bSession->onSessionReady.connect( - boost::bind(&RemoteJingleTransportCandidateSelector::handleSessionReady, this, _1)); - s5bSession->start(); - } - else { - SWIFT_LOG(debug) << "Can't handle this type of candidate" << std::endl; - tryNextCandidate(); - } - } + if (candidates.empty()) { + SWIFT_LOG(debug) << "No more candidates" << std::endl; + onCandidateSelectFinished( + boost::optional<JingleS5BTransportPayload::Candidate>(), boost::shared_ptr<SOCKS5BytestreamClientSession>()); + } + else { + lastCandidate = candidates.top(); + candidates.pop(); + SWIFT_LOG(debug) << "Trying candidate " << lastCandidate.cid << std::endl; + if ((lastCandidate.type == JingleS5BTransportPayload::Candidate::DirectType && options.isDirectAllowed()) || + (lastCandidate.type == JingleS5BTransportPayload::Candidate::AssistedType && options.isAssistedAllowed()) || + (lastCandidate.type == JingleS5BTransportPayload::Candidate::ProxyType && options.isProxiedAllowed())) { + boost::shared_ptr<Connection> connection = connectionFactory->createConnection(); + s5bSession = boost::make_shared<SOCKS5BytestreamClientSession>( + connection, lastCandidate.hostPort, socks5DstAddr, timerFactory); + sessionReadyConnection = s5bSession->onSessionReady.connect( + boost::bind(&RemoteJingleTransportCandidateSelector::handleSessionReady, this, _1)); + s5bSession->start(); + } + else { + SWIFT_LOG(debug) << "Can't handle this type of candidate" << std::endl; + tryNextCandidate(); + } + } } void RemoteJingleTransportCandidateSelector::handleSessionReady(bool error) { - sessionReadyConnection.disconnect(); - if (error) { - s5bSession.reset(); - tryNextCandidate(); - } - else { - onCandidateSelectFinished(lastCandidate, s5bSession); - } + sessionReadyConnection.disconnect(); + if (error) { + s5bSession.reset(); + tryNextCandidate(); + } + else { + onCandidateSelectFinished(lastCandidate, s5bSession); + } } void RemoteJingleTransportCandidateSelector::setSOCKS5DstAddr(const std::string& socks5DstAddr) { - this->socks5DstAddr = socks5DstAddr; + this->socks5DstAddr = socks5DstAddr; } diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h index 0266f9d..5928754 100644 --- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h +++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h @@ -27,37 +27,37 @@ #include <Swiften/Network/Connection.h> namespace Swift { - class ConnectionFactory; - class TimerFactory; - - class RemoteJingleTransportCandidateSelector { - public: - RemoteJingleTransportCandidateSelector(ConnectionFactory*, TimerFactory*, const FileTransferOptions&); - virtual ~RemoteJingleTransportCandidateSelector(); - - virtual void addCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&); - virtual void setSOCKS5DstAddr(const std::string&); - virtual void startSelectingCandidate(); - virtual void stopSelectingCandidate(); - - boost::signal<void (const boost::optional<JingleS5BTransportPayload::Candidate>&, boost::shared_ptr<SOCKS5BytestreamClientSession>)> onCandidateSelectFinished; - - private: - void tryNextCandidate(); - void handleSessionReady(bool error); - - private: - ConnectionFactory* connectionFactory; - TimerFactory* timerFactory; - - std::priority_queue< - JingleS5BTransportPayload::Candidate, - std::vector<JingleS5BTransportPayload::Candidate>, - JingleS5BTransportPayload::CompareCandidate> candidates; - boost::shared_ptr<SOCKS5BytestreamClientSession> s5bSession; - boost::bsignals::connection sessionReadyConnection; - JingleS5BTransportPayload::Candidate lastCandidate; - std::string socks5DstAddr; - FileTransferOptions options; - }; + class ConnectionFactory; + class TimerFactory; + + class RemoteJingleTransportCandidateSelector { + public: + RemoteJingleTransportCandidateSelector(ConnectionFactory*, TimerFactory*, const FileTransferOptions&); + virtual ~RemoteJingleTransportCandidateSelector(); + + virtual void addCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&); + virtual void setSOCKS5DstAddr(const std::string&); + virtual void startSelectingCandidate(); + virtual void stopSelectingCandidate(); + + boost::signal<void (const boost::optional<JingleS5BTransportPayload::Candidate>&, boost::shared_ptr<SOCKS5BytestreamClientSession>)> onCandidateSelectFinished; + + private: + void tryNextCandidate(); + void handleSessionReady(bool error); + + private: + ConnectionFactory* connectionFactory; + TimerFactory* timerFactory; + + std::priority_queue< + JingleS5BTransportPayload::Candidate, + std::vector<JingleS5BTransportPayload::Candidate>, + JingleS5BTransportPayload::CompareCandidate> candidates; + boost::shared_ptr<SOCKS5BytestreamClientSession> s5bSession; + boost::bsignals::connection sessionReadyConnection; + JingleS5BTransportPayload::Candidate lastCandidate; + std::string socks5DstAddr; + FileTransferOptions options; + }; } diff --git a/Swiften/FileTransfer/S5BTransportSession.h b/Swiften/FileTransfer/S5BTransportSession.h index b3eee3c..95143bd 100644 --- a/Swiften/FileTransfer/S5BTransportSession.h +++ b/Swiften/FileTransfer/S5BTransportSession.h @@ -18,52 +18,52 @@ namespace Swift { template <typename T> class SWIFTEN_API S5BTransportSession : public TransportSession { - public: - S5BTransportSession( - boost::shared_ptr<T> session, - boost::shared_ptr<ReadBytestream> readStream) : - session(session), - readStream(readStream) { - initialize(); - } + public: + S5BTransportSession( + boost::shared_ptr<T> session, + boost::shared_ptr<ReadBytestream> readStream) : + session(session), + readStream(readStream) { + initialize(); + } - S5BTransportSession( - boost::shared_ptr<T> session, - boost::shared_ptr<WriteBytestream> writeStream) : - session(session), - writeStream(writeStream) { - initialize(); - } + S5BTransportSession( + boost::shared_ptr<T> session, + boost::shared_ptr<WriteBytestream> writeStream) : + session(session), + writeStream(writeStream) { + initialize(); + } - virtual ~S5BTransportSession() { - } + virtual ~S5BTransportSession() { + } - virtual void start() SWIFTEN_OVERRIDE { - if (readStream) { - session->startSending(readStream); - } - else { - session->startReceiving(writeStream); - } - } + virtual void start() SWIFTEN_OVERRIDE { + if (readStream) { + session->startSending(readStream); + } + else { + session->startReceiving(writeStream); + } + } - virtual void stop() SWIFTEN_OVERRIDE { - session->stop(); - } + virtual void stop() SWIFTEN_OVERRIDE { + session->stop(); + } - private: - void initialize() { - finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1)); - bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1)); - } + private: + void initialize() { + finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1)); + bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1)); + } - private: - boost::shared_ptr<T> session; - boost::shared_ptr<ReadBytestream> readStream; - boost::shared_ptr<WriteBytestream> writeStream; + private: + boost::shared_ptr<T> session; + boost::shared_ptr<ReadBytestream> readStream; + boost::shared_ptr<WriteBytestream> writeStream; - boost::bsignals::scoped_connection finishedConnection; - boost::bsignals::scoped_connection bytesSentConnection; + boost::bsignals::scoped_connection finishedConnection; + boost::bsignals::scoped_connection bytesSentConnection; }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp index 1a23e29..98a0988 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp @@ -27,250 +27,250 @@ namespace Swift { SOCKS5BytestreamClientSession::SOCKS5BytestreamClientSession( - boost::shared_ptr<Connection> connection, - const HostAddressPort& addressPort, - const std::string& destination, - TimerFactory* timerFactory) : - connection(connection), - addressPort(addressPort), - destination(destination), - state(Initial), - chunkSize(131072) { - weFailedTimeout = timerFactory->createTimer(3000); - weFailedTimeout->onTick.connect( - boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this)); + boost::shared_ptr<Connection> connection, + const HostAddressPort& addressPort, + const std::string& destination, + TimerFactory* timerFactory) : + connection(connection), + addressPort(addressPort), + destination(destination), + state(Initial), + chunkSize(131072) { + weFailedTimeout = timerFactory->createTimer(3000); + weFailedTimeout->onTick.connect( + boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this)); } SOCKS5BytestreamClientSession::~SOCKS5BytestreamClientSession() { - weFailedTimeout->onTick.disconnect( - boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this)); - weFailedTimeout->stop(); + weFailedTimeout->onTick.disconnect( + boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this)); + weFailedTimeout->stop(); } void SOCKS5BytestreamClientSession::start() { - assert(state == Initial); - SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << "." << std::endl; - weFailedTimeout->start(); - connectFinishedConnection = connection->onConnectFinished.connect( - boost::bind(&SOCKS5BytestreamClientSession::handleConnectFinished, this, _1)); - connection->connect(addressPort); + assert(state == Initial); + SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << "." << std::endl; + weFailedTimeout->start(); + connectFinishedConnection = connection->onConnectFinished.connect( + boost::bind(&SOCKS5BytestreamClientSession::handleConnectFinished, this, _1)); + connection->connect(addressPort); } void SOCKS5BytestreamClientSession::stop() { - SWIFT_LOG(debug) << std::endl; - if (state < Ready) { - weFailedTimeout->stop(); - } - if (state == Finished) { - return; - } - closeConnection(); - readBytestream.reset(); - state = Finished; + SWIFT_LOG(debug) << std::endl; + if (state < Ready) { + weFailedTimeout->stop(); + } + if (state == Finished) { + return; + } + closeConnection(); + readBytestream.reset(); + state = Finished; } void SOCKS5BytestreamClientSession::process() { - SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl; - ByteArray bndAddress; - switch(state) { - case Initial: - hello(); - break; - case Hello: - if (unprocessedData.size() > 1) { - unsigned char version = unprocessedData[0]; - unsigned char authMethod = unprocessedData[1]; - if (version != 5 || authMethod != 0) { - // signal failure to upper level - finish(true); - return; - } - unprocessedData.clear(); - authenticate(); - } - break; - case Authenticating: - if (unprocessedData.size() < 5) { - // need more data to start progressing - break; - } - if (unprocessedData[0] != '\x05') { - // wrong version - // disconnect & signal failure - finish(true); - break; - } - if (unprocessedData[1] != '\x00') { - // no success - // disconnect & signal failure - finish(true); - break; - } - if (unprocessedData[3] != '\x03') { - // we expect x'03' = DOMAINNAME here - // disconnect & signal failure - finish(true); - break; - } - if (static_cast<size_t>(unprocessedData[4]) + 1 > unprocessedData.size() + 5) { - // complete domainname and port not available yet - break; - } - bndAddress = createByteArray(&vecptr(unprocessedData)[5], unprocessedData[4]); - if (unprocessedData[unprocessedData[4] + 5] != 0 && bndAddress == createByteArray(destination)) { - // we expect a 0 as port - // disconnect and fail - finish(true); - } - unprocessedData.clear(); - state = Ready; - SWIFT_LOG(debug) << "session ready" << std::endl; - // issue ready signal so the bytestream can be used for reading or writing - weFailedTimeout->stop(); - onSessionReady(false); - break; - case Ready: - SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl; - break; - case Reading: - case Writing: - case Finished: - SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl; - SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl; - unprocessedData.clear(); - //assert(false); - } + SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl; + ByteArray bndAddress; + switch(state) { + case Initial: + hello(); + break; + case Hello: + if (unprocessedData.size() > 1) { + unsigned char version = unprocessedData[0]; + unsigned char authMethod = unprocessedData[1]; + if (version != 5 || authMethod != 0) { + // signal failure to upper level + finish(true); + return; + } + unprocessedData.clear(); + authenticate(); + } + break; + case Authenticating: + if (unprocessedData.size() < 5) { + // need more data to start progressing + break; + } + if (unprocessedData[0] != '\x05') { + // wrong version + // disconnect & signal failure + finish(true); + break; + } + if (unprocessedData[1] != '\x00') { + // no success + // disconnect & signal failure + finish(true); + break; + } + if (unprocessedData[3] != '\x03') { + // we expect x'03' = DOMAINNAME here + // disconnect & signal failure + finish(true); + break; + } + if (static_cast<size_t>(unprocessedData[4]) + 1 > unprocessedData.size() + 5) { + // complete domainname and port not available yet + break; + } + bndAddress = createByteArray(&vecptr(unprocessedData)[5], unprocessedData[4]); + if (unprocessedData[unprocessedData[4] + 5] != 0 && bndAddress == createByteArray(destination)) { + // we expect a 0 as port + // disconnect and fail + finish(true); + } + unprocessedData.clear(); + state = Ready; + SWIFT_LOG(debug) << "session ready" << std::endl; + // issue ready signal so the bytestream can be used for reading or writing + weFailedTimeout->stop(); + onSessionReady(false); + break; + case Ready: + SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl; + break; + case Reading: + case Writing: + case Finished: + SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl; + SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl; + unprocessedData.clear(); + //assert(false); + } } void SOCKS5BytestreamClientSession::hello() { - // Version 5, 1 auth method, No authentication - const SafeByteArray hello = createSafeByteArray("\x05\x01\x00", 3); - connection->write(hello); - state = Hello; + // Version 5, 1 auth method, No authentication + const SafeByteArray hello = createSafeByteArray("\x05\x01\x00", 3); + connection->write(hello); + state = Hello; } void SOCKS5BytestreamClientSession::authenticate() { - SWIFT_LOG(debug) << std::endl; - SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4); - SafeByteArray message = header; - append(message, createSafeByteArray(boost::numeric_cast<char>(destination.size()))); - authenticateAddress = createByteArray(destination); - append(message, authenticateAddress); - append(message, createSafeByteArray("\x00\x00", 2)); // 2 byte for port - connection->write(message); - state = Authenticating; + SWIFT_LOG(debug) << std::endl; + SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4); + SafeByteArray message = header; + append(message, createSafeByteArray(boost::numeric_cast<char>(destination.size()))); + authenticateAddress = createByteArray(destination); + append(message, authenticateAddress); + append(message, createSafeByteArray("\x00\x00", 2)); // 2 byte for port + connection->write(message); + state = Authenticating; } void SOCKS5BytestreamClientSession::startReceiving(boost::shared_ptr<WriteBytestream> writeStream) { - if (state == Ready) { - state = Reading; - writeBytestream = writeStream; - writeBytestream->write(unprocessedData); - unprocessedData.clear(); - } else { - SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl; - } + if (state == Ready) { + state = Reading; + writeBytestream = writeStream; + writeBytestream->write(unprocessedData); + unprocessedData.clear(); + } else { + SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl; + } } void SOCKS5BytestreamClientSession::startSending(boost::shared_ptr<ReadBytestream> readStream) { - if (state == Ready) { - state = Writing; - readBytestream = readStream; - dataWrittenConnection = connection->onDataWritten.connect( - boost::bind(&SOCKS5BytestreamClientSession::sendData, this)); - sendData(); - } else { - SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl; - } + if (state == Ready) { + state = Writing; + readBytestream = readStream; + dataWrittenConnection = connection->onDataWritten.connect( + boost::bind(&SOCKS5BytestreamClientSession::sendData, this)); + sendData(); + } else { + SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl; + } } HostAddressPort SOCKS5BytestreamClientSession::getAddressPort() const { - return addressPort; + return addressPort; } void SOCKS5BytestreamClientSession::sendData() { - if (!readBytestream->isFinished()) { - try { - boost::shared_ptr<ByteArray> dataToSend = readBytestream->read(boost::numeric_cast<size_t>(chunkSize)); - connection->write(createSafeByteArray(*dataToSend)); - onBytesSent(dataToSend->size()); - } - catch (const BytestreamException&) { - finish(true); - } - } - else { - finish(false); - } + if (!readBytestream->isFinished()) { + try { + boost::shared_ptr<ByteArray> dataToSend = readBytestream->read(boost::numeric_cast<size_t>(chunkSize)); + connection->write(createSafeByteArray(*dataToSend)); + onBytesSent(dataToSend->size()); + } + catch (const BytestreamException&) { + finish(true); + } + } + else { + finish(false); + } } void SOCKS5BytestreamClientSession::finish(bool error) { - SWIFT_LOG(debug) << std::endl; - if (state < Ready) { - weFailedTimeout->stop(); - } - closeConnection(); - readBytestream.reset(); - if (state == Initial || state == Hello || state == Authenticating) { - onSessionReady(true); - } - else { - state = Finished; - if (error) { - onFinished(boost::optional<FileTransferError>(FileTransferError::ReadError)); - } else { - onFinished(boost::optional<FileTransferError>()); - } - } + SWIFT_LOG(debug) << std::endl; + if (state < Ready) { + weFailedTimeout->stop(); + } + closeConnection(); + readBytestream.reset(); + if (state == Initial || state == Hello || state == Authenticating) { + onSessionReady(true); + } + else { + state = Finished; + if (error) { + onFinished(boost::optional<FileTransferError>(FileTransferError::ReadError)); + } else { + onFinished(boost::optional<FileTransferError>()); + } + } } void SOCKS5BytestreamClientSession::handleConnectFinished(bool error) { - connectFinishedConnection.disconnect(); - if (error) { - SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << "." << std::endl; - finish(true); - } else { - SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << "." << std::endl; - disconnectedConnection = connection->onDisconnected.connect( - boost::bind(&SOCKS5BytestreamClientSession::handleDisconnected, this, _1)); - dataReadConnection = connection->onDataRead.connect( - boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1)); - weFailedTimeout->stop(); - weFailedTimeout->start(); - process(); - } + connectFinishedConnection.disconnect(); + if (error) { + SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << "." << std::endl; + finish(true); + } else { + SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << "." << std::endl; + disconnectedConnection = connection->onDisconnected.connect( + boost::bind(&SOCKS5BytestreamClientSession::handleDisconnected, this, _1)); + dataReadConnection = connection->onDataRead.connect( + boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1)); + weFailedTimeout->stop(); + weFailedTimeout->start(); + process(); + } } void SOCKS5BytestreamClientSession::handleDataRead(boost::shared_ptr<SafeByteArray> data) { - SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data->size() << std::endl; - if (state != Reading) { - append(unprocessedData, *data); - process(); - } - else { - writeBytestream->write(createByteArray(vecptr(*data), data->size())); - //onBytesReceived(data->size()); - } + SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data->size() << std::endl; + if (state != Reading) { + append(unprocessedData, *data); + process(); + } + else { + writeBytestream->write(createByteArray(vecptr(*data), data->size())); + //onBytesReceived(data->size()); + } } void SOCKS5BytestreamClientSession::handleDisconnected(const boost::optional<Connection::Error>& error) { - SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl; - if (error) { - finish(true); - } + SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl; + if (error) { + finish(true); + } } void SOCKS5BytestreamClientSession::handleWeFailedTimeout() { - SWIFT_LOG(debug) << "Failed due to timeout!" << std::endl; - finish(true); + SWIFT_LOG(debug) << "Failed due to timeout!" << std::endl; + finish(true); } void SOCKS5BytestreamClientSession::closeConnection() { - connectFinishedConnection.disconnect(); - dataWrittenConnection.disconnect(); - dataReadConnection.disconnect(); - disconnectedConnection.disconnect(); - connection->disconnect(); + connectFinishedConnection.disconnect(); + dataWrittenConnection.disconnect(); + dataReadConnection.disconnect(); + disconnectedConnection.disconnect(); + connection->disconnect(); } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h index 1c0563a..5aea7d0 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h @@ -37,75 +37,75 @@ class TimerFactory; */ class SWIFTEN_API SOCKS5BytestreamClientSession { public: - enum State { - Initial, - Hello, - Authenticating, - Ready, - Writing, - Reading, - Finished - }; + enum State { + Initial, + Hello, + Authenticating, + Ready, + Writing, + Reading, + Finished + }; public: - typedef boost::shared_ptr<SOCKS5BytestreamClientSession> ref; + typedef boost::shared_ptr<SOCKS5BytestreamClientSession> ref; public: - SOCKS5BytestreamClientSession( - boost::shared_ptr<Connection> connection, - const HostAddressPort&, - const std::string&, - TimerFactory*); - ~SOCKS5BytestreamClientSession(); + SOCKS5BytestreamClientSession( + boost::shared_ptr<Connection> connection, + const HostAddressPort&, + const std::string&, + TimerFactory*); + ~SOCKS5BytestreamClientSession(); - void start(); - void stop(); + void start(); + void stop(); - void startReceiving(boost::shared_ptr<WriteBytestream>); - void startSending(boost::shared_ptr<ReadBytestream>); + void startReceiving(boost::shared_ptr<WriteBytestream>); + void startSending(boost::shared_ptr<ReadBytestream>); - HostAddressPort getAddressPort() const; + HostAddressPort getAddressPort() const; - boost::signal<void (bool /*error*/)> onSessionReady; + boost::signal<void (bool /*error*/)> onSessionReady; - boost::signal<void (boost::optional<FileTransferError>)> onFinished; - boost::signal<void (size_t)> onBytesSent; - // boost::signal<void (size_t)> onBytesReceived; + boost::signal<void (boost::optional<FileTransferError>)> onFinished; + boost::signal<void (size_t)> onBytesSent; + // boost::signal<void (size_t)> onBytesReceived; private: - void process(); - void hello(); - void authenticate(); + void process(); + void hello(); + void authenticate(); - void handleConnectFinished(bool error); - void handleDataRead(boost::shared_ptr<SafeByteArray>); - void handleDisconnected(const boost::optional<Connection::Error>&); - void handleWeFailedTimeout(); + void handleConnectFinished(bool error); + void handleDataRead(boost::shared_ptr<SafeByteArray>); + void handleDisconnected(const boost::optional<Connection::Error>&); + void handleWeFailedTimeout(); - void finish(bool error); - void sendData(); - void closeConnection(); + void finish(bool error); + void sendData(); + void closeConnection(); private: - boost::shared_ptr<Connection> connection; - HostAddressPort addressPort; - std::string destination; // hexify(SHA1(sessionID + requester + target)) + boost::shared_ptr<Connection> connection; + HostAddressPort addressPort; + std::string destination; // hexify(SHA1(sessionID + requester + target)) - State state; + State state; - ByteArray unprocessedData; - ByteArray authenticateAddress; + ByteArray unprocessedData; + ByteArray authenticateAddress; - int chunkSize; - boost::shared_ptr<WriteBytestream> writeBytestream; - boost::shared_ptr<ReadBytestream> readBytestream; + int chunkSize; + boost::shared_ptr<WriteBytestream> writeBytestream; + boost::shared_ptr<ReadBytestream> readBytestream; - Timer::ref weFailedTimeout; + Timer::ref weFailedTimeout; - boost::bsignals::scoped_connection connectFinishedConnection; - boost::bsignals::scoped_connection dataWrittenConnection; - boost::bsignals::scoped_connection dataReadConnection; - boost::bsignals::scoped_connection disconnectedConnection; + boost::bsignals::scoped_connection connectFinishedConnection; + boost::bsignals::scoped_connection dataWrittenConnection; + boost::bsignals::scoped_connection dataReadConnection; + boost::bsignals::scoped_connection disconnectedConnection; }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp index a1ef8f6..881a82d 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp @@ -32,172 +32,172 @@ SOCKS5BytestreamProxiesManager::SOCKS5BytestreamProxiesManager(ConnectionFactory } SOCKS5BytestreamProxiesManager::~SOCKS5BytestreamProxiesManager() { - if (proxyFinder_) { - proxyFinder_->stop(); - } - - foreach (const ProxySessionsMap::value_type& sessionsForID, proxySessions_) { - foreach (const ProxyJIDClientSessionVector::value_type& session, sessionsForID.second) { - session.second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionsForID.first, session.first, session.second, _1)); - session.second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionsForID.first, session.first, session.second, _1)); - } - } + if (proxyFinder_) { + proxyFinder_->stop(); + } + + foreach (const ProxySessionsMap::value_type& sessionsForID, proxySessions_) { + foreach (const ProxyJIDClientSessionVector::value_type& session, sessionsForID.second) { + session.second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionsForID.first, session.first, session.second, _1)); + session.second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionsForID.first, session.first, session.second, _1)); + } + } } void SOCKS5BytestreamProxiesManager::addS5BProxy(S5BProxyRequest::ref proxy) { - if (proxy) { - SWIFT_LOG_ASSERT(HostAddress(proxy->getStreamHost().get().host).isValid(), warning) << std::endl; - if (!localS5BProxies_) { - localS5BProxies_ = std::vector<S5BProxyRequest::ref>(); - } - localS5BProxies_->push_back(proxy); - } + if (proxy) { + SWIFT_LOG_ASSERT(HostAddress(proxy->getStreamHost().get().host).isValid(), warning) << std::endl; + if (!localS5BProxies_) { + localS5BProxies_ = std::vector<S5BProxyRequest::ref>(); + } + localS5BProxies_->push_back(proxy); + } } const boost::optional<std::vector<S5BProxyRequest::ref> >& SOCKS5BytestreamProxiesManager::getOrDiscoverS5BProxies() { - if (!localS5BProxies_ && !proxyFinder_) { - queryForProxies(); - } - return localS5BProxies_; + if (!localS5BProxies_ && !proxyFinder_) { + queryForProxies(); + } + return localS5BProxies_; } void SOCKS5BytestreamProxiesManager::connectToProxies(const std::string& sessionID) { - SWIFT_LOG(debug) << "session ID: " << sessionID << std::endl; - ProxyJIDClientSessionVector clientSessions; - - if (localS5BProxies_) { - foreach(S5BProxyRequest::ref proxy, localS5BProxies_.get()) { - boost::shared_ptr<Connection> conn = connectionFactory_->createConnection(); - - HostAddressPort addressPort = HostAddressPort(proxy->getStreamHost().get().host, proxy->getStreamHost().get().port); - SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl; - boost::shared_ptr<SOCKS5BytestreamClientSession> session = boost::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_); - JID proxyJid = proxy->getStreamHost().get().jid; - clientSessions.push_back(std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> >(proxyJid, session)); - session->onSessionReady.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJid, session, _1)); - session->onFinished.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJid, session, _1)); - session->start(); - } - } - - proxySessions_[sessionID] = clientSessions; + SWIFT_LOG(debug) << "session ID: " << sessionID << std::endl; + ProxyJIDClientSessionVector clientSessions; + + if (localS5BProxies_) { + foreach(S5BProxyRequest::ref proxy, localS5BProxies_.get()) { + boost::shared_ptr<Connection> conn = connectionFactory_->createConnection(); + + HostAddressPort addressPort = HostAddressPort(proxy->getStreamHost().get().host, proxy->getStreamHost().get().port); + SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl; + boost::shared_ptr<SOCKS5BytestreamClientSession> session = boost::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_); + JID proxyJid = proxy->getStreamHost().get().jid; + clientSessions.push_back(std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> >(proxyJid, session)); + session->onSessionReady.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJid, session, _1)); + session->onFinished.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJid, session, _1)); + session->start(); + } + } + + proxySessions_[sessionID] = clientSessions; } boost::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID) { - // checking parameters - if (proxySessions_.find(sessionID) == proxySessions_.end()) { - return boost::shared_ptr<SOCKS5BytestreamClientSession>(); - } - - // get active session - boost::shared_ptr<SOCKS5BytestreamClientSession> activeSession; - for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end(); i++) { - i->second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJID, i->second, _1)); - i->second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJID, i->second, _1)); - if (i->first == proxyJID && !activeSession) { - activeSession = i->second; - } - else { - i->second->stop(); - } - } - - proxySessions_.erase(sessionID); - - return activeSession; + // checking parameters + if (proxySessions_.find(sessionID) == proxySessions_.end()) { + return boost::shared_ptr<SOCKS5BytestreamClientSession>(); + } + + // get active session + boost::shared_ptr<SOCKS5BytestreamClientSession> activeSession; + for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end(); i++) { + i->second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJID, i->second, _1)); + i->second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJID, i->second, _1)); + if (i->first == proxyJID && !activeSession) { + activeSession = i->second; + } + else { + i->second->stop(); + } + } + + proxySessions_.erase(sessionID); + + return activeSession; } boost::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr) { - SOCKS5BytestreamClientSession::ref connection = boost::make_shared<SOCKS5BytestreamClientSession>(connectionFactory_->createConnection(), addressPort, destAddr, timerFactory_); - return connection; + SOCKS5BytestreamClientSession::ref connection = boost::make_shared<SOCKS5BytestreamClientSession>(connectionFactory_->createConnection(), addressPort, destAddr, timerFactory_); + return connection; } void SOCKS5BytestreamProxiesManager::handleProxiesFound(std::vector<S5BProxyRequest::ref> proxyHosts) { - proxyFinder_->onProxiesFound.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1)); - foreach(S5BProxyRequest::ref proxy, proxyHosts) { - if (proxy) { - if (HostAddress(proxy->getStreamHost().get().host).isValid()) { - addS5BProxy(proxy); - onDiscoveredProxiesChanged(); - } - else { - DomainNameAddressQuery::ref resolveRequest = resolver_->createAddressQuery(proxy->getStreamHost().get().host); - resolveRequest->onResult.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleNameLookupResult, this, _1, _2, proxy)); - resolveRequest->run(); - } - } - } - proxyFinder_->stop(); - proxyFinder_.reset(); - if (proxyHosts.empty()) { - onDiscoveredProxiesChanged(); - } + proxyFinder_->onProxiesFound.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1)); + foreach(S5BProxyRequest::ref proxy, proxyHosts) { + if (proxy) { + if (HostAddress(proxy->getStreamHost().get().host).isValid()) { + addS5BProxy(proxy); + onDiscoveredProxiesChanged(); + } + else { + DomainNameAddressQuery::ref resolveRequest = resolver_->createAddressQuery(proxy->getStreamHost().get().host); + resolveRequest->onResult.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleNameLookupResult, this, _1, _2, proxy)); + resolveRequest->run(); + } + } + } + proxyFinder_->stop(); + proxyFinder_.reset(); + if (proxyHosts.empty()) { + onDiscoveredProxiesChanged(); + } } void SOCKS5BytestreamProxiesManager::handleNameLookupResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error, S5BProxyRequest::ref proxy) { - if (error) { - onDiscoveredProxiesChanged(); - } - else { - if (addresses.empty()) { - SWIFT_LOG(warning) << "S5B proxy hostname does not resolve." << std::endl; - } - else { - // generate proxy per returned address - foreach (const HostAddress& address, addresses) { - S5BProxyRequest::StreamHost streamHost = proxy->getStreamHost().get(); - S5BProxyRequest::ref proxyForAddress = boost::make_shared<S5BProxyRequest>(*proxy); - streamHost.host = address.toString(); - proxyForAddress->setStreamHost(streamHost); - addS5BProxy(proxyForAddress); - } - } - onDiscoveredProxiesChanged(); - } + if (error) { + onDiscoveredProxiesChanged(); + } + else { + if (addresses.empty()) { + SWIFT_LOG(warning) << "S5B proxy hostname does not resolve." << std::endl; + } + else { + // generate proxy per returned address + foreach (const HostAddress& address, addresses) { + S5BProxyRequest::StreamHost streamHost = proxy->getStreamHost().get(); + S5BProxyRequest::ref proxyForAddress = boost::make_shared<S5BProxyRequest>(*proxy); + streamHost.host = address.toString(); + proxyForAddress->setStreamHost(streamHost); + addS5BProxy(proxyForAddress); + } + } + onDiscoveredProxiesChanged(); + } } void SOCKS5BytestreamProxiesManager::queryForProxies() { - proxyFinder_ = boost::make_shared<SOCKS5BytestreamProxyFinder>(serviceRoot_, iqRouter_); + proxyFinder_ = boost::make_shared<SOCKS5BytestreamProxyFinder>(serviceRoot_, iqRouter_); - proxyFinder_->onProxiesFound.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1)); - proxyFinder_->start(); + proxyFinder_->onProxiesFound.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1)); + proxyFinder_->start(); } void SOCKS5BytestreamProxiesManager::handleProxySessionReady(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, bool error) { - session->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this, boost::cref(sessionID), boost::cref(jid), session, _1)); - if (!error) { - // The SOCKS5 bytestream session to the proxy succeeded; stop and remove other sessions. - if (proxySessions_.find(sessionID) != proxySessions_.end()) { - for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) { - if ((i->first == jid) && (i->second != session)) { - i->second->stop(); - i = proxySessions_[sessionID].erase(i); - } - else { - i++; - } - } - } - } + session->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this, boost::cref(sessionID), boost::cref(jid), session, _1)); + if (!error) { + // The SOCKS5 bytestream session to the proxy succeeded; stop and remove other sessions. + if (proxySessions_.find(sessionID) != proxySessions_.end()) { + for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) { + if ((i->first == jid) && (i->second != session)) { + i->second->stop(); + i = proxySessions_[sessionID].erase(i); + } + else { + i++; + } + } + } + } } void SOCKS5BytestreamProxiesManager::handleProxySessionFinished(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, boost::optional<FileTransferError> error) { - session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, jid, session, _1)); - if (error.is_initialized()) { - // The SOCKS5 bytestream session to the proxy failed; remove it. - if (proxySessions_.find(sessionID) != proxySessions_.end()) { - for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) { - if ((i->first == jid) && (i->second == session)) { - i->second->stop(); - i = proxySessions_[sessionID].erase(i); - break; - } - else { - i++; - } - } - } - } + session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, jid, session, _1)); + if (error.is_initialized()) { + // The SOCKS5 bytestream session to the proxy failed; remove it. + if (proxySessions_.find(sessionID) != proxySessions_.end()) { + for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) { + if ((i->first == jid) && (i->second == session)) { + i->second->stop(); + i = proxySessions_[sessionID].erase(i); + break; + } + else { + i++; + } + } + } + } } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h index c7daee7..b490ffa 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h @@ -25,60 +25,60 @@ #include <Swiften/JID/JID.h> namespace Swift { - class TimerFactory; - class ConnectionFactory; - class DomainNameResolver; - class DomainNameResolveError; - class IQRouter; + class TimerFactory; + class ConnectionFactory; + class DomainNameResolver; + class DomainNameResolveError; + class IQRouter; - /** - * - manages list of working S5B proxies - * - creates initial connections (for the candidates you provide) - */ - class SWIFTEN_API SOCKS5BytestreamProxiesManager { - public: - SOCKS5BytestreamProxiesManager(ConnectionFactory*, TimerFactory*, DomainNameResolver*, IQRouter*, const JID&); - ~SOCKS5BytestreamProxiesManager(); + /** + * - manages list of working S5B proxies + * - creates initial connections (for the candidates you provide) + */ + class SWIFTEN_API SOCKS5BytestreamProxiesManager { + public: + SOCKS5BytestreamProxiesManager(ConnectionFactory*, TimerFactory*, DomainNameResolver*, IQRouter*, const JID&); + ~SOCKS5BytestreamProxiesManager(); - void addS5BProxy(S5BProxyRequest::ref); + void addS5BProxy(S5BProxyRequest::ref); - /* - * Returns a list of external S5B proxies. If the optinal return value is not initialized a discovery process has been started and - * onDiscoveredProxiesChanged signal will be emitted when it is finished. - */ - const boost::optional<std::vector<S5BProxyRequest::ref> >& getOrDiscoverS5BProxies(); + /* + * Returns a list of external S5B proxies. If the optinal return value is not initialized a discovery process has been started and + * onDiscoveredProxiesChanged signal will be emitted when it is finished. + */ + const boost::optional<std::vector<S5BProxyRequest::ref> >& getOrDiscoverS5BProxies(); - void connectToProxies(const std::string& sessionID); - boost::shared_ptr<SOCKS5BytestreamClientSession> getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID); + void connectToProxies(const std::string& sessionID); + boost::shared_ptr<SOCKS5BytestreamClientSession> getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID); - boost::shared_ptr<SOCKS5BytestreamClientSession> createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr); + boost::shared_ptr<SOCKS5BytestreamClientSession> createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr); - public: - boost::signal<void ()> onDiscoveredProxiesChanged; + public: + boost::signal<void ()> onDiscoveredProxiesChanged; - private: - void handleProxiesFound(std::vector<S5BProxyRequest::ref> proxyHosts); - void handleNameLookupResult(const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>, S5BProxyRequest::ref proxy); + private: + void handleProxiesFound(std::vector<S5BProxyRequest::ref> proxyHosts); + void handleNameLookupResult(const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>, S5BProxyRequest::ref proxy); - void queryForProxies(); + void queryForProxies(); - void handleProxySessionReady(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, bool error); - void handleProxySessionFinished(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, boost::optional<FileTransferError> error); + void handleProxySessionReady(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, bool error); + void handleProxySessionFinished(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, boost::optional<FileTransferError> error); - private: - ConnectionFactory* connectionFactory_; - TimerFactory* timerFactory_; - DomainNameResolver* resolver_; - IQRouter* iqRouter_; - JID serviceRoot_; + private: + ConnectionFactory* connectionFactory_; + TimerFactory* timerFactory_; + DomainNameResolver* resolver_; + IQRouter* iqRouter_; + JID serviceRoot_; - typedef std::vector<std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> > > ProxyJIDClientSessionVector; - typedef std::map<std::string, ProxyJIDClientSessionVector> ProxySessionsMap; - ProxySessionsMap proxySessions_; + typedef std::vector<std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> > > ProxyJIDClientSessionVector; + typedef std::map<std::string, ProxyJIDClientSessionVector> ProxySessionsMap; + ProxySessionsMap proxySessions_; - boost::shared_ptr<SOCKS5BytestreamProxyFinder> proxyFinder_; + boost::shared_ptr<SOCKS5BytestreamProxyFinder> proxyFinder_; - boost::optional<std::vector<S5BProxyRequest::ref> > localS5BProxies_; - }; + boost::optional<std::vector<S5BProxyRequest::ref> > localS5BProxies_; + }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp index 78cf2e6..e6c85cf 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp @@ -30,58 +30,58 @@ SOCKS5BytestreamProxyFinder::~SOCKS5BytestreamProxyFinder() { } void SOCKS5BytestreamProxyFinder::start() { - serviceWalker = boost::make_shared<DiscoServiceWalker>(service, iqRouter); - serviceWalker->onServiceFound.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2)); - serviceWalker->onWalkComplete.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this)); - serviceWalker->beginWalk(); + serviceWalker = boost::make_shared<DiscoServiceWalker>(service, iqRouter); + serviceWalker->onServiceFound.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2)); + serviceWalker->onWalkComplete.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this)); + serviceWalker->beginWalk(); } void SOCKS5BytestreamProxyFinder::stop() { - typedef boost::shared_ptr<GenericRequest<S5BProxyRequest> > S5BProxyRequestGenericRequest; - foreach (S5BProxyRequestGenericRequest requester, pendingRequests) { - requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2)); - } + typedef boost::shared_ptr<GenericRequest<S5BProxyRequest> > S5BProxyRequestGenericRequest; + foreach (S5BProxyRequestGenericRequest requester, pendingRequests) { + requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2)); + } - serviceWalker->endWalk(); - serviceWalker->onServiceFound.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2)); - serviceWalker->onWalkComplete.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this)); - serviceWalker.reset(); + serviceWalker->endWalk(); + serviceWalker->onServiceFound.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2)); + serviceWalker->onWalkComplete.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this)); + serviceWalker.reset(); } void SOCKS5BytestreamProxyFinder::sendBytestreamQuery(const JID& jid) { - S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>(); - boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Get, jid, proxyRequest, iqRouter); - request->onResponse.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, request, _1, _2)); - pendingRequests.insert(request); - request->send(); + S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>(); + boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Get, jid, proxyRequest, iqRouter); + request->onResponse.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, request, _1, _2)); + pendingRequests.insert(request); + request->send(); } void SOCKS5BytestreamProxyFinder::handleServiceFound(const JID& jid, boost::shared_ptr<DiscoInfo> discoInfo) { - if (discoInfo->hasFeature(DiscoInfo::Bytestream)) { - sendBytestreamQuery(jid); - } + if (discoInfo->hasFeature(DiscoInfo::Bytestream)) { + sendBytestreamQuery(jid); + } } void SOCKS5BytestreamProxyFinder::handleWalkEnded() { - if (pendingRequests.empty()) { - onProxiesFound(proxyHosts); - } + if (pendingRequests.empty()) { + onProxiesFound(proxyHosts); + } } void SOCKS5BytestreamProxyFinder::handleProxyResponse(boost::shared_ptr<GenericRequest<S5BProxyRequest> > requester, boost::shared_ptr<S5BProxyRequest> request, ErrorPayload::ref error) { - requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2)); - pendingRequests.erase(requester); - if (error) { - SWIFT_LOG(debug) << "ERROR" << std::endl; - } else { - if (request) { - SWIFT_LOG(debug) << "add request" << std::endl; - proxyHosts.push_back(request); - } - } - if (pendingRequests.empty() && !serviceWalker->isActive()) { - onProxiesFound(proxyHosts); - } + requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2)); + pendingRequests.erase(requester); + if (error) { + SWIFT_LOG(debug) << "ERROR" << std::endl; + } else { + if (request) { + SWIFT_LOG(debug) << "add request" << std::endl; + proxyHosts.push_back(request); + } + } + if (pendingRequests.empty() && !serviceWalker->isActive()) { + onProxiesFound(proxyHosts); + } } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h index 1c24497..1047df0 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h @@ -29,28 +29,28 @@ class IQRouter; * restrictive environments. */ class SWIFTEN_API SOCKS5BytestreamProxyFinder { - public: - SOCKS5BytestreamProxyFinder(const JID& service, IQRouter *iqRouter); - ~SOCKS5BytestreamProxyFinder(); + public: + SOCKS5BytestreamProxyFinder(const JID& service, IQRouter *iqRouter); + ~SOCKS5BytestreamProxyFinder(); - void start(); - void stop(); + void start(); + void stop(); - boost::signal<void(std::vector<boost::shared_ptr<S5BProxyRequest> >)> onProxiesFound; + boost::signal<void(std::vector<boost::shared_ptr<S5BProxyRequest> >)> onProxiesFound; - private: - void sendBytestreamQuery(const JID&); + private: + void sendBytestreamQuery(const JID&); - void handleServiceFound(const JID&, boost::shared_ptr<DiscoInfo>); - void handleProxyResponse(boost::shared_ptr<GenericRequest<S5BProxyRequest> > requester, boost::shared_ptr<S5BProxyRequest>, ErrorPayload::ref); - void handleWalkEnded(); + void handleServiceFound(const JID&, boost::shared_ptr<DiscoInfo>); + void handleProxyResponse(boost::shared_ptr<GenericRequest<S5BProxyRequest> > requester, boost::shared_ptr<S5BProxyRequest>, ErrorPayload::ref); + void handleWalkEnded(); - private: - JID service; - IQRouter* iqRouter; - boost::shared_ptr<DiscoServiceWalker> serviceWalker; - std::vector<S5BProxyRequest::ref> proxyHosts; - std::set<boost::shared_ptr<GenericRequest<S5BProxyRequest> > > pendingRequests; + private: + JID service; + IQRouter* iqRouter; + boost::shared_ptr<DiscoServiceWalker> serviceWalker; + std::vector<S5BProxyRequest::ref> proxyHosts; + std::set<boost::shared_ptr<GenericRequest<S5BProxyRequest> > > pendingRequests; }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp index 5f3756d..2f66dff 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp @@ -18,20 +18,20 @@ SOCKS5BytestreamRegistry::SOCKS5BytestreamRegistry() { } void SOCKS5BytestreamRegistry::setHasBytestream(const std::string& destination, bool b) { - if (b) { - availableBytestreams.insert(destination); - } - else { - availableBytestreams.erase(destination); - } + if (b) { + availableBytestreams.insert(destination); + } + else { + availableBytestreams.erase(destination); + } } bool SOCKS5BytestreamRegistry::hasBytestream(const std::string& destination) const { - return availableBytestreams.find(destination) != availableBytestreams.end(); + return availableBytestreams.find(destination) != availableBytestreams.end(); } std::string SOCKS5BytestreamRegistry::generateSessionID() { - return idGenerator.generateID(); + return idGenerator.generateID(); } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h index 0575aed..2fa67fa 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h @@ -14,22 +14,22 @@ #include <Swiften/Base/IDGenerator.h> namespace Swift { - class SOCKS5BytestreamServerSession; + class SOCKS5BytestreamServerSession; - class SWIFTEN_API SOCKS5BytestreamRegistry { - public: - SOCKS5BytestreamRegistry(); + class SWIFTEN_API SOCKS5BytestreamRegistry { + public: + SOCKS5BytestreamRegistry(); - void setHasBytestream(const std::string& destination, bool); - bool hasBytestream(const std::string& destination) const; + void setHasBytestream(const std::string& destination, bool); + bool hasBytestream(const std::string& destination) const; - /** - * Generate a new session ID to use for new S5B streams. - */ - std::string generateSessionID(); + /** + * Generate a new session ID to use for new S5B streams. + */ + std::string generateSessionID(); - private: - std::set<std::string> availableBytestreams; - IDGenerator idGenerator; - }; + private: + std::set<std::string> availableBytestreams; + IDGenerator idGenerator; + }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp index 4ec95d3..f25227a 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp @@ -18,51 +18,51 @@ namespace Swift { SOCKS5BytestreamServer::SOCKS5BytestreamServer( - boost::shared_ptr<ConnectionServer> connectionServer, - SOCKS5BytestreamRegistry* registry) : - connectionServer(connectionServer), - registry(registry) { + boost::shared_ptr<ConnectionServer> connectionServer, + SOCKS5BytestreamRegistry* registry) : + connectionServer(connectionServer), + registry(registry) { } void SOCKS5BytestreamServer::start() { - connectionServer->onNewConnection.connect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1)); + connectionServer->onNewConnection.connect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1)); } void SOCKS5BytestreamServer::stop() { - connectionServer->onNewConnection.disconnect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1)); - foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) { - session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session)); - session->stop(); - } - sessions.clear(); + connectionServer->onNewConnection.disconnect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1)); + foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) { + session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session)); + session->stop(); + } + sessions.clear(); } void SOCKS5BytestreamServer::handleNewConnection(boost::shared_ptr<Connection> connection) { - boost::shared_ptr<SOCKS5BytestreamServerSession> session = - boost::make_shared<SOCKS5BytestreamServerSession>(connection, registry); - session->onFinished.connect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session)); - sessions.push_back(session); - session->start(); + boost::shared_ptr<SOCKS5BytestreamServerSession> session = + boost::make_shared<SOCKS5BytestreamServerSession>(connection, registry); + session->onFinished.connect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session)); + sessions.push_back(session); + session->start(); } HostAddressPort SOCKS5BytestreamServer::getAddressPort() const { - return connectionServer->getAddressPort(); + return connectionServer->getAddressPort(); } std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > SOCKS5BytestreamServer::getSessions( - const std::string& streamID) const { - std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > result; - foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) { - if (session->getStreamID() == streamID) { - result.push_back(session); - } - } - return result; + const std::string& streamID) const { + std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > result; + foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) { + if (session->getStreamID() == streamID) { + result.push_back(session); + } + } + return result; } void SOCKS5BytestreamServer::handleSessionFinished(boost::shared_ptr<SOCKS5BytestreamServerSession> session) { - sessions.erase(std::remove(sessions.begin(), sessions.end(), session), sessions.end()); - session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session)); + sessions.erase(std::remove(sessions.begin(), sessions.end(), session), sessions.end()); + session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session)); } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServer.h b/Swiften/FileTransfer/SOCKS5BytestreamServer.h index 4954f33..f9b293e 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServer.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.h @@ -18,32 +18,32 @@ #include <Swiften/Network/ConnectionServer.h> namespace Swift { - class SOCKS5BytestreamServerSession; - class CryptoProvider; + class SOCKS5BytestreamServerSession; + class CryptoProvider; - class SWIFTEN_API SOCKS5BytestreamServer { - public: - SOCKS5BytestreamServer( - boost::shared_ptr<ConnectionServer> connectionServer, - SOCKS5BytestreamRegistry* registry); + class SWIFTEN_API SOCKS5BytestreamServer { + public: + SOCKS5BytestreamServer( + boost::shared_ptr<ConnectionServer> connectionServer, + SOCKS5BytestreamRegistry* registry); - HostAddressPort getAddressPort() const; + HostAddressPort getAddressPort() const; - void start(); - void stop(); + void start(); + void stop(); - std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > getSessions(const std::string& id) const; + std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > getSessions(const std::string& id) const; - private: - void handleNewConnection(boost::shared_ptr<Connection> connection); - void handleSessionFinished(boost::shared_ptr<SOCKS5BytestreamServerSession>); + private: + void handleNewConnection(boost::shared_ptr<Connection> connection); + void handleSessionFinished(boost::shared_ptr<SOCKS5BytestreamServerSession>); - private: - friend class SOCKS5BytestreamServerSession; + private: + friend class SOCKS5BytestreamServerSession; - boost::shared_ptr<ConnectionServer> connectionServer; - SOCKS5BytestreamRegistry* registry; - std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > sessions; - }; + boost::shared_ptr<ConnectionServer> connectionServer; + SOCKS5BytestreamRegistry* registry; + std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > sessions; + }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp index 3b1be89..2129815 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp @@ -34,223 +34,223 @@ static const int LISTEN_PORTS_BEGIN = 10000; static const int LISTEN_PORTS_END = 11000; SOCKS5BytestreamServerManager::SOCKS5BytestreamServerManager( - SOCKS5BytestreamRegistry* bytestreamRegistry, - ConnectionServerFactory* connectionServerFactory, - NetworkEnvironment* networkEnvironment, - NATTraverser* natTraverser) : - bytestreamRegistry(bytestreamRegistry), - connectionServerFactory(connectionServerFactory), - networkEnvironment(networkEnvironment), - natTraverser(natTraverser), - state(Start), - server(NULL), - attemptedPortMapping_(false) { + SOCKS5BytestreamRegistry* bytestreamRegistry, + ConnectionServerFactory* connectionServerFactory, + NetworkEnvironment* networkEnvironment, + NATTraverser* natTraverser) : + bytestreamRegistry(bytestreamRegistry), + connectionServerFactory(connectionServerFactory), + networkEnvironment(networkEnvironment), + natTraverser(natTraverser), + state(Start), + server(NULL), + attemptedPortMapping_(false) { } SOCKS5BytestreamServerManager::~SOCKS5BytestreamServerManager() { - SWIFT_LOG_ASSERT(!connectionServer, warning) << std::endl; - SWIFT_LOG_ASSERT(!getPublicIPRequest, warning) << std::endl; - SWIFT_LOG_ASSERT(!forwardPortRequest, warning) << std::endl; - SWIFT_LOG_ASSERT(state == Start, warning) << std::endl; - if (portMapping && !unforwardPortRequest) { - SWIFT_LOG(warning) << "Port forwarding still alive. Trying to remove it now." << std::endl; - unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort()); - unforwardPortRequest->start(); - } + SWIFT_LOG_ASSERT(!connectionServer, warning) << std::endl; + SWIFT_LOG_ASSERT(!getPublicIPRequest, warning) << std::endl; + SWIFT_LOG_ASSERT(!forwardPortRequest, warning) << std::endl; + SWIFT_LOG_ASSERT(state == Start, warning) << std::endl; + if (portMapping && !unforwardPortRequest) { + SWIFT_LOG(warning) << "Port forwarding still alive. Trying to remove it now." << std::endl; + unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort()); + unforwardPortRequest->start(); + } } boost::shared_ptr<SOCKS5BytestreamServerResourceUser> SOCKS5BytestreamServerManager::aquireResourceUser() { - boost::shared_ptr<SOCKS5BytestreamServerResourceUser> resourceUser; - if (s5bServerResourceUser_.expired()) { - resourceUser = boost::make_shared<SOCKS5BytestreamServerResourceUser>(this); - s5bServerResourceUser_ = resourceUser; - } - else { - resourceUser = s5bServerResourceUser_.lock(); - } - return resourceUser; + boost::shared_ptr<SOCKS5BytestreamServerResourceUser> resourceUser; + if (s5bServerResourceUser_.expired()) { + resourceUser = boost::make_shared<SOCKS5BytestreamServerResourceUser>(this); + s5bServerResourceUser_ = resourceUser; + } + else { + resourceUser = s5bServerResourceUser_.lock(); + } + return resourceUser; } boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> SOCKS5BytestreamServerManager::aquirePortForwardingUser() { - boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> portForwardingUser; - if (s5bServerPortForwardingUser_.expired()) { - portForwardingUser = boost::make_shared<SOCKS5BytestreamServerPortForwardingUser>(this); - s5bServerPortForwardingUser_ = portForwardingUser; - } - else { - portForwardingUser = s5bServerPortForwardingUser_.lock(); - } - return portForwardingUser; + boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> portForwardingUser; + if (s5bServerPortForwardingUser_.expired()) { + portForwardingUser = boost::make_shared<SOCKS5BytestreamServerPortForwardingUser>(this); + s5bServerPortForwardingUser_ = portForwardingUser; + } + else { + portForwardingUser = s5bServerPortForwardingUser_.lock(); + } + return portForwardingUser; } std::vector<HostAddressPort> SOCKS5BytestreamServerManager::getHostAddressPorts() const { - std::vector<HostAddressPort> result; - if (connectionServer) { - std::vector<NetworkInterface> networkInterfaces = networkEnvironment->getNetworkInterfaces(); - foreach (const NetworkInterface& networkInterface, networkInterfaces) { - foreach (const HostAddress& address, networkInterface.getAddresses()) { - result.push_back(HostAddressPort(address, connectionServerPort)); - } - } - } - return result; + std::vector<HostAddressPort> result; + if (connectionServer) { + std::vector<NetworkInterface> networkInterfaces = networkEnvironment->getNetworkInterfaces(); + foreach (const NetworkInterface& networkInterface, networkInterfaces) { + foreach (const HostAddress& address, networkInterface.getAddresses()) { + result.push_back(HostAddressPort(address, connectionServerPort)); + } + } + } + return result; } std::vector<HostAddressPort> SOCKS5BytestreamServerManager::getAssistedHostAddressPorts() const { - std::vector<HostAddressPort> result; - if (publicAddress && portMapping) { - result.push_back(HostAddressPort(*publicAddress, portMapping->getPublicPort())); - } - return result; + std::vector<HostAddressPort> result; + if (publicAddress && portMapping) { + result.push_back(HostAddressPort(*publicAddress, portMapping->getPublicPort())); + } + return result; } bool SOCKS5BytestreamServerManager::isInitialized() const { - return state == Initialized; + return state == Initialized; } void SOCKS5BytestreamServerManager::initialize() { - if (state == Start) { - state = Initializing; + if (state == Start) { + state = Initializing; - // Find a port to listen on - assert(!connectionServer); - int port; - for (port = LISTEN_PORTS_BEGIN; port < LISTEN_PORTS_END; ++port) { - SWIFT_LOG(debug) << "Trying to start server on port " << port << std::endl; - connectionServer = connectionServerFactory->createConnectionServer(HostAddress("::"), port); - boost::optional<ConnectionServer::Error> error = connectionServer->tryStart(); - if (!error) { - break; - } - else if (*error != ConnectionServer::Conflict) { - SWIFT_LOG(debug) << "Error starting server" << std::endl; - onInitialized(false); - return; - } - connectionServer.reset(); - } - if (!connectionServer) { - SWIFT_LOG(debug) << "Unable to find an open port" << std::endl; - onInitialized(false); - return; - } - SWIFT_LOG(debug) << "Server started succesfully" << std::endl; - connectionServerPort = port; + // Find a port to listen on + assert(!connectionServer); + int port; + for (port = LISTEN_PORTS_BEGIN; port < LISTEN_PORTS_END; ++port) { + SWIFT_LOG(debug) << "Trying to start server on port " << port << std::endl; + connectionServer = connectionServerFactory->createConnectionServer(HostAddress("::"), port); + boost::optional<ConnectionServer::Error> error = connectionServer->tryStart(); + if (!error) { + break; + } + else if (*error != ConnectionServer::Conflict) { + SWIFT_LOG(debug) << "Error starting server" << std::endl; + onInitialized(false); + return; + } + connectionServer.reset(); + } + if (!connectionServer) { + SWIFT_LOG(debug) << "Unable to find an open port" << std::endl; + onInitialized(false); + return; + } + SWIFT_LOG(debug) << "Server started succesfully" << std::endl; + connectionServerPort = port; - // Start bytestream server. Should actually happen before the connectionserver is started - // but that doesn't really matter here. - assert(!server); - server = new SOCKS5BytestreamServer(connectionServer, bytestreamRegistry); - server->start(); - checkInitializeFinished(); - } + // Start bytestream server. Should actually happen before the connectionserver is started + // but that doesn't really matter here. + assert(!server); + server = new SOCKS5BytestreamServer(connectionServer, bytestreamRegistry); + server->start(); + checkInitializeFinished(); + } } bool SOCKS5BytestreamServerManager::isPortForwardingReady() const { - return attemptedPortMapping_ && !getPublicIPRequest && !forwardPortRequest; + return attemptedPortMapping_ && !getPublicIPRequest && !forwardPortRequest; } void SOCKS5BytestreamServerManager::setupPortForwarding() { - assert(server); - attemptedPortMapping_ = true; + assert(server); + attemptedPortMapping_ = true; - // Retrieve public addresses - assert(!getPublicIPRequest); - publicAddress = boost::optional<HostAddress>(); - if ((getPublicIPRequest = natTraverser->createGetPublicIPRequest())) { - getPublicIPRequest->onResult.connect( - boost::bind(&SOCKS5BytestreamServerManager::handleGetPublicIPResult, this, _1)); - getPublicIPRequest->start(); - } + // Retrieve public addresses + assert(!getPublicIPRequest); + publicAddress = boost::optional<HostAddress>(); + if ((getPublicIPRequest = natTraverser->createGetPublicIPRequest())) { + getPublicIPRequest->onResult.connect( + boost::bind(&SOCKS5BytestreamServerManager::handleGetPublicIPResult, this, _1)); + getPublicIPRequest->start(); + } - // Forward ports - int port = server->getAddressPort().getPort(); - assert(!forwardPortRequest); - portMapping = boost::optional<NATPortMapping>(); - if ((forwardPortRequest = natTraverser->createForwardPortRequest(port, port))) { - forwardPortRequest->onResult.connect( - boost::bind(&SOCKS5BytestreamServerManager::handleForwardPortResult, this, _1)); - forwardPortRequest->start(); - } + // Forward ports + int port = server->getAddressPort().getPort(); + assert(!forwardPortRequest); + portMapping = boost::optional<NATPortMapping>(); + if ((forwardPortRequest = natTraverser->createForwardPortRequest(port, port))) { + forwardPortRequest->onResult.connect( + boost::bind(&SOCKS5BytestreamServerManager::handleForwardPortResult, this, _1)); + forwardPortRequest->start(); + } } void SOCKS5BytestreamServerManager::removePortForwarding() { - // remove port forwards - if (portMapping) { - unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort()); - unforwardPortRequest->onResult.connect(boost::bind(&SOCKS5BytestreamServerManager::handleUnforwardPortResult, this, _1)); - unforwardPortRequest->start(); - } + // remove port forwards + if (portMapping) { + unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort()); + unforwardPortRequest->onResult.connect(boost::bind(&SOCKS5BytestreamServerManager::handleUnforwardPortResult, this, _1)); + unforwardPortRequest->start(); + } } void SOCKS5BytestreamServerManager::stop() { - if (getPublicIPRequest) { - getPublicIPRequest->stop(); - getPublicIPRequest.reset(); - } - if (forwardPortRequest) { - forwardPortRequest->stop(); - forwardPortRequest.reset(); - } - if (unforwardPortRequest) { - unforwardPortRequest->stop(); - unforwardPortRequest.reset(); - } - if (server) { - server->stop(); - delete server; - server = NULL; - } - if (connectionServer) { - connectionServer->stop(); - connectionServer.reset(); - } + if (getPublicIPRequest) { + getPublicIPRequest->stop(); + getPublicIPRequest.reset(); + } + if (forwardPortRequest) { + forwardPortRequest->stop(); + forwardPortRequest.reset(); + } + if (unforwardPortRequest) { + unforwardPortRequest->stop(); + unforwardPortRequest.reset(); + } + if (server) { + server->stop(); + delete server; + server = NULL; + } + if (connectionServer) { + connectionServer->stop(); + connectionServer.reset(); + } - state = Start; + state = Start; } void SOCKS5BytestreamServerManager::handleGetPublicIPResult(boost::optional<HostAddress> address) { - if (address) { - SWIFT_LOG(debug) << "Public IP discovered as " << address.get().toString() << "." << std::endl; - } - else { - SWIFT_LOG(debug) << "No public IP discoverable." << std::endl; - } + if (address) { + SWIFT_LOG(debug) << "Public IP discovered as " << address.get().toString() << "." << std::endl; + } + else { + SWIFT_LOG(debug) << "No public IP discoverable." << std::endl; + } - publicAddress = address; + publicAddress = address; - getPublicIPRequest->stop(); - getPublicIPRequest.reset(); + getPublicIPRequest->stop(); + getPublicIPRequest.reset(); } void SOCKS5BytestreamServerManager::handleForwardPortResult(boost::optional<NATPortMapping> mapping) { - if (mapping) { - SWIFT_LOG(debug) << "Mapping port was successful." << std::endl; - } - else { - SWIFT_LOG(debug) << "Mapping port has failed." << std::endl; - } + if (mapping) { + SWIFT_LOG(debug) << "Mapping port was successful." << std::endl; + } + else { + SWIFT_LOG(debug) << "Mapping port has failed." << std::endl; + } - portMapping = mapping; - onPortForwardingSetup(mapping.is_initialized()); + portMapping = mapping; + onPortForwardingSetup(mapping.is_initialized()); - forwardPortRequest->stop(); - forwardPortRequest.reset(); + forwardPortRequest->stop(); + forwardPortRequest.reset(); } void SOCKS5BytestreamServerManager::handleUnforwardPortResult(boost::optional<bool> result) { - if (result.is_initialized() && result.get()) { - portMapping.reset(); - } - else { - SWIFT_LOG(warning) << "Failed to remove port forwarding." << std::endl; - } - attemptedPortMapping_ = false; - unforwardPortRequest.reset(); + if (result.is_initialized() && result.get()) { + portMapping.reset(); + } + else { + SWIFT_LOG(warning) << "Failed to remove port forwarding." << std::endl; + } + attemptedPortMapping_ = false; + unforwardPortRequest.reset(); } void SOCKS5BytestreamServerManager::checkInitializeFinished() { - assert(state == Initializing); - state = Initialized; - onInitialized(true); + assert(state == Initializing); + state = Initialized; + onInitialized(true); } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h index c49031b..ab12dfe 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h @@ -17,79 +17,79 @@ #include <Swiften/Network/NATPortMapping.h> namespace Swift { - class NetworkEnvironment; - class NATTraverser; - class NATTraversalGetPublicIPRequest; - class NATTraversalForwardPortRequest; - class NATTraversalRemovePortForwardingRequest; - class SOCKS5BytestreamRegistry; - class ConnectionServerFactory; - class ConnectionServer; - class SOCKS5BytestreamServer; - class SOCKS5BytestreamServerResourceUser; - class SOCKS5BytestreamServerPortForwardingUser; - - class SWIFTEN_API SOCKS5BytestreamServerManager { - friend class SOCKS5BytestreamServerResourceUser; - friend class SOCKS5BytestreamServerPortForwardingUser; - - public: - SOCKS5BytestreamServerManager( - SOCKS5BytestreamRegistry* bytestreamRegistry, - ConnectionServerFactory* connectionServerFactory, - NetworkEnvironment* networkEnvironment, - NATTraverser* natTraverser); - ~SOCKS5BytestreamServerManager(); - - boost::shared_ptr<SOCKS5BytestreamServerResourceUser> aquireResourceUser(); - boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> aquirePortForwardingUser(); - - void stop(); - - std::vector<HostAddressPort> getHostAddressPorts() const; - std::vector<HostAddressPort> getAssistedHostAddressPorts() const; - - SOCKS5BytestreamServer* getServer() const { - return server; - } - - private: - bool isInitialized() const; - void initialize(); - - bool isPortForwardingReady() const; - void setupPortForwarding(); - void removePortForwarding(); - - void checkInitializeFinished(); - - void handleGetPublicIPResult(boost::optional<HostAddress> address); - void handleForwardPortResult(boost::optional<NATPortMapping> mapping); - void handleUnforwardPortResult(boost::optional<bool> result); - - boost::signal<void (bool /* success */)> onInitialized; - boost::signal<void (bool /* success */)> onPortForwardingSetup; - - private: - friend class SOCKS5BytestreamServerInitializeRequest; - SOCKS5BytestreamRegistry* bytestreamRegistry; - ConnectionServerFactory* connectionServerFactory; - NetworkEnvironment* networkEnvironment; - NATTraverser* natTraverser; - enum { Start, Initializing, Initialized } state; - SOCKS5BytestreamServer* server; - boost::shared_ptr<ConnectionServer> connectionServer; - int connectionServerPort; - - boost::shared_ptr<NATTraversalGetPublicIPRequest> getPublicIPRequest; - boost::shared_ptr<NATTraversalForwardPortRequest> forwardPortRequest; - boost::shared_ptr<NATTraversalRemovePortForwardingRequest> unforwardPortRequest; - boost::optional<HostAddress> publicAddress; - boost::optional<NATPortMapping> portMapping; - bool attemptedPortMapping_; - - boost::weak_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_; - boost::weak_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_; - }; + class NetworkEnvironment; + class NATTraverser; + class NATTraversalGetPublicIPRequest; + class NATTraversalForwardPortRequest; + class NATTraversalRemovePortForwardingRequest; + class SOCKS5BytestreamRegistry; + class ConnectionServerFactory; + class ConnectionServer; + class SOCKS5BytestreamServer; + class SOCKS5BytestreamServerResourceUser; + class SOCKS5BytestreamServerPortForwardingUser; + + class SWIFTEN_API SOCKS5BytestreamServerManager { + friend class SOCKS5BytestreamServerResourceUser; + friend class SOCKS5BytestreamServerPortForwardingUser; + + public: + SOCKS5BytestreamServerManager( + SOCKS5BytestreamRegistry* bytestreamRegistry, + ConnectionServerFactory* connectionServerFactory, + NetworkEnvironment* networkEnvironment, + NATTraverser* natTraverser); + ~SOCKS5BytestreamServerManager(); + + boost::shared_ptr<SOCKS5BytestreamServerResourceUser> aquireResourceUser(); + boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> aquirePortForwardingUser(); + + void stop(); + + std::vector<HostAddressPort> getHostAddressPorts() const; + std::vector<HostAddressPort> getAssistedHostAddressPorts() const; + + SOCKS5BytestreamServer* getServer() const { + return server; + } + + private: + bool isInitialized() const; + void initialize(); + + bool isPortForwardingReady() const; + void setupPortForwarding(); + void removePortForwarding(); + + void checkInitializeFinished(); + + void handleGetPublicIPResult(boost::optional<HostAddress> address); + void handleForwardPortResult(boost::optional<NATPortMapping> mapping); + void handleUnforwardPortResult(boost::optional<bool> result); + + boost::signal<void (bool /* success */)> onInitialized; + boost::signal<void (bool /* success */)> onPortForwardingSetup; + + private: + friend class SOCKS5BytestreamServerInitializeRequest; + SOCKS5BytestreamRegistry* bytestreamRegistry; + ConnectionServerFactory* connectionServerFactory; + NetworkEnvironment* networkEnvironment; + NATTraverser* natTraverser; + enum { Start, Initializing, Initialized } state; + SOCKS5BytestreamServer* server; + boost::shared_ptr<ConnectionServer> connectionServer; + int connectionServerPort; + + boost::shared_ptr<NATTraversalGetPublicIPRequest> getPublicIPRequest; + boost::shared_ptr<NATTraversalForwardPortRequest> forwardPortRequest; + boost::shared_ptr<NATTraversalRemovePortForwardingRequest> unforwardPortRequest; + boost::optional<HostAddress> publicAddress; + boost::optional<NATPortMapping> portMapping; + bool attemptedPortMapping_; + + boost::weak_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_; + boost::weak_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_; + }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp index 2118782..fc7fe58 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp @@ -13,29 +13,29 @@ namespace Swift { SOCKS5BytestreamServerPortForwardingUser::SOCKS5BytestreamServerPortForwardingUser(SOCKS5BytestreamServerManager* s5bServerManager) : s5bServerManager_(s5bServerManager) { - // the server should be initialized, so we know what port to setup a forward for - assert(s5bServerManager->isInitialized()); - if (s5bServerManager_->isPortForwardingReady()) { - onSetup(!s5bServerManager_->getAssistedHostAddressPorts().empty()); - } - else { - onPortForwardingSetupConnection_ = s5bServerManager_->onPortForwardingSetup.connect(boost::bind(&SOCKS5BytestreamServerPortForwardingUser::handleServerManagerPortForwardingSetup, this, _1)); - s5bServerManager_->setupPortForwarding(); - } + // the server should be initialized, so we know what port to setup a forward for + assert(s5bServerManager->isInitialized()); + if (s5bServerManager_->isPortForwardingReady()) { + onSetup(!s5bServerManager_->getAssistedHostAddressPorts().empty()); + } + else { + onPortForwardingSetupConnection_ = s5bServerManager_->onPortForwardingSetup.connect(boost::bind(&SOCKS5BytestreamServerPortForwardingUser::handleServerManagerPortForwardingSetup, this, _1)); + s5bServerManager_->setupPortForwarding(); + } } SOCKS5BytestreamServerPortForwardingUser::~SOCKS5BytestreamServerPortForwardingUser() { - if (s5bServerManager_->isPortForwardingReady()) { - s5bServerManager_->removePortForwarding(); - } + if (s5bServerManager_->isPortForwardingReady()) { + s5bServerManager_->removePortForwarding(); + } } bool SOCKS5BytestreamServerPortForwardingUser::isForwardingSetup() const { - return s5bServerManager_->isPortForwardingReady(); + return s5bServerManager_->isPortForwardingReady(); } void SOCKS5BytestreamServerPortForwardingUser::handleServerManagerPortForwardingSetup(bool successful) { - onSetup(successful); + onSetup(successful); } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h index cd79ecc..5d1f59a 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h @@ -14,20 +14,20 @@ namespace Swift { class SOCKS5BytestreamServerManager; class SWIFTEN_API SOCKS5BytestreamServerPortForwardingUser { - public: - SOCKS5BytestreamServerPortForwardingUser(SOCKS5BytestreamServerManager* s5bServerManager); - ~SOCKS5BytestreamServerPortForwardingUser(); + public: + SOCKS5BytestreamServerPortForwardingUser(SOCKS5BytestreamServerManager* s5bServerManager); + ~SOCKS5BytestreamServerPortForwardingUser(); - bool isForwardingSetup() const; + bool isForwardingSetup() const; - boost::signal<void (bool /* success */)> onSetup; + boost::signal<void (bool /* success */)> onSetup; - private: - void handleServerManagerPortForwardingSetup(bool successful); + private: + void handleServerManagerPortForwardingSetup(bool successful); - private: - SOCKS5BytestreamServerManager* s5bServerManager_; - boost::bsignals::scoped_connection onPortForwardingSetupConnection_; + private: + SOCKS5BytestreamServerManager* s5bServerManager_; + boost::bsignals::scoped_connection onPortForwardingSetupConnection_; }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp index 41a728f..2fc2e76 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp @@ -13,23 +13,23 @@ namespace Swift { SOCKS5BytestreamServerResourceUser::SOCKS5BytestreamServerResourceUser(SOCKS5BytestreamServerManager* s5bServerManager) : s5bServerManager_(s5bServerManager) { - assert(!s5bServerManager_->isInitialized()); - onInitializedConnection_ = s5bServerManager_->onInitialized.connect(boost::bind(&SOCKS5BytestreamServerResourceUser::handleServerManagerInitialized, this, _1)); - s5bServerManager_->initialize(); + assert(!s5bServerManager_->isInitialized()); + onInitializedConnection_ = s5bServerManager_->onInitialized.connect(boost::bind(&SOCKS5BytestreamServerResourceUser::handleServerManagerInitialized, this, _1)); + s5bServerManager_->initialize(); } SOCKS5BytestreamServerResourceUser::~SOCKS5BytestreamServerResourceUser() { - if (s5bServerManager_->isInitialized()) { - s5bServerManager_->stop(); - } + if (s5bServerManager_->isInitialized()) { + s5bServerManager_->stop(); + } } bool SOCKS5BytestreamServerResourceUser::isInitialized() const { - return s5bServerManager_->isInitialized(); + return s5bServerManager_->isInitialized(); } void SOCKS5BytestreamServerResourceUser::handleServerManagerInitialized(bool successfulInitialize) { - onSuccessfulInitialized(successfulInitialize); + onSuccessfulInitialized(successfulInitialize); } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h index 9e0d702..b369184 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h @@ -14,20 +14,20 @@ namespace Swift { class SOCKS5BytestreamServerManager; class SWIFTEN_API SOCKS5BytestreamServerResourceUser { - public: - SOCKS5BytestreamServerResourceUser(SOCKS5BytestreamServerManager* s5bServerManager); - ~SOCKS5BytestreamServerResourceUser(); + public: + SOCKS5BytestreamServerResourceUser(SOCKS5BytestreamServerManager* s5bServerManager); + ~SOCKS5BytestreamServerResourceUser(); - bool isInitialized() const; + bool isInitialized() const; - boost::signal<void (bool /* success */)> onSuccessfulInitialized; + boost::signal<void (bool /* success */)> onSuccessfulInitialized; - private: - void handleServerManagerInitialized(bool successfulInitialize); + private: + void handleServerManagerInitialized(bool successfulInitialize); - private: - SOCKS5BytestreamServerManager* s5bServerManager_; - boost::bsignals::scoped_connection onInitializedConnection_; + private: + SOCKS5BytestreamServerManager* s5bServerManager_; + boost::bsignals::scoped_connection onInitializedConnection_; }; } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp index 0e1eb6b..e2d46f4 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp @@ -21,175 +21,175 @@ namespace Swift { SOCKS5BytestreamServerSession::SOCKS5BytestreamServerSession( - boost::shared_ptr<Connection> connection, - SOCKS5BytestreamRegistry* bytestreams) : - connection(connection), - bytestreams(bytestreams), - state(Initial), - chunkSize(131072), - waitingForData(false) { - disconnectedConnection = connection->onDisconnected.connect(boost::bind(&SOCKS5BytestreamServerSession::handleDisconnected, this, _1)); + boost::shared_ptr<Connection> connection, + SOCKS5BytestreamRegistry* bytestreams) : + connection(connection), + bytestreams(bytestreams), + state(Initial), + chunkSize(131072), + waitingForData(false) { + disconnectedConnection = connection->onDisconnected.connect(boost::bind(&SOCKS5BytestreamServerSession::handleDisconnected, this, _1)); } SOCKS5BytestreamServerSession::~SOCKS5BytestreamServerSession() { - if (state != Finished && state != Initial) { - SWIFT_LOG(warning) << "SOCKS5BytestreamServerSession unfinished" << std::endl; - finish(); - } + if (state != Finished && state != Initial) { + SWIFT_LOG(warning) << "SOCKS5BytestreamServerSession unfinished" << std::endl; + finish(); + } } void SOCKS5BytestreamServerSession::start() { - SWIFT_LOG(debug) << std::endl; - dataReadConnection = connection->onDataRead.connect( - boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1)); - state = WaitingForAuthentication; + SWIFT_LOG(debug) << std::endl; + dataReadConnection = connection->onDataRead.connect( + boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1)); + state = WaitingForAuthentication; } void SOCKS5BytestreamServerSession::stop() { - finish(); + finish(); } void SOCKS5BytestreamServerSession::startSending(boost::shared_ptr<ReadBytestream> stream) { - if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; } - - readBytestream = stream; - state = WritingData; - dataAvailableConnection = readBytestream->onDataAvailable.connect( - boost::bind(&SOCKS5BytestreamServerSession::handleDataAvailable, this)); - dataWrittenConnection = connection->onDataWritten.connect( - boost::bind(&SOCKS5BytestreamServerSession::sendData, this)); - sendData(); + if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; } + + readBytestream = stream; + state = WritingData; + dataAvailableConnection = readBytestream->onDataAvailable.connect( + boost::bind(&SOCKS5BytestreamServerSession::handleDataAvailable, this)); + dataWrittenConnection = connection->onDataWritten.connect( + boost::bind(&SOCKS5BytestreamServerSession::sendData, this)); + sendData(); } void SOCKS5BytestreamServerSession::startReceiving(boost::shared_ptr<WriteBytestream> stream) { - if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; } + if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; } - writeBytestream = stream; - state = ReadingData; - writeBytestream->write(unprocessedData); - // onBytesReceived(unprocessedData.size()); - unprocessedData.clear(); + writeBytestream = stream; + state = ReadingData; + writeBytestream->write(unprocessedData); + // onBytesReceived(unprocessedData.size()); + unprocessedData.clear(); } HostAddressPort SOCKS5BytestreamServerSession::getAddressPort() const { - return connection->getLocalAddress(); + return connection->getLocalAddress(); } void SOCKS5BytestreamServerSession::handleDataRead(boost::shared_ptr<SafeByteArray> data) { - if (state != ReadingData) { - append(unprocessedData, *data); - process(); - } else { - if (!writeBytestream->write(createByteArray(vecptr(*data), data->size()))) { - finish(boost::optional<FileTransferError>(FileTransferError::WriteError)); - } - } + if (state != ReadingData) { + append(unprocessedData, *data); + process(); + } else { + if (!writeBytestream->write(createByteArray(vecptr(*data), data->size()))) { + finish(boost::optional<FileTransferError>(FileTransferError::WriteError)); + } + } } void SOCKS5BytestreamServerSession::handleDataAvailable() { - if (waitingForData) { - sendData(); - } + if (waitingForData) { + sendData(); + } } void SOCKS5BytestreamServerSession::handleDisconnected(const boost::optional<Connection::Error>& error) { - SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl; - finish(error ? boost::optional<FileTransferError>(FileTransferError::PeerError) : boost::optional<FileTransferError>()); + SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl; + finish(error ? boost::optional<FileTransferError>(FileTransferError::PeerError) : boost::optional<FileTransferError>()); } void SOCKS5BytestreamServerSession::process() { - if (state == WaitingForAuthentication) { - if (unprocessedData.size() >= 2) { - size_t authCount = unprocessedData[1]; - size_t i = 2; - while (i < 2 + authCount && i < unprocessedData.size()) { - // Skip authentication mechanism - ++i; - } - if (i == 2 + authCount) { - // Authentication message is complete - if (i != unprocessedData.size()) { - SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl; - } - unprocessedData.clear(); - connection->write(createSafeByteArray("\x05\x00", 2)); - state = WaitingForRequest; - } - } - } - else if (state == WaitingForRequest) { - if (unprocessedData.size() >= 5) { - ByteArray requestID; - size_t i = 5; - size_t hostnameSize = unprocessedData[4]; - while (i < 5 + hostnameSize && i < unprocessedData.size()) { - requestID.push_back(unprocessedData[i]); - ++i; - } - // Skip the port: 2 byte large, one already skipped. Add one for comparison with size - i += 2; - if (i <= unprocessedData.size()) { - if (i != unprocessedData.size()) { - SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl; - } - unprocessedData.clear(); - streamID = byteArrayToString(requestID); - bool hasBytestream = bytestreams->hasBytestream(streamID); - SafeByteArray result = createSafeByteArray("\x05", 1); - result.push_back(hasBytestream ? 0x0 : 0x4); - append(result, createByteArray("\x00\x03", 2)); - result.push_back(boost::numeric_cast<unsigned char>(requestID.size())); - append(result, concat(requestID, createByteArray("\x00\x00", 2))); - if (!hasBytestream) { - SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl; - connection->write(result); - finish(boost::optional<FileTransferError>(FileTransferError::PeerError)); - } - else { - SWIFT_LOG(debug) << "Found stream. Sent OK." << std::endl; - connection->write(result); - state = ReadyForTransfer; - } - } - } - } + if (state == WaitingForAuthentication) { + if (unprocessedData.size() >= 2) { + size_t authCount = unprocessedData[1]; + size_t i = 2; + while (i < 2 + authCount && i < unprocessedData.size()) { + // Skip authentication mechanism + ++i; + } + if (i == 2 + authCount) { + // Authentication message is complete + if (i != unprocessedData.size()) { + SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl; + } + unprocessedData.clear(); + connection->write(createSafeByteArray("\x05\x00", 2)); + state = WaitingForRequest; + } + } + } + else if (state == WaitingForRequest) { + if (unprocessedData.size() >= 5) { + ByteArray requestID; + size_t i = 5; + size_t hostnameSize = unprocessedData[4]; + while (i < 5 + hostnameSize && i < unprocessedData.size()) { + requestID.push_back(unprocessedData[i]); + ++i; + } + // Skip the port: 2 byte large, one already skipped. Add one for comparison with size + i += 2; + if (i <= unprocessedData.size()) { + if (i != unprocessedData.size()) { + SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl; + } + unprocessedData.clear(); + streamID = byteArrayToString(requestID); + bool hasBytestream = bytestreams->hasBytestream(streamID); + SafeByteArray result = createSafeByteArray("\x05", 1); + result.push_back(hasBytestream ? 0x0 : 0x4); + append(result, createByteArray("\x00\x03", 2)); + result.push_back(boost::numeric_cast<unsigned char>(requestID.size())); + append(result, concat(requestID, createByteArray("\x00\x00", 2))); + if (!hasBytestream) { + SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl; + connection->write(result); + finish(boost::optional<FileTransferError>(FileTransferError::PeerError)); + } + else { + SWIFT_LOG(debug) << "Found stream. Sent OK." << std::endl; + connection->write(result); + state = ReadyForTransfer; + } + } + } + } } void SOCKS5BytestreamServerSession::sendData() { - if (!readBytestream->isFinished()) { - try { - SafeByteArray dataToSend = createSafeByteArray(*readBytestream->read(boost::numeric_cast<size_t>(chunkSize))); - if (!dataToSend.empty()) { - connection->write(dataToSend); - onBytesSent(dataToSend.size()); - waitingForData = false; - } - else { - waitingForData = true; - } - } - catch (const BytestreamException&) { - finish(boost::optional<FileTransferError>(FileTransferError::PeerError)); - } - } - else { - finish(); - } + if (!readBytestream->isFinished()) { + try { + SafeByteArray dataToSend = createSafeByteArray(*readBytestream->read(boost::numeric_cast<size_t>(chunkSize))); + if (!dataToSend.empty()) { + connection->write(dataToSend); + onBytesSent(dataToSend.size()); + waitingForData = false; + } + else { + waitingForData = true; + } + } + catch (const BytestreamException&) { + finish(boost::optional<FileTransferError>(FileTransferError::PeerError)); + } + } + else { + finish(); + } } void SOCKS5BytestreamServerSession::finish(const boost::optional<FileTransferError>& error) { - SWIFT_LOG(debug) << "state: " << state << std::endl; - if (state == Finished) { - return; - } - - disconnectedConnection.disconnect(); - dataReadConnection.disconnect(); - dataWrittenConnection.disconnect(); - dataAvailableConnection.disconnect(); - readBytestream.reset(); - state = Finished; - onFinished(error); + SWIFT_LOG(debug) << "state: " << state << std::endl; + if (state == Finished) { + return; + } + + disconnectedConnection.disconnect(); + dataReadConnection.disconnect(); + dataWrittenConnection.disconnect(); + dataAvailableConnection.disconnect(); + readBytestream.reset(); + state = Finished; + onFinished(error); } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h index ed5272f..a90e8c5 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h @@ -16,68 +16,68 @@ #include <Swiften/Network/Connection.h> namespace Swift { - class SOCKS5BytestreamRegistry; - - class SWIFTEN_API SOCKS5BytestreamServerSession { - public: - typedef boost::shared_ptr<SOCKS5BytestreamServerSession> ref; - - public: - enum State { - Initial, - WaitingForAuthentication, - WaitingForRequest, - ReadyForTransfer, - ReadingData, - WritingData, - Finished - }; - - SOCKS5BytestreamServerSession(boost::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* registry); - ~SOCKS5BytestreamServerSession(); - - void setChunkSize(int chunkSize) { - this->chunkSize = chunkSize; - } - - void start(); - void stop(); - - void startSending(boost::shared_ptr<ReadBytestream>); - void startReceiving(boost::shared_ptr<WriteBytestream>); - - HostAddressPort getAddressPort() const; - - boost::signal<void (boost::optional<FileTransferError>)> onFinished; - boost::signal<void (unsigned long long)> onBytesSent; - - const std::string& getStreamID() const { - return streamID; - } - - private: - void finish(const boost::optional<FileTransferError>& error = boost::optional<FileTransferError>()); - void process(); - void handleDataRead(boost::shared_ptr<SafeByteArray>); - void handleDisconnected(const boost::optional<Connection::Error>&); - void handleDataAvailable(); - void sendData(); - - private: - boost::shared_ptr<Connection> connection; - SOCKS5BytestreamRegistry* bytestreams; - ByteArray unprocessedData; - State state; - int chunkSize; - std::string streamID; - boost::shared_ptr<ReadBytestream> readBytestream; - boost::shared_ptr<WriteBytestream> writeBytestream; - bool waitingForData; - - boost::bsignals::connection disconnectedConnection; - boost::bsignals::connection dataReadConnection; - boost::bsignals::connection dataWrittenConnection; - boost::bsignals::connection dataAvailableConnection; - - }; + class SOCKS5BytestreamRegistry; + + class SWIFTEN_API SOCKS5BytestreamServerSession { + public: + typedef boost::shared_ptr<SOCKS5BytestreamServerSession> ref; + + public: + enum State { + Initial, + WaitingForAuthentication, + WaitingForRequest, + ReadyForTransfer, + ReadingData, + WritingData, + Finished + }; + + SOCKS5BytestreamServerSession(boost::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* registry); + ~SOCKS5BytestreamServerSession(); + + void setChunkSize(int chunkSize) { + this->chunkSize = chunkSize; + } + + void start(); + void stop(); + + void startSending(boost::shared_ptr<ReadBytestream>); + void startReceiving(boost::shared_ptr<WriteBytestream>); + + HostAddressPort getAddressPort() const; + + boost::signal<void (boost::optional<FileTransferError>)> onFinished; + boost::signal<void (unsigned long long)> onBytesSent; + + const std::string& getStreamID() const { + return streamID; + } + + private: + void finish(const boost::optional<FileTransferError>& error = boost::optional<FileTransferError>()); + void process(); + void handleDataRead(boost::shared_ptr<SafeByteArray>); + void handleDisconnected(const boost::optional<Connection::Error>&); + void handleDataAvailable(); + void sendData(); + + private: + boost::shared_ptr<Connection> connection; + SOCKS5BytestreamRegistry* bytestreams; + ByteArray unprocessedData; + State state; + int chunkSize; + std::string streamID; + boost::shared_ptr<ReadBytestream> readBytestream; + boost::shared_ptr<WriteBytestream> writeBytestream; + bool waitingForData; + + boost::bsignals::connection disconnectedConnection; + boost::bsignals::connection dataReadConnection; + boost::bsignals::connection dataWrittenConnection; + boost::bsignals::connection dataAvailableConnection; + + }; } diff --git a/Swiften/FileTransfer/StreamInitiationRequest.h b/Swiften/FileTransfer/StreamInitiationRequest.h index be70d72..c03fae6 100644 --- a/Swiften/FileTransfer/StreamInitiationRequest.h +++ b/Swiften/FileTransfer/StreamInitiationRequest.h @@ -11,23 +11,23 @@ #include <Swiften/Queries/GenericRequest.h> namespace Swift { - class SWIFTEN_API StreamInitiationRequest : public GenericRequest<StreamInitiation> { - public: - typedef boost::shared_ptr<StreamInitiationRequest> ref; + class SWIFTEN_API StreamInitiationRequest : public GenericRequest<StreamInitiation> { + public: + typedef boost::shared_ptr<StreamInitiationRequest> ref; - static ref create(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) { - return ref(new StreamInitiationRequest(jid, payload, router)); - } + static ref create(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) { + return ref(new StreamInitiationRequest(jid, payload, router)); + } - static ref create(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) { - return ref(new StreamInitiationRequest(from, to, payload, router)); - } + static ref create(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) { + return ref(new StreamInitiationRequest(from, to, payload, router)); + } - private: - StreamInitiationRequest(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, jid, payload, router) { - } + private: + StreamInitiationRequest(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, jid, payload, router) { + } - StreamInitiationRequest(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, from, to, payload, router) { - } - }; + StreamInitiationRequest(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, from, to, payload, router) { + } + }; } diff --git a/Swiften/FileTransfer/TransportSession.h b/Swiften/FileTransfer/TransportSession.h index 9064c78..b42f0bd 100644 --- a/Swiften/FileTransfer/TransportSession.h +++ b/Swiften/FileTransfer/TransportSession.h @@ -12,14 +12,14 @@ #include <Swiften/FileTransfer/FileTransferError.h> namespace Swift { - class SWIFTEN_API TransportSession { - public: - virtual ~TransportSession(); + class SWIFTEN_API TransportSession { + public: + virtual ~TransportSession(); - virtual void start() = 0; - virtual void stop() = 0; + virtual void start() = 0; + virtual void stop() = 0; - boost::signal<void (size_t)> onBytesSent; - boost::signal<void (boost::optional<FileTransferError>)> onFinished; - }; + boost::signal<void (size_t)> onBytesSent; + boost::signal<void (boost::optional<FileTransferError>)> onFinished; + }; } diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h index d08b5c3..70d25a5 100644 --- a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h +++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h @@ -21,36 +21,36 @@ #include <Swiften/FileTransfer/FileTransferManager.h> namespace Swift { - class S5BProxyRequest; - class FileTransferOptions; - - class DummyFileTransferManager : public FileTransferManager { - public: - DummyFileTransferManager() : FileTransferManager() { - } - - virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( - const JID&, - const boost::filesystem::path&, - const std::string&, - boost::shared_ptr<ReadBytestream>, - const FileTransferOptions&) SWIFTEN_OVERRIDE { - return OutgoingFileTransfer::ref(); - } - - virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( - const JID&, - const std::string&, - const std::string&, - const boost::uintmax_t, - const boost::posix_time::ptime&, - boost::shared_ptr<ReadBytestream>, - const FileTransferOptions&) SWIFTEN_OVERRIDE { - return OutgoingFileTransfer::ref(); - } - - virtual void addS5BProxy(boost::shared_ptr<S5BProxyRequest>) { - } - - }; + class S5BProxyRequest; + class FileTransferOptions; + + class DummyFileTransferManager : public FileTransferManager { + public: + DummyFileTransferManager() : FileTransferManager() { + } + + virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( + const JID&, + const boost::filesystem::path&, + const std::string&, + boost::shared_ptr<ReadBytestream>, + const FileTransferOptions&) SWIFTEN_OVERRIDE { + return OutgoingFileTransfer::ref(); + } + + virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( + const JID&, + const std::string&, + const std::string&, + const boost::uintmax_t, + const boost::posix_time::ptime&, + boost::shared_ptr<ReadBytestream>, + const FileTransferOptions&) SWIFTEN_OVERRIDE { + return OutgoingFileTransfer::ref(); + } + + virtual void addS5BProxy(boost::shared_ptr<S5BProxyRequest>) { + } + + }; } diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h index 00a931f..59fc40a 100644 --- a/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h +++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h @@ -28,175 +28,175 @@ namespace Swift { class DummyFileTransferTransporter : public FileTransferTransporter { public: - enum Role { - Initiator, - Responder - }; + enum Role { + Initiator, + Responder + }; public: - DummyFileTransferTransporter( - const JID& initiator, - const JID& responder, - Role role, - SOCKS5BytestreamRegistry* s5bRegistry, - SOCKS5BytestreamServerManager* /* s5bServerManager */, - SOCKS5BytestreamProxiesManager* /* s5bProxy */, - IDGenerator* /* idGenerator */, - ConnectionFactory*, - TimerFactory*, - CryptoProvider* cryptoProvider, - IQRouter* iqRouter, - const FileTransferOptions& ftOptions) : initiator_(initiator), responder_(responder), role_(role), s5bRegistry_(s5bRegistry), crypto_(cryptoProvider), iqRouter_(iqRouter), ftOptions_(ftOptions) { - - } - - void initialize() { - s5bSessionID_ = s5bRegistry_->generateSessionID(); - } - - virtual void startGeneratingLocalCandidates() { - std::vector<JingleS5BTransportPayload::Candidate> candidates; - if (ftOptions_.isDirectAllowed()) { - JingleS5BTransportPayload::Candidate candidate; - candidate.cid = "123"; - candidate.priority = 1235; - candidates.push_back(candidate); - } - onLocalCandidatesGenerated(s5bSessionID_, candidates, getSOCKS5DstAddr()); - } - - virtual void stopGeneratingLocalCandidates() { - } - - virtual void addRemoteCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) { - } - - virtual void startTryingRemoteCandidates() { - onRemoteCandidateSelectFinished(s5bSessionID_, boost::optional<JingleS5BTransportPayload::Candidate>()); - } - - virtual void stopTryingRemoteCandidates() { - } - - virtual void startActivatingProxy(const JID& /* proxy */) { - } - - virtual void stopActivatingProxy() { - } - - virtual boost::shared_ptr<TransportSession> createIBBSendSession(const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) { - boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>( - sessionID, initiator_, responder_, stream, iqRouter_); - ibbSession->setBlockSize(blockSize); - return boost::make_shared<IBBSendTransportSession>(ibbSession); - } - - virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) { - boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>( - sessionID, initiator_, responder_, size, stream, iqRouter_); - return boost::make_shared<IBBReceiveTransportSession>(ibbSession); - } - - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( - boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { - return boost::shared_ptr<TransportSession>(); - } - - virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( - boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { - return boost::shared_ptr<TransportSession>(); - } - - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( - boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { - return boost::shared_ptr<TransportSession>(); - } - - virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( - boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { - return boost::shared_ptr<TransportSession>(); - } + DummyFileTransferTransporter( + const JID& initiator, + const JID& responder, + Role role, + SOCKS5BytestreamRegistry* s5bRegistry, + SOCKS5BytestreamServerManager* /* s5bServerManager */, + SOCKS5BytestreamProxiesManager* /* s5bProxy */, + IDGenerator* /* idGenerator */, + ConnectionFactory*, + TimerFactory*, + CryptoProvider* cryptoProvider, + IQRouter* iqRouter, + const FileTransferOptions& ftOptions) : initiator_(initiator), responder_(responder), role_(role), s5bRegistry_(s5bRegistry), crypto_(cryptoProvider), iqRouter_(iqRouter), ftOptions_(ftOptions) { + + } + + void initialize() { + s5bSessionID_ = s5bRegistry_->generateSessionID(); + } + + virtual void startGeneratingLocalCandidates() { + std::vector<JingleS5BTransportPayload::Candidate> candidates; + if (ftOptions_.isDirectAllowed()) { + JingleS5BTransportPayload::Candidate candidate; + candidate.cid = "123"; + candidate.priority = 1235; + candidates.push_back(candidate); + } + onLocalCandidatesGenerated(s5bSessionID_, candidates, getSOCKS5DstAddr()); + } + + virtual void stopGeneratingLocalCandidates() { + } + + virtual void addRemoteCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) { + } + + virtual void startTryingRemoteCandidates() { + onRemoteCandidateSelectFinished(s5bSessionID_, boost::optional<JingleS5BTransportPayload::Candidate>()); + } + + virtual void stopTryingRemoteCandidates() { + } + + virtual void startActivatingProxy(const JID& /* proxy */) { + } + + virtual void stopActivatingProxy() { + } + + virtual boost::shared_ptr<TransportSession> createIBBSendSession(const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) { + boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>( + sessionID, initiator_, responder_, stream, iqRouter_); + ibbSession->setBlockSize(blockSize); + return boost::make_shared<IBBSendTransportSession>(ibbSession); + } + + virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) { + boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>( + sessionID, initiator_, responder_, size, stream, iqRouter_); + return boost::make_shared<IBBReceiveTransportSession>(ibbSession); + } + + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( + boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { + return boost::shared_ptr<TransportSession>(); + } + + virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession( + boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { + return boost::shared_ptr<TransportSession>(); + } + + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( + boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { + return boost::shared_ptr<TransportSession>(); + } + + virtual boost::shared_ptr<TransportSession> createLocalCandidateSession( + boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) { + return boost::shared_ptr<TransportSession>(); + } private: - std::string getSOCKS5DstAddr() const { - std::string result; - if (role_ == Initiator) { - result = getInitiatorCandidateSOCKS5DstAddr(); - } - else { - result = getResponderCandidateSOCKS5DstAddr(); - } - return result; - } - - std::string getInitiatorCandidateSOCKS5DstAddr() const { - return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + initiator_.toString() + responder_.toString()))); - } - - std::string getResponderCandidateSOCKS5DstAddr() const { - return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + responder_.toString() + initiator_.toString()))); - } + std::string getSOCKS5DstAddr() const { + std::string result; + if (role_ == Initiator) { + result = getInitiatorCandidateSOCKS5DstAddr(); + } + else { + result = getResponderCandidateSOCKS5DstAddr(); + } + return result; + } + + std::string getInitiatorCandidateSOCKS5DstAddr() const { + return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + initiator_.toString() + responder_.toString()))); + } + + std::string getResponderCandidateSOCKS5DstAddr() const { + return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + responder_.toString() + initiator_.toString()))); + } private: - JID initiator_; - JID responder_; - Role role_; - SOCKS5BytestreamRegistry* s5bRegistry_; - CryptoProvider* crypto_; - std::string s5bSessionID_; - IQRouter* iqRouter_; - FileTransferOptions ftOptions_; + JID initiator_; + JID responder_; + Role role_; + SOCKS5BytestreamRegistry* s5bRegistry_; + CryptoProvider* crypto_; + std::string s5bSessionID_; + IQRouter* iqRouter_; + FileTransferOptions ftOptions_; }; class DummyFileTransferTransporterFactory : public FileTransferTransporterFactory { public: - DummyFileTransferTransporterFactory( - SOCKS5BytestreamRegistry* s5bRegistry, - SOCKS5BytestreamServerManager* s5bServerManager, - SOCKS5BytestreamProxiesManager* s5bProxy, - IDGenerator* idGenerator, - ConnectionFactory* connectionFactory, - TimerFactory* timerFactory, - CryptoProvider* cryptoProvider, - IQRouter* iqRouter) : s5bRegistry_(s5bRegistry), s5bServerManager_(s5bServerManager), s5bProxy_(s5bProxy), idGenerator_(idGenerator), connectionFactory_(connectionFactory), timerFactory_(timerFactory), cryptoProvider_(cryptoProvider), iqRouter_(iqRouter) { - - } - - virtual ~DummyFileTransferTransporterFactory() { - } - - virtual FileTransferTransporter* createInitiatorTransporter(const JID& initiator, const JID& responder, const FileTransferOptions& options) { - DummyFileTransferTransporter* transporter = new DummyFileTransferTransporter( - initiator, - responder, - DummyFileTransferTransporter::Initiator, - s5bRegistry_, - s5bServerManager_, - s5bProxy_, - idGenerator_, - connectionFactory_, - timerFactory_, - cryptoProvider_, - iqRouter_, - options); - transporter->initialize(); - return transporter; - } - - virtual FileTransferTransporter* createResponderTransporter(const JID& /* initiator */, const JID& /* responder */, const std::string& /* s5bSessionID */, const FileTransferOptions& /* options */) { - return NULL; - } + DummyFileTransferTransporterFactory( + SOCKS5BytestreamRegistry* s5bRegistry, + SOCKS5BytestreamServerManager* s5bServerManager, + SOCKS5BytestreamProxiesManager* s5bProxy, + IDGenerator* idGenerator, + ConnectionFactory* connectionFactory, + TimerFactory* timerFactory, + CryptoProvider* cryptoProvider, + IQRouter* iqRouter) : s5bRegistry_(s5bRegistry), s5bServerManager_(s5bServerManager), s5bProxy_(s5bProxy), idGenerator_(idGenerator), connectionFactory_(connectionFactory), timerFactory_(timerFactory), cryptoProvider_(cryptoProvider), iqRouter_(iqRouter) { + + } + + virtual ~DummyFileTransferTransporterFactory() { + } + + virtual FileTransferTransporter* createInitiatorTransporter(const JID& initiator, const JID& responder, const FileTransferOptions& options) { + DummyFileTransferTransporter* transporter = new DummyFileTransferTransporter( + initiator, + responder, + DummyFileTransferTransporter::Initiator, + s5bRegistry_, + s5bServerManager_, + s5bProxy_, + idGenerator_, + connectionFactory_, + timerFactory_, + cryptoProvider_, + iqRouter_, + options); + transporter->initialize(); + return transporter; + } + + virtual FileTransferTransporter* createResponderTransporter(const JID& /* initiator */, const JID& /* responder */, const std::string& /* s5bSessionID */, const FileTransferOptions& /* options */) { + return NULL; + } private: - SOCKS5BytestreamRegistry* s5bRegistry_; - SOCKS5BytestreamServerManager* s5bServerManager_; - SOCKS5BytestreamProxiesManager* s5bProxy_; - IDGenerator* idGenerator_; - ConnectionFactory* connectionFactory_; - TimerFactory* timerFactory_; - CryptoProvider* cryptoProvider_; - IQRouter* iqRouter_; + SOCKS5BytestreamRegistry* s5bRegistry_; + SOCKS5BytestreamServerManager* s5bServerManager_; + SOCKS5BytestreamProxiesManager* s5bProxy_; + IDGenerator* idGenerator_; + ConnectionFactory* connectionFactory_; + TimerFactory* timerFactory_; + CryptoProvider* cryptoProvider_; + IQRouter* iqRouter_; }; } diff --git a/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp b/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp index 2678758..d78f4f0 100644 --- a/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp @@ -22,166 +22,166 @@ using namespace Swift; class IBBReceiveSessionTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(IBBReceiveSessionTest); - CPPUNIT_TEST(testOpen); - CPPUNIT_TEST(testReceiveData); - CPPUNIT_TEST(testReceiveMultipleData); - CPPUNIT_TEST(testReceiveDataForOtherSession); - CPPUNIT_TEST(testReceiveDataOutOfOrder); - CPPUNIT_TEST(testReceiveLastData); - CPPUNIT_TEST(testReceiveClose); - CPPUNIT_TEST(testStopWhileActive); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - stanzaChannel = new DummyStanzaChannel(); - iqRouter = new IQRouter(stanzaChannel); - finished = false; - bytestream = boost::make_shared<ByteArrayWriteBytestream>(); - } + CPPUNIT_TEST_SUITE(IBBReceiveSessionTest); + CPPUNIT_TEST(testOpen); + CPPUNIT_TEST(testReceiveData); + CPPUNIT_TEST(testReceiveMultipleData); + CPPUNIT_TEST(testReceiveDataForOtherSession); + CPPUNIT_TEST(testReceiveDataOutOfOrder); + CPPUNIT_TEST(testReceiveLastData); + CPPUNIT_TEST(testReceiveClose); + CPPUNIT_TEST(testStopWhileActive); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + stanzaChannel = new DummyStanzaChannel(); + iqRouter = new IQRouter(stanzaChannel); + finished = false; + bytestream = boost::make_shared<ByteArrayWriteBytestream>(); + } - void tearDown() { - delete iqRouter; - delete stanzaChannel; - } - - void testOpen() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + void tearDown() { + delete iqRouter; + delete stanzaChannel; + } + + void testOpen() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(0, "id-open")); - CPPUNIT_ASSERT(!finished); - - testling->stop(); - } + CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(0, "id-open")); + CPPUNIT_ASSERT(!finished); + + testling->stop(); + } - void testReceiveData() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); - - CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(1, "id-a")); - CPPUNIT_ASSERT(createByteArray("abc") == bytestream->getData()); - CPPUNIT_ASSERT(!finished); - - testling->stop(); - } - - void testReceiveMultipleData() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b")); - - CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b")); - CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData()); - CPPUNIT_ASSERT(!finished); - - testling->stop(); - } - - void testReceiveDataForOtherSession() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("othersession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); - - CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(1, "id-a")); - - testling->stop(); - } - - void testReceiveDataOutOfOrder() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("def")), "foo@bar.com/baz", "id-b")); - - CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(2, "id-b")); - CPPUNIT_ASSERT(finished); - CPPUNIT_ASSERT(error); - - testling->stop(); - } - - void testReceiveLastData() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession", 6)); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b")); - - CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b")); - CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData()); - CPPUNIT_ASSERT(finished); - CPPUNIT_ASSERT(!error); - - testling->stop(); - } - - void testReceiveClose() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBClose("mysession"), "foo@bar.com/baz", "id-close")); + void testReceiveData() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); + + CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(1, "id-a")); + CPPUNIT_ASSERT(createByteArray("abc") == bytestream->getData()); + CPPUNIT_ASSERT(!finished); + + testling->stop(); + } + + void testReceiveMultipleData() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b")); + + CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b")); + CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData()); + CPPUNIT_ASSERT(!finished); + + testling->stop(); + } + + void testReceiveDataForOtherSession() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("othersession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); + + CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(1, "id-a")); + + testling->stop(); + } + + void testReceiveDataOutOfOrder() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("def")), "foo@bar.com/baz", "id-b")); + + CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(2, "id-b")); + CPPUNIT_ASSERT(finished); + CPPUNIT_ASSERT(error); + + testling->stop(); + } + + void testReceiveLastData() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession", 6)); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b")); + + CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b")); + CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData()); + CPPUNIT_ASSERT(finished); + CPPUNIT_ASSERT(!error); + + testling->stop(); + } + + void testReceiveClose() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBClose("mysession"), "foo@bar.com/baz", "id-close")); - CPPUNIT_ASSERT(finished); - CPPUNIT_ASSERT(error); + CPPUNIT_ASSERT(finished); + CPPUNIT_ASSERT(error); - testling->stop(); - } + testling->stop(); + } - void testStopWhileActive() { - boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); - testling->start(); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + void testStopWhileActive() { + boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession")); + testling->start(); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - testling->stop(); + testling->stop(); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set)); - IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>(); - CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction()); - CPPUNIT_ASSERT_EQUAL(std::string("mysession"), ibb->getStreamID()); - CPPUNIT_ASSERT(finished); - CPPUNIT_ASSERT(!error); - } + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set)); + IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>(); + CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction()); + CPPUNIT_ASSERT_EQUAL(std::string("mysession"), ibb->getStreamID()); + CPPUNIT_ASSERT(finished); + CPPUNIT_ASSERT(!error); + } - private: - IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) { - IQ::ref request = IQ::createRequest(IQ::Set, JID("baz@fum.com/dum"), id, ibb); - request->setFrom(from); - return request; - } + private: + IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) { + IQ::ref request = IQ::createRequest(IQ::Set, JID("baz@fum.com/dum"), id, ibb); + request->setFrom(from); + return request; + } - IBBReceiveSession* createSession(const std::string& from, const std::string& id, size_t size = 0x1000) { - IBBReceiveSession* session = new IBBReceiveSession(id, JID(from), JID(), size, bytestream, iqRouter); - session->onFinished.connect(boost::bind(&IBBReceiveSessionTest::handleFinished, this, _1)); - return session; - } + IBBReceiveSession* createSession(const std::string& from, const std::string& id, size_t size = 0x1000) { + IBBReceiveSession* session = new IBBReceiveSession(id, JID(from), JID(), size, bytestream, iqRouter); + session->onFinished.connect(boost::bind(&IBBReceiveSessionTest::handleFinished, this, _1)); + return session; + } - void handleFinished(boost::optional<FileTransferError> error) { - finished = true; - this->error = error; - } + void handleFinished(boost::optional<FileTransferError> error) { + finished = true; + this->error = error; + } - private: - DummyStanzaChannel* stanzaChannel; - IQRouter* iqRouter; - bool finished; - boost::optional<FileTransferError> error; - boost::shared_ptr<ByteArrayWriteBytestream> bytestream; + private: + DummyStanzaChannel* stanzaChannel; + IQRouter* iqRouter; + bool finished; + boost::optional<FileTransferError> error; + boost::shared_ptr<ByteArrayWriteBytestream> bytestream; }; CPPUNIT_TEST_SUITE_REGISTRATION(IBBReceiveSessionTest); diff --git a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp index a1c9c4c..e417c77 100644 --- a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp @@ -20,213 +20,213 @@ using namespace Swift; class IBBSendSessionTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(IBBSendSessionTest); - CPPUNIT_TEST(testStart); - CPPUNIT_TEST(testStart_ResponseStartsSending); - CPPUNIT_TEST(testResponseContinuesSending); - CPPUNIT_TEST(testRespondToAllFinishes); - CPPUNIT_TEST(testErrorResponseFinishesWithError); - CPPUNIT_TEST(testStopDuringSessionCloses); - CPPUNIT_TEST(testStopAfterFinishedDoesNotClose); - CPPUNIT_TEST(testDataStreamPauseStopsSendingData); - CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData); - CPPUNIT_TEST(testDataStreamResumeBeforePauseDoesNotSendData); - CPPUNIT_TEST(testDataStreamResumeAfterResumeDoesNotSendData); - - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - stanzaChannel = new DummyStanzaChannel(); - iqRouter = new IQRouter(stanzaChannel); - bytestream = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")); - finished = false; - } - - void tearDown() { - delete iqRouter; - delete stanzaChannel; - } - - void testStart() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - testling->setBlockSize(1234); - - testling->start(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size())); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(0, JID("foo@bar.com/baz"), IQ::Set)); - IBB::ref ibb = stanzaChannel->sentStanzas[0]->getPayload<IBB>(); - CPPUNIT_ASSERT_EQUAL(IBB::Open, ibb->getAction()); - CPPUNIT_ASSERT_EQUAL(1234, ibb->getBlockSize()); - CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); - } - - void testStart_ResponseStartsSending() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - testling->setBlockSize(3); - testling->start(); - - stanzaChannel->onIQReceived(createIBBResult()); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set)); - IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>(); - CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction()); - CPPUNIT_ASSERT(createByteArray("abc") == ibb->getData()); - CPPUNIT_ASSERT_EQUAL(0, ibb->getSequenceNumber()); - CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); - } - - void testResponseContinuesSending() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - testling->setBlockSize(3); - testling->start(); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - - CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(stanzaChannel->sentStanzas.size())); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(2, JID("foo@bar.com/baz"), IQ::Set)); - IBB::ref ibb = stanzaChannel->sentStanzas[2]->getPayload<IBB>(); - CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction()); - CPPUNIT_ASSERT(createByteArray("def") == ibb->getData()); - CPPUNIT_ASSERT_EQUAL(1, ibb->getSequenceNumber()); - CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); - } - - void testRespondToAllFinishes() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - testling->setBlockSize(3); - testling->start(); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - - CPPUNIT_ASSERT(finished); - CPPUNIT_ASSERT(!error); - } - - void testErrorResponseFinishesWithError() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - testling->setBlockSize(3); - testling->start(); - stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); - - CPPUNIT_ASSERT(finished); - CPPUNIT_ASSERT(error); - } - - void testStopDuringSessionCloses() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - testling->setBlockSize(3); - testling->start(); - testling->stop(); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); - CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set)); - IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>(); - CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction()); - CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); - CPPUNIT_ASSERT(finished); - CPPUNIT_ASSERT(!error); - } - - void testStopAfterFinishedDoesNotClose() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - testling->setBlockSize(16); - testling->start(); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - CPPUNIT_ASSERT(finished); - - testling->stop(); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testDataStreamPauseStopsSendingData() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - bytestream->setDataComplete(false); - testling->setBlockSize(3); - testling->start(); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - - CPPUNIT_ASSERT(!finished); - CPPUNIT_ASSERT(!error); - - CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testDataStreamResumeAfterPauseSendsData() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - bytestream->setDataComplete(false); - testling->setBlockSize(3); - testling->start(); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - - bytestream->addData(createByteArray("xyz")); - - CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testDataStreamResumeBeforePauseDoesNotSendData() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - bytestream->setDataComplete(false); - testling->setBlockSize(3); - testling->start(); - stanzaChannel->onIQReceived(createIBBResult()); - - bytestream->addData(createByteArray("xyz")); - - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - void testDataStreamResumeAfterResumeDoesNotSendData() { - boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); - bytestream->setDataComplete(false); - testling->setBlockSize(3); - testling->start(); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - stanzaChannel->onIQReceived(createIBBResult()); - - bytestream->addData(createByteArray("xyz")); - bytestream->addData(createByteArray("xuv")); - - CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size())); - } - - private: - IQ::ref createIBBResult() { - return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getTo(), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getID(), boost::shared_ptr<IBB>()); - } - - private: - boost::shared_ptr<IBBSendSession> createSession(const std::string& to) { - boost::shared_ptr<IBBSendSession> session(new IBBSendSession("myid", JID(), JID(to), bytestream, iqRouter)); - session->onFinished.connect(boost::bind(&IBBSendSessionTest::handleFinished, this, _1)); - return session; - } - - void handleFinished(boost::optional<FileTransferError> error) { - finished = true; - this->error = error; - } - - private: - DummyStanzaChannel* stanzaChannel; - IQRouter* iqRouter; - bool finished; - boost::optional<FileTransferError> error; - boost::shared_ptr<ByteArrayReadBytestream> bytestream; + CPPUNIT_TEST_SUITE(IBBSendSessionTest); + CPPUNIT_TEST(testStart); + CPPUNIT_TEST(testStart_ResponseStartsSending); + CPPUNIT_TEST(testResponseContinuesSending); + CPPUNIT_TEST(testRespondToAllFinishes); + CPPUNIT_TEST(testErrorResponseFinishesWithError); + CPPUNIT_TEST(testStopDuringSessionCloses); + CPPUNIT_TEST(testStopAfterFinishedDoesNotClose); + CPPUNIT_TEST(testDataStreamPauseStopsSendingData); + CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData); + CPPUNIT_TEST(testDataStreamResumeBeforePauseDoesNotSendData); + CPPUNIT_TEST(testDataStreamResumeAfterResumeDoesNotSendData); + + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + stanzaChannel = new DummyStanzaChannel(); + iqRouter = new IQRouter(stanzaChannel); + bytestream = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")); + finished = false; + } + + void tearDown() { + delete iqRouter; + delete stanzaChannel; + } + + void testStart() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + testling->setBlockSize(1234); + + testling->start(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size())); + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(0, JID("foo@bar.com/baz"), IQ::Set)); + IBB::ref ibb = stanzaChannel->sentStanzas[0]->getPayload<IBB>(); + CPPUNIT_ASSERT_EQUAL(IBB::Open, ibb->getAction()); + CPPUNIT_ASSERT_EQUAL(1234, ibb->getBlockSize()); + CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); + } + + void testStart_ResponseStartsSending() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + testling->setBlockSize(3); + testling->start(); + + stanzaChannel->onIQReceived(createIBBResult()); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set)); + IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>(); + CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction()); + CPPUNIT_ASSERT(createByteArray("abc") == ibb->getData()); + CPPUNIT_ASSERT_EQUAL(0, ibb->getSequenceNumber()); + CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); + } + + void testResponseContinuesSending() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + testling->setBlockSize(3); + testling->start(); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + + CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(stanzaChannel->sentStanzas.size())); + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(2, JID("foo@bar.com/baz"), IQ::Set)); + IBB::ref ibb = stanzaChannel->sentStanzas[2]->getPayload<IBB>(); + CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction()); + CPPUNIT_ASSERT(createByteArray("def") == ibb->getData()); + CPPUNIT_ASSERT_EQUAL(1, ibb->getSequenceNumber()); + CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); + } + + void testRespondToAllFinishes() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + testling->setBlockSize(3); + testling->start(); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + + CPPUNIT_ASSERT(finished); + CPPUNIT_ASSERT(!error); + } + + void testErrorResponseFinishesWithError() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + testling->setBlockSize(3); + testling->start(); + stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID())); + + CPPUNIT_ASSERT(finished); + CPPUNIT_ASSERT(error); + } + + void testStopDuringSessionCloses() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + testling->setBlockSize(3); + testling->start(); + testling->stop(); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); + CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set)); + IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>(); + CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction()); + CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); + CPPUNIT_ASSERT(finished); + CPPUNIT_ASSERT(!error); + } + + void testStopAfterFinishedDoesNotClose() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + testling->setBlockSize(16); + testling->start(); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + CPPUNIT_ASSERT(finished); + + testling->stop(); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testDataStreamPauseStopsSendingData() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + bytestream->setDataComplete(false); + testling->setBlockSize(3); + testling->start(); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + + CPPUNIT_ASSERT(!finished); + CPPUNIT_ASSERT(!error); + + CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testDataStreamResumeAfterPauseSendsData() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + bytestream->setDataComplete(false); + testling->setBlockSize(3); + testling->start(); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + + bytestream->addData(createByteArray("xyz")); + + CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testDataStreamResumeBeforePauseDoesNotSendData() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + bytestream->setDataComplete(false); + testling->setBlockSize(3); + testling->start(); + stanzaChannel->onIQReceived(createIBBResult()); + + bytestream->addData(createByteArray("xyz")); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + void testDataStreamResumeAfterResumeDoesNotSendData() { + boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); + bytestream->setDataComplete(false); + testling->setBlockSize(3); + testling->start(); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + stanzaChannel->onIQReceived(createIBBResult()); + + bytestream->addData(createByteArray("xyz")); + bytestream->addData(createByteArray("xuv")); + + CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size())); + } + + private: + IQ::ref createIBBResult() { + return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getTo(), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getID(), boost::shared_ptr<IBB>()); + } + + private: + boost::shared_ptr<IBBSendSession> createSession(const std::string& to) { + boost::shared_ptr<IBBSendSession> session(new IBBSendSession("myid", JID(), JID(to), bytestream, iqRouter)); + session->onFinished.connect(boost::bind(&IBBSendSessionTest::handleFinished, this, _1)); + return session; + } + + void handleFinished(boost::optional<FileTransferError> error) { + finished = true; + this->error = error; + } + + private: + DummyStanzaChannel* stanzaChannel; + IQRouter* iqRouter; + bool finished; + boost::optional<FileTransferError> error; + boost::shared_ptr<ByteArrayReadBytestream> bytestream; }; CPPUNIT_TEST_SUITE_REGISTRATION(IBBSendSessionTest); diff --git a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp index 2fb39bb..a76773c 100644 --- a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp +++ b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp @@ -48,198 +48,198 @@ using namespace Swift; using namespace boost; class IncomingJingleFileTransferTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(IncomingJingleFileTransferTest); - CPPUNIT_TEST(test_AcceptOnyIBBSendsSessionAccept); - CPPUNIT_TEST(test_OnlyIBBTransferReceiveWorks); - //CPPUNIT_TEST(test_AcceptFailingS5BFallsBackToIBB); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(IncomingJingleFileTransferTest); + CPPUNIT_TEST(test_AcceptOnyIBBSendsSessionAccept); + CPPUNIT_TEST(test_OnlyIBBTransferReceiveWorks); + //CPPUNIT_TEST(test_AcceptFailingS5BFallsBackToIBB); + CPPUNIT_TEST_SUITE_END(); public: - shared_ptr<IncomingJingleFileTransfer> createTestling() { - JID ourJID("our@jid.org/full"); - return boost::make_shared<IncomingJingleFileTransfer>(ourJID, shared_ptr<JingleSession>(session), jingleContentPayload, ftTransporterFactory, timerFactory, crypto.get()); - } - - IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) { - IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb); - request->setFrom(from); - return request; - } - - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - eventLoop = new DummyEventLoop(); - resolver = new StaticDomainNameResolver(eventLoop); - session = boost::make_shared<FakeJingleSession>("foo@bar.com/baz", "mysession"); - jingleContentPayload = make_shared<JingleContentPayload>(); - // fakeRJTCSF = make_shared<FakeRemoteJingleTransportCandidateSelectorFactory>(); - // fakeLJTCF = make_shared<FakeLocalJingleTransportCandidateGeneratorFactory>(); - stanzaChannel = new DummyStanzaChannel(); - connectionFactory = new DummyConnectionFactory(eventLoop); - serverConnectionFactory = new DummyConnectionServerFactory(eventLoop); - iqRouter = new IQRouter(stanzaChannel); - bytestreamRegistry = new SOCKS5BytestreamRegistry(); - networkEnvironment = new PlatformNetworkEnvironment(); - natTraverser = new PlatformNATTraversalWorker(eventLoop); - bytestreamServerManager = new SOCKS5BytestreamServerManager(bytestreamRegistry, serverConnectionFactory, networkEnvironment, natTraverser); - idGenerator = new SimpleIDGenerator(); - timerFactory = new DummyTimerFactory(); - bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com"); - ftTransporterFactory = new DefaultFileTransferTransporterFactory(bytestreamRegistry, bytestreamServerManager, bytestreamProxy, idGenerator, connectionFactory, timerFactory, crypto.get(), iqRouter); - } - - void tearDown() { - delete ftTransporterFactory; - delete bytestreamProxy; - delete timerFactory; - delete idGenerator; - delete bytestreamServerManager; - delete natTraverser; - delete networkEnvironment; - delete bytestreamRegistry; - delete iqRouter; - delete serverConnectionFactory; - delete connectionFactory; - delete stanzaChannel; - delete resolver; - delete eventLoop; - Log::setLogLevel(Log::error); - } - - // Tests whether IncomingJingleFileTransfer would accept a IBB only file transfer. - void test_AcceptOnyIBBSendsSessionAccept() { - //1. create your test incoming file transfer - shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>(); - desc->setFileInfo(JingleFileTransferFileInfo("foo.txt", "", 10)); - jingleContentPayload->addDescription(desc); - JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>(); - tpRef->setSessionID("mysession"); - jingleContentPayload->addTransport(tpRef); - - shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling(); - - //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one) - shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>(); - fileTransfer->accept(byteStream); - - // check whether accept has been called - getCall<FakeJingleSession::AcceptCall>(0); - } - - void test_OnlyIBBTransferReceiveWorks() { - //1. create your test incoming file transfer - shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>(); - desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10)); - jingleContentPayload->addDescription(desc); - JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>(); - tpRef->setSessionID("mysession"); - jingleContentPayload->addTransport(tpRef); - - shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling(); - - //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one) - shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>(); - fileTransfer->accept(byteStream); - - // check whether accept has been called - getCall<FakeJingleSession::AcceptCall>(0); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); - CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData()); - } - - void test_AcceptFailingS5BFallsBackToIBB() { - //1. create your test incoming file transfer - addFileTransferDescription(); - - // add SOCKS5BytestreamTransportPayload - JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload(); - - shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling(); - - //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one) - shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>(); - fileTransfer->accept(byteStream); - - // candidates are gathered - - // check whether accept has been called - FakeJingleSession::AcceptCall acceptCall = getCall<FakeJingleSession::AcceptCall>(0); - CPPUNIT_ASSERT_EQUAL(payLoad->getSessionID(), acceptCall.payload->getSessionID()); - - // check for candidate error - FakeJingleSession::InfoTransportCall infoTransportCall = getCall<FakeJingleSession::InfoTransportCall>(1); - JingleS5BTransportPayload::ref s5bPayload = dynamic_pointer_cast<JingleS5BTransportPayload>(infoTransportCall.payload); - CPPUNIT_ASSERT(s5bPayload->hasCandidateError()); - - // indicate transport replace (Romeo) - session->handleTransportReplaceReceived(getContentID(), addJingleIBBPayload()); - - FakeJingleSession::AcceptTransportCall acceptTransportCall = getCall<FakeJingleSession::AcceptTransportCall>(2); - - // send a bit of data - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); - stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); - CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData()); - } + shared_ptr<IncomingJingleFileTransfer> createTestling() { + JID ourJID("our@jid.org/full"); + return boost::make_shared<IncomingJingleFileTransfer>(ourJID, shared_ptr<JingleSession>(session), jingleContentPayload, ftTransporterFactory, timerFactory, crypto.get()); + } + + IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) { + IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb); + request->setFrom(from); + return request; + } + + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + eventLoop = new DummyEventLoop(); + resolver = new StaticDomainNameResolver(eventLoop); + session = boost::make_shared<FakeJingleSession>("foo@bar.com/baz", "mysession"); + jingleContentPayload = make_shared<JingleContentPayload>(); + // fakeRJTCSF = make_shared<FakeRemoteJingleTransportCandidateSelectorFactory>(); + // fakeLJTCF = make_shared<FakeLocalJingleTransportCandidateGeneratorFactory>(); + stanzaChannel = new DummyStanzaChannel(); + connectionFactory = new DummyConnectionFactory(eventLoop); + serverConnectionFactory = new DummyConnectionServerFactory(eventLoop); + iqRouter = new IQRouter(stanzaChannel); + bytestreamRegistry = new SOCKS5BytestreamRegistry(); + networkEnvironment = new PlatformNetworkEnvironment(); + natTraverser = new PlatformNATTraversalWorker(eventLoop); + bytestreamServerManager = new SOCKS5BytestreamServerManager(bytestreamRegistry, serverConnectionFactory, networkEnvironment, natTraverser); + idGenerator = new SimpleIDGenerator(); + timerFactory = new DummyTimerFactory(); + bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com"); + ftTransporterFactory = new DefaultFileTransferTransporterFactory(bytestreamRegistry, bytestreamServerManager, bytestreamProxy, idGenerator, connectionFactory, timerFactory, crypto.get(), iqRouter); + } + + void tearDown() { + delete ftTransporterFactory; + delete bytestreamProxy; + delete timerFactory; + delete idGenerator; + delete bytestreamServerManager; + delete natTraverser; + delete networkEnvironment; + delete bytestreamRegistry; + delete iqRouter; + delete serverConnectionFactory; + delete connectionFactory; + delete stanzaChannel; + delete resolver; + delete eventLoop; + Log::setLogLevel(Log::error); + } + + // Tests whether IncomingJingleFileTransfer would accept a IBB only file transfer. + void test_AcceptOnyIBBSendsSessionAccept() { + //1. create your test incoming file transfer + shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>(); + desc->setFileInfo(JingleFileTransferFileInfo("foo.txt", "", 10)); + jingleContentPayload->addDescription(desc); + JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>(); + tpRef->setSessionID("mysession"); + jingleContentPayload->addTransport(tpRef); + + shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling(); + + //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one) + shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>(); + fileTransfer->accept(byteStream); + + // check whether accept has been called + getCall<FakeJingleSession::AcceptCall>(0); + } + + void test_OnlyIBBTransferReceiveWorks() { + //1. create your test incoming file transfer + shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>(); + desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10)); + jingleContentPayload->addDescription(desc); + JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>(); + tpRef->setSessionID("mysession"); + jingleContentPayload->addTransport(tpRef); + + shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling(); + + //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one) + shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>(); + fileTransfer->accept(byteStream); + + // check whether accept has been called + getCall<FakeJingleSession::AcceptCall>(0); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); + CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData()); + } + + void test_AcceptFailingS5BFallsBackToIBB() { + //1. create your test incoming file transfer + addFileTransferDescription(); + + // add SOCKS5BytestreamTransportPayload + JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload(); + + shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling(); + + //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one) + shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>(); + fileTransfer->accept(byteStream); + + // candidates are gathered + + // check whether accept has been called + FakeJingleSession::AcceptCall acceptCall = getCall<FakeJingleSession::AcceptCall>(0); + CPPUNIT_ASSERT_EQUAL(payLoad->getSessionID(), acceptCall.payload->getSessionID()); + + // check for candidate error + FakeJingleSession::InfoTransportCall infoTransportCall = getCall<FakeJingleSession::InfoTransportCall>(1); + JingleS5BTransportPayload::ref s5bPayload = dynamic_pointer_cast<JingleS5BTransportPayload>(infoTransportCall.payload); + CPPUNIT_ASSERT(s5bPayload->hasCandidateError()); + + // indicate transport replace (Romeo) + session->handleTransportReplaceReceived(getContentID(), addJingleIBBPayload()); + + FakeJingleSession::AcceptTransportCall acceptTransportCall = getCall<FakeJingleSession::AcceptTransportCall>(2); + + // send a bit of data + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open")); + stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a")); + CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData()); + } #if 0 - void test_S5BTransferReceiveTest() { - addFileTransferDescription(); - JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload(); - } + void test_S5BTransferReceiveTest() { + addFileTransferDescription(); + JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload(); + } #endif private: - void addFileTransferDescription() { - shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>(); - desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10)); - jingleContentPayload->addDescription(desc); - } - - shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() { - JingleS5BTransportPayload::ref payLoad = make_shared<JingleS5BTransportPayload>(); - payLoad->setSessionID("mysession"); - jingleContentPayload->addTransport(payLoad); - return payLoad; - } - - shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() { - JingleIBBTransportPayload::ref payLoad = make_shared<JingleIBBTransportPayload>(); - payLoad->setSessionID("mysession"); - jingleContentPayload->addTransport(payLoad); - return payLoad; - } - - JingleContentID getContentID() const { - return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator()); - } - - template <typename T> T getCall(int i) const { - size_t index = static_cast<size_t>(i); - CPPUNIT_ASSERT(index < session->calledCommands.size()); - T* cmd = boost::get<T>(&session->calledCommands[index]); - CPPUNIT_ASSERT(cmd); - return *cmd; - } + void addFileTransferDescription() { + shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>(); + desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10)); + jingleContentPayload->addDescription(desc); + } + + shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() { + JingleS5BTransportPayload::ref payLoad = make_shared<JingleS5BTransportPayload>(); + payLoad->setSessionID("mysession"); + jingleContentPayload->addTransport(payLoad); + return payLoad; + } + + shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() { + JingleIBBTransportPayload::ref payLoad = make_shared<JingleIBBTransportPayload>(); + payLoad->setSessionID("mysession"); + jingleContentPayload->addTransport(payLoad); + return payLoad; + } + + JingleContentID getContentID() const { + return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator()); + } + + template <typename T> T getCall(int i) const { + size_t index = static_cast<size_t>(i); + CPPUNIT_ASSERT(index < session->calledCommands.size()); + T* cmd = boost::get<T>(&session->calledCommands[index]); + CPPUNIT_ASSERT(cmd); + return *cmd; + } private: - EventLoop* eventLoop; - boost::shared_ptr<CryptoProvider> crypto; - boost::shared_ptr<FakeJingleSession> session; - shared_ptr<JingleContentPayload> jingleContentPayload; -// shared_ptr<FakeRemoteJingleTransportCandidateSelectorFactory> fakeRJTCSF; -// shared_ptr<FakeLocalJingleTransportCandidateGeneratorFactory> fakeLJTCF; - FileTransferTransporterFactory* ftTransporterFactory; - SOCKS5BytestreamServerManager* bytestreamServerManager; - DummyStanzaChannel* stanzaChannel; - IQRouter* iqRouter; - SOCKS5BytestreamRegistry* bytestreamRegistry; - DummyConnectionFactory* connectionFactory; - DummyConnectionServerFactory* serverConnectionFactory; - SOCKS5BytestreamProxiesManager* bytestreamProxy; - DummyTimerFactory* timerFactory; - NetworkEnvironment* networkEnvironment; - NATTraverser* natTraverser; - IDGenerator* idGenerator; - DomainNameResolver* resolver; + EventLoop* eventLoop; + boost::shared_ptr<CryptoProvider> crypto; + boost::shared_ptr<FakeJingleSession> session; + shared_ptr<JingleContentPayload> jingleContentPayload; +// shared_ptr<FakeRemoteJingleTransportCandidateSelectorFactory> fakeRJTCSF; +// shared_ptr<FakeLocalJingleTransportCandidateGeneratorFactory> fakeLJTCF; + FileTransferTransporterFactory* ftTransporterFactory; + SOCKS5BytestreamServerManager* bytestreamServerManager; + DummyStanzaChannel* stanzaChannel; + IQRouter* iqRouter; + SOCKS5BytestreamRegistry* bytestreamRegistry; + DummyConnectionFactory* connectionFactory; + DummyConnectionServerFactory* serverConnectionFactory; + SOCKS5BytestreamProxiesManager* bytestreamProxy; + DummyTimerFactory* timerFactory; + NetworkEnvironment* networkEnvironment; + NATTraverser* natTraverser; + IDGenerator* idGenerator; + DomainNameResolver* resolver; }; CPPUNIT_TEST_SUITE_REGISTRATION(IncomingJingleFileTransferTest); diff --git a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp index fee26d5..401463c 100644 --- a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp +++ b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp @@ -52,232 +52,232 @@ using namespace Swift; class OutgoingJingleFileTransferTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(OutgoingJingleFileTransferTest); - CPPUNIT_TEST(test_SendSessionInitiateOnStart); - CPPUNIT_TEST(test_FallbackToIBBAfterFailingS5B); - CPPUNIT_TEST(test_ReceiveSessionTerminateAfterSessionInitiate); - CPPUNIT_TEST(test_DeclineEmitsFinishedStateCanceled); - CPPUNIT_TEST_SUITE_END(); - - class FTStatusHelper { - public: - FTStatusHelper() : finishedCalled(false), error(FileTransferError::UnknownError) { - } - - void handleFileTransferFinished(boost::optional<FileTransferError> error) { - finishedCalled = true; - if (error.is_initialized()) this->error = error.get().getType(); - } - - void handleFileTransferStatusChanged(FileTransfer::State fileTransferSTate) { - state = fileTransferSTate; - } - - public: - bool finishedCalled; - FileTransferError::Type error; - boost::optional<FileTransfer::State> state; - }; + CPPUNIT_TEST_SUITE(OutgoingJingleFileTransferTest); + CPPUNIT_TEST(test_SendSessionInitiateOnStart); + CPPUNIT_TEST(test_FallbackToIBBAfterFailingS5B); + CPPUNIT_TEST(test_ReceiveSessionTerminateAfterSessionInitiate); + CPPUNIT_TEST(test_DeclineEmitsFinishedStateCanceled); + CPPUNIT_TEST_SUITE_END(); + + class FTStatusHelper { + public: + FTStatusHelper() : finishedCalled(false), error(FileTransferError::UnknownError) { + } + + void handleFileTransferFinished(boost::optional<FileTransferError> error) { + finishedCalled = true; + if (error.is_initialized()) this->error = error.get().getType(); + } + + void handleFileTransferStatusChanged(FileTransfer::State fileTransferSTate) { + state = fileTransferSTate; + } + + public: + bool finishedCalled; + FileTransferError::Type error; + boost::optional<FileTransfer::State> state; + }; public: - boost::shared_ptr<OutgoingJingleFileTransfer> createTestling(const FileTransferOptions& options = FileTransferOptions().withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false)) { - JID to("test@foo.com/bla"); - JingleFileTransferFileInfo fileInfo; - fileInfo.setDescription("some file"); - fileInfo.setName("test.bin"); - fileInfo.addHash(HashElement("sha-1", ByteArray())); - fileInfo.setSize(1024 * 1024); - return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer( - to, - boost::shared_ptr<JingleSession>(fakeJingleSession), - stream, - ftTransportFactory, - timerFactory, - idGen, - fileInfo, - options, - crypto.get())); - } - - IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) { - IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb); - request->setFrom(from); - return request; - } - - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - fakeJingleSession = new FakeJingleSession("foo@bar.com/baz", "mysession"); - jingleContentPayload = boost::make_shared<JingleContentPayload>(); - stanzaChannel = new DummyStanzaChannel(); - iqRouter = new IQRouter(stanzaChannel); - eventLoop = new DummyEventLoop(); - timerFactory = new DummyTimerFactory(); - connectionFactory = new DummyConnectionFactory(eventLoop); - serverConnectionFactory = new DummyConnectionServerFactory(eventLoop); - s5bRegistry = new SOCKS5BytestreamRegistry(); - networkEnvironment = new PlatformNetworkEnvironment(); - natTraverser = new PlatformNATTraversalWorker(eventLoop); - bytestreamServerManager = new SOCKS5BytestreamServerManager(s5bRegistry, serverConnectionFactory, networkEnvironment, natTraverser); - - data.clear(); - for (int n=0; n < 1024 * 1024; ++n) { - data.push_back(34); - } - - stream = boost::make_shared<ByteArrayReadBytestream>(data); - - idGen = new IDGenerator(); - s5bProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com"); - ftTransportFactory = new DummyFileTransferTransporterFactory(s5bRegistry, bytestreamServerManager, s5bProxy, idGen, connectionFactory, timerFactory, crypto.get(), iqRouter); - } - - void tearDown() { - delete ftTransportFactory; - delete s5bProxy; - delete idGen; - delete bytestreamServerManager; - delete natTraverser; - delete networkEnvironment; - delete s5bRegistry; - delete serverConnectionFactory; - delete connectionFactory; - delete timerFactory; - delete eventLoop; - delete iqRouter; - delete stanzaChannel; - } - - - void test_SendSessionInitiateOnStart() { - boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(); - transfer->start(); - - FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0); - JingleFileTransferDescription::ref description = boost::dynamic_pointer_cast<JingleFileTransferDescription>(call.description); - CPPUNIT_ASSERT(description); - CPPUNIT_ASSERT(static_cast<size_t>(1048576) == description->getFileInfo().getSize()); - - JingleIBBTransportPayload::ref transport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(call.payload); - CPPUNIT_ASSERT(transport); - } - - void test_FallbackToIBBAfterFailingS5B() { - boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(FileTransferOptions().withAssistedAllowed(true).withDirectAllowed(true).withProxiedAllowed(true)); - transfer->start(); - - FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0); - - CPPUNIT_ASSERT(boost::dynamic_pointer_cast<JingleS5BTransportPayload>(call.payload)); - fakeJingleSession->handleSessionAcceptReceived(call.id, call.description, call.payload); - - // send candidate failure - JingleS5BTransportPayload::ref candidateFailurePayload = boost::make_shared<JingleS5BTransportPayload>(); - candidateFailurePayload->setCandidateError(true); - candidateFailurePayload->setSessionID(call.payload->getSessionID()); - fakeJingleSession->handleTransportInfoReceived(call.id, candidateFailurePayload); - - // no S5B candidates -> fallback to IBB - // call at position 1 is the candidate our candidate error - FakeJingleSession::ReplaceTransportCall replaceCall = getCall<FakeJingleSession::ReplaceTransportCall>(2); - - // accept transport replace - fakeJingleSession->handleTransportAcceptReceived(replaceCall.id, replaceCall.payload); - - IQ::ref iqOpenStanza = stanzaChannel->getStanzaAtIndex<IQ>(0); - CPPUNIT_ASSERT(iqOpenStanza); - IBB::ref ibbOpen = iqOpenStanza->getPayload<IBB>(); - CPPUNIT_ASSERT(ibbOpen); - CPPUNIT_ASSERT_EQUAL(IBB::Open, ibbOpen->getAction()); - } - - void test_ReceiveSessionTerminateAfterSessionInitiate() { - boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(); - transfer->start(); - - getCall<FakeJingleSession::InitiateCall>(0); - - FTStatusHelper helper; - helper.finishedCalled = false; - transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1)); - fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Busy)); - CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled); - CPPUNIT_ASSERT(FileTransferError::PeerError == helper.error); - } - - void test_DeclineEmitsFinishedStateCanceled() { - boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(); - transfer->start(); - - getCall<FakeJingleSession::InitiateCall>(0); - - FTStatusHelper helper; - helper.finishedCalled = false; - transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1)); - transfer->onStateChanged.connect(bind(&FTStatusHelper::handleFileTransferStatusChanged, &helper, _1)); - fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Decline)); - CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled); - CPPUNIT_ASSERT(FileTransferError::UnknownError == helper.error); - CPPUNIT_ASSERT_EQUAL(true, helper.state.is_initialized()); - CPPUNIT_ASSERT(FileTransfer::State::Canceled == helper.state.get().type); - } + boost::shared_ptr<OutgoingJingleFileTransfer> createTestling(const FileTransferOptions& options = FileTransferOptions().withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false)) { + JID to("test@foo.com/bla"); + JingleFileTransferFileInfo fileInfo; + fileInfo.setDescription("some file"); + fileInfo.setName("test.bin"); + fileInfo.addHash(HashElement("sha-1", ByteArray())); + fileInfo.setSize(1024 * 1024); + return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer( + to, + boost::shared_ptr<JingleSession>(fakeJingleSession), + stream, + ftTransportFactory, + timerFactory, + idGen, + fileInfo, + options, + crypto.get())); + } + + IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) { + IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb); + request->setFrom(from); + return request; + } + + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + fakeJingleSession = new FakeJingleSession("foo@bar.com/baz", "mysession"); + jingleContentPayload = boost::make_shared<JingleContentPayload>(); + stanzaChannel = new DummyStanzaChannel(); + iqRouter = new IQRouter(stanzaChannel); + eventLoop = new DummyEventLoop(); + timerFactory = new DummyTimerFactory(); + connectionFactory = new DummyConnectionFactory(eventLoop); + serverConnectionFactory = new DummyConnectionServerFactory(eventLoop); + s5bRegistry = new SOCKS5BytestreamRegistry(); + networkEnvironment = new PlatformNetworkEnvironment(); + natTraverser = new PlatformNATTraversalWorker(eventLoop); + bytestreamServerManager = new SOCKS5BytestreamServerManager(s5bRegistry, serverConnectionFactory, networkEnvironment, natTraverser); + + data.clear(); + for (int n=0; n < 1024 * 1024; ++n) { + data.push_back(34); + } + + stream = boost::make_shared<ByteArrayReadBytestream>(data); + + idGen = new IDGenerator(); + s5bProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com"); + ftTransportFactory = new DummyFileTransferTransporterFactory(s5bRegistry, bytestreamServerManager, s5bProxy, idGen, connectionFactory, timerFactory, crypto.get(), iqRouter); + } + + void tearDown() { + delete ftTransportFactory; + delete s5bProxy; + delete idGen; + delete bytestreamServerManager; + delete natTraverser; + delete networkEnvironment; + delete s5bRegistry; + delete serverConnectionFactory; + delete connectionFactory; + delete timerFactory; + delete eventLoop; + delete iqRouter; + delete stanzaChannel; + } + + + void test_SendSessionInitiateOnStart() { + boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(); + transfer->start(); + + FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0); + JingleFileTransferDescription::ref description = boost::dynamic_pointer_cast<JingleFileTransferDescription>(call.description); + CPPUNIT_ASSERT(description); + CPPUNIT_ASSERT(static_cast<size_t>(1048576) == description->getFileInfo().getSize()); + + JingleIBBTransportPayload::ref transport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(call.payload); + CPPUNIT_ASSERT(transport); + } + + void test_FallbackToIBBAfterFailingS5B() { + boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(FileTransferOptions().withAssistedAllowed(true).withDirectAllowed(true).withProxiedAllowed(true)); + transfer->start(); + + FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0); + + CPPUNIT_ASSERT(boost::dynamic_pointer_cast<JingleS5BTransportPayload>(call.payload)); + fakeJingleSession->handleSessionAcceptReceived(call.id, call.description, call.payload); + + // send candidate failure + JingleS5BTransportPayload::ref candidateFailurePayload = boost::make_shared<JingleS5BTransportPayload>(); + candidateFailurePayload->setCandidateError(true); + candidateFailurePayload->setSessionID(call.payload->getSessionID()); + fakeJingleSession->handleTransportInfoReceived(call.id, candidateFailurePayload); + + // no S5B candidates -> fallback to IBB + // call at position 1 is the candidate our candidate error + FakeJingleSession::ReplaceTransportCall replaceCall = getCall<FakeJingleSession::ReplaceTransportCall>(2); + + // accept transport replace + fakeJingleSession->handleTransportAcceptReceived(replaceCall.id, replaceCall.payload); + + IQ::ref iqOpenStanza = stanzaChannel->getStanzaAtIndex<IQ>(0); + CPPUNIT_ASSERT(iqOpenStanza); + IBB::ref ibbOpen = iqOpenStanza->getPayload<IBB>(); + CPPUNIT_ASSERT(ibbOpen); + CPPUNIT_ASSERT_EQUAL(IBB::Open, ibbOpen->getAction()); + } + + void test_ReceiveSessionTerminateAfterSessionInitiate() { + boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(); + transfer->start(); + + getCall<FakeJingleSession::InitiateCall>(0); + + FTStatusHelper helper; + helper.finishedCalled = false; + transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1)); + fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Busy)); + CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled); + CPPUNIT_ASSERT(FileTransferError::PeerError == helper.error); + } + + void test_DeclineEmitsFinishedStateCanceled() { + boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(); + transfer->start(); + + getCall<FakeJingleSession::InitiateCall>(0); + + FTStatusHelper helper; + helper.finishedCalled = false; + transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1)); + transfer->onStateChanged.connect(bind(&FTStatusHelper::handleFileTransferStatusChanged, &helper, _1)); + fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Decline)); + CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled); + CPPUNIT_ASSERT(FileTransferError::UnknownError == helper.error); + CPPUNIT_ASSERT_EQUAL(true, helper.state.is_initialized()); + CPPUNIT_ASSERT(FileTransfer::State::Canceled == helper.state.get().type); + } //TODO: some more testcases private: - void addFileTransferDescription() { - boost::shared_ptr<JingleFileTransferDescription> desc = boost::make_shared<JingleFileTransferDescription>(); - desc->setFileInfo(JingleFileTransferFileInfo()); - jingleContentPayload->addDescription(desc); - } - - boost::shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() { - JingleS5BTransportPayload::ref payLoad = boost::make_shared<JingleS5BTransportPayload>(); - payLoad->setSessionID("mysession"); - jingleContentPayload->addTransport(payLoad); - return payLoad; - } - - boost::shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() { - JingleIBBTransportPayload::ref payLoad = boost::make_shared<JingleIBBTransportPayload>(); - payLoad->setSessionID("mysession"); - jingleContentPayload->addTransport(payLoad); - return payLoad; - } - - JingleContentID getContentID() const { - return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator()); - } - - template <typename T> T getCall(int i) const { - size_t index = static_cast<size_t>(i); - CPPUNIT_ASSERT(index < fakeJingleSession->calledCommands.size()); - T* cmd = boost::get<T>(&fakeJingleSession->calledCommands[index]); - CPPUNIT_ASSERT(cmd); - return *cmd; - } + void addFileTransferDescription() { + boost::shared_ptr<JingleFileTransferDescription> desc = boost::make_shared<JingleFileTransferDescription>(); + desc->setFileInfo(JingleFileTransferFileInfo()); + jingleContentPayload->addDescription(desc); + } + + boost::shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() { + JingleS5BTransportPayload::ref payLoad = boost::make_shared<JingleS5BTransportPayload>(); + payLoad->setSessionID("mysession"); + jingleContentPayload->addTransport(payLoad); + return payLoad; + } + + boost::shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() { + JingleIBBTransportPayload::ref payLoad = boost::make_shared<JingleIBBTransportPayload>(); + payLoad->setSessionID("mysession"); + jingleContentPayload->addTransport(payLoad); + return payLoad; + } + + JingleContentID getContentID() const { + return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator()); + } + + template <typename T> T getCall(int i) const { + size_t index = static_cast<size_t>(i); + CPPUNIT_ASSERT(index < fakeJingleSession->calledCommands.size()); + T* cmd = boost::get<T>(&fakeJingleSession->calledCommands[index]); + CPPUNIT_ASSERT(cmd); + return *cmd; + } private: - std::vector<unsigned char> data; - boost::shared_ptr<ByteArrayReadBytestream> stream; - FakeJingleSession* fakeJingleSession; - boost::shared_ptr<JingleContentPayload> jingleContentPayload; - FileTransferTransporterFactory* ftTransportFactory; - SOCKS5BytestreamServerManager* bytestreamServerManager; - DummyStanzaChannel* stanzaChannel; - IQRouter* iqRouter; - IDGenerator* idGen; - EventLoop *eventLoop; - SOCKS5BytestreamRegistry* s5bRegistry; - SOCKS5BytestreamProxiesManager* s5bProxy; - DummyTimerFactory* timerFactory; - DummyConnectionFactory* connectionFactory; - DummyConnectionServerFactory* serverConnectionFactory; - boost::shared_ptr<CryptoProvider> crypto; - NetworkEnvironment* networkEnvironment; - NATTraverser* natTraverser; - DomainNameResolver* resolver; + std::vector<unsigned char> data; + boost::shared_ptr<ByteArrayReadBytestream> stream; + FakeJingleSession* fakeJingleSession; + boost::shared_ptr<JingleContentPayload> jingleContentPayload; + FileTransferTransporterFactory* ftTransportFactory; + SOCKS5BytestreamServerManager* bytestreamServerManager; + DummyStanzaChannel* stanzaChannel; + IQRouter* iqRouter; + IDGenerator* idGen; + EventLoop *eventLoop; + SOCKS5BytestreamRegistry* s5bRegistry; + SOCKS5BytestreamProxiesManager* s5bProxy; + DummyTimerFactory* timerFactory; + DummyConnectionFactory* connectionFactory; + DummyConnectionServerFactory* serverConnectionFactory; + boost::shared_ptr<CryptoProvider> crypto; + NetworkEnvironment* networkEnvironment; + NATTraverser* natTraverser; + DomainNameResolver* resolver; }; CPPUNIT_TEST_SUITE_REGISTRATION(OutgoingJingleFileTransferTest); diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp index a0f6033..ceffdb7 100644 --- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp @@ -43,275 +43,275 @@ using namespace Swift; static boost::mt19937 randomGen; class SOCKS5BytestreamClientSessionTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SOCKS5BytestreamClientSessionTest); - CPPUNIT_TEST(testForSessionReady); - CPPUNIT_TEST(testErrorHandlingHello); - CPPUNIT_TEST(testErrorHandlingRequest); - CPPUNIT_TEST(testWriteBytestream); - CPPUNIT_TEST(testReadBytestream); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(SOCKS5BytestreamClientSessionTest); + CPPUNIT_TEST(testForSessionReady); + CPPUNIT_TEST(testErrorHandlingHello); + CPPUNIT_TEST(testErrorHandlingRequest); + CPPUNIT_TEST(testWriteBytestream); + CPPUNIT_TEST(testReadBytestream); + CPPUNIT_TEST_SUITE_END(); public: - SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress("127.0.0.1"), 8888)) {} - - void setUp() { - crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - destination = "092a44d859d19c9eed676b551ee80025903351c2"; - randomGen.seed(static_cast<unsigned int>(time(NULL))); - eventLoop = new DummyEventLoop(); - timerFactory = new DummyTimerFactory(); - connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop); - //connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1)); - //stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"))); -// connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1)); - } - - void tearDown() { - //connection.reset(); - delete timerFactory; - delete eventLoop; - } - - void testForSessionReady() { - TestHelper helper; - connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); - - SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); - clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); - - clientSession->start(); - eventLoop->processEvents(); - CPPUNIT_ASSERT(createByteArray("\x05\x01\x00", 3) == helper.unprocessedInput); - - helper.unprocessedInput.clear(); - serverRespondHelloOK(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4)); - CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4]))); - CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size())); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1)); - - helper.unprocessedInput.clear(); - serverRespondRequestOK(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); - CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError); - } - - void testErrorHandlingHello() { - TestHelper helper; - connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); - - SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); - clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); - - clientSession->start(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput); - - helper.unprocessedInput.clear(); - serverRespondHelloAuthFail(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); - CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError); - CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled); - } - - void testErrorHandlingRequest() { - TestHelper helper; - connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); - - SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); - clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); - - clientSession->start(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput); - - helper.unprocessedInput.clear(); - serverRespondHelloOK(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4)); - CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4]))); - CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size())); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1)); - - helper.unprocessedInput.clear(); - serverRespondRequestFail(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); - CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError); - CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled); - } - - void testWriteBytestream() { - TestHelper helper; - connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); - - SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); - clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); - - clientSession->start(); - eventLoop->processEvents(); - - helper.unprocessedInput.clear(); - serverRespondHelloOK(); - eventLoop->processEvents(); - - helper.unprocessedInput.clear(); - serverRespondRequestOK(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); - CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError); - - boost::shared_ptr<ByteArrayWriteBytestream> output = boost::make_shared<ByteArrayWriteBytestream>(); - clientSession->startReceiving(output); - - ByteArray transferData = generateRandomByteArray(1024); - connection->onDataRead(createSafeByteArrayRef(vecptr(transferData), transferData.size())); - CPPUNIT_ASSERT_EQUAL(transferData, output->getData()); - } - - void testReadBytestream() { - TestHelper helper; - connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); - - SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); - clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); - - clientSession->start(); - eventLoop->processEvents(); - - helper.unprocessedInput.clear(); - serverRespondHelloOK(); - eventLoop->processEvents(); - - helper.unprocessedInput.clear(); - serverRespondRequestOK(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); - CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError); - - helper.unprocessedInput.clear(); - ByteArray transferData = generateRandomByteArray(1024); - boost::shared_ptr<ByteArrayReadBytestream> input = boost::make_shared<ByteArrayReadBytestream>(transferData); - clientSession->startSending(input); - eventLoop->processEvents(); + SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress("127.0.0.1"), 8888)) {} + + void setUp() { + crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); + destination = "092a44d859d19c9eed676b551ee80025903351c2"; + randomGen.seed(static_cast<unsigned int>(time(NULL))); + eventLoop = new DummyEventLoop(); + timerFactory = new DummyTimerFactory(); + connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop); + //connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1)); + //stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"))); +// connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1)); + } + + void tearDown() { + //connection.reset(); + delete timerFactory; + delete eventLoop; + } + + void testForSessionReady() { + TestHelper helper; + connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); + + SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); + clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); + + clientSession->start(); + eventLoop->processEvents(); + CPPUNIT_ASSERT(createByteArray("\x05\x01\x00", 3) == helper.unprocessedInput); + + helper.unprocessedInput.clear(); + serverRespondHelloOK(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4)); + CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4]))); + CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size())); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1)); + + helper.unprocessedInput.clear(); + serverRespondRequestOK(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); + CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError); + } + + void testErrorHandlingHello() { + TestHelper helper; + connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); + + SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); + clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); + + clientSession->start(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput); + + helper.unprocessedInput.clear(); + serverRespondHelloAuthFail(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); + CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError); + CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled); + } + + void testErrorHandlingRequest() { + TestHelper helper; + connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); + + SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); + clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); + + clientSession->start(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput); + + helper.unprocessedInput.clear(); + serverRespondHelloOK(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4)); + CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4]))); + CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size())); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1)); + + helper.unprocessedInput.clear(); + serverRespondRequestFail(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); + CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError); + CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled); + } + + void testWriteBytestream() { + TestHelper helper; + connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); + + SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); + clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); + + clientSession->start(); + eventLoop->processEvents(); + + helper.unprocessedInput.clear(); + serverRespondHelloOK(); + eventLoop->processEvents(); + + helper.unprocessedInput.clear(); + serverRespondRequestOK(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); + CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError); + + boost::shared_ptr<ByteArrayWriteBytestream> output = boost::make_shared<ByteArrayWriteBytestream>(); + clientSession->startReceiving(output); + + ByteArray transferData = generateRandomByteArray(1024); + connection->onDataRead(createSafeByteArrayRef(vecptr(transferData), transferData.size())); + CPPUNIT_ASSERT_EQUAL(transferData, output->getData()); + } + + void testReadBytestream() { + TestHelper helper; + connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1)); + + SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory); + clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1)); + + clientSession->start(); + eventLoop->processEvents(); + + helper.unprocessedInput.clear(); + serverRespondHelloOK(); + eventLoop->processEvents(); + + helper.unprocessedInput.clear(); + serverRespondRequestOK(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled); + CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError); + + helper.unprocessedInput.clear(); + ByteArray transferData = generateRandomByteArray(1024); + boost::shared_ptr<ByteArrayReadBytestream> input = boost::make_shared<ByteArrayReadBytestream>(transferData); + clientSession->startSending(input); + eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(createByteArray(vecptr(transferData), transferData.size()), helper.unprocessedInput); - } + CPPUNIT_ASSERT_EQUAL(createByteArray(vecptr(transferData), transferData.size()), helper.unprocessedInput); + } private: - static ByteArray generateRandomByteArray(size_t len) { - boost::uniform_int<> dist(0, 255); - boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randomByte(randomGen, dist); - ByteArray result(len); - for (size_t i=0; i < len; ++i ) { - result[i] = static_cast<unsigned char>(randomByte()); - } - return result; - } - - // Server responses - void serverRespondHelloOK() { - connection->onDataRead(createSafeByteArrayRef("\x05\00", 2)); - } - - void serverRespondHelloAuthFail() { - connection->onDataRead(createSafeByteArrayRef("\x05\xFF", 2)); - } - - void serverRespondRequestOK() { - boost::shared_ptr<SafeByteArray> dataToSend = createSafeByteArrayRef("\x05\x00\x00\x03", 4); - append(*dataToSend, createSafeByteArray(static_cast<char>(destination.size()))); - append(*dataToSend, createSafeByteArray(destination)); - append(*dataToSend, createSafeByteArray("\x00", 1)); - connection->onDataRead(dataToSend); - } - - void serverRespondRequestFail() { - boost::shared_ptr<SafeByteArray> correctData = createSafeByteArrayRef("\x05\x00\x00\x03", 4); - append(*correctData, createSafeByteArray(static_cast<char>(destination.size()))); - append(*correctData, createSafeByteArray(destination)); - append(*correctData, createSafeByteArray("\x00", 1)); - - boost::shared_ptr<SafeByteArray> dataToSend; - //ByteArray failingData = Hexify::unhexify("8417947d1d305c72c11520ea7d2c6e787396705e72c312c6ccc3f66613d7cae1b91b7ab48e8b59a17d559c15fb51"); - //append(dataToSend, failingData); - //SWIFT_LOG(debug) << "hexed: " << Hexify::hexify(failingData) << std::endl; - do { - ByteArray rndArray = generateRandomByteArray(correctData->size()); - dataToSend = createSafeByteArrayRef(vecptr(rndArray), rndArray.size()); - } while (*dataToSend == *correctData); - connection->onDataRead(dataToSend); - } + static ByteArray generateRandomByteArray(size_t len) { + boost::uniform_int<> dist(0, 255); + boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randomByte(randomGen, dist); + ByteArray result(len); + for (size_t i=0; i < len; ++i ) { + result[i] = static_cast<unsigned char>(randomByte()); + } + return result; + } + + // Server responses + void serverRespondHelloOK() { + connection->onDataRead(createSafeByteArrayRef("\x05\00", 2)); + } + + void serverRespondHelloAuthFail() { + connection->onDataRead(createSafeByteArrayRef("\x05\xFF", 2)); + } + + void serverRespondRequestOK() { + boost::shared_ptr<SafeByteArray> dataToSend = createSafeByteArrayRef("\x05\x00\x00\x03", 4); + append(*dataToSend, createSafeByteArray(static_cast<char>(destination.size()))); + append(*dataToSend, createSafeByteArray(destination)); + append(*dataToSend, createSafeByteArray("\x00", 1)); + connection->onDataRead(dataToSend); + } + + void serverRespondRequestFail() { + boost::shared_ptr<SafeByteArray> correctData = createSafeByteArrayRef("\x05\x00\x00\x03", 4); + append(*correctData, createSafeByteArray(static_cast<char>(destination.size()))); + append(*correctData, createSafeByteArray(destination)); + append(*correctData, createSafeByteArray("\x00", 1)); + + boost::shared_ptr<SafeByteArray> dataToSend; + //ByteArray failingData = Hexify::unhexify("8417947d1d305c72c11520ea7d2c6e787396705e72c312c6ccc3f66613d7cae1b91b7ab48e8b59a17d559c15fb51"); + //append(dataToSend, failingData); + //SWIFT_LOG(debug) << "hexed: " << Hexify::hexify(failingData) << std::endl; + do { + ByteArray rndArray = generateRandomByteArray(correctData->size()); + dataToSend = createSafeByteArrayRef(vecptr(rndArray), rndArray.size()); + } while (*dataToSend == *correctData); + connection->onDataRead(dataToSend); + } private: - struct TestHelper { - TestHelper() : sessionReadyCalled(false), sessionReadyError(false) {} - ByteArray unprocessedInput; - bool sessionReadyCalled; - bool sessionReadyError; + struct TestHelper { + TestHelper() : sessionReadyCalled(false), sessionReadyError(false) {} + ByteArray unprocessedInput; + bool sessionReadyCalled; + bool sessionReadyError; - void handleConnectionDataWritten(const SafeByteArray& data) { - append(unprocessedInput, data); - //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput) << std::endl; - } + void handleConnectionDataWritten(const SafeByteArray& data) { + append(unprocessedInput, data); + //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput) << std::endl; + } - void handleSessionReady(bool error) { - sessionReadyCalled = true; - sessionReadyError = error; - } - }; + void handleSessionReady(bool error) { + sessionReadyCalled = true; + sessionReadyError = error; + } + }; private: - struct MockeryConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<MockeryConnection> { - public: - MockeryConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive), disconnectCalled(false) {} - - void listen() { assert(false); } - void connect(const HostAddressPort& address) { - hostAddressPort = address; - if (isResponsive) { - bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end(); - eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail)); - } - } - - HostAddressPort getLocalAddress() const { return HostAddressPort(); } - - HostAddressPort getRemoteAddress() const { return HostAddressPort(); } - - void disconnect() { - disconnectCalled = true; - } - - void write(const SafeByteArray& data) { - eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this()); - onDataSent(data); - } - - boost::signal<void (const SafeByteArray&)> onDataSent; - - EventLoop* eventLoop; - boost::optional<HostAddressPort> hostAddressPort; - std::vector<HostAddressPort> failingPorts; - bool isResponsive; - bool disconnectCalled; - }; + struct MockeryConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<MockeryConnection> { + public: + MockeryConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive), disconnectCalled(false) {} + + void listen() { assert(false); } + void connect(const HostAddressPort& address) { + hostAddressPort = address; + if (isResponsive) { + bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end(); + eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail)); + } + } + + HostAddressPort getLocalAddress() const { return HostAddressPort(); } + + HostAddressPort getRemoteAddress() const { return HostAddressPort(); } + + void disconnect() { + disconnectCalled = true; + } + + void write(const SafeByteArray& data) { + eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this()); + onDataSent(data); + } + + boost::signal<void (const SafeByteArray&)> onDataSent; + + EventLoop* eventLoop; + boost::optional<HostAddressPort> hostAddressPort; + std::vector<HostAddressPort> failingPorts; + bool isResponsive; + bool disconnectCalled; + }; private: - HostAddressPort destinationAddressPort; - std::string destination; - DummyEventLoop* eventLoop; - DummyTimerFactory* timerFactory; - boost::shared_ptr<MockeryConnection> connection; - const std::vector<HostAddressPort> failingPorts; - boost::shared_ptr<CryptoProvider> crypto; + HostAddressPort destinationAddressPort; + std::string destination; + DummyEventLoop* eventLoop; + DummyTimerFactory* timerFactory; + boost::shared_ptr<MockeryConnection> connection; + const std::vector<HostAddressPort> failingPorts; + boost::shared_ptr<CryptoProvider> crypto; }; CPPUNIT_TEST_SUITE_REGISTRATION(SOCKS5BytestreamClientSessionTest); diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp index 84dcf7c..12690ff 100644 --- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp @@ -21,193 +21,193 @@ using namespace Swift; class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SOCKS5BytestreamServerSessionTest); - CPPUNIT_TEST(testAuthenticate); - CPPUNIT_TEST(testAuthenticate_Chunked); - CPPUNIT_TEST(testRequest); - CPPUNIT_TEST(testRequest_UnknownBytestream); - CPPUNIT_TEST(testReceiveData); - CPPUNIT_TEST(testReceiveData_Chunked); - CPPUNIT_TEST(testDataStreamPauseStopsSendingData); - CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - receivedDataChunks = 0; - eventLoop = new DummyEventLoop(); - bytestreams = new SOCKS5BytestreamRegistry(); - connection = boost::make_shared<DummyConnection>(eventLoop); - connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1)); - stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")); - finished = false; - } - - void tearDown() { - connection.reset(); - delete bytestreams; - delete eventLoop; - } - - void testAuthenticate() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - - receive(createSafeByteArray("\x05\x02\x01\x02")); - - CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData); - } - - void testAuthenticate_Chunked() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - - receive(createSafeByteArray("\x05\x02\x01")); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedData.size())); - receive(createSafeByteArray("\x01")); - CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData); - } - - void testRequest() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - bytestreams->setHasBytestream("abcdef", true); - authenticate(); - - ByteArray hostname(createByteArray("abcdef")); - receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); - CPPUNIT_ASSERT(createByteArray("\x05\x00\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == createByteArray(&receivedData[0], 13)); - } - - void testRequest_UnknownBytestream() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - authenticate(); - - ByteArray hostname(createByteArray("abcdef")); - receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); - CPPUNIT_ASSERT(createByteArray("\x05\x04\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == receivedData); - } - - void testReceiveData() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - bytestreams->setHasBytestream("abcdef", true); - authenticate(); - request("abcdef"); - eventLoop->processEvents(); - testling->startSending(stream1); - skipHeader("abcdef"); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData); - CPPUNIT_ASSERT_EQUAL(2, receivedDataChunks); - } - - void testReceiveData_Chunked() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - testling->setChunkSize(3); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - bytestreams->setHasBytestream("abcdef", true); - authenticate(); - request("abcdef"); - eventLoop->processEvents(); - testling->startSending(stream1); - eventLoop->processEvents(); - skipHeader("abcdef"); - CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData); - CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks); - } - - void testDataStreamPauseStopsSendingData() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - testling->setChunkSize(3); - stream1->setDataComplete(false); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - bytestreams->setHasBytestream("abcdef", true); - authenticate(); - request("abcdef"); - eventLoop->processEvents(); - testling->startSending(stream1); - eventLoop->processEvents(); - skipHeader("abcdef"); - CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData); - CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks); - - CPPUNIT_ASSERT(!finished); - CPPUNIT_ASSERT(!error); - } - - void testDataStreamResumeAfterPauseSendsData() { - boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); - testling->setChunkSize(3); - stream1->setDataComplete(false); - StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); - bytestreams->setHasBytestream("abcdef", true); - authenticate(); - request("abcdef"); - eventLoop->processEvents(); - testling->startSending(stream1); - eventLoop->processEvents(); - skipHeader("abcdef"); - - stream1->addData(createByteArray("xyz")); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(createByteArray("abcdefgxyz") == receivedData); - CPPUNIT_ASSERT(!finished); - CPPUNIT_ASSERT(!error); - } - - private: - void receive(const SafeByteArray& data) { - connection->receive(data); - eventLoop->processEvents(); - } - - void authenticate() { - receive(createSafeByteArray("\x05\x02\x01\x02")); - receivedData.clear(); - receivedDataChunks = 0; - } - - void request(const std::string& hostname) { - receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); - } - - void skipHeader(const std::string& hostname) { - size_t headerSize = 7 + hostname.size(); - receivedData = createByteArray(&receivedData[headerSize], receivedData.size() - headerSize); - } - - - void handleDataWritten(const SafeByteArray& data) { - receivedData.insert(receivedData.end(), data.begin(), data.end()); - receivedDataChunks++; - } - - private: - SOCKS5BytestreamServerSession* createSession() { - SOCKS5BytestreamServerSession* session = new SOCKS5BytestreamServerSession(connection, bytestreams); - session->onFinished.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleFinished, this, _1)); - return session; - } - - void handleFinished(boost::optional<FileTransferError> error) { - finished = true; - this->error = error; - } - - private: - DummyEventLoop* eventLoop; - SOCKS5BytestreamRegistry* bytestreams; - boost::shared_ptr<DummyConnection> connection; - std::vector<unsigned char> receivedData; - int receivedDataChunks; - boost::shared_ptr<ByteArrayReadBytestream> stream1; - bool finished; - boost::optional<FileTransferError> error; + CPPUNIT_TEST_SUITE(SOCKS5BytestreamServerSessionTest); + CPPUNIT_TEST(testAuthenticate); + CPPUNIT_TEST(testAuthenticate_Chunked); + CPPUNIT_TEST(testRequest); + CPPUNIT_TEST(testRequest_UnknownBytestream); + CPPUNIT_TEST(testReceiveData); + CPPUNIT_TEST(testReceiveData_Chunked); + CPPUNIT_TEST(testDataStreamPauseStopsSendingData); + CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + receivedDataChunks = 0; + eventLoop = new DummyEventLoop(); + bytestreams = new SOCKS5BytestreamRegistry(); + connection = boost::make_shared<DummyConnection>(eventLoop); + connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1)); + stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")); + finished = false; + } + + void tearDown() { + connection.reset(); + delete bytestreams; + delete eventLoop; + } + + void testAuthenticate() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + + receive(createSafeByteArray("\x05\x02\x01\x02")); + + CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData); + } + + void testAuthenticate_Chunked() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + + receive(createSafeByteArray("\x05\x02\x01")); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedData.size())); + receive(createSafeByteArray("\x01")); + CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData); + } + + void testRequest() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + bytestreams->setHasBytestream("abcdef", true); + authenticate(); + + ByteArray hostname(createByteArray("abcdef")); + receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); + CPPUNIT_ASSERT(createByteArray("\x05\x00\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == createByteArray(&receivedData[0], 13)); + } + + void testRequest_UnknownBytestream() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + authenticate(); + + ByteArray hostname(createByteArray("abcdef")); + receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); + CPPUNIT_ASSERT(createByteArray("\x05\x04\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == receivedData); + } + + void testReceiveData() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + bytestreams->setHasBytestream("abcdef", true); + authenticate(); + request("abcdef"); + eventLoop->processEvents(); + testling->startSending(stream1); + skipHeader("abcdef"); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData); + CPPUNIT_ASSERT_EQUAL(2, receivedDataChunks); + } + + void testReceiveData_Chunked() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + testling->setChunkSize(3); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + bytestreams->setHasBytestream("abcdef", true); + authenticate(); + request("abcdef"); + eventLoop->processEvents(); + testling->startSending(stream1); + eventLoop->processEvents(); + skipHeader("abcdef"); + CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData); + CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks); + } + + void testDataStreamPauseStopsSendingData() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + testling->setChunkSize(3); + stream1->setDataComplete(false); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + bytestreams->setHasBytestream("abcdef", true); + authenticate(); + request("abcdef"); + eventLoop->processEvents(); + testling->startSending(stream1); + eventLoop->processEvents(); + skipHeader("abcdef"); + CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData); + CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks); + + CPPUNIT_ASSERT(!finished); + CPPUNIT_ASSERT(!error); + } + + void testDataStreamResumeAfterPauseSendsData() { + boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession()); + testling->setChunkSize(3); + stream1->setDataComplete(false); + StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get()); + bytestreams->setHasBytestream("abcdef", true); + authenticate(); + request("abcdef"); + eventLoop->processEvents(); + testling->startSending(stream1); + eventLoop->processEvents(); + skipHeader("abcdef"); + + stream1->addData(createByteArray("xyz")); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(createByteArray("abcdefgxyz") == receivedData); + CPPUNIT_ASSERT(!finished); + CPPUNIT_ASSERT(!error); + } + + private: + void receive(const SafeByteArray& data) { + connection->receive(data); + eventLoop->processEvents(); + } + + void authenticate() { + receive(createSafeByteArray("\x05\x02\x01\x02")); + receivedData.clear(); + receivedDataChunks = 0; + } + + void request(const std::string& hostname) { + receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); + } + + void skipHeader(const std::string& hostname) { + size_t headerSize = 7 + hostname.size(); + receivedData = createByteArray(&receivedData[headerSize], receivedData.size() - headerSize); + } + + + void handleDataWritten(const SafeByteArray& data) { + receivedData.insert(receivedData.end(), data.begin(), data.end()); + receivedDataChunks++; + } + + private: + SOCKS5BytestreamServerSession* createSession() { + SOCKS5BytestreamServerSession* session = new SOCKS5BytestreamServerSession(connection, bytestreams); + session->onFinished.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleFinished, this, _1)); + return session; + } + + void handleFinished(boost::optional<FileTransferError> error) { + finished = true; + this->error = error; + } + + private: + DummyEventLoop* eventLoop; + SOCKS5BytestreamRegistry* bytestreams; + boost::shared_ptr<DummyConnection> connection; + std::vector<unsigned char> receivedData; + int receivedDataChunks; + boost::shared_ptr<ByteArrayReadBytestream> stream1; + bool finished; + boost::optional<FileTransferError> error; }; CPPUNIT_TEST_SUITE_REGISTRATION(SOCKS5BytestreamServerSessionTest); diff --git a/Swiften/FileTransfer/WriteBytestream.h b/Swiften/FileTransfer/WriteBytestream.h index 76237c4..ffcfdcc 100644 --- a/Swiften/FileTransfer/WriteBytestream.h +++ b/Swiften/FileTransfer/WriteBytestream.h @@ -14,19 +14,19 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - class SWIFTEN_API WriteBytestream { - public: - typedef boost::shared_ptr<WriteBytestream> ref; + class SWIFTEN_API WriteBytestream { + public: + typedef boost::shared_ptr<WriteBytestream> ref; - virtual ~WriteBytestream(); + virtual ~WriteBytestream(); - /** - * Write data from vector argument to bytestream. - * - * On success true is returned and \ref onWrite is called. On failure false is returned. - */ - virtual bool write(const std::vector<unsigned char>&) = 0; + /** + * Write data from vector argument to bytestream. + * + * On success true is returned and \ref onWrite is called. On failure false is returned. + */ + virtual bool write(const std::vector<unsigned char>&) = 0; - boost::signal<void (const std::vector<unsigned char>&)> onWrite; - }; + boost::signal<void (const std::vector<unsigned char>&)> onWrite; + }; } diff --git a/Swiften/History/HistoryMessage.h b/Swiften/History/HistoryMessage.h index e07ef60..e910899 100644 --- a/Swiften/History/HistoryMessage.h +++ b/Swiften/History/HistoryMessage.h @@ -12,63 +12,63 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API HistoryMessage { - public: - enum Type { - Chat = 0, - Groupchat = 1, - PrivateMessage = 2 - }; + class SWIFTEN_API HistoryMessage { + public: + enum Type { + Chat = 0, + Groupchat = 1, + PrivateMessage = 2 + }; - HistoryMessage( - const std::string& message, - const JID& fromJID, - const JID& toJID, - Type type, - const boost::posix_time::ptime& time, - int utcOffset = 0) : - message_(message), - fromJID_(fromJID), - toJID_(toJID), - type_(type), - time_(time), - utcOffset_(utcOffset) { - } + HistoryMessage( + const std::string& message, + const JID& fromJID, + const JID& toJID, + Type type, + const boost::posix_time::ptime& time, + int utcOffset = 0) : + message_(message), + fromJID_(fromJID), + toJID_(toJID), + type_(type), + time_(time), + utcOffset_(utcOffset) { + } - const std::string& getMessage() const { - return message_; - } + const std::string& getMessage() const { + return message_; + } - const JID& getFromJID() const { - return fromJID_; - } + const JID& getFromJID() const { + return fromJID_; + } - const JID& getToJID() const { - return toJID_; - } + const JID& getToJID() const { + return toJID_; + } - Type getType() const { - return type_; - } + Type getType() const { + return type_; + } - boost::posix_time::ptime getTime() const { - return time_; - } + boost::posix_time::ptime getTime() const { + return time_; + } - int getOffset() const { - return utcOffset_; - } + int getOffset() const { + return utcOffset_; + } - bool operator==(const HistoryMessage& o) const { - return message_ == o.message_ && fromJID_ == o.fromJID_ && toJID_ == o.toJID_ && type_ == o.type_ && time_ == o.time_; - } + bool operator==(const HistoryMessage& o) const { + return message_ == o.message_ && fromJID_ == o.fromJID_ && toJID_ == o.toJID_ && type_ == o.type_ && time_ == o.time_; + } - private: - std::string message_; - JID fromJID_; - JID toJID_; - Type type_; - boost::posix_time::ptime time_; - int utcOffset_; - }; + private: + std::string message_; + JID fromJID_; + JID toJID_; + Type type_; + boost::posix_time::ptime time_; + int utcOffset_; + }; } diff --git a/Swiften/History/HistoryStorage.h b/Swiften/History/HistoryStorage.h index ee8f15b..10b6bb0 100644 --- a/Swiften/History/HistoryStorage.h +++ b/Swiften/History/HistoryStorage.h @@ -17,20 +17,20 @@ #include <Swiften/JID/JID.h> namespace Swift { - typedef std::map<JID, std::set<boost::gregorian::date> > ContactsMap; + typedef std::map<JID, std::set<boost::gregorian::date> > ContactsMap; - class SWIFTEN_API HistoryStorage { - /** - * Messages are stored using localtime timestamps. - */ - public: - virtual ~HistoryStorage() {} + class SWIFTEN_API HistoryStorage { + /** + * Messages are stored using localtime timestamps. + */ + public: + virtual ~HistoryStorage() {} - virtual void addMessage(const HistoryMessage& message) = 0; - virtual std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0; - virtual std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0; - virtual std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0; - virtual ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const = 0; - virtual boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const = 0; - }; + virtual void addMessage(const HistoryMessage& message) = 0; + virtual std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0; + virtual std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0; + virtual std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0; + virtual ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const = 0; + virtual boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const = 0; + }; } diff --git a/Swiften/History/SQLiteHistoryStorage.cpp b/Swiften/History/SQLiteHistoryStorage.cpp index 8306803..beb7ba1 100644 --- a/Swiften/History/SQLiteHistoryStorage.cpp +++ b/Swiften/History/SQLiteHistoryStorage.cpp @@ -17,366 +17,366 @@ #include <Swiften/Base/Path.h> inline std::string getEscapedString(const std::string& s) { - std::string result(s); - - size_t pos = result.find('\''); - while (pos != std::string::npos) { - result.insert(pos, "'"); - pos = result.find('\'', pos + 2); - } - return result; + std::string result(s); + + size_t pos = result.find('\''); + while (pos != std::string::npos) { + result.insert(pos, "'"); + pos = result.find('\'', pos + 2); + } + return result; } namespace Swift { SQLiteHistoryStorage::SQLiteHistoryStorage(const boost::filesystem::path& file) : db_(0) { - thread_ = new boost::thread(boost::bind(&SQLiteHistoryStorage::run, this)); - - sqlite3_open(pathToString(file).c_str(), &db_); - if (!db_) { - std::cerr << "Error opening database " << pathToString(file) << std::endl; - } - - char* errorMessage; - int result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS messages('message' STRING, 'fromBare' INTEGER, 'fromResource' STRING, 'toBare' INTEGER, 'toResource' STRING, 'type' INTEGER, 'time' INTEGER, 'offset' INTEGER)", 0, 0, &errorMessage); - if (result != SQLITE_OK) { - std::cerr << "SQL Error: " << errorMessage << std::endl; - sqlite3_free(errorMessage); - } - - result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS jids('id' INTEGER PRIMARY KEY ASC AUTOINCREMENT, 'jid' STRING UNIQUE NOT NULL)", 0, 0, &errorMessage); - if (result != SQLITE_OK) { - std::cerr << "SQL Error: " << errorMessage << std::endl; - sqlite3_free(errorMessage); - } + thread_ = new boost::thread(boost::bind(&SQLiteHistoryStorage::run, this)); + + sqlite3_open(pathToString(file).c_str(), &db_); + if (!db_) { + std::cerr << "Error opening database " << pathToString(file) << std::endl; + } + + char* errorMessage; + int result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS messages('message' STRING, 'fromBare' INTEGER, 'fromResource' STRING, 'toBare' INTEGER, 'toResource' STRING, 'type' INTEGER, 'time' INTEGER, 'offset' INTEGER)", 0, 0, &errorMessage); + if (result != SQLITE_OK) { + std::cerr << "SQL Error: " << errorMessage << std::endl; + sqlite3_free(errorMessage); + } + + result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS jids('id' INTEGER PRIMARY KEY ASC AUTOINCREMENT, 'jid' STRING UNIQUE NOT NULL)", 0, 0, &errorMessage); + if (result != SQLITE_OK) { + std::cerr << "SQL Error: " << errorMessage << std::endl; + sqlite3_free(errorMessage); + } } SQLiteHistoryStorage::~SQLiteHistoryStorage() { - sqlite3_close(db_); - delete thread_; + sqlite3_close(db_); + delete thread_; } void SQLiteHistoryStorage::addMessage(const HistoryMessage& message) { - int secondsSinceEpoch = (message.getTime() - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds(); - - std::string statement = std::string("INSERT INTO messages('message', 'fromBare', 'fromResource', 'toBare', 'toResource', 'type', 'time', 'offset') VALUES(") + - "'" + getEscapedString(message.getMessage()) + "', " + - boost::lexical_cast<std::string>(getIDForJID(message.getFromJID().toBare())) + ", '" + - getEscapedString(message.getFromJID().getResource()) + "', " + - boost::lexical_cast<std::string>(getIDForJID(message.getToJID().toBare())) + ", '" + - getEscapedString(message.getToJID().getResource()) + "', " + - boost::lexical_cast<std::string>(message.getType()) + ", " + - boost::lexical_cast<std::string>(secondsSinceEpoch) + ", " + - boost::lexical_cast<std::string>(message.getOffset()) + ")"; - char* errorMessage; - int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage); - if (result != SQLITE_OK) { - std::cerr << "SQL Error: " << errorMessage << std::endl; - sqlite3_free(errorMessage); - } + int secondsSinceEpoch = (message.getTime() - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds(); + + std::string statement = std::string("INSERT INTO messages('message', 'fromBare', 'fromResource', 'toBare', 'toResource', 'type', 'time', 'offset') VALUES(") + + "'" + getEscapedString(message.getMessage()) + "', " + + boost::lexical_cast<std::string>(getIDForJID(message.getFromJID().toBare())) + ", '" + + getEscapedString(message.getFromJID().getResource()) + "', " + + boost::lexical_cast<std::string>(getIDForJID(message.getToJID().toBare())) + ", '" + + getEscapedString(message.getToJID().getResource()) + "', " + + boost::lexical_cast<std::string>(message.getType()) + ", " + + boost::lexical_cast<std::string>(secondsSinceEpoch) + ", " + + boost::lexical_cast<std::string>(message.getOffset()) + ")"; + char* errorMessage; + int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage); + if (result != SQLITE_OK) { + std::cerr << "SQL Error: " << errorMessage << std::endl; + sqlite3_free(errorMessage); + } } std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const { - sqlite3_stmt* selectStatement; - - boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); - boost::optional<long long> contactID = getIDFromJID(contactJID.toBare()); - - if (!selfID || !contactID) { - // JIDs missing from the database - return std::vector<HistoryMessage>(); - } - - std::string selectQuery = "SELECT * FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type); - if (contactJID.isBare()) { - // match only bare jid - selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" + - boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" + - boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))"; - } - else { - // match resource too - selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" + - boost::lexical_cast<std::string>(*contactID) +" AND toResource='" + - getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" + - boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" + - getEscapedString(contactJID.getResource()) + "') AND toBare=" + - boost::lexical_cast<std::string>(*selfID) + ")))"; - } - - if (!date.is_not_a_date()) { - int lowerBound = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds(); - int upperBound = lowerBound + 86400; - - selectQuery += " AND (time>=" + boost::lexical_cast<std::string>(lowerBound) + - " AND time<" + boost::lexical_cast<std::string>(upperBound) + ")"; - } - - int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); - if (r != SQLITE_OK) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } - r = sqlite3_step(selectStatement); - - // Retrieve result - std::vector<HistoryMessage> result; - while (r == SQLITE_ROW) { - std::string message(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0))); - - // fromJID - boost::optional<JID> fromJID(getJIDFromID(sqlite3_column_int(selectStatement, 1))); - std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 2))); - if (fromJID) { - fromJID = boost::optional<JID>(JID(fromJID->getNode(), fromJID->getDomain(), fromResource)); - } - - // toJID - boost::optional<JID> toJID(getJIDFromID(sqlite3_column_int(selectStatement, 3))); - std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 4))); - if (toJID) { - toJID = boost::optional<JID>(JID(toJID->getNode(), toJID->getDomain(), toResource)); - } - - // message type - HistoryMessage::Type type = static_cast<HistoryMessage::Type>(sqlite3_column_int(selectStatement, 5)); - - // timestamp - int secondsSinceEpoch(sqlite3_column_int(selectStatement, 6)); - boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); - - // offset from utc - int offset = sqlite3_column_int(selectStatement, 7); - - result.push_back(HistoryMessage(message, (fromJID ? *fromJID : JID()), (toJID ? *toJID : JID()), type, time, offset)); - r = sqlite3_step(selectStatement); - } - if (r != SQLITE_DONE) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } - sqlite3_finalize(selectStatement); - - return result; + sqlite3_stmt* selectStatement; + + boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); + boost::optional<long long> contactID = getIDFromJID(contactJID.toBare()); + + if (!selfID || !contactID) { + // JIDs missing from the database + return std::vector<HistoryMessage>(); + } + + std::string selectQuery = "SELECT * FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type); + if (contactJID.isBare()) { + // match only bare jid + selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" + + boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" + + boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))"; + } + else { + // match resource too + selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" + + boost::lexical_cast<std::string>(*contactID) +" AND toResource='" + + getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" + + boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" + + getEscapedString(contactJID.getResource()) + "') AND toBare=" + + boost::lexical_cast<std::string>(*selfID) + ")))"; + } + + if (!date.is_not_a_date()) { + int lowerBound = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds(); + int upperBound = lowerBound + 86400; + + selectQuery += " AND (time>=" + boost::lexical_cast<std::string>(lowerBound) + + " AND time<" + boost::lexical_cast<std::string>(upperBound) + ")"; + } + + int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); + if (r != SQLITE_OK) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } + r = sqlite3_step(selectStatement); + + // Retrieve result + std::vector<HistoryMessage> result; + while (r == SQLITE_ROW) { + std::string message(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0))); + + // fromJID + boost::optional<JID> fromJID(getJIDFromID(sqlite3_column_int(selectStatement, 1))); + std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 2))); + if (fromJID) { + fromJID = boost::optional<JID>(JID(fromJID->getNode(), fromJID->getDomain(), fromResource)); + } + + // toJID + boost::optional<JID> toJID(getJIDFromID(sqlite3_column_int(selectStatement, 3))); + std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 4))); + if (toJID) { + toJID = boost::optional<JID>(JID(toJID->getNode(), toJID->getDomain(), toResource)); + } + + // message type + HistoryMessage::Type type = static_cast<HistoryMessage::Type>(sqlite3_column_int(selectStatement, 5)); + + // timestamp + int secondsSinceEpoch(sqlite3_column_int(selectStatement, 6)); + boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); + + // offset from utc + int offset = sqlite3_column_int(selectStatement, 7); + + result.push_back(HistoryMessage(message, (fromJID ? *fromJID : JID()), (toJID ? *toJID : JID()), type, time, offset)); + r = sqlite3_step(selectStatement); + } + if (r != SQLITE_DONE) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } + sqlite3_finalize(selectStatement); + + return result; } long long SQLiteHistoryStorage::getIDForJID(const JID& jid) { - boost::optional<long long> id = getIDFromJID(jid); - if (id) { - return *id; - } - else { - return addJID(jid); - } + boost::optional<long long> id = getIDFromJID(jid); + if (id) { + return *id; + } + else { + return addJID(jid); + } } long long SQLiteHistoryStorage::addJID(const JID& jid) { - std::string statement = std::string("INSERT INTO jids('jid') VALUES('") + getEscapedString(jid.toString()) + "')"; - char* errorMessage; - int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage); - if (result != SQLITE_OK) { - std::cerr << "SQL Error: " << errorMessage << std::endl; - sqlite3_free(errorMessage); - } - return sqlite3_last_insert_rowid(db_); + std::string statement = std::string("INSERT INTO jids('jid') VALUES('") + getEscapedString(jid.toString()) + "')"; + char* errorMessage; + int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage); + if (result != SQLITE_OK) { + std::cerr << "SQL Error: " << errorMessage << std::endl; + sqlite3_free(errorMessage); + } + return sqlite3_last_insert_rowid(db_); } boost::optional<JID> SQLiteHistoryStorage::getJIDFromID(long long id) const { - boost::optional<JID> result; - sqlite3_stmt* selectStatement; - std::string selectQuery("SELECT jid FROM jids WHERE id=" + boost::lexical_cast<std::string>(id)); - int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); - if (r != SQLITE_OK) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } - r = sqlite3_step(selectStatement); - if (r == SQLITE_ROW) { - result = boost::optional<JID>(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0))); - } - sqlite3_finalize(selectStatement); - return result; + boost::optional<JID> result; + sqlite3_stmt* selectStatement; + std::string selectQuery("SELECT jid FROM jids WHERE id=" + boost::lexical_cast<std::string>(id)); + int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); + if (r != SQLITE_OK) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } + r = sqlite3_step(selectStatement); + if (r == SQLITE_ROW) { + result = boost::optional<JID>(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0))); + } + sqlite3_finalize(selectStatement); + return result; } boost::optional<long long> SQLiteHistoryStorage::getIDFromJID(const JID& jid) const { - boost::optional<long long> result; - sqlite3_stmt* selectStatement; - std::string selectQuery("SELECT id FROM jids WHERE jid='" + jid.toString() + "'"); - long long r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); - if (r != SQLITE_OK) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } - r = sqlite3_step(selectStatement); - if (r == SQLITE_ROW) { - result = boost::optional<long long>(sqlite3_column_int(selectStatement, 0)); - } - sqlite3_finalize(selectStatement); - return result; + boost::optional<long long> result; + sqlite3_stmt* selectStatement; + std::string selectQuery("SELECT id FROM jids WHERE jid='" + jid.toString() + "'"); + long long r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); + if (r != SQLITE_OK) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } + r = sqlite3_step(selectStatement); + if (r == SQLITE_ROW) { + result = boost::optional<long long>(sqlite3_column_int(selectStatement, 0)); + } + sqlite3_finalize(selectStatement); + return result; } ContactsMap SQLiteHistoryStorage::getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const { - ContactsMap result; - sqlite3_stmt* selectStatement; - - // get id - boost::optional<long long> id = getIDFromJID(selfJID); - if (!id) { - return result; - } - - // get contacts - std::string query = "SELECT DISTINCT messages.'fromBare', messages.'fromResource', messages.'toBare', messages.'toResource', messages.'time' " - "FROM messages WHERE (type=" - + boost::lexical_cast<std::string>(type) + " AND (toBare=" - + boost::lexical_cast<std::string>(*id) + " OR fromBare=" + boost::lexical_cast<std::string>(*id) + "))"; - - // match keyword - if (getEscapedString(keyword).length()) { - query += " AND message LIKE '%" + getEscapedString(keyword) + "%'"; - } - - int r = sqlite3_prepare(db_, query.c_str(), boost::numeric_cast<int>(query.size()), &selectStatement, NULL); - if (r != SQLITE_OK) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } - - r = sqlite3_step(selectStatement); - while (r == SQLITE_ROW) { - int fromBareID = sqlite3_column_int(selectStatement, 0); - std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 1))); - int toBareID = sqlite3_column_int(selectStatement, 2); - std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 3))); - std::string resource; - - int secondsSinceEpoch(sqlite3_column_int(selectStatement, 4)); - boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); - - boost::optional<JID> contactJID; - - if (fromBareID == *id) { - contactJID = getJIDFromID(toBareID); - resource = toResource; - } - else { - contactJID = getJIDFromID(fromBareID); - resource = fromResource; - } - - // check if it is a MUC contact (from a private conversation) - if (type == HistoryMessage::PrivateMessage) { - contactJID = boost::optional<JID>(JID(contactJID->getNode(), contactJID->getDomain(), resource)); - } - - if (contactJID) { - result[*contactJID].insert(time.date()); - } - - r = sqlite3_step(selectStatement); - } - - if (r != SQLITE_DONE) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } - sqlite3_finalize(selectStatement); - - return result; + ContactsMap result; + sqlite3_stmt* selectStatement; + + // get id + boost::optional<long long> id = getIDFromJID(selfJID); + if (!id) { + return result; + } + + // get contacts + std::string query = "SELECT DISTINCT messages.'fromBare', messages.'fromResource', messages.'toBare', messages.'toResource', messages.'time' " + "FROM messages WHERE (type=" + + boost::lexical_cast<std::string>(type) + " AND (toBare=" + + boost::lexical_cast<std::string>(*id) + " OR fromBare=" + boost::lexical_cast<std::string>(*id) + "))"; + + // match keyword + if (getEscapedString(keyword).length()) { + query += " AND message LIKE '%" + getEscapedString(keyword) + "%'"; + } + + int r = sqlite3_prepare(db_, query.c_str(), boost::numeric_cast<int>(query.size()), &selectStatement, NULL); + if (r != SQLITE_OK) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } + + r = sqlite3_step(selectStatement); + while (r == SQLITE_ROW) { + int fromBareID = sqlite3_column_int(selectStatement, 0); + std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 1))); + int toBareID = sqlite3_column_int(selectStatement, 2); + std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 3))); + std::string resource; + + int secondsSinceEpoch(sqlite3_column_int(selectStatement, 4)); + boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); + + boost::optional<JID> contactJID; + + if (fromBareID == *id) { + contactJID = getJIDFromID(toBareID); + resource = toResource; + } + else { + contactJID = getJIDFromID(fromBareID); + resource = fromResource; + } + + // check if it is a MUC contact (from a private conversation) + if (type == HistoryMessage::PrivateMessage) { + contactJID = boost::optional<JID>(JID(contactJID->getNode(), contactJID->getDomain(), resource)); + } + + if (contactJID) { + result[*contactJID].insert(time.date()); + } + + r = sqlite3_step(selectStatement); + } + + if (r != SQLITE_DONE) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } + sqlite3_finalize(selectStatement); + + return result; } boost::gregorian::date SQLiteHistoryStorage::getNextDateWithLogs(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date, bool reverseOrder) const { - sqlite3_stmt* selectStatement; - boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); - boost::optional<long long> contactID = getIDFromJID(contactJID.toBare()); - - if (!selfID || !contactID) { - // JIDs missing from the database - return boost::gregorian::date(boost::gregorian::not_a_date_time); - } - - std::string selectQuery = "SELECT time FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type); - if (contactJID.isBare()) { - // match only bare jid - selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" + - boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" + - boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))"; - } - else { - // match resource too - selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" + - boost::lexical_cast<std::string>(*contactID) +" AND toResource='" + - getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" + - boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" + - getEscapedString(contactJID.getResource()) + "') AND toBare=" + - boost::lexical_cast<std::string>(*selfID) + ")))"; - } - - int timeStamp = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds() + (reverseOrder ? 0 : 86400); - - selectQuery += " AND time" + (reverseOrder ? std::string("<") : std::string(">")) + boost::lexical_cast<std::string>(timeStamp); - selectQuery += " ORDER BY time " + (reverseOrder ? std::string("DESC") : std::string("ASC")) + " LIMIT 1"; - - int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); - if (r != SQLITE_OK) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } - - r = sqlite3_step(selectStatement); - if (r == SQLITE_ROW) { - int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0)); - boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); - std::cout << "next day is: " << time.date() << "\n"; - return time.date(); - } - - return boost::gregorian::date(boost::gregorian::not_a_date_time); + sqlite3_stmt* selectStatement; + boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); + boost::optional<long long> contactID = getIDFromJID(contactJID.toBare()); + + if (!selfID || !contactID) { + // JIDs missing from the database + return boost::gregorian::date(boost::gregorian::not_a_date_time); + } + + std::string selectQuery = "SELECT time FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type); + if (contactJID.isBare()) { + // match only bare jid + selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" + + boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" + + boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))"; + } + else { + // match resource too + selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" + + boost::lexical_cast<std::string>(*contactID) +" AND toResource='" + + getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" + + boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" + + getEscapedString(contactJID.getResource()) + "') AND toBare=" + + boost::lexical_cast<std::string>(*selfID) + ")))"; + } + + int timeStamp = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds() + (reverseOrder ? 0 : 86400); + + selectQuery += " AND time" + (reverseOrder ? std::string("<") : std::string(">")) + boost::lexical_cast<std::string>(timeStamp); + selectQuery += " ORDER BY time " + (reverseOrder ? std::string("DESC") : std::string("ASC")) + " LIMIT 1"; + + int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); + if (r != SQLITE_OK) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } + + r = sqlite3_step(selectStatement); + if (r == SQLITE_ROW) { + int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0)); + boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); + std::cout << "next day is: " << time.date() << "\n"; + return time.date(); + } + + return boost::gregorian::date(boost::gregorian::not_a_date_time); } std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const { - boost::gregorian::date nextDate = getNextDateWithLogs(selfJID, contactJID, type, date, false); + boost::gregorian::date nextDate = getNextDateWithLogs(selfJID, contactJID, type, date, false); - if (nextDate.is_not_a_date()) { - return std::vector<HistoryMessage>(); - } + if (nextDate.is_not_a_date()) { + return std::vector<HistoryMessage>(); + } - return getMessagesFromDate(selfJID, contactJID, type, nextDate); + return getMessagesFromDate(selfJID, contactJID, type, nextDate); } std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const { - boost::gregorian::date previousDate = getNextDateWithLogs(selfJID, contactJID, type, date, true); + boost::gregorian::date previousDate = getNextDateWithLogs(selfJID, contactJID, type, date, true); - if (previousDate.is_not_a_date()) { - return std::vector<HistoryMessage>(); - } + if (previousDate.is_not_a_date()) { + return std::vector<HistoryMessage>(); + } - return getMessagesFromDate(selfJID, contactJID, type, previousDate); + return getMessagesFromDate(selfJID, contactJID, type, previousDate); } boost::posix_time::ptime SQLiteHistoryStorage::getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const { - boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); - boost::optional<long long> mucID = getIDFromJID(mucJID.toBare()); + boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); + boost::optional<long long> mucID = getIDFromJID(mucJID.toBare()); - if (!selfID || !mucID) { - // JIDs missing from the database - return boost::posix_time::ptime(boost::posix_time::not_a_date_time); - } + if (!selfID || !mucID) { + // JIDs missing from the database + return boost::posix_time::ptime(boost::posix_time::not_a_date_time); + } - sqlite3_stmt* selectStatement; - std::string selectQuery = "SELECT messages.'time', messages.'offset' from messages WHERE type=1 AND (toBare=" + - boost::lexical_cast<std::string>(*selfID) + " AND fromBare=" + - boost::lexical_cast<std::string>(*mucID) + ") ORDER BY time DESC LIMIT 1"; + sqlite3_stmt* selectStatement; + std::string selectQuery = "SELECT messages.'time', messages.'offset' from messages WHERE type=1 AND (toBare=" + + boost::lexical_cast<std::string>(*selfID) + " AND fromBare=" + + boost::lexical_cast<std::string>(*mucID) + ") ORDER BY time DESC LIMIT 1"; - int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); - if (r != SQLITE_OK) { - std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; - } + int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL); + if (r != SQLITE_OK) { + std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl; + } - r = sqlite3_step(selectStatement); - if (r == SQLITE_ROW) { - int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0)); - boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); - int offset = sqlite3_column_int(selectStatement, 1); + r = sqlite3_step(selectStatement); + if (r == SQLITE_ROW) { + int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0)); + boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch)); + int offset = sqlite3_column_int(selectStatement, 1); - return time - boost::posix_time::hours(offset); - } + return time - boost::posix_time::hours(offset); + } - return boost::posix_time::ptime(boost::posix_time::not_a_date_time); + return boost::posix_time::ptime(boost::posix_time::not_a_date_time); } void SQLiteHistoryStorage::run() { diff --git a/Swiften/History/SQLiteHistoryStorage.h b/Swiften/History/SQLiteHistoryStorage.h index 95b13b9..b0223f5 100644 --- a/Swiften/History/SQLiteHistoryStorage.h +++ b/Swiften/History/SQLiteHistoryStorage.h @@ -16,28 +16,28 @@ struct sqlite3; namespace Swift { - class SWIFTEN_API SQLiteHistoryStorage : public HistoryStorage { - public: - SQLiteHistoryStorage(const boost::filesystem::path& file); - ~SQLiteHistoryStorage(); - - void addMessage(const HistoryMessage& message); - ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const; - std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; - std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; - std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; - boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const; - - private: - void run(); - boost::gregorian::date getNextDateWithLogs(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date, bool reverseOrder) const; - long long getIDForJID(const JID&); - long long addJID(const JID&); - - boost::optional<JID> getJIDFromID(long long id) const; - boost::optional<long long> getIDFromJID(const JID& jid) const; - - sqlite3* db_; - boost::thread* thread_; - }; + class SWIFTEN_API SQLiteHistoryStorage : public HistoryStorage { + public: + SQLiteHistoryStorage(const boost::filesystem::path& file); + ~SQLiteHistoryStorage(); + + void addMessage(const HistoryMessage& message); + ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const; + std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; + std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; + std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; + boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const; + + private: + void run(); + boost::gregorian::date getNextDateWithLogs(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date, bool reverseOrder) const; + long long getIDForJID(const JID&); + long long addJID(const JID&); + + boost::optional<JID> getJIDFromID(long long id) const; + boost::optional<long long> getIDFromJID(const JID& jid) const; + + sqlite3* db_; + boost::thread* thread_; + }; } diff --git a/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp b/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp index 560c992..5968d7e 100644 --- a/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp +++ b/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp @@ -14,103 +14,103 @@ using namespace Swift; class SQLiteHistoryManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SQLiteHistoryManagerTest); - //CPPUNIT_TEST(testAddMessage); - //CPPUNIT_TEST(testAddMessage_TwoMessages); - //CPPUNIT_TEST(testGetIDForJID_SameJID); - //CPPUNIT_TEST(testGetIDForJID_DifferentJIDs); - //CPPUNIT_TEST(getJIDFromID); - //CPPUNIT_TEST(getJIDFromID_UnexistingID); - //CPPUNIT_TEST(getIDFromJID); - //CPPUNIT_TEST(getIDFromJID_UnexistingJID); - //CPPUNIT_TEST_SUITE_END(); - - public: - SQLiteHistoryManagerTest() {} - - void setUp() { - } - - void tearDown() { - } - - void testAddMessage() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - HistoryMessage testMessage("Test", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03")); - testling->addMessage(testMessage); - - std::vector<HistoryMessage> messages = testling->getMessages(); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(messages.size())); - CPPUNIT_ASSERT(testMessage == messages[0]); - } - - void testAddMessage_TwoMessages() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - HistoryMessage testMessage1("Test1", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03")); - testling->addMessage(testMessage1); - HistoryMessage testMessage2("Test2", JID("fum@baz.org"), JID("foo@bar.com"), boost::posix_time::time_from_string("1975-03-09 22:04")); - testling->addMessage(testMessage2); - - std::vector<HistoryMessage> messages = testling->getMessages(); - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(messages.size())); - CPPUNIT_ASSERT(testMessage1 == messages[0]); - CPPUNIT_ASSERT(testMessage2 == messages[1]); - } - - void testGetIDForJID_SameJID() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - int id1 = testling->getIDForJID(JID("foo@bar.com")); - int id2 = testling->getIDForJID(JID("foo@bar.com")); - - CPPUNIT_ASSERT_EQUAL(id1, id2); - } - - void testGetIDForJID_DifferentJIDs() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - int id1 = testling->getIDForJID(JID("foo@bar.com")); - int id2 = testling->getIDForJID(JID("foo@baz.com")); - - CPPUNIT_ASSERT(id1 != id2); - } - - void getJIDFromID() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - int id = testling->addJID(JID("foo@bar.com")); - - boost::optional<JID> result(testling->getJIDFromID(id)); - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), *result); - } - - void getJIDFromID_UnexistingID() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - - boost::optional<JID> result(testling->getJIDFromID(1)); - - CPPUNIT_ASSERT(!result); - } - - void getIDFromJID() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - int id = testling->addJID(JID("foo@bar.com")); - - boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com"))); - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(id, *result); - } - - void getIDFromJID_UnexistingJID() { - boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); - - boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com"))); - - CPPUNIT_ASSERT(!result); - } - - private: - SQLiteHistoryManager* createHistoryManager() { - return new SQLiteHistoryManager(":memory:"); - } + CPPUNIT_TEST_SUITE(SQLiteHistoryManagerTest); + //CPPUNIT_TEST(testAddMessage); + //CPPUNIT_TEST(testAddMessage_TwoMessages); + //CPPUNIT_TEST(testGetIDForJID_SameJID); + //CPPUNIT_TEST(testGetIDForJID_DifferentJIDs); + //CPPUNIT_TEST(getJIDFromID); + //CPPUNIT_TEST(getJIDFromID_UnexistingID); + //CPPUNIT_TEST(getIDFromJID); + //CPPUNIT_TEST(getIDFromJID_UnexistingJID); + //CPPUNIT_TEST_SUITE_END(); + + public: + SQLiteHistoryManagerTest() {} + + void setUp() { + } + + void tearDown() { + } + + void testAddMessage() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + HistoryMessage testMessage("Test", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03")); + testling->addMessage(testMessage); + + std::vector<HistoryMessage> messages = testling->getMessages(); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(messages.size())); + CPPUNIT_ASSERT(testMessage == messages[0]); + } + + void testAddMessage_TwoMessages() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + HistoryMessage testMessage1("Test1", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03")); + testling->addMessage(testMessage1); + HistoryMessage testMessage2("Test2", JID("fum@baz.org"), JID("foo@bar.com"), boost::posix_time::time_from_string("1975-03-09 22:04")); + testling->addMessage(testMessage2); + + std::vector<HistoryMessage> messages = testling->getMessages(); + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(messages.size())); + CPPUNIT_ASSERT(testMessage1 == messages[0]); + CPPUNIT_ASSERT(testMessage2 == messages[1]); + } + + void testGetIDForJID_SameJID() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + int id1 = testling->getIDForJID(JID("foo@bar.com")); + int id2 = testling->getIDForJID(JID("foo@bar.com")); + + CPPUNIT_ASSERT_EQUAL(id1, id2); + } + + void testGetIDForJID_DifferentJIDs() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + int id1 = testling->getIDForJID(JID("foo@bar.com")); + int id2 = testling->getIDForJID(JID("foo@baz.com")); + + CPPUNIT_ASSERT(id1 != id2); + } + + void getJIDFromID() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + int id = testling->addJID(JID("foo@bar.com")); + + boost::optional<JID> result(testling->getJIDFromID(id)); + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), *result); + } + + void getJIDFromID_UnexistingID() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + + boost::optional<JID> result(testling->getJIDFromID(1)); + + CPPUNIT_ASSERT(!result); + } + + void getIDFromJID() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + int id = testling->addJID(JID("foo@bar.com")); + + boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com"))); + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(id, *result); + } + + void getIDFromJID_UnexistingJID() { + boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager()); + + boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com"))); + + CPPUNIT_ASSERT(!result); + } + + private: + SQLiteHistoryManager* createHistoryManager() { + return new SQLiteHistoryManager(":memory:"); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(SQLiteHistoryManagerTest); diff --git a/Swiften/IDN/ICUConverter.cpp b/Swiften/IDN/ICUConverter.cpp index 74b2813..b83739c 100644 --- a/Swiften/IDN/ICUConverter.cpp +++ b/Swiften/IDN/ICUConverter.cpp @@ -19,139 +19,139 @@ using namespace Swift; using boost::numeric_cast; namespace { - typedef std::vector<UChar, SafeAllocator<UChar> > ICUString; - - const char* toConstCharArray(const std::string& input) { - return input.c_str(); - } - - const char* toConstCharArray(const std::vector<unsigned char, SafeAllocator<unsigned char> >& input) { - return reinterpret_cast<const char*>(vecptr(input)); - } - - template<typename T> - ICUString convertToICUString(const T& s) { - ICUString result; - result.resize(s.size()); - UErrorCode status = U_ZERO_ERROR; - int32_t icuResultLength = numeric_cast<int32_t>(result.size()); - u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status); - if (status == U_BUFFER_OVERFLOW_ERROR) { - status = U_ZERO_ERROR; - result.resize(numeric_cast<size_t>(icuResultLength)); - u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status); - } - if (U_FAILURE(status)) { - return ICUString(); - } - result.resize(numeric_cast<size_t>(icuResultLength)); - return result; - } - - std::vector<char, SafeAllocator<char> > convertToArray(const ICUString& input) { - std::vector<char, SafeAllocator<char> > result; - result.resize(input.size()); - UErrorCode status = U_ZERO_ERROR; - int32_t inputLength = numeric_cast<int32_t>(result.size()); - u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status); - if (status == U_BUFFER_OVERFLOW_ERROR) { - status = U_ZERO_ERROR; - result.resize(numeric_cast<size_t>(inputLength)); - u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status); - } - if (U_FAILURE(status)) { - return std::vector<char, SafeAllocator<char> >(); - } - - result.resize(numeric_cast<size_t>(inputLength) + 1); - result[result.size() - 1] = '\0'; - return result; - } - - std::string convertToString(const ICUString& input) { - return std::string(vecptr(convertToArray(input))); - } - - UStringPrepProfileType getICUProfileType(IDNConverter::StringPrepProfile profile) { - switch(profile) { - case IDNConverter::NamePrep: return USPREP_RFC3491_NAMEPREP; - case IDNConverter::XMPPNodePrep: return USPREP_RFC3920_NODEPREP; - case IDNConverter::XMPPResourcePrep: return USPREP_RFC3920_RESOURCEPREP; - case IDNConverter::SASLPrep: return USPREP_RFC4013_SASLPREP; - } - assert(false); - return USPREP_RFC3491_NAMEPREP; - } - - template<typename StringType> - std::vector<char, SafeAllocator<char> > getStringPreparedDetail(const StringType& s, IDNConverter::StringPrepProfile profile) { - UErrorCode status = U_ZERO_ERROR; - - boost::shared_ptr<UStringPrepProfile> icuProfile(usprep_openByType(getICUProfileType(profile), &status), usprep_close); - assert(U_SUCCESS(status)); - - ICUString icuInput = convertToICUString(s); - ICUString icuResult; - UParseError parseError; - icuResult.resize(icuInput.size()); - int32_t icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status); - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - if (status == U_BUFFER_OVERFLOW_ERROR) { - status = U_ZERO_ERROR; - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status); - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - } - if (U_FAILURE(status)) { - return std::vector<char, SafeAllocator<char> >(); - } - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - - return convertToArray(icuResult); - } + typedef std::vector<UChar, SafeAllocator<UChar> > ICUString; + + const char* toConstCharArray(const std::string& input) { + return input.c_str(); + } + + const char* toConstCharArray(const std::vector<unsigned char, SafeAllocator<unsigned char> >& input) { + return reinterpret_cast<const char*>(vecptr(input)); + } + + template<typename T> + ICUString convertToICUString(const T& s) { + ICUString result; + result.resize(s.size()); + UErrorCode status = U_ZERO_ERROR; + int32_t icuResultLength = numeric_cast<int32_t>(result.size()); + u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status); + if (status == U_BUFFER_OVERFLOW_ERROR) { + status = U_ZERO_ERROR; + result.resize(numeric_cast<size_t>(icuResultLength)); + u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status); + } + if (U_FAILURE(status)) { + return ICUString(); + } + result.resize(numeric_cast<size_t>(icuResultLength)); + return result; + } + + std::vector<char, SafeAllocator<char> > convertToArray(const ICUString& input) { + std::vector<char, SafeAllocator<char> > result; + result.resize(input.size()); + UErrorCode status = U_ZERO_ERROR; + int32_t inputLength = numeric_cast<int32_t>(result.size()); + u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status); + if (status == U_BUFFER_OVERFLOW_ERROR) { + status = U_ZERO_ERROR; + result.resize(numeric_cast<size_t>(inputLength)); + u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status); + } + if (U_FAILURE(status)) { + return std::vector<char, SafeAllocator<char> >(); + } + + result.resize(numeric_cast<size_t>(inputLength) + 1); + result[result.size() - 1] = '\0'; + return result; + } + + std::string convertToString(const ICUString& input) { + return std::string(vecptr(convertToArray(input))); + } + + UStringPrepProfileType getICUProfileType(IDNConverter::StringPrepProfile profile) { + switch(profile) { + case IDNConverter::NamePrep: return USPREP_RFC3491_NAMEPREP; + case IDNConverter::XMPPNodePrep: return USPREP_RFC3920_NODEPREP; + case IDNConverter::XMPPResourcePrep: return USPREP_RFC3920_RESOURCEPREP; + case IDNConverter::SASLPrep: return USPREP_RFC4013_SASLPREP; + } + assert(false); + return USPREP_RFC3491_NAMEPREP; + } + + template<typename StringType> + std::vector<char, SafeAllocator<char> > getStringPreparedDetail(const StringType& s, IDNConverter::StringPrepProfile profile) { + UErrorCode status = U_ZERO_ERROR; + + boost::shared_ptr<UStringPrepProfile> icuProfile(usprep_openByType(getICUProfileType(profile), &status), usprep_close); + assert(U_SUCCESS(status)); + + ICUString icuInput = convertToICUString(s); + ICUString icuResult; + UParseError parseError; + icuResult.resize(icuInput.size()); + int32_t icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status); + icuResult.resize(numeric_cast<size_t>(icuResultLength)); + if (status == U_BUFFER_OVERFLOW_ERROR) { + status = U_ZERO_ERROR; + icuResult.resize(numeric_cast<size_t>(icuResultLength)); + icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status); + icuResult.resize(numeric_cast<size_t>(icuResultLength)); + } + if (U_FAILURE(status)) { + return std::vector<char, SafeAllocator<char> >(); + } + icuResult.resize(numeric_cast<size_t>(icuResultLength)); + + return convertToArray(icuResult); + } } namespace Swift { std::string ICUConverter::getStringPrepared(const std::string& s, StringPrepProfile profile) { - if (s.empty()) { - return ""; - } - std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile); - if (preparedData.empty()) { - throw std::exception(); - } - return std::string(vecptr(preparedData)); + if (s.empty()) { + return ""; + } + std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile); + if (preparedData.empty()) { + throw std::exception(); + } + return std::string(vecptr(preparedData)); } SafeByteArray ICUConverter::getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) { - if (s.empty()) { - return SafeByteArray(); - } - std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile); - if (preparedData.empty()) { - throw std::exception(); - } - return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData))); + if (s.empty()) { + return SafeByteArray(); + } + std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile); + if (preparedData.empty()) { + throw std::exception(); + } + return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData))); } boost::optional<std::string> ICUConverter::getIDNAEncoded(const std::string& domain) { - UErrorCode status = U_ZERO_ERROR; - ICUString icuInput = convertToICUString(domain); - ICUString icuResult; - icuResult.resize(icuInput.size()); - UParseError parseError; - int32_t icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status); - if (status == U_BUFFER_OVERFLOW_ERROR) { - status = U_ZERO_ERROR; - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status); - } - if (U_FAILURE(status)) { - return boost::optional<std::string>(); - } - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - return convertToString(icuResult); + UErrorCode status = U_ZERO_ERROR; + ICUString icuInput = convertToICUString(domain); + ICUString icuResult; + icuResult.resize(icuInput.size()); + UParseError parseError; + int32_t icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status); + if (status == U_BUFFER_OVERFLOW_ERROR) { + status = U_ZERO_ERROR; + icuResult.resize(numeric_cast<size_t>(icuResultLength)); + icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status); + } + if (U_FAILURE(status)) { + return boost::optional<std::string>(); + } + icuResult.resize(numeric_cast<size_t>(icuResultLength)); + return convertToString(icuResult); } } diff --git a/Swiften/IDN/ICUConverter.h b/Swiften/IDN/ICUConverter.h index da66d2f..0a0b0d3 100644 --- a/Swiften/IDN/ICUConverter.h +++ b/Swiften/IDN/ICUConverter.h @@ -13,11 +13,11 @@ #include <Swiften/IDN/IDNConverter.h> namespace Swift { - class SWIFTEN_API ICUConverter : public IDNConverter { - public: - virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; - virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; + class SWIFTEN_API ICUConverter : public IDNConverter { + public: + virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; + virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; - virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE; - }; + virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE; + }; } diff --git a/Swiften/IDN/IDNConverter.h b/Swiften/IDN/IDNConverter.h index cbd5124..27ddd78 100644 --- a/Swiften/IDN/IDNConverter.h +++ b/Swiften/IDN/IDNConverter.h @@ -14,21 +14,21 @@ #include <Swiften/Base/SafeByteArray.h> namespace Swift { - class SWIFTEN_API IDNConverter { - public: - virtual ~IDNConverter(); - - enum StringPrepProfile { - NamePrep, - XMPPNodePrep, - XMPPResourcePrep, - SASLPrep - }; - - virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) = 0; - virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) = 0; - - // Thread-safe - virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) = 0; - }; + class SWIFTEN_API IDNConverter { + public: + virtual ~IDNConverter(); + + enum StringPrepProfile { + NamePrep, + XMPPNodePrep, + XMPPResourcePrep, + SASLPrep + }; + + virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) = 0; + virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) = 0; + + // Thread-safe + virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) = 0; + }; } diff --git a/Swiften/IDN/LibIDNConverter.cpp b/Swiften/IDN/LibIDNConverter.cpp index 78303b1..334f43b 100644 --- a/Swiften/IDN/LibIDNConverter.cpp +++ b/Swiften/IDN/LibIDNConverter.cpp @@ -7,8 +7,8 @@ #include <Swiften/IDN/LibIDNConverter.h> extern "C" { - #include <stringprep.h> - #include <idna.h> + #include <stringprep.h> + #include <idna.h> } #include <cassert> @@ -24,64 +24,64 @@ extern "C" { using namespace Swift; namespace { - static const int MAX_STRINGPREP_SIZE = 1024; + static const int MAX_STRINGPREP_SIZE = 1024; - const Stringprep_profile* getLibIDNProfile(IDNConverter::StringPrepProfile profile) { - switch(profile) { - case IDNConverter::NamePrep: return stringprep_nameprep; - case IDNConverter::XMPPNodePrep: return stringprep_xmpp_nodeprep; - case IDNConverter::XMPPResourcePrep: return stringprep_xmpp_resourceprep; - case IDNConverter::SASLPrep: return stringprep_saslprep; - } - assert(false); - return 0; - } + const Stringprep_profile* getLibIDNProfile(IDNConverter::StringPrepProfile profile) { + switch(profile) { + case IDNConverter::NamePrep: return stringprep_nameprep; + case IDNConverter::XMPPNodePrep: return stringprep_xmpp_nodeprep; + case IDNConverter::XMPPResourcePrep: return stringprep_xmpp_resourceprep; + case IDNConverter::SASLPrep: return stringprep_saslprep; + } + assert(false); + return 0; + } - template<typename StringType, typename ContainerType> - ContainerType getStringPreparedInternal(const StringType& s, IDNConverter::StringPrepProfile profile) { - ContainerType input(s.begin(), s.end()); - if (!UTF8IsValid(s.data(), s.size())) { - return ContainerType(); - } + template<typename StringType, typename ContainerType> + ContainerType getStringPreparedInternal(const StringType& s, IDNConverter::StringPrepProfile profile) { + ContainerType input(s.begin(), s.end()); + if (!UTF8IsValid(s.data(), s.size())) { + return ContainerType(); + } - input.resize(MAX_STRINGPREP_SIZE); - if (stringprep(&input[0], MAX_STRINGPREP_SIZE, static_cast<Stringprep_profile_flags>(0), getLibIDNProfile(profile)) == 0) { - return input; - } - else { - return ContainerType(); - } - } + input.resize(MAX_STRINGPREP_SIZE); + if (stringprep(&input[0], MAX_STRINGPREP_SIZE, static_cast<Stringprep_profile_flags>(0), getLibIDNProfile(profile)) == 0) { + return input; + } + else { + return ContainerType(); + } + } } namespace Swift { std::string LibIDNConverter::getStringPrepared(const std::string& s, StringPrepProfile profile) { - std::vector<char> preparedData = getStringPreparedInternal< std::string, std::vector<char> >(s, profile); - if (preparedData.empty()) { - throw std::exception(); - } - return std::string(vecptr(preparedData)); + std::vector<char> preparedData = getStringPreparedInternal< std::string, std::vector<char> >(s, profile); + if (preparedData.empty()) { + throw std::exception(); + } + return std::string(vecptr(preparedData)); } SafeByteArray LibIDNConverter::getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) { - std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedInternal<SafeByteArray, std::vector<char, SafeAllocator<char> > >(s, profile); - if (preparedData.empty()) { - throw std::exception(); - } - return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData))); + std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedInternal<SafeByteArray, std::vector<char, SafeAllocator<char> > >(s, profile); + if (preparedData.empty()) { + throw std::exception(); + } + return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData))); } boost::optional<std::string> LibIDNConverter::getIDNAEncoded(const std::string& domain) { - char* output; - if (idna_to_ascii_8z(domain.c_str(), &output, IDNA_USE_STD3_ASCII_RULES) == IDNA_SUCCESS) { - std::string result(output); - free(output); - return result; - } - else { - return boost::optional<std::string>(); - } + char* output; + if (idna_to_ascii_8z(domain.c_str(), &output, IDNA_USE_STD3_ASCII_RULES) == IDNA_SUCCESS) { + std::string result(output); + free(output); + return result; + } + else { + return boost::optional<std::string>(); + } } } diff --git a/Swiften/IDN/LibIDNConverter.h b/Swiften/IDN/LibIDNConverter.h index fe68710..3f1d1f7 100644 --- a/Swiften/IDN/LibIDNConverter.h +++ b/Swiften/IDN/LibIDNConverter.h @@ -13,12 +13,12 @@ #include <Swiften/IDN/IDNConverter.h> namespace Swift { - class SWIFTEN_API LibIDNConverter : public IDNConverter { - public: - virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; - virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; + class SWIFTEN_API LibIDNConverter : public IDNConverter { + public: + virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; + virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; - virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE; - }; + virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE; + }; } diff --git a/Swiften/IDN/PlatformIDNConverter.cpp b/Swiften/IDN/PlatformIDNConverter.cpp index 4735d8e..041c934 100644 --- a/Swiften/IDN/PlatformIDNConverter.cpp +++ b/Swiften/IDN/PlatformIDNConverter.cpp @@ -15,14 +15,14 @@ namespace Swift { IDNConverter* PlatformIDNConverter::create() { #if defined(HAVE_LIBIDN) - return new LibIDNConverter(); + return new LibIDNConverter(); #elif defined(HAVE_ICU) - return new ICUConverter(); + return new ICUConverter(); #else #if defined(NEED_IDN) #error "No IDN implementation" #endif - return 0; + return 0; #endif } diff --git a/Swiften/IDN/PlatformIDNConverter.h b/Swiften/IDN/PlatformIDNConverter.h index eaa7aa0..704f7a7 100644 --- a/Swiften/IDN/PlatformIDNConverter.h +++ b/Swiften/IDN/PlatformIDNConverter.h @@ -9,9 +9,9 @@ #include <Swiften/Base/API.h> namespace Swift { - class IDNConverter; + class IDNConverter; - namespace PlatformIDNConverter { - SWIFTEN_API IDNConverter* create(); - } + namespace PlatformIDNConverter { + SWIFTEN_API IDNConverter* create(); + } } diff --git a/Swiften/IDN/UTF8Validator.h b/Swiften/IDN/UTF8Validator.h index 5df8769..d912ef9 100644 --- a/Swiften/IDN/UTF8Validator.h +++ b/Swiften/IDN/UTF8Validator.h @@ -13,55 +13,55 @@ namespace Swift { // UTF-8 validation based on the description in https://tools.ietf.org/html/rfc3629#section-3 . template <typename CharType> bool UTF8IsValid(const CharType* data, size_t length) { - bool isValid = true; - const CharType* current = data; - const CharType* end = data + length; - while (isValid && (current < end)) { - // one byte sequences - if ((*current & 0x80) == 0x0) { - current++; - continue; - } - // longer byte sequences - else { - // two byte sequences - if ((*current & 0xE0) == 0xC0) { - current++; - if ( (current < end) && ((*current & 0xC0) == 0x80) ) { - current++; - continue; - } - } - // three byte sequences - else if ((*current & 0xF0) == 0xE0) { - current++; - if ( ((current + 1) < end) && ((*current & 0xC0) == 0x80) ) { - current++; - if ((*current & 0xC0) == 0x80) { - current++; - continue; - } - } - } - // four byte sequences - else if ((*current & 0xF8) == 0xF0) { - current++; - if ( ((current + 2) < end) && ((*current & 0xC0) == 0x80) ) { - current++; - if ((*current & 0xC0) == 0x80) { - current++; - if ((*current & 0xC0) == 0x80) { - current++; - continue; - } - } - } - } - // invalid sequences - isValid = false; - } - } - return isValid; + bool isValid = true; + const CharType* current = data; + const CharType* end = data + length; + while (isValid && (current < end)) { + // one byte sequences + if ((*current & 0x80) == 0x0) { + current++; + continue; + } + // longer byte sequences + else { + // two byte sequences + if ((*current & 0xE0) == 0xC0) { + current++; + if ( (current < end) && ((*current & 0xC0) == 0x80) ) { + current++; + continue; + } + } + // three byte sequences + else if ((*current & 0xF0) == 0xE0) { + current++; + if ( ((current + 1) < end) && ((*current & 0xC0) == 0x80) ) { + current++; + if ((*current & 0xC0) == 0x80) { + current++; + continue; + } + } + } + // four byte sequences + else if ((*current & 0xF8) == 0xF0) { + current++; + if ( ((current + 2) < end) && ((*current & 0xC0) == 0x80) ) { + current++; + if ((*current & 0xC0) == 0x80) { + current++; + if ((*current & 0xC0) == 0x80) { + current++; + continue; + } + } + } + } + // invalid sequences + isValid = false; + } + } + return isValid; } } diff --git a/Swiften/IDN/UnitTest/IDNConverterTest.cpp b/Swiften/IDN/UnitTest/IDNConverterTest.cpp index 7d1bcf0..e0c97b5 100644 --- a/Swiften/IDN/UnitTest/IDNConverterTest.cpp +++ b/Swiften/IDN/UnitTest/IDNConverterTest.cpp @@ -15,50 +15,50 @@ using namespace Swift; class IDNConverterTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(IDNConverterTest); - CPPUNIT_TEST(testStringPrep); - CPPUNIT_TEST(testStringPrep_Empty); - CPPUNIT_TEST(testGetEncoded); - CPPUNIT_TEST(testGetEncoded_International); - CPPUNIT_TEST(testGetEncoded_Invalid); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(IDNConverterTest); + CPPUNIT_TEST(testStringPrep); + CPPUNIT_TEST(testStringPrep_Empty); + CPPUNIT_TEST(testGetEncoded); + CPPUNIT_TEST(testGetEncoded_International); + CPPUNIT_TEST(testGetEncoded_Invalid); + CPPUNIT_TEST_SUITE_END(); - public: - void setUp() { - testling = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create()); - } + public: + void setUp() { + testling = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create()); + } - void testStringPrep() { - std::string result = testling->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep); + void testStringPrep() { + std::string result = testling->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep); - CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), result); - } + CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), result); + } - void testStringPrep_Empty() { - CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::NamePrep)); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPNodePrep)); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPResourcePrep)); - } + void testStringPrep_Empty() { + CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::NamePrep)); + CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPNodePrep)); + CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPResourcePrep)); + } - void testGetEncoded() { - boost::optional<std::string> result = testling->getIDNAEncoded("www.swift.im"); - CPPUNIT_ASSERT(!!result); - CPPUNIT_ASSERT_EQUAL(std::string("www.swift.im"), *result); - } + void testGetEncoded() { + boost::optional<std::string> result = testling->getIDNAEncoded("www.swift.im"); + CPPUNIT_ASSERT(!!result); + CPPUNIT_ASSERT_EQUAL(std::string("www.swift.im"), *result); + } - void testGetEncoded_International() { - boost::optional<std::string> result = testling->getIDNAEncoded("www.tron\xc3\x87on.com"); - CPPUNIT_ASSERT(!!result); - CPPUNIT_ASSERT_EQUAL(std::string("www.xn--tronon-zua.com"), *result); - } + void testGetEncoded_International() { + boost::optional<std::string> result = testling->getIDNAEncoded("www.tron\xc3\x87on.com"); + CPPUNIT_ASSERT(!!result); + CPPUNIT_ASSERT_EQUAL(std::string("www.xn--tronon-zua.com"), *result); + } - void testGetEncoded_Invalid() { - boost::optional<std::string> result = testling->getIDNAEncoded("www.foo,bar.com"); - CPPUNIT_ASSERT(!result); - } + void testGetEncoded_Invalid() { + boost::optional<std::string> result = testling->getIDNAEncoded("www.foo,bar.com"); + CPPUNIT_ASSERT(!result); + } - private: - boost::shared_ptr<IDNConverter> testling; + private: + boost::shared_ptr<IDNConverter> testling; }; CPPUNIT_TEST_SUITE_REGISTRATION(IDNConverterTest); diff --git a/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp b/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp index 0295757..6db7770 100644 --- a/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp +++ b/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp @@ -12,42 +12,42 @@ using namespace Swift; class UTF8ValidatorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(UTF8ValidatorTest); + CPPUNIT_TEST_SUITE(UTF8ValidatorTest); - CPPUNIT_TEST(testValidUTF8Sequences); - CPPUNIT_TEST(testInvalidUTF8Sequences); + CPPUNIT_TEST(testValidUTF8Sequences); + CPPUNIT_TEST(testInvalidUTF8Sequences); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE_END(); public: - void testValidUTF8Sequences() { - { - unsigned char test[] = {0x74, 0x65, 0x73, 0x74}; - CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test))); - } - - { - unsigned char test[] = {0xf4, 0x8f, 0x80, 0xbf}; - CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test))); - } - } - - void testInvalidUTF8Sequences() { - { - unsigned char test[] = {0x41, 0xC2, 0x3E, 0x42}; - CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test))); - } - - { - unsigned char test[] = {0xf4}; - CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test))); - } - - { - unsigned char test[] = {0xf4, 0x8f, 0x65, 0x73, 0x80, 0xbf}; - CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test))); - } - } + void testValidUTF8Sequences() { + { + unsigned char test[] = {0x74, 0x65, 0x73, 0x74}; + CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test))); + } + + { + unsigned char test[] = {0xf4, 0x8f, 0x80, 0xbf}; + CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test))); + } + } + + void testInvalidUTF8Sequences() { + { + unsigned char test[] = {0x41, 0xC2, 0x3E, 0x42}; + CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test))); + } + + { + unsigned char test[] = {0xf4}; + CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test))); + } + + { + unsigned char test[] = {0xf4, 0x8f, 0x65, 0x73, 0x80, 0xbf}; + CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test))); + } + } }; diff --git a/Swiften/JID/JID.cpp b/Swiften/JID/JID.cpp index 37fb755..ae08386 100644 --- a/Swiften/JID/JID.cpp +++ b/Swiften/JID/JID.cpp @@ -47,283 +47,283 @@ static IDNConverter* idnConverter = NULL; #ifndef SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER namespace { - struct IDNInitializer { - IDNInitializer() : defaultIDNConverter(PlatformIDNConverter::create()) { - idnConverter = defaultIDNConverter.get(); - } - boost::shared_ptr<IDNConverter> defaultIDNConverter; - } initializer; + struct IDNInitializer { + IDNInitializer() : defaultIDNConverter(PlatformIDNConverter::create()) { + idnConverter = defaultIDNConverter.get(); + } + boost::shared_ptr<IDNConverter> defaultIDNConverter; + } initializer; } #endif static std::string getEscaped(char c) { - return makeString() << '\\' << std::hex << static_cast<int>(c); + return makeString() << '\\' << std::hex << static_cast<int>(c); } static bool getEscapeSequenceValue(const std::string& sequence, unsigned char& value) { - std::stringstream s; - unsigned int v; - s << std::hex << sequence; - s >> v; - value = static_cast<unsigned char>(v); - return (!s.fail() && !s.bad() && (value == 0x5C || std::find(escapedChars.begin(), escapedChars.end(), value) != escapedChars.end())); + std::stringstream s; + unsigned int v; + s << std::hex << sequence; + s >> v; + value = static_cast<unsigned char>(v); + return (!s.fail() && !s.bad() && (value == 0x5C || std::find(escapedChars.begin(), escapedChars.end(), value) != escapedChars.end())); } // Disabling this code for now, since GCC4.5+boost1.42 (on ubuntu) seems to // result in a bug. Replacing it with naive code. #if 0 struct UnescapedCharacterFinder { - template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) { - for (; begin != end; ++begin) { - if (std::find(escapedChars.begin(), escapedChars.end(), *begin) != escapedChars.end()) { - return boost::iterator_range<Iterator>(begin, begin + 1); - } - else if (*begin == '\\') { - // Check if we have an escaped dissalowed character sequence - Iterator innerBegin = begin + 1; - if (innerBegin != end && innerBegin + 1 != end) { - Iterator innerEnd = innerBegin + 2; - unsigned char value; - if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) { - return boost::iterator_range<Iterator>(begin, begin + 1); - } - } - } - } - return boost::iterator_range<Iterator>(end, end); - } + template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) { + for (; begin != end; ++begin) { + if (std::find(escapedChars.begin(), escapedChars.end(), *begin) != escapedChars.end()) { + return boost::iterator_range<Iterator>(begin, begin + 1); + } + else if (*begin == '\\') { + // Check if we have an escaped dissalowed character sequence + Iterator innerBegin = begin + 1; + if (innerBegin != end && innerBegin + 1 != end) { + Iterator innerEnd = innerBegin + 2; + unsigned char value; + if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) { + return boost::iterator_range<Iterator>(begin, begin + 1); + } + } + } + } + return boost::iterator_range<Iterator>(end, end); + } }; struct UnescapedCharacterFormatter { - template<typename FindResult> std::string operator()(const FindResult& match) const { - std::ostringstream s; - s << '\\' << std::hex << static_cast<int>(*match.begin()); - return s.str(); - } + template<typename FindResult> std::string operator()(const FindResult& match) const { + std::ostringstream s; + s << '\\' << std::hex << static_cast<int>(*match.begin()); + return s.str(); + } }; struct EscapedCharacterFinder { - template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) { - for (; begin != end; ++begin) { - if (*begin == '\\') { - Iterator innerEnd = begin + 1; - for (size_t i = 0; i < 2 && innerEnd != end; ++i, ++innerEnd) { - } - unsigned char value; - if (getEscapeSequenceValue(std::string(begin + 1, innerEnd), value)) { - return boost::iterator_range<Iterator>(begin, innerEnd); - } - } - } - return boost::iterator_range<Iterator>(end, end); - } + template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) { + for (; begin != end; ++begin) { + if (*begin == '\\') { + Iterator innerEnd = begin + 1; + for (size_t i = 0; i < 2 && innerEnd != end; ++i, ++innerEnd) { + } + unsigned char value; + if (getEscapeSequenceValue(std::string(begin + 1, innerEnd), value)) { + return boost::iterator_range<Iterator>(begin, innerEnd); + } + } + } + return boost::iterator_range<Iterator>(end, end); + } }; struct EscapedCharacterFormatter { - template<typename FindResult> std::string operator()(const FindResult& match) const { - unsigned char value; - if (getEscapeSequenceValue(std::string(match.begin() + 1, match.end()), value)) { - return std::string(reinterpret_cast<const char*>(&value), 1); - } - return boost::copy_range<std::string>(match); - } + template<typename FindResult> std::string operator()(const FindResult& match) const { + unsigned char value; + if (getEscapeSequenceValue(std::string(match.begin() + 1, match.end()), value)) { + return std::string(reinterpret_cast<const char*>(&value), 1); + } + return boost::copy_range<std::string>(match); + } }; #endif namespace Swift { JID::JID(const char* jid) : valid_(true) { - assert(jid); - initializeFromString(std::string(jid)); + assert(jid); + initializeFromString(std::string(jid)); } JID::JID(const std::string& jid) : valid_(true) { - initializeFromString(jid); + initializeFromString(jid); } JID::JID(const std::string& node, const std::string& domain) : valid_(true), hasResource_(false) { - nameprepAndSetComponents(node, domain, ""); + nameprepAndSetComponents(node, domain, ""); } JID::JID(const std::string& node, const std::string& domain, const std::string& resource) : valid_(true), hasResource_(true) { - if (resource.empty()) { - valid_ = false; - } - nameprepAndSetComponents(node, domain, resource); + if (resource.empty()) { + valid_ = false; + } + nameprepAndSetComponents(node, domain, resource); } void JID::initializeFromString(const std::string& jid) { - if (String::beginsWith(jid, '@')) { - valid_ = false; - return; - } - - std::string bare, resource; - size_t slashIndex = jid.find('/'); - if (slashIndex != jid.npos) { - hasResource_ = true; - bare = jid.substr(0, slashIndex); - resource = jid.substr(slashIndex + 1, jid.npos); - } - else { - hasResource_ = false; - bare = jid; - } - std::pair<std::string,std::string> nodeAndDomain = String::getSplittedAtFirst(bare, '@'); - if (nodeAndDomain.second.empty()) { - nameprepAndSetComponents("", nodeAndDomain.first, resource); - } - else { - nameprepAndSetComponents(nodeAndDomain.first, nodeAndDomain.second, resource); - } + if (String::beginsWith(jid, '@')) { + valid_ = false; + return; + } + + std::string bare, resource; + size_t slashIndex = jid.find('/'); + if (slashIndex != jid.npos) { + hasResource_ = true; + bare = jid.substr(0, slashIndex); + resource = jid.substr(slashIndex + 1, jid.npos); + } + else { + hasResource_ = false; + bare = jid; + } + std::pair<std::string,std::string> nodeAndDomain = String::getSplittedAtFirst(bare, '@'); + if (nodeAndDomain.second.empty()) { + nameprepAndSetComponents("", nodeAndDomain.first, resource); + } + else { + nameprepAndSetComponents(nodeAndDomain.first, nodeAndDomain.second, resource); + } } void JID::nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource) { - if (domain.empty() || !idnConverter->getIDNAEncoded(domain)) { - valid_ = false; - return; - } + if (domain.empty() || !idnConverter->getIDNAEncoded(domain)) { + valid_ = false; + return; + } #ifndef SWIFTEN_CACHE_JID_PREP - node_ = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep); - domain_ = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep); - resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep); + node_ = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep); + domain_ = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep); + resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep); #else - boost::mutex::scoped_lock lock(namePrepCacheMutex); - - std::pair<PrepCache::iterator, bool> r; - - r = nodePrepCache.insert(std::make_pair(node, std::string())); - if (r.second) { - try { - r.first->second = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep); - } - catch (...) { - nodePrepCache.erase(r.first); - valid_ = false; - return; - } - } - node_ = r.first->second; - - r = domainPrepCache.insert(std::make_pair(domain, std::string())); - if (r.second) { - try { - r.first->second = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep); - } - catch (...) { - domainPrepCache.erase(r.first); - valid_ = false; - return; - } - } - domain_ = r.first->second; - - r = resourcePrepCache.insert(std::make_pair(resource, std::string())); - if (r.second) { - try { - r.first->second = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep); - } - catch (...) { - resourcePrepCache.erase(r.first); - valid_ = false; - return; - } - } - resource_ = r.first->second; + boost::mutex::scoped_lock lock(namePrepCacheMutex); + + std::pair<PrepCache::iterator, bool> r; + + r = nodePrepCache.insert(std::make_pair(node, std::string())); + if (r.second) { + try { + r.first->second = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep); + } + catch (...) { + nodePrepCache.erase(r.first); + valid_ = false; + return; + } + } + node_ = r.first->second; + + r = domainPrepCache.insert(std::make_pair(domain, std::string())); + if (r.second) { + try { + r.first->second = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep); + } + catch (...) { + domainPrepCache.erase(r.first); + valid_ = false; + return; + } + } + domain_ = r.first->second; + + r = resourcePrepCache.insert(std::make_pair(resource, std::string())); + if (r.second) { + try { + r.first->second = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep); + } + catch (...) { + resourcePrepCache.erase(r.first); + valid_ = false; + return; + } + } + resource_ = r.first->second; #endif - if (domain_.empty()) { - valid_ = false; - return; - } + if (domain_.empty()) { + valid_ = false; + return; + } } std::string JID::toString() const { - std::string string; - if (!node_.empty()) { - string += node_ + "@"; - } - string += domain_; - if (!isBare()) { - string += "/" + resource_; - } - return string; + std::string string; + if (!node_.empty()) { + string += node_ + "@"; + } + string += domain_; + if (!isBare()) { + string += "/" + resource_; + } + return string; } int JID::compare(const Swift::JID& o, CompareType compareType) const { - if (node_ < o.node_) { return -1; } - if (node_ > o.node_) { return 1; } - if (domain_ < o.domain_) { return -1; } - if (domain_ > o.domain_) { return 1; } - if (compareType == WithResource) { - if (hasResource_ != o.hasResource_) { - return hasResource_ ? 1 : -1; - } - if (resource_ < o.resource_) { return -1; } - if (resource_ > o.resource_) { return 1; } - } - return 0; + if (node_ < o.node_) { return -1; } + if (node_ > o.node_) { return 1; } + if (domain_ < o.domain_) { return -1; } + if (domain_ > o.domain_) { return 1; } + if (compareType == WithResource) { + if (hasResource_ != o.hasResource_) { + return hasResource_ ? 1 : -1; + } + if (resource_ < o.resource_) { return -1; } + if (resource_ > o.resource_) { return 1; } + } + return 0; } std::string JID::getEscapedNode(const std::string& node) { - std::string result; - for (std::string::const_iterator i = node.begin(); i != node.end(); ++i) { - if (std::find(escapedChars.begin(), escapedChars.end(), *i) != escapedChars.end()) { - result += getEscaped(*i); - continue; - } - else if (*i == '\\') { - // Check if we have an escaped dissalowed character sequence - std::string::const_iterator innerBegin = i + 1; - if (innerBegin != node.end() && innerBegin + 1 != node.end()) { - std::string::const_iterator innerEnd = innerBegin + 2; - unsigned char value; - if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) { - result += getEscaped(*i); - continue; - } - } - } - result += *i; - } - return result; - //return boost::find_format_all_copy(node, UnescapedCharacterFinder(), UnescapedCharacterFormatter()); + std::string result; + for (std::string::const_iterator i = node.begin(); i != node.end(); ++i) { + if (std::find(escapedChars.begin(), escapedChars.end(), *i) != escapedChars.end()) { + result += getEscaped(*i); + continue; + } + else if (*i == '\\') { + // Check if we have an escaped dissalowed character sequence + std::string::const_iterator innerBegin = i + 1; + if (innerBegin != node.end() && innerBegin + 1 != node.end()) { + std::string::const_iterator innerEnd = innerBegin + 2; + unsigned char value; + if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) { + result += getEscaped(*i); + continue; + } + } + } + result += *i; + } + return result; + //return boost::find_format_all_copy(node, UnescapedCharacterFinder(), UnescapedCharacterFormatter()); } - + std::string JID::getUnescapedNode() const { - std::string result; - for (std::string::const_iterator j = node_.begin(); j != node_.end();) { - if (*j == '\\') { - std::string::const_iterator innerEnd = j + 1; - for (size_t i = 0; i < 2 && innerEnd != node_.end(); ++i, ++innerEnd) { - } - unsigned char value; - if (getEscapeSequenceValue(std::string(j + 1, innerEnd), value)) { - result += std::string(reinterpret_cast<const char*>(&value), 1); - j = innerEnd; - continue; - } - } - result += *j; - ++j; - } - return result; - //return boost::find_format_all_copy(node_, EscapedCharacterFinder(), EscapedCharacterFormatter()); + std::string result; + for (std::string::const_iterator j = node_.begin(); j != node_.end();) { + if (*j == '\\') { + std::string::const_iterator innerEnd = j + 1; + for (size_t i = 0; i < 2 && innerEnd != node_.end(); ++i, ++innerEnd) { + } + unsigned char value; + if (getEscapeSequenceValue(std::string(j + 1, innerEnd), value)) { + result += std::string(reinterpret_cast<const char*>(&value), 1); + j = innerEnd; + continue; + } + } + result += *j; + ++j; + } + return result; + //return boost::find_format_all_copy(node_, EscapedCharacterFinder(), EscapedCharacterFormatter()); } void JID::setIDNConverter(IDNConverter* converter) { - idnConverter = converter; + idnConverter = converter; } std::ostream& operator<<(std::ostream& os, const JID& j) { - os << j.toString(); - return os; + os << j.toString(); + return os; } boost::optional<JID> JID::parse(const std::string& s) { - JID jid(s); - return jid.isValid() ? jid : boost::optional<JID>(); + JID jid(s); + return jid.isValid() ? jid : boost::optional<JID>(); } } diff --git a/Swiften/JID/JID.h b/Swiften/JID/JID.h index 2be7ca9..302e37e 100644 --- a/Swiften/JID/JID.h +++ b/Swiften/JID/JID.h @@ -14,185 +14,185 @@ #include <Swiften/Base/API.h> namespace Swift { - class IDNConverter; - - /** - * This represents the JID used in XMPP - * (RFC6120 - http://tools.ietf.org/html/rfc6120 ). - * For a description of format, see the RFC or page 14 of - * XMPP: The Definitive Guide (Saint-Andre et al.) - * - * Particularly - a Bare JID is a JID without a resource part. - * - * A JID can be invalid (when isValid() returns false). No member methods are - * guaranteed to work correctly if they do. - */ - class SWIFTEN_API JID { - public: - enum CompareType { - WithResource, WithoutResource - }; - - /** - * Create a JID from its String representation. - * - * e.g. - * wonderland.lit - * wonderland.lit/rabbithole - * alice@wonderland.lit - * alice@wonderland.lit/TeaParty - * - * @param jid String representation. Invalid JID if empty or invalid. - */ - JID(const std::string& jid = std::string()); - - /** - * See std::string constructor. - * - * Must not be NULL. - */ - JID(const char*); - - /** - * Create a bare JID from the node and domain parts. - * - * JID("node@domain") == JID("node", "domain") - * unless you pass in empty values. - * - * @param node JID node part. - * @param domain JID domain part. - */ - JID(const std::string& node, const std::string& domain); - /** - * Create a bare JID from the node, domain and resource parts. - * - * JID("node@domain/resource") == JID("node", "domain", "resource") - * unless you pass in empty values. - * - * @param node JID node part. - * @param domain JID domain part. - * @param resource JID resource part. - */ - JID(const std::string& node, const std::string& domain, const std::string& resource); - - /** - * @return Is a correctly-formatted JID. - */ - bool isValid() const { - return valid_; - } - - /** - * e.g. JID("node@domain").getNode() == "node" - * @return could be empty. - */ - const std::string& getNode() const { - return node_; - } - - /** - * e.g. JID("node@domain").getDomain() == "domain" - */ - const std::string& getDomain() const { - return domain_; - } - - /** - * e.g. JID("node@domain/resource").getResource() == "resource" - * @return could be empty. - */ - const std::string& getResource() const { - return resource_; - } - - /** - * Is a bare JID, i.e. has no resource part. - */ - bool isBare() const { - return !hasResource_; - } - - /** - * Returns the given node, escaped according to XEP-0106. - * The resulting node is a valid node for a JID, whereas the input value can contain characters - * that are not allowed. - */ - static std::string getEscapedNode(const std::string& node); - - /** - * Returns the node of the current JID, unescaped according to XEP-0106. - */ - std::string getUnescapedNode() const; - - /** - * Get the JID without a resource. - * @return Invalid if the original is invalid. - */ - JID toBare() const { - JID result(*this); - result.hasResource_ = false; - result.resource_ = ""; - return result; - } - - /** - * Get the full JID with the supplied resource. - */ - JID withResource(const std::string& resource) const { - JID result(this->getNode(), this->getDomain(), resource); - return result; - } - - std::string toString() const; - - bool equals(const JID& o, CompareType compareType) const { - return compare(o, compareType) == 0; - } - - int compare(const JID& o, CompareType compareType) const; - - operator std::string() const { - return toString(); - } - - bool operator<(const Swift::JID& b) const { - return compare(b, Swift::JID::WithResource) < 0; - } - - SWIFTEN_API friend std::ostream& operator<<(std::ostream& os, const Swift::JID& j); - - friend bool operator==(const Swift::JID& a, const Swift::JID& b) { - return a.compare(b, Swift::JID::WithResource) == 0; - } - - friend bool operator!=(const Swift::JID& a, const Swift::JID& b) { - return a.compare(b, Swift::JID::WithResource) != 0; - } - - /** - * Returns an empty optional if the JID is invalid, and an - * optional with a value if the JID is valid. - */ - static boost::optional<JID> parse(const std::string&); - - /** - * If Swiften was compiled with SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER (not default), use this method at - * the beginning of the program to set an IDN converter to use for JID IDN conversions. - * By default, this method shouldn't be used. - */ - static void setIDNConverter(IDNConverter*); - - private: - void nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource); - void initializeFromString(const std::string&); - - private: - bool valid_; - std::string node_; - std::string domain_; - bool hasResource_; - std::string resource_; - }; - - SWIFTEN_API std::ostream& operator<<(std::ostream& os, const Swift::JID& j); + class IDNConverter; + + /** + * This represents the JID used in XMPP + * (RFC6120 - http://tools.ietf.org/html/rfc6120 ). + * For a description of format, see the RFC or page 14 of + * XMPP: The Definitive Guide (Saint-Andre et al.) + * + * Particularly - a Bare JID is a JID without a resource part. + * + * A JID can be invalid (when isValid() returns false). No member methods are + * guaranteed to work correctly if they do. + */ + class SWIFTEN_API JID { + public: + enum CompareType { + WithResource, WithoutResource + }; + + /** + * Create a JID from its String representation. + * + * e.g. + * wonderland.lit + * wonderland.lit/rabbithole + * alice@wonderland.lit + * alice@wonderland.lit/TeaParty + * + * @param jid String representation. Invalid JID if empty or invalid. + */ + JID(const std::string& jid = std::string()); + + /** + * See std::string constructor. + * + * Must not be NULL. + */ + JID(const char*); + + /** + * Create a bare JID from the node and domain parts. + * + * JID("node@domain") == JID("node", "domain") + * unless you pass in empty values. + * + * @param node JID node part. + * @param domain JID domain part. + */ + JID(const std::string& node, const std::string& domain); + /** + * Create a bare JID from the node, domain and resource parts. + * + * JID("node@domain/resource") == JID("node", "domain", "resource") + * unless you pass in empty values. + * + * @param node JID node part. + * @param domain JID domain part. + * @param resource JID resource part. + */ + JID(const std::string& node, const std::string& domain, const std::string& resource); + + /** + * @return Is a correctly-formatted JID. + */ + bool isValid() const { + return valid_; + } + + /** + * e.g. JID("node@domain").getNode() == "node" + * @return could be empty. + */ + const std::string& getNode() const { + return node_; + } + + /** + * e.g. JID("node@domain").getDomain() == "domain" + */ + const std::string& getDomain() const { + return domain_; + } + + /** + * e.g. JID("node@domain/resource").getResource() == "resource" + * @return could be empty. + */ + const std::string& getResource() const { + return resource_; + } + + /** + * Is a bare JID, i.e. has no resource part. + */ + bool isBare() const { + return !hasResource_; + } + + /** + * Returns the given node, escaped according to XEP-0106. + * The resulting node is a valid node for a JID, whereas the input value can contain characters + * that are not allowed. + */ + static std::string getEscapedNode(const std::string& node); + + /** + * Returns the node of the current JID, unescaped according to XEP-0106. + */ + std::string getUnescapedNode() const; + + /** + * Get the JID without a resource. + * @return Invalid if the original is invalid. + */ + JID toBare() const { + JID result(*this); + result.hasResource_ = false; + result.resource_ = ""; + return result; + } + + /** + * Get the full JID with the supplied resource. + */ + JID withResource(const std::string& resource) const { + JID result(this->getNode(), this->getDomain(), resource); + return result; + } + + std::string toString() const; + + bool equals(const JID& o, CompareType compareType) const { + return compare(o, compareType) == 0; + } + + int compare(const JID& o, CompareType compareType) const; + + operator std::string() const { + return toString(); + } + + bool operator<(const Swift::JID& b) const { + return compare(b, Swift::JID::WithResource) < 0; + } + + SWIFTEN_API friend std::ostream& operator<<(std::ostream& os, const Swift::JID& j); + + friend bool operator==(const Swift::JID& a, const Swift::JID& b) { + return a.compare(b, Swift::JID::WithResource) == 0; + } + + friend bool operator!=(const Swift::JID& a, const Swift::JID& b) { + return a.compare(b, Swift::JID::WithResource) != 0; + } + + /** + * Returns an empty optional if the JID is invalid, and an + * optional with a value if the JID is valid. + */ + static boost::optional<JID> parse(const std::string&); + + /** + * If Swiften was compiled with SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER (not default), use this method at + * the beginning of the program to set an IDN converter to use for JID IDN conversions. + * By default, this method shouldn't be used. + */ + static void setIDNConverter(IDNConverter*); + + private: + void nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource); + void initializeFromString(const std::string&); + + private: + bool valid_; + std::string node_; + std::string domain_; + bool hasResource_; + std::string resource_; + }; + + SWIFTEN_API std::ostream& operator<<(std::ostream& os, const Swift::JID& j); } diff --git a/Swiften/JID/UnitTest/JIDTest.cpp b/Swiften/JID/UnitTest/JIDTest.cpp index 8f43576..ffe28a1 100644 --- a/Swiften/JID/UnitTest/JIDTest.cpp +++ b/Swiften/JID/UnitTest/JIDTest.cpp @@ -13,405 +13,405 @@ using namespace Swift; class JIDTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(JIDTest); - CPPUNIT_TEST(testConstructorWithString); - CPPUNIT_TEST(testConstructorWithString_NoResource); - CPPUNIT_TEST(testConstructorWithString_NoNode); - CPPUNIT_TEST(testConstructorWithString_EmptyResource); - CPPUNIT_TEST(testConstructorWithString_OnlyDomain); - CPPUNIT_TEST(testConstructorWithString_InvalidDomain); - CPPUNIT_TEST(testConstructorWithString_UpperCaseNode); - CPPUNIT_TEST(testConstructorWithString_UpperCaseDomain); - CPPUNIT_TEST(testConstructorWithString_UpperCaseResource); - CPPUNIT_TEST(testConstructorWithString_EmptyNode); - CPPUNIT_TEST(testConstructorWithString_IllegalResource); - CPPUNIT_TEST(testConstructorWithString_SpacesInNode); - CPPUNIT_TEST(testConstructorWithStrings); - CPPUNIT_TEST(testConstructorWithStrings_EmptyDomain); - CPPUNIT_TEST(testConstructorWithStrings_EmptyResource); - CPPUNIT_TEST(testIsBare); - CPPUNIT_TEST(testIsBare_NotBare); - CPPUNIT_TEST(testToBare); - CPPUNIT_TEST(testToBare_EmptyNode); - CPPUNIT_TEST(testToBare_EmptyResource); - CPPUNIT_TEST(testToString); - CPPUNIT_TEST(testToString_EmptyNode); - CPPUNIT_TEST(testToString_EmptyResource); - CPPUNIT_TEST(testToString_NoResource); - CPPUNIT_TEST(testCompare_SmallerNode); - CPPUNIT_TEST(testCompare_LargerNode); - CPPUNIT_TEST(testCompare_SmallerDomain); - CPPUNIT_TEST(testCompare_LargerDomain); - CPPUNIT_TEST(testCompare_SmallerResource); - CPPUNIT_TEST(testCompare_LargerResource); - CPPUNIT_TEST(testCompare_Equal); - CPPUNIT_TEST(testCompare_EqualWithoutResource); - CPPUNIT_TEST(testCompare_NoResourceAndEmptyResource); - CPPUNIT_TEST(testCompare_EmptyResourceAndNoResource); - CPPUNIT_TEST(testEquals); - CPPUNIT_TEST(testEquals_NotEqual); - CPPUNIT_TEST(testEquals_WithoutResource); - CPPUNIT_TEST(testSmallerThan); - CPPUNIT_TEST(testSmallerThan_Equal); - CPPUNIT_TEST(testSmallerThan_Larger); - CPPUNIT_TEST(testHasResource); - CPPUNIT_TEST(testHasResource_NoResource); - CPPUNIT_TEST(testGetEscapedNode); - CPPUNIT_TEST(testGetEscapedNode_XEP106Examples); - CPPUNIT_TEST(testGetEscapedNode_BackslashAtEnd); - CPPUNIT_TEST(testGetUnescapedNode); - CPPUNIT_TEST(testGetUnescapedNode_XEP106Examples); - CPPUNIT_TEST_SUITE_END(); - - public: - JIDTest() {} - - void testConstructorWithString() { - JID testling("foo@bar/baz"); - - CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); - CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource()); - CPPUNIT_ASSERT(!testling.isBare()); - CPPUNIT_ASSERT(testling.isValid()); - } - - void testConstructorWithString_NoResource() { - JID testling("foo@bar"); - - CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource()); - CPPUNIT_ASSERT(testling.isBare()); - CPPUNIT_ASSERT(testling.isValid()); - } - - void testConstructorWithString_EmptyResource() { - JID testling("bar/"); - - CPPUNIT_ASSERT(testling.isValid()); - CPPUNIT_ASSERT(!testling.isBare()); - } - - void testConstructorWithString_NoNode() { - JID testling("bar/baz"); - - CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); - CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource()); - CPPUNIT_ASSERT(!testling.isBare()); - CPPUNIT_ASSERT(testling.isValid()); - } - - void testConstructorWithString_OnlyDomain() { - JID testling("bar"); - - CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource()); - CPPUNIT_ASSERT(testling.isBare()); - CPPUNIT_ASSERT(testling.isValid()); - } - - void testConstructorWithString_InvalidDomain() { - CPPUNIT_ASSERT(!JID("foo@bar,baz").isValid()); - } - - void testConstructorWithString_UpperCaseNode() { - JID testling("Fo\xCE\xA9@bar"); - - CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); - CPPUNIT_ASSERT(testling.isValid()); - } - - void testConstructorWithString_UpperCaseDomain() { - JID testling("Fo\xCE\xA9"); - - CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getDomain()); - CPPUNIT_ASSERT(testling.isValid()); - } - - void testConstructorWithString_UpperCaseResource() { - JID testling("bar/Fo\xCE\xA9"); - - CPPUNIT_ASSERT_EQUAL(testling.getResource(), std::string("Fo\xCE\xA9")); - CPPUNIT_ASSERT(testling.isValid()); - } - - void testConstructorWithString_EmptyNode() { - JID testling("@bar"); - - CPPUNIT_ASSERT(!testling.isValid()); - } - - void testConstructorWithString_IllegalResource() { - JID testling("foo@bar.com/\xd8\xb1\xd9\x85\xd9\x82\xd9\x87\x20\xd8\xaa\xd8\xb1\xd9\x86\xd8\xb3\x20"); + CPPUNIT_TEST_SUITE(JIDTest); + CPPUNIT_TEST(testConstructorWithString); + CPPUNIT_TEST(testConstructorWithString_NoResource); + CPPUNIT_TEST(testConstructorWithString_NoNode); + CPPUNIT_TEST(testConstructorWithString_EmptyResource); + CPPUNIT_TEST(testConstructorWithString_OnlyDomain); + CPPUNIT_TEST(testConstructorWithString_InvalidDomain); + CPPUNIT_TEST(testConstructorWithString_UpperCaseNode); + CPPUNIT_TEST(testConstructorWithString_UpperCaseDomain); + CPPUNIT_TEST(testConstructorWithString_UpperCaseResource); + CPPUNIT_TEST(testConstructorWithString_EmptyNode); + CPPUNIT_TEST(testConstructorWithString_IllegalResource); + CPPUNIT_TEST(testConstructorWithString_SpacesInNode); + CPPUNIT_TEST(testConstructorWithStrings); + CPPUNIT_TEST(testConstructorWithStrings_EmptyDomain); + CPPUNIT_TEST(testConstructorWithStrings_EmptyResource); + CPPUNIT_TEST(testIsBare); + CPPUNIT_TEST(testIsBare_NotBare); + CPPUNIT_TEST(testToBare); + CPPUNIT_TEST(testToBare_EmptyNode); + CPPUNIT_TEST(testToBare_EmptyResource); + CPPUNIT_TEST(testToString); + CPPUNIT_TEST(testToString_EmptyNode); + CPPUNIT_TEST(testToString_EmptyResource); + CPPUNIT_TEST(testToString_NoResource); + CPPUNIT_TEST(testCompare_SmallerNode); + CPPUNIT_TEST(testCompare_LargerNode); + CPPUNIT_TEST(testCompare_SmallerDomain); + CPPUNIT_TEST(testCompare_LargerDomain); + CPPUNIT_TEST(testCompare_SmallerResource); + CPPUNIT_TEST(testCompare_LargerResource); + CPPUNIT_TEST(testCompare_Equal); + CPPUNIT_TEST(testCompare_EqualWithoutResource); + CPPUNIT_TEST(testCompare_NoResourceAndEmptyResource); + CPPUNIT_TEST(testCompare_EmptyResourceAndNoResource); + CPPUNIT_TEST(testEquals); + CPPUNIT_TEST(testEquals_NotEqual); + CPPUNIT_TEST(testEquals_WithoutResource); + CPPUNIT_TEST(testSmallerThan); + CPPUNIT_TEST(testSmallerThan_Equal); + CPPUNIT_TEST(testSmallerThan_Larger); + CPPUNIT_TEST(testHasResource); + CPPUNIT_TEST(testHasResource_NoResource); + CPPUNIT_TEST(testGetEscapedNode); + CPPUNIT_TEST(testGetEscapedNode_XEP106Examples); + CPPUNIT_TEST(testGetEscapedNode_BackslashAtEnd); + CPPUNIT_TEST(testGetUnescapedNode); + CPPUNIT_TEST(testGetUnescapedNode_XEP106Examples); + CPPUNIT_TEST_SUITE_END(); + + public: + JIDTest() {} + + void testConstructorWithString() { + JID testling("foo@bar/baz"); + + CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource()); + CPPUNIT_ASSERT(!testling.isBare()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_NoResource() { + JID testling("foo@bar"); + + CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource()); + CPPUNIT_ASSERT(testling.isBare()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_EmptyResource() { + JID testling("bar/"); + + CPPUNIT_ASSERT(testling.isValid()); + CPPUNIT_ASSERT(!testling.isBare()); + } + + void testConstructorWithString_NoNode() { + JID testling("bar/baz"); + + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource()); + CPPUNIT_ASSERT(!testling.isBare()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_OnlyDomain() { + JID testling("bar"); + + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource()); + CPPUNIT_ASSERT(testling.isBare()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_InvalidDomain() { + CPPUNIT_ASSERT(!JID("foo@bar,baz").isValid()); + } + + void testConstructorWithString_UpperCaseNode() { + JID testling("Fo\xCE\xA9@bar"); + + CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_UpperCaseDomain() { + JID testling("Fo\xCE\xA9"); + + CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getDomain()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_UpperCaseResource() { + JID testling("bar/Fo\xCE\xA9"); + + CPPUNIT_ASSERT_EQUAL(testling.getResource(), std::string("Fo\xCE\xA9")); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_EmptyNode() { + JID testling("@bar"); + + CPPUNIT_ASSERT(!testling.isValid()); + } + + void testConstructorWithString_IllegalResource() { + JID testling("foo@bar.com/\xd8\xb1\xd9\x85\xd9\x82\xd9\x87\x20\xd8\xaa\xd8\xb1\xd9\x86\xd8\xb3\x20"); - CPPUNIT_ASSERT(!testling.isValid()); - } + CPPUNIT_ASSERT(!testling.isValid()); + } - void testConstructorWithString_SpacesInNode() { - CPPUNIT_ASSERT(!JID(" alice@wonderland.lit").isValid()); - CPPUNIT_ASSERT(!JID("alice @wonderland.lit").isValid()); - } + void testConstructorWithString_SpacesInNode() { + CPPUNIT_ASSERT(!JID(" alice@wonderland.lit").isValid()); + CPPUNIT_ASSERT(!JID("alice @wonderland.lit").isValid()); + } - void testConstructorWithStrings() { - JID testling("foo", "bar", "baz"); + void testConstructorWithStrings() { + JID testling("foo", "bar", "baz"); - CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); - CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource()); - CPPUNIT_ASSERT(testling.isValid()); - } + CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource()); + CPPUNIT_ASSERT(testling.isValid()); + } - void testConstructorWithStrings_EmptyDomain() { - JID testling("foo", "", "baz"); + void testConstructorWithStrings_EmptyDomain() { + JID testling("foo", "", "baz"); - CPPUNIT_ASSERT(!testling.isValid()); - } + CPPUNIT_ASSERT(!testling.isValid()); + } - void testConstructorWithStrings_EmptyResource() { - JID testling("foo", "bar", ""); + void testConstructorWithStrings_EmptyResource() { + JID testling("foo", "bar", ""); - CPPUNIT_ASSERT(!testling.isValid()); - } + CPPUNIT_ASSERT(!testling.isValid()); + } - void testIsBare() { - CPPUNIT_ASSERT(JID("foo@bar").isBare()); - } + void testIsBare() { + CPPUNIT_ASSERT(JID("foo@bar").isBare()); + } - void testIsBare_NotBare() { - CPPUNIT_ASSERT(!JID("foo@bar/baz").isBare()); - } + void testIsBare_NotBare() { + CPPUNIT_ASSERT(!JID("foo@bar/baz").isBare()); + } - void testToBare() { - JID testling("foo@bar/baz"); + void testToBare() { + JID testling("foo@bar/baz"); - CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.toBare().getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain()); - CPPUNIT_ASSERT(testling.toBare().isBare()); - } + CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.toBare().getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain()); + CPPUNIT_ASSERT(testling.toBare().isBare()); + } - void testToBare_EmptyNode() { - JID testling("bar/baz"); + void testToBare_EmptyNode() { + JID testling("bar/baz"); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain()); - CPPUNIT_ASSERT(testling.toBare().isBare()); - CPPUNIT_ASSERT(testling.isValid()); - } + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain()); + CPPUNIT_ASSERT(testling.toBare().isBare()); + CPPUNIT_ASSERT(testling.isValid()); + } - void testToBare_EmptyResource() { - JID testling("bar/"); + void testToBare_EmptyResource() { + JID testling("bar/"); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode()); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain()); - CPPUNIT_ASSERT(testling.toBare().isBare()); - } + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain()); + CPPUNIT_ASSERT(testling.toBare().isBare()); + } - void testToString() { - JID testling("foo@bar/baz"); + void testToString() { + JID testling("foo@bar/baz"); - CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/baz"), testling.toString()); - } + CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/baz"), testling.toString()); + } - void testToString_EmptyNode() { - JID testling("bar/baz"); + void testToString_EmptyNode() { + JID testling("bar/baz"); - CPPUNIT_ASSERT_EQUAL(std::string("bar/baz"), testling.toString()); - } + CPPUNIT_ASSERT_EQUAL(std::string("bar/baz"), testling.toString()); + } - void testToString_NoResource() { - JID testling("foo@bar"); + void testToString_NoResource() { + JID testling("foo@bar"); - CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), testling.toString()); - } + CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), testling.toString()); + } - void testToString_EmptyResource() { - JID testling("foo@bar/"); + void testToString_EmptyResource() { + JID testling("foo@bar/"); - CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/"), testling.toString()); - } + CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/"), testling.toString()); + } - void testCompare_SmallerNode() { - JID testling1("a@c"); - JID testling2("b@b"); + void testCompare_SmallerNode() { + JID testling1("a@c"); + JID testling2("b@b"); - CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_LargerNode() { - JID testling1("c@a"); - JID testling2("b@b"); + void testCompare_LargerNode() { + JID testling1("c@a"); + JID testling2("b@b"); - CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_SmallerDomain() { - JID testling1("x@a/c"); - JID testling2("x@b/b"); + void testCompare_SmallerDomain() { + JID testling1("x@a/c"); + JID testling2("x@b/b"); - CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_LargerDomain() { - JID testling1("x@b/b"); - JID testling2("x@a/c"); + void testCompare_LargerDomain() { + JID testling1("x@b/b"); + JID testling2("x@a/c"); - CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_SmallerResource() { - JID testling1("x@y/a"); - JID testling2("x@y/b"); + void testCompare_SmallerResource() { + JID testling1("x@y/a"); + JID testling2("x@y/b"); - CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_LargerResource() { - JID testling1("x@y/b"); - JID testling2("x@y/a"); + void testCompare_LargerResource() { + JID testling1("x@y/b"); + JID testling2("x@y/a"); - CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_Equal() { - JID testling1("x@y/z"); - JID testling2("x@y/z"); + void testCompare_Equal() { + JID testling1("x@y/z"); + JID testling2("x@y/z"); - CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_EqualWithoutResource() { - JID testling1("x@y/a"); - JID testling2("x@y/b"); + void testCompare_EqualWithoutResource() { + JID testling1("x@y/a"); + JID testling2("x@y/b"); - CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithoutResource)); - } + CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithoutResource)); + } - void testCompare_NoResourceAndEmptyResource() { - JID testling1("x@y/"); - JID testling2("x@y"); + void testCompare_NoResourceAndEmptyResource() { + JID testling1("x@y/"); + JID testling2("x@y"); - CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource)); + } - void testCompare_EmptyResourceAndNoResource() { - JID testling1("x@y"); - JID testling2("x@y/"); + void testCompare_EmptyResourceAndNoResource() { + JID testling1("x@y"); + JID testling2("x@y/"); - CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); - } + CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource)); + } - void testEquals() { - JID testling1("x@y/c"); - JID testling2("x@y/c"); + void testEquals() { + JID testling1("x@y/c"); + JID testling2("x@y/c"); - CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithResource)); - } - - void testEquals_NotEqual() { - JID testling1("x@y/c"); - JID testling2("x@y/d"); - - CPPUNIT_ASSERT(!testling1.equals(testling2, JID::WithResource)); - } - - void testEquals_WithoutResource() { - JID testling1("x@y/c"); - JID testling2("x@y/d"); - - CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithoutResource)); - } - - void testSmallerThan() { - JID testling1("x@y/c"); - JID testling2("x@y/d"); - - CPPUNIT_ASSERT(testling1 < testling2); - } - - void testSmallerThan_Equal() { - JID testling1("x@y/d"); - JID testling2("x@y/d"); - - CPPUNIT_ASSERT(!(testling1 < testling2)); - } - - void testSmallerThan_Larger() { - JID testling1("x@y/d"); - JID testling2("x@y/c"); - - CPPUNIT_ASSERT(!(testling1 < testling2)); - } - - void testHasResource() { - JID testling("x@y/d"); - - CPPUNIT_ASSERT(!testling.isBare()); - } - - void testHasResource_NoResource() { - JID testling("x@y"); - - CPPUNIT_ASSERT(testling.isBare()); - } - - void testGetEscapedNode() { - std::string escaped = JID::getEscapedNode("alice@wonderland.lit"); - CPPUNIT_ASSERT_EQUAL(std::string("alice\\40wonderland.lit"), escaped); - - escaped = JID::getEscapedNode("\\& \" ' / <\\\\> @ :\\3a\\40"); - CPPUNIT_ASSERT_EQUAL(std::string("\\\\26\\20\\22\\20\\27\\20\\2f\\20\\3c\\\\\\3e\\20\\40\\20\\3a\\5c3a\\5c40"), escaped); - } - - void testGetEscapedNode_XEP106Examples() { - CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID::getEscapedNode("\\2plus\\2is\\4")); - CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID::getEscapedNode("foo\\bar")); - CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID::getEscapedNode("foob\\41r")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("space cadet"), std::string("space\\20cadet")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("call me \"ishmael\""), std::string("call\\20me\\20\\22ishmael\\22")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("at&t guy"), std::string("at\\26t\\20guy")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("d'artagnan"), std::string("d\\27artagnan")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("/.fanboy"), std::string("\\2f.fanboy")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("::foo::"), std::string("\\3a\\3afoo\\3a\\3a")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("<foo>"), std::string("\\3cfoo\\3e")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("user@host"), std::string("user\\40host")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\net"), std::string("c\\3a\\net")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\\\net"), std::string("c\\3a\\\\net")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\cool stuff"), std::string("c\\3a\\cool\\20stuff")); - CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\5commas"), std::string("c\\3a\\5c5commas")); - } - - void testGetEscapedNode_BackslashAtEnd() { - CPPUNIT_ASSERT_EQUAL(std::string("foo\\"), JID::getEscapedNode("foo\\")); - } - - void testGetUnescapedNode() { - std::string input = "\\& \" ' / <\\\\> @ : \\5c\\40"; - JID testling(JID::getEscapedNode(input) + "@y"); - CPPUNIT_ASSERT(testling.isValid()); - CPPUNIT_ASSERT_EQUAL(input, testling.getUnescapedNode()); - } - - void testGetUnescapedNode_XEP106Examples() { - CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID("\\2plus\\2is\\4@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID("foo\\bar@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID("foob\\41r@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("space cadet"), JID("space\\20cadet@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("call me \"ishmael\""), JID("call\\20me\\20\\22ishmael\\22@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("at&t guy"), JID("at\\26t\\20guy@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("d'artagnan"), JID("d\\27artagnan@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("/.fanboy"), JID("\\2f.fanboy@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("::foo::"), JID("\\3a\\3afoo\\3a\\3a@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("<foo>"), JID("\\3cfoo\\3e@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("user@host"), JID("user\\40host@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("c:\\net"), JID("c\\3a\\net@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("c:\\\\net"), JID("c\\3a\\\\net@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("c:\\cool stuff"), JID("c\\3a\\cool\\20stuff@example.com").getUnescapedNode()); - CPPUNIT_ASSERT_EQUAL(std::string("c:\\5commas"), JID("c\\3a\\5c5commas@example.com").getUnescapedNode()); - } + CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithResource)); + } + + void testEquals_NotEqual() { + JID testling1("x@y/c"); + JID testling2("x@y/d"); + + CPPUNIT_ASSERT(!testling1.equals(testling2, JID::WithResource)); + } + + void testEquals_WithoutResource() { + JID testling1("x@y/c"); + JID testling2("x@y/d"); + + CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithoutResource)); + } + + void testSmallerThan() { + JID testling1("x@y/c"); + JID testling2("x@y/d"); + + CPPUNIT_ASSERT(testling1 < testling2); + } + + void testSmallerThan_Equal() { + JID testling1("x@y/d"); + JID testling2("x@y/d"); + + CPPUNIT_ASSERT(!(testling1 < testling2)); + } + + void testSmallerThan_Larger() { + JID testling1("x@y/d"); + JID testling2("x@y/c"); + + CPPUNIT_ASSERT(!(testling1 < testling2)); + } + + void testHasResource() { + JID testling("x@y/d"); + + CPPUNIT_ASSERT(!testling.isBare()); + } + + void testHasResource_NoResource() { + JID testling("x@y"); + + CPPUNIT_ASSERT(testling.isBare()); + } + + void testGetEscapedNode() { + std::string escaped = JID::getEscapedNode("alice@wonderland.lit"); + CPPUNIT_ASSERT_EQUAL(std::string("alice\\40wonderland.lit"), escaped); + + escaped = JID::getEscapedNode("\\& \" ' / <\\\\> @ :\\3a\\40"); + CPPUNIT_ASSERT_EQUAL(std::string("\\\\26\\20\\22\\20\\27\\20\\2f\\20\\3c\\\\\\3e\\20\\40\\20\\3a\\5c3a\\5c40"), escaped); + } + + void testGetEscapedNode_XEP106Examples() { + CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID::getEscapedNode("\\2plus\\2is\\4")); + CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID::getEscapedNode("foo\\bar")); + CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID::getEscapedNode("foob\\41r")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("space cadet"), std::string("space\\20cadet")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("call me \"ishmael\""), std::string("call\\20me\\20\\22ishmael\\22")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("at&t guy"), std::string("at\\26t\\20guy")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("d'artagnan"), std::string("d\\27artagnan")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("/.fanboy"), std::string("\\2f.fanboy")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("::foo::"), std::string("\\3a\\3afoo\\3a\\3a")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("<foo>"), std::string("\\3cfoo\\3e")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("user@host"), std::string("user\\40host")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\net"), std::string("c\\3a\\net")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\\\net"), std::string("c\\3a\\\\net")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\cool stuff"), std::string("c\\3a\\cool\\20stuff")); + CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\5commas"), std::string("c\\3a\\5c5commas")); + } + + void testGetEscapedNode_BackslashAtEnd() { + CPPUNIT_ASSERT_EQUAL(std::string("foo\\"), JID::getEscapedNode("foo\\")); + } + + void testGetUnescapedNode() { + std::string input = "\\& \" ' / <\\\\> @ : \\5c\\40"; + JID testling(JID::getEscapedNode(input) + "@y"); + CPPUNIT_ASSERT(testling.isValid()); + CPPUNIT_ASSERT_EQUAL(input, testling.getUnescapedNode()); + } + + void testGetUnescapedNode_XEP106Examples() { + CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID("\\2plus\\2is\\4@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID("foo\\bar@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID("foob\\41r@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("space cadet"), JID("space\\20cadet@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("call me \"ishmael\""), JID("call\\20me\\20\\22ishmael\\22@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("at&t guy"), JID("at\\26t\\20guy@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("d'artagnan"), JID("d\\27artagnan@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("/.fanboy"), JID("\\2f.fanboy@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("::foo::"), JID("\\3a\\3afoo\\3a\\3a@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("<foo>"), JID("\\3cfoo\\3e@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("user@host"), JID("user\\40host@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("c:\\net"), JID("c\\3a\\net@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("c:\\\\net"), JID("c\\3a\\\\net@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("c:\\cool stuff"), JID("c\\3a\\cool\\20stuff@example.com").getUnescapedNode()); + CPPUNIT_ASSERT_EQUAL(std::string("c:\\5commas"), JID("c\\3a\\5c5commas@example.com").getUnescapedNode()); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(JIDTest); diff --git a/Swiften/Jingle/AbstractJingleSessionListener.cpp b/Swiften/Jingle/AbstractJingleSessionListener.cpp index c533f12..791dcb3 100644 --- a/Swiften/Jingle/AbstractJingleSessionListener.cpp +++ b/Swiften/Jingle/AbstractJingleSessionListener.cpp @@ -11,31 +11,31 @@ using namespace Swift; void AbstractJingleSessionListener::handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) { - SWIFT_LOG(warning) << "Unimplemented" << std::endl; + SWIFT_LOG(warning) << "Unimplemented" << std::endl; } void AbstractJingleSessionListener::handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) { - SWIFT_LOG(warning) << "Unimplemented" << std::endl; + SWIFT_LOG(warning) << "Unimplemented" << std::endl; } void AbstractJingleSessionListener::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) { - SWIFT_LOG(warning) << "Unimplemented" << std::endl; + SWIFT_LOG(warning) << "Unimplemented" << std::endl; } void AbstractJingleSessionListener::handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) { - SWIFT_LOG(warning) << "Unimplemented" << std::endl; + SWIFT_LOG(warning) << "Unimplemented" << std::endl; } void AbstractJingleSessionListener::handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) { - SWIFT_LOG(warning) << "Unimplemented" << std::endl; + SWIFT_LOG(warning) << "Unimplemented" << std::endl; } void AbstractJingleSessionListener::handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) { - SWIFT_LOG(warning) << "Unimplemented" << std::endl; + SWIFT_LOG(warning) << "Unimplemented" << std::endl; } void AbstractJingleSessionListener::handleTransportReplaceReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) { - SWIFT_LOG(warning) << "Unimplemented" << std::endl; + SWIFT_LOG(warning) << "Unimplemented" << std::endl; } void AbstractJingleSessionListener::handleTransportInfoAcknowledged(const std::string&) { diff --git a/Swiften/Jingle/AbstractJingleSessionListener.h b/Swiften/Jingle/AbstractJingleSessionListener.h index 6256506..678f173 100644 --- a/Swiften/Jingle/AbstractJingleSessionListener.h +++ b/Swiften/Jingle/AbstractJingleSessionListener.h @@ -11,16 +11,16 @@ #include <Swiften/Jingle/JingleSessionListener.h> namespace Swift { - class SWIFTEN_API AbstractJingleSessionListener : public JingleSessionListener { - public: - virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE; - virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) SWIFTEN_OVERRIDE; - virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportReplaceReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE; - }; + class SWIFTEN_API AbstractJingleSessionListener : public JingleSessionListener { + public: + virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE; + virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) SWIFTEN_OVERRIDE; + virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void handleTransportReplaceReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE; + }; } diff --git a/Swiften/Jingle/FakeJingleSession.cpp b/Swiften/Jingle/FakeJingleSession.cpp index fae3425..ec792ab 100644 --- a/Swiften/Jingle/FakeJingleSession.cpp +++ b/Swiften/Jingle/FakeJingleSession.cpp @@ -26,56 +26,56 @@ FakeJingleSession::~FakeJingleSession() { } void FakeJingleSession::sendInitiate(const JingleContentID& id, JingleDescription::ref desc, JingleTransportPayload::ref payload) { - calledCommands.push_back(InitiateCall(id, desc, payload)); + calledCommands.push_back(InitiateCall(id, desc, payload)); } void FakeJingleSession::sendTerminate(JinglePayload::Reason::Type reason) { - calledCommands.push_back(TerminateCall(reason)); + calledCommands.push_back(TerminateCall(reason)); } void FakeJingleSession::sendInfo(boost::shared_ptr<Payload> payload) { - calledCommands.push_back(InfoCall(payload)); + calledCommands.push_back(InfoCall(payload)); } void FakeJingleSession::sendAccept(const JingleContentID& id, JingleDescription::ref desc, JingleTransportPayload::ref payload) { - calledCommands.push_back(AcceptCall(id, desc, payload)); + calledCommands.push_back(AcceptCall(id, desc, payload)); } std::string FakeJingleSession::sendTransportInfo(const JingleContentID& id, JingleTransportPayload::ref payload) { - calledCommands.push_back(InfoTransportCall(id, payload)); - return idGenerator.generateID(); + calledCommands.push_back(InfoTransportCall(id, payload)); + return idGenerator.generateID(); } void FakeJingleSession::sendTransportAccept(const JingleContentID& id, JingleTransportPayload::ref payload) { - calledCommands.push_back(AcceptTransportCall(id, payload)); + calledCommands.push_back(AcceptTransportCall(id, payload)); } void FakeJingleSession::sendTransportReject(const JingleContentID& id, JingleTransportPayload::ref payload) { - calledCommands.push_back(RejectTransportCall(id, payload)); + calledCommands.push_back(RejectTransportCall(id, payload)); } void FakeJingleSession::sendTransportReplace(const JingleContentID& id, JingleTransportPayload::ref payload) { - calledCommands.push_back(ReplaceTransportCall(id, payload)); + calledCommands.push_back(ReplaceTransportCall(id, payload)); } void FakeJingleSession::handleTransportReplaceReceived(const JingleContentID& contentID, JingleTransportPayload::ref transport) { - notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport); + notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport); } void FakeJingleSession::handleTransportAcceptReceived(const JingleContentID& contentID, JingleTransportPayload::ref transport) { - notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport); + notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport); } void FakeJingleSession::handleTransportInfoReceived(const JingleContentID& contentID, JingleTransportPayload::ref transport) { - notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport); + notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport); } void FakeJingleSession::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) { - notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, reason); + notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, reason); } void FakeJingleSession::handleSessionAcceptReceived(const JingleContentID& contentID, boost::shared_ptr<JingleDescription> desc, boost::shared_ptr<JingleTransportPayload> payload) { - notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, desc, payload); + notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, desc, payload); } } diff --git a/Swiften/Jingle/FakeJingleSession.h b/Swiften/Jingle/FakeJingleSession.h index dc7e56a..0107384 100644 --- a/Swiften/Jingle/FakeJingleSession.h +++ b/Swiften/Jingle/FakeJingleSession.h @@ -28,87 +28,87 @@ #include <Swiften/Jingle/JingleSession.h> namespace Swift { - class JingleContentID; - - class SWIFTEN_API FakeJingleSession : public JingleSession { - public: - struct InitiateCall { - InitiateCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {} - JingleContentID id; - JingleDescription::ref description; - JingleTransportPayload::ref payload; - }; - - struct TerminateCall { - TerminateCall(JinglePayload::Reason::Type r) : reason(r) {} - JinglePayload::Reason::Type reason; - }; - - struct InfoCall { - InfoCall(boost::shared_ptr<Payload> info) : payload(info) {} - boost::shared_ptr<Payload> payload; - }; - - struct AcceptCall { - AcceptCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {} - JingleContentID id; - JingleDescription::ref description; - JingleTransportPayload::ref payload; - }; - - struct InfoTransportCall { - InfoTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} - JingleContentID id; - JingleTransportPayload::ref payload; - }; - - struct AcceptTransportCall { - AcceptTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} - JingleContentID id; - JingleTransportPayload::ref payload; - }; - - struct RejectTransportCall { - RejectTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} - JingleContentID id; - JingleTransportPayload::ref payload; - }; - - struct ReplaceTransportCall { - ReplaceTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} - JingleContentID id; - JingleTransportPayload::ref payload; - }; - - typedef boost::variant<InitiateCall, TerminateCall, AcceptCall, InfoCall, InfoTransportCall, AcceptTransportCall, RejectTransportCall, ReplaceTransportCall> Command; - - public: - typedef boost::shared_ptr<FakeJingleSession> ref; - - FakeJingleSession(const JID& initiator, const std::string& id); - virtual ~FakeJingleSession(); - - virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTerminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; - virtual void sendInfo(boost::shared_ptr<Payload>) SWIFTEN_OVERRIDE; - virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) SWIFTEN_OVERRIDE; - virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - - void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>); - void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>); - void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>); - - void handleTransportReplaceReceived(const JingleContentID&, JingleTransportPayload::ref); - void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>); - void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>); - void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>); - void handleTransportInfoAcknowledged(const std::string& id); - - public: - std::vector<Command> calledCommands; - SimpleIDGenerator idGenerator; - }; + class JingleContentID; + + class SWIFTEN_API FakeJingleSession : public JingleSession { + public: + struct InitiateCall { + InitiateCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {} + JingleContentID id; + JingleDescription::ref description; + JingleTransportPayload::ref payload; + }; + + struct TerminateCall { + TerminateCall(JinglePayload::Reason::Type r) : reason(r) {} + JinglePayload::Reason::Type reason; + }; + + struct InfoCall { + InfoCall(boost::shared_ptr<Payload> info) : payload(info) {} + boost::shared_ptr<Payload> payload; + }; + + struct AcceptCall { + AcceptCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {} + JingleContentID id; + JingleDescription::ref description; + JingleTransportPayload::ref payload; + }; + + struct InfoTransportCall { + InfoTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} + JingleContentID id; + JingleTransportPayload::ref payload; + }; + + struct AcceptTransportCall { + AcceptTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} + JingleContentID id; + JingleTransportPayload::ref payload; + }; + + struct RejectTransportCall { + RejectTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} + JingleContentID id; + JingleTransportPayload::ref payload; + }; + + struct ReplaceTransportCall { + ReplaceTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {} + JingleContentID id; + JingleTransportPayload::ref payload; + }; + + typedef boost::variant<InitiateCall, TerminateCall, AcceptCall, InfoCall, InfoTransportCall, AcceptTransportCall, RejectTransportCall, ReplaceTransportCall> Command; + + public: + typedef boost::shared_ptr<FakeJingleSession> ref; + + FakeJingleSession(const JID& initiator, const std::string& id); + virtual ~FakeJingleSession(); + + virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual void sendTerminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; + virtual void sendInfo(boost::shared_ptr<Payload>) SWIFTEN_OVERRIDE; + virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) SWIFTEN_OVERRIDE; + virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + + void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>); + void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>); + void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>); + + void handleTransportReplaceReceived(const JingleContentID&, JingleTransportPayload::ref); + void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>); + void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>); + void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>); + void handleTransportInfoAcknowledged(const std::string& id); + + public: + std::vector<Command> calledCommands; + SimpleIDGenerator idGenerator; + }; } diff --git a/Swiften/Jingle/IncomingJingleSessionHandler.h b/Swiften/Jingle/IncomingJingleSessionHandler.h index fba9acc..4c30f7c 100644 --- a/Swiften/Jingle/IncomingJingleSessionHandler.h +++ b/Swiften/Jingle/IncomingJingleSessionHandler.h @@ -10,10 +10,10 @@ #include <Swiften/Jingle/JingleSession.h> namespace Swift { - class SWIFTEN_API IncomingJingleSessionHandler { - public: - virtual ~IncomingJingleSessionHandler(); + class SWIFTEN_API IncomingJingleSessionHandler { + public: + virtual ~IncomingJingleSessionHandler(); - virtual bool handleIncomingJingleSession(JingleSession::ref, const std::vector<JingleContentPayload::ref>& contents, const JID& recipient) = 0; - }; + virtual bool handleIncomingJingleSession(JingleSession::ref, const std::vector<JingleContentPayload::ref>& contents, const JID& recipient) = 0; + }; } diff --git a/Swiften/Jingle/Jingle.h b/Swiften/Jingle/Jingle.h index bf05b1c..13c235b 100644 --- a/Swiften/Jingle/Jingle.h +++ b/Swiften/Jingle/Jingle.h @@ -11,15 +11,15 @@ #include <Swiften/Elements/JingleContentPayload.h> namespace Swift { - namespace Jingle { - template<typename T> - JingleContentPayload::ref getContentWithDescription(const std::vector<JingleContentPayload::ref>& contents) { - for (size_t i = 0; i < contents.size(); ++i) { - if (contents[i]->getDescription<T>()) { - return contents[i]; - } - } - return JingleContentPayload::ref(); - } - } + namespace Jingle { + template<typename T> + JingleContentPayload::ref getContentWithDescription(const std::vector<JingleContentPayload::ref>& contents) { + for (size_t i = 0; i < contents.size(); ++i) { + if (contents[i]->getDescription<T>()) { + return contents[i]; + } + } + return JingleContentPayload::ref(); + } + } } diff --git a/Swiften/Jingle/JingleContentID.h b/Swiften/Jingle/JingleContentID.h index 2d842fa..60f412b 100644 --- a/Swiften/Jingle/JingleContentID.h +++ b/Swiften/Jingle/JingleContentID.h @@ -12,21 +12,21 @@ #include <Swiften/Elements/JingleContentPayload.h> namespace Swift { - class SWIFTEN_API JingleContentID { - public: - JingleContentID(const std::string& name, JingleContentPayload::Creator creator) : name(name), creator(creator) { - } - - const std::string getName() const { - return this->name; - } - - JingleContentPayload::Creator getCreator() const { - return this->creator; - } + class SWIFTEN_API JingleContentID { + public: + JingleContentID(const std::string& name, JingleContentPayload::Creator creator) : name(name), creator(creator) { + } - private: - std::string name; - JingleContentPayload::Creator creator; - }; + const std::string getName() const { + return this->name; + } + + JingleContentPayload::Creator getCreator() const { + return this->creator; + } + + private: + std::string name; + JingleContentPayload::Creator creator; + }; } diff --git a/Swiften/Jingle/JingleResponder.cpp b/Swiften/Jingle/JingleResponder.cpp index 16ed1da..d0c2edd 100644 --- a/Swiften/Jingle/JingleResponder.cpp +++ b/Swiften/Jingle/JingleResponder.cpp @@ -21,41 +21,41 @@ JingleResponder::~JingleResponder() { } bool JingleResponder::handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload) { - if (payload->getAction() == JinglePayload::SessionInitiate) { - if (sessionManager->getSession(from, payload->getSessionID())) { - // TODO: Add tie-break error - sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel); - } - else { - sendResponse(from, id, boost::shared_ptr<JinglePayload>()); - if (!payload->getInitiator().isBare()) { - JingleSessionImpl::ref session = boost::make_shared<JingleSessionImpl>(payload->getInitiator(), from, payload->getSessionID(), router); - sessionManager->handleIncomingSession(from, to, session, payload->getContents()); - } else { - SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID." << std::endl; - } - } - } - else { - JingleSessionImpl::ref session; - if (payload->getInitiator().isValid()) { - SWIFT_LOG(debug) << "Lookup session by initiator." << std::endl; - session = sessionManager->getSession(payload->getInitiator(), payload->getSessionID()); - } else { - SWIFT_LOG(debug) << "Lookup session by from attribute." << std::endl; - session = sessionManager->getSession(from, payload->getSessionID()); - } - if (session) { - session->handleIncomingAction(payload); - sendResponse(from, id, boost::shared_ptr<JinglePayload>()); - } - else { - SWIFT_LOG(warning) << "Didn't find jingle session!"; - // TODO: Add jingle-specific error - sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); - } - } - return true; + if (payload->getAction() == JinglePayload::SessionInitiate) { + if (sessionManager->getSession(from, payload->getSessionID())) { + // TODO: Add tie-break error + sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel); + } + else { + sendResponse(from, id, boost::shared_ptr<JinglePayload>()); + if (!payload->getInitiator().isBare()) { + JingleSessionImpl::ref session = boost::make_shared<JingleSessionImpl>(payload->getInitiator(), from, payload->getSessionID(), router); + sessionManager->handleIncomingSession(from, to, session, payload->getContents()); + } else { + SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID." << std::endl; + } + } + } + else { + JingleSessionImpl::ref session; + if (payload->getInitiator().isValid()) { + SWIFT_LOG(debug) << "Lookup session by initiator." << std::endl; + session = sessionManager->getSession(payload->getInitiator(), payload->getSessionID()); + } else { + SWIFT_LOG(debug) << "Lookup session by from attribute." << std::endl; + session = sessionManager->getSession(from, payload->getSessionID()); + } + if (session) { + session->handleIncomingAction(payload); + sendResponse(from, id, boost::shared_ptr<JinglePayload>()); + } + else { + SWIFT_LOG(warning) << "Didn't find jingle session!"; + // TODO: Add jingle-specific error + sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); + } + } + return true; } } diff --git a/Swiften/Jingle/JingleResponder.h b/Swiften/Jingle/JingleResponder.h index 1468a54..1340835 100644 --- a/Swiften/Jingle/JingleResponder.h +++ b/Swiften/Jingle/JingleResponder.h @@ -11,18 +11,18 @@ #include <Swiften/Queries/SetResponder.h> namespace Swift { - class IQRouter; - class JingleSessionManager; + class IQRouter; + class JingleSessionManager; - class SWIFTEN_API JingleResponder : public SetResponder<JinglePayload> { - public: - JingleResponder(JingleSessionManager* sessionManager, IQRouter* router); - virtual ~JingleResponder(); - private: - virtual bool handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload); + class SWIFTEN_API JingleResponder : public SetResponder<JinglePayload> { + public: + JingleResponder(JingleSessionManager* sessionManager, IQRouter* router); + virtual ~JingleResponder(); + private: + virtual bool handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload); - private: - JingleSessionManager* sessionManager; - IQRouter* router; - }; + private: + JingleSessionManager* sessionManager; + IQRouter* router; + }; } diff --git a/Swiften/Jingle/JingleSession.cpp b/Swiften/Jingle/JingleSession.cpp index 65a68f9..8abbd56 100644 --- a/Swiften/Jingle/JingleSession.cpp +++ b/Swiften/Jingle/JingleSession.cpp @@ -16,9 +16,9 @@ using namespace Swift; JingleSession::JingleSession(const JID& initiator, const std::string& id) : initiator(initiator), id(id) { - // initiator must always be a full JID; session lookup based on it wouldn't work otherwise - // this is checked on an upper level so that the assert never fails - assert(!initiator.isBare()); + // initiator must always be a full JID; session lookup based on it wouldn't work otherwise + // this is checked on an upper level so that the assert never fails + assert(!initiator.isBare()); } JingleSession::~JingleSession() { diff --git a/Swiften/Jingle/JingleSession.h b/Swiften/Jingle/JingleSession.h index 6c76f3c..7a64c47 100644 --- a/Swiften/Jingle/JingleSession.h +++ b/Swiften/Jingle/JingleSession.h @@ -19,36 +19,36 @@ #include <Swiften/JID/JID.h> namespace Swift { - class JingleSessionListener; - class JingleContentID; - - class SWIFTEN_API JingleSession : public Listenable<JingleSessionListener> { - public: - typedef boost::shared_ptr<JingleSession> ref; - - JingleSession(const JID& initiator, const std::string& id); - virtual ~JingleSession(); - - const JID& getInitiator() const { - return initiator; - } - - const std::string& getID() const { - return id; - } - - virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) = 0; - virtual void sendTerminate(JinglePayload::Reason::Type reason) = 0; - virtual void sendInfo(boost::shared_ptr<Payload>) = 0; - virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) = 0; - virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) = 0; - virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) = 0; - virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) = 0; - virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) = 0; - - private: - JID initiator; - std::string id; - std::vector<JingleSessionListener*> listeners; - }; + class JingleSessionListener; + class JingleContentID; + + class SWIFTEN_API JingleSession : public Listenable<JingleSessionListener> { + public: + typedef boost::shared_ptr<JingleSession> ref; + + JingleSession(const JID& initiator, const std::string& id); + virtual ~JingleSession(); + + const JID& getInitiator() const { + return initiator; + } + + const std::string& getID() const { + return id; + } + + virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) = 0; + virtual void sendTerminate(JinglePayload::Reason::Type reason) = 0; + virtual void sendInfo(boost::shared_ptr<Payload>) = 0; + virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) = 0; + virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) = 0; + virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) = 0; + virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) = 0; + virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) = 0; + + private: + JID initiator; + std::string id; + std::vector<JingleSessionListener*> listeners; + }; } diff --git a/Swiften/Jingle/JingleSessionImpl.cpp b/Swiften/Jingle/JingleSessionImpl.cpp index a19947a..3063242 100644 --- a/Swiften/Jingle/JingleSessionImpl.cpp +++ b/Swiften/Jingle/JingleSessionImpl.cpp @@ -23,185 +23,185 @@ namespace Swift { JingleSessionImpl::JingleSessionImpl(const JID& initiator, const JID& peerJID, const std::string& id, IQRouter* router) : JingleSession(initiator, id), iqRouter(router), peerJID(peerJID) { - SWIFT_LOG(debug) << "initiator: " << initiator << ", peerJID: " << peerJID << std::endl; + SWIFT_LOG(debug) << "initiator: " << initiator << ", peerJID: " << peerJID << std::endl; } void JingleSessionImpl::handleIncomingAction(JinglePayload::ref action) { - if (action->getAction() == JinglePayload::SessionTerminate) { - notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, action->getReason()); - return; - } - if (action->getAction() == JinglePayload::SessionInfo) { - notifyListeners(&JingleSessionListener::handleSessionInfoReceived, action); - return; - } - - JingleContentPayload::ref content = action->getPayload<JingleContentPayload>(); - if (!content) { - SWIFT_LOG(debug) << "no content payload!" << std::endl; - return; - } - JingleContentID contentID(content->getName(), content->getCreator()); - JingleDescription::ref description = content->getDescriptions().empty() ? JingleDescription::ref() : content->getDescriptions()[0]; - JingleTransportPayload::ref transport = content->getTransports().empty() ? JingleTransportPayload::ref() : content->getTransports()[0]; - switch(action->getAction()) { - case JinglePayload::SessionAccept: - notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, description, transport); - return; - case JinglePayload::TransportAccept: - notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport); - return; - case JinglePayload::TransportInfo: - notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport); - return; - case JinglePayload::TransportReject: - notifyListeners(&JingleSessionListener::handleTransportRejectReceived, contentID, transport); - return; - case JinglePayload::TransportReplace: - notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport); - return; - // following unused Jingle actions - case JinglePayload::ContentAccept: - case JinglePayload::ContentAdd: - case JinglePayload::ContentModify: - case JinglePayload::ContentReject: - case JinglePayload::ContentRemove: - case JinglePayload::DescriptionInfo: - case JinglePayload::SecurityInfo: - - // handled elsewhere - case JinglePayload::SessionInitiate: - case JinglePayload::SessionInfo: - case JinglePayload::SessionTerminate: - - case JinglePayload::UnknownAction: - return; - } - assert(false); + if (action->getAction() == JinglePayload::SessionTerminate) { + notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, action->getReason()); + return; + } + if (action->getAction() == JinglePayload::SessionInfo) { + notifyListeners(&JingleSessionListener::handleSessionInfoReceived, action); + return; + } + + JingleContentPayload::ref content = action->getPayload<JingleContentPayload>(); + if (!content) { + SWIFT_LOG(debug) << "no content payload!" << std::endl; + return; + } + JingleContentID contentID(content->getName(), content->getCreator()); + JingleDescription::ref description = content->getDescriptions().empty() ? JingleDescription::ref() : content->getDescriptions()[0]; + JingleTransportPayload::ref transport = content->getTransports().empty() ? JingleTransportPayload::ref() : content->getTransports()[0]; + switch(action->getAction()) { + case JinglePayload::SessionAccept: + notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, description, transport); + return; + case JinglePayload::TransportAccept: + notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport); + return; + case JinglePayload::TransportInfo: + notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport); + return; + case JinglePayload::TransportReject: + notifyListeners(&JingleSessionListener::handleTransportRejectReceived, contentID, transport); + return; + case JinglePayload::TransportReplace: + notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport); + return; + // following unused Jingle actions + case JinglePayload::ContentAccept: + case JinglePayload::ContentAdd: + case JinglePayload::ContentModify: + case JinglePayload::ContentReject: + case JinglePayload::ContentRemove: + case JinglePayload::DescriptionInfo: + case JinglePayload::SecurityInfo: + + // handled elsewhere + case JinglePayload::SessionInitiate: + case JinglePayload::SessionInfo: + case JinglePayload::SessionTerminate: + + case JinglePayload::UnknownAction: + return; + } + assert(false); } void JingleSessionImpl::sendInitiate(const JingleContentID& id, JingleDescription::ref description, JingleTransportPayload::ref transport) { - JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInitiate, getID()); - payload->setInitiator(getInitiator()); - JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); - content->setCreator(id.getCreator()); - content->setName(id.getName()); - content->addDescription(description); - content->addTransport(transport); - payload->addPayload(content); - - sendSetRequest(payload); + JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInitiate, getID()); + payload->setInitiator(getInitiator()); + JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); + content->setCreator(id.getCreator()); + content->setName(id.getName()); + content->addDescription(description); + content->addTransport(transport); + payload->addPayload(content); + + sendSetRequest(payload); } void JingleSessionImpl::sendTerminate(JinglePayload::Reason::Type reason) { - JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionTerminate, getID()); - payload->setReason(JinglePayload::Reason(reason)); - payload->setInitiator(getInitiator()); - sendSetRequest(payload); + JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionTerminate, getID()); + payload->setReason(JinglePayload::Reason(reason)); + payload->setInitiator(getInitiator()); + sendSetRequest(payload); } void JingleSessionImpl::sendInfo(boost::shared_ptr<Payload> info) { - JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInfo, getID()); - payload->addPayload(info); + JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInfo, getID()); + payload->addPayload(info); - sendSetRequest(payload); + sendSetRequest(payload); } void JingleSessionImpl::sendAccept(const JingleContentID& id, JingleDescription::ref description, JingleTransportPayload::ref transPayload) { - JinglePayload::ref payload = createPayload(); - - JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); - content->setCreator(id.getCreator()); - content->setName(id.getName()); - content->addTransport(transPayload); - content->addDescription(description); - payload->setAction(JinglePayload::SessionAccept); - payload->addPayload(content); - - // put into IQ:set and send it away - sendSetRequest(payload); + JinglePayload::ref payload = createPayload(); + + JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); + content->setCreator(id.getCreator()); + content->setName(id.getName()); + content->addTransport(transPayload); + content->addDescription(description); + payload->setAction(JinglePayload::SessionAccept); + payload->addPayload(content); + + // put into IQ:set and send it away + sendSetRequest(payload); } void JingleSessionImpl::sendTransportAccept(const JingleContentID& id, JingleTransportPayload::ref transPayload) { - JinglePayload::ref payload = createPayload(); + JinglePayload::ref payload = createPayload(); - JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); - content->setCreator(id.getCreator()); - content->setName(id.getName()); - content->addTransport(transPayload); - payload->setAction(JinglePayload::TransportAccept); - payload->addPayload(content); + JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); + content->setCreator(id.getCreator()); + content->setName(id.getName()); + content->addTransport(transPayload); + payload->setAction(JinglePayload::TransportAccept); + payload->addPayload(content); - // put into IQ:set and send it away - sendSetRequest(payload); + // put into IQ:set and send it away + sendSetRequest(payload); } std::string JingleSessionImpl::sendTransportInfo(const JingleContentID& id, JingleTransportPayload::ref transPayload) { - JinglePayload::ref payload = createPayload(); + JinglePayload::ref payload = createPayload(); - JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); - content->setCreator(id.getCreator()); - content->setName(id.getName()); - content->addTransport(transPayload); - payload->setAction(JinglePayload::TransportInfo); - payload->addPayload(content); + JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); + content->setCreator(id.getCreator()); + content->setName(id.getName()); + content->addTransport(transPayload); + payload->setAction(JinglePayload::TransportInfo); + payload->addPayload(content); - return sendSetRequest(payload); + return sendSetRequest(payload); } void JingleSessionImpl::sendTransportReject(const JingleContentID& id, JingleTransportPayload::ref transPayload) { - JinglePayload::ref payload = createPayload(); + JinglePayload::ref payload = createPayload(); - JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); - content->setCreator(id.getCreator()); - content->setName(id.getName()); - content->addTransport(transPayload); - payload->setAction(JinglePayload::TransportReject); - payload->addPayload(content); + JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); + content->setCreator(id.getCreator()); + content->setName(id.getName()); + content->addTransport(transPayload); + payload->setAction(JinglePayload::TransportReject); + payload->addPayload(content); - sendSetRequest(payload); + sendSetRequest(payload); } void JingleSessionImpl::sendTransportReplace(const JingleContentID& id, JingleTransportPayload::ref transPayload) { - JinglePayload::ref payload = createPayload(); + JinglePayload::ref payload = createPayload(); - JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); - content->setCreator(id.getCreator()); - content->setName(id.getName()); - content->addTransport(transPayload); - payload->setAction(JinglePayload::TransportReplace); - payload->addContent(content); + JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>(); + content->setCreator(id.getCreator()); + content->setName(id.getName()); + content->addTransport(transPayload); + payload->setAction(JinglePayload::TransportReplace); + payload->addContent(content); - sendSetRequest(payload); + sendSetRequest(payload); } std::string JingleSessionImpl::sendSetRequest(JinglePayload::ref payload) { - boost::shared_ptr<GenericRequest<JinglePayload> > request = boost::make_shared<GenericRequest<JinglePayload> >( - IQ::Set, peerJID, payload, iqRouter); - pendingRequests.insert(std::make_pair( - request, - request->onResponse.connect(boost::bind(&JingleSessionImpl::handleRequestResponse, this, request)))); - return request->send(); + boost::shared_ptr<GenericRequest<JinglePayload> > request = boost::make_shared<GenericRequest<JinglePayload> >( + IQ::Set, peerJID, payload, iqRouter); + pendingRequests.insert(std::make_pair( + request, + request->onResponse.connect(boost::bind(&JingleSessionImpl::handleRequestResponse, this, request)))); + return request->send(); } JinglePayload::ref JingleSessionImpl::createPayload() const { - JinglePayload::ref payload = boost::make_shared<JinglePayload>(); - payload->setSessionID(getID()); - payload->setInitiator(getInitiator()); - return payload; + JinglePayload::ref payload = boost::make_shared<JinglePayload>(); + payload->setSessionID(getID()); + payload->setInitiator(getInitiator()); + return payload; } void JingleSessionImpl::handleRequestResponse(RequestRef request) { - RequestsMap::iterator i = pendingRequests.find(request); - assert(i != pendingRequests.end()); - if (i->first->getPayloadGeneric()->getAction() == JinglePayload::TransportInfo) { - notifyListeners(&JingleSessionListener::handleTransportInfoAcknowledged, i->first->getID()); - } - i->second.disconnect(); - pendingRequests.erase(i); + RequestsMap::iterator i = pendingRequests.find(request); + assert(i != pendingRequests.end()); + if (i->first->getPayloadGeneric()->getAction() == JinglePayload::TransportInfo) { + notifyListeners(&JingleSessionListener::handleTransportInfoAcknowledged, i->first->getID()); + } + i->second.disconnect(); + pendingRequests.erase(i); } diff --git a/Swiften/Jingle/JingleSessionImpl.h b/Swiften/Jingle/JingleSessionImpl.h index 4d21cd3..eec2370 100644 --- a/Swiften/Jingle/JingleSessionImpl.h +++ b/Swiften/Jingle/JingleSessionImpl.h @@ -14,38 +14,38 @@ #include <Swiften/Queries/GenericRequest.h> namespace Swift { - class IQRouter; - class Request; - - class JingleSessionImpl : public JingleSession { - friend class JingleResponder; - public: - typedef boost::shared_ptr<JingleSessionImpl> ref; - - JingleSessionImpl(const JID& initiator, const JID&, const std::string& id, IQRouter* router); - - virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref); - virtual void sendTerminate(JinglePayload::Reason::Type reason); - virtual void sendInfo(boost::shared_ptr<Payload>); - virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref); - virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref); - virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref); - virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref); - virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref); - - private: - typedef boost::shared_ptr<GenericRequest<JinglePayload> > RequestRef; - - void handleIncomingAction(JinglePayload::ref); - - std::string sendSetRequest(JinglePayload::ref payload); - JinglePayload::ref createPayload() const; - void handleRequestResponse(RequestRef); - - private: - IQRouter *iqRouter; - JID peerJID; - typedef std::map<RequestRef, boost::bsignals::connection > RequestsMap; - RequestsMap pendingRequests; - }; + class IQRouter; + class Request; + + class JingleSessionImpl : public JingleSession { + friend class JingleResponder; + public: + typedef boost::shared_ptr<JingleSessionImpl> ref; + + JingleSessionImpl(const JID& initiator, const JID&, const std::string& id, IQRouter* router); + + virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref); + virtual void sendTerminate(JinglePayload::Reason::Type reason); + virtual void sendInfo(boost::shared_ptr<Payload>); + virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref); + virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref); + virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref); + virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref); + virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref); + + private: + typedef boost::shared_ptr<GenericRequest<JinglePayload> > RequestRef; + + void handleIncomingAction(JinglePayload::ref); + + std::string sendSetRequest(JinglePayload::ref payload); + JinglePayload::ref createPayload() const; + void handleRequestResponse(RequestRef); + + private: + IQRouter *iqRouter; + JID peerJID; + typedef std::map<RequestRef, boost::bsignals::connection > RequestsMap; + RequestsMap pendingRequests; + }; } diff --git a/Swiften/Jingle/JingleSessionListener.h b/Swiften/Jingle/JingleSessionListener.h index dabeb05..54101b6 100644 --- a/Swiften/Jingle/JingleSessionListener.h +++ b/Swiften/Jingle/JingleSessionListener.h @@ -10,31 +10,31 @@ #include <Swiften/Elements/JinglePayload.h> namespace Swift { - class JingleContentID; - class JingleTransportPayload; - class JingleDescription; + class JingleContentID; + class JingleTransportPayload; + class JingleDescription; - class SWIFTEN_API JingleSessionListener { - public: - virtual ~JingleSessionListener(); + class SWIFTEN_API JingleSessionListener { + public: + virtual ~JingleSessionListener(); - virtual void handleSessionAcceptReceived( - const JingleContentID&, - boost::shared_ptr<JingleDescription>, - boost::shared_ptr<JingleTransportPayload>) = 0; - virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) = 0; - virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) = 0; - virtual void handleTransportAcceptReceived( - const JingleContentID&, - boost::shared_ptr<JingleTransportPayload>) = 0; - virtual void handleTransportInfoReceived( - const JingleContentID&, - boost::shared_ptr<JingleTransportPayload>) = 0; - virtual void handleTransportRejectReceived( - const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0; - virtual void handleTransportReplaceReceived( - const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0; + virtual void handleSessionAcceptReceived( + const JingleContentID&, + boost::shared_ptr<JingleDescription>, + boost::shared_ptr<JingleTransportPayload>) = 0; + virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) = 0; + virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) = 0; + virtual void handleTransportAcceptReceived( + const JingleContentID&, + boost::shared_ptr<JingleTransportPayload>) = 0; + virtual void handleTransportInfoReceived( + const JingleContentID&, + boost::shared_ptr<JingleTransportPayload>) = 0; + virtual void handleTransportRejectReceived( + const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0; + virtual void handleTransportReplaceReceived( + const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0; - virtual void handleTransportInfoAcknowledged(const std::string& id) = 0; - }; + virtual void handleTransportInfoAcknowledged(const std::string& id) = 0; + }; } diff --git a/Swiften/Jingle/JingleSessionManager.cpp b/Swiften/Jingle/JingleSessionManager.cpp index 81014e7..ca6cebb 100644 --- a/Swiften/Jingle/JingleSessionManager.cpp +++ b/Swiften/Jingle/JingleSessionManager.cpp @@ -15,41 +15,41 @@ namespace Swift { JingleSessionManager::JingleSessionManager(IQRouter* router) : router(router) { - responder = new JingleResponder(this, router); - responder->start(); + responder = new JingleResponder(this, router); + responder->start(); } JingleSessionManager::~JingleSessionManager() { - responder->stop(); - delete responder; + responder->stop(); + delete responder; } JingleSessionImpl::ref JingleSessionManager::getSession(const JID& jid, const std::string& id) const { - SessionMap::const_iterator i = sessions.find(JIDSession(jid, id)); - return i != sessions.end() ? i->second : JingleSessionImpl::ref(); + SessionMap::const_iterator i = sessions.find(JIDSession(jid, id)); + return i != sessions.end() ? i->second : JingleSessionImpl::ref(); } void JingleSessionManager::addIncomingSessionHandler(IncomingJingleSessionHandler* handler) { - incomingSessionHandlers.push_back(handler); + incomingSessionHandlers.push_back(handler); } void JingleSessionManager::removeIncomingSessionHandler(IncomingJingleSessionHandler* handler) { - erase(incomingSessionHandlers, handler); + erase(incomingSessionHandlers, handler); } void JingleSessionManager::registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref session) { - sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session)); - SWIFT_LOG(debug) << "Added session " << session->getID() << " for initiator " << initiator.toString() << std::endl; + sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session)); + SWIFT_LOG(debug) << "Added session " << session->getID() << " for initiator " << initiator.toString() << std::endl; } void JingleSessionManager::handleIncomingSession(const JID& initiator, const JID& recipient, JingleSessionImpl::ref session, const std::vector<JingleContentPayload::ref>& contents) { - sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session)); - foreach (IncomingJingleSessionHandler* handler, incomingSessionHandlers) { - if (handler->handleIncomingJingleSession(session, contents, recipient)) { - return; - } - } - // TODO: Finish session + sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session)); + foreach (IncomingJingleSessionHandler* handler, incomingSessionHandlers) { + if (handler->handleIncomingJingleSession(session, contents, recipient)) { + return; + } + } + // TODO: Finish session } diff --git a/Swiften/Jingle/JingleSessionManager.h b/Swiften/Jingle/JingleSessionManager.h index fbfdb50..fea6c73 100644 --- a/Swiften/Jingle/JingleSessionManager.h +++ b/Swiften/Jingle/JingleSessionManager.h @@ -15,38 +15,38 @@ #include <Swiften/Jingle/JingleSessionImpl.h> namespace Swift { - class IQRouter; - class JingleResponder; - class IncomingJingleSessionHandler; - - class SWIFTEN_API JingleSessionManager { - friend class JingleResponder; - public: - JingleSessionManager(IQRouter* router); - ~JingleSessionManager(); - - JingleSessionImpl::ref getSession(const JID& jid, const std::string& id) const; - - void addIncomingSessionHandler(IncomingJingleSessionHandler* handler); - void removeIncomingSessionHandler(IncomingJingleSessionHandler* handler); - - void registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref); - protected: - void handleIncomingSession(const JID& initiator, const JID& recipient, JingleSessionImpl::ref, const std::vector<JingleContentPayload::ref>& contents); - - private: - IQRouter* router; - JingleResponder* responder; - std::vector<IncomingJingleSessionHandler*> incomingSessionHandlers; - struct JIDSession { - JIDSession(const JID& initiator, const std::string& session) : initiator(initiator), session(session) {} - bool operator<(const JIDSession& o) const { - return initiator == o.initiator ? session < o.session : initiator < o.initiator; - } - JID initiator; - std::string session; - }; - typedef std::map<JIDSession, JingleSessionImpl::ref> SessionMap; - SessionMap sessions; - }; + class IQRouter; + class JingleResponder; + class IncomingJingleSessionHandler; + + class SWIFTEN_API JingleSessionManager { + friend class JingleResponder; + public: + JingleSessionManager(IQRouter* router); + ~JingleSessionManager(); + + JingleSessionImpl::ref getSession(const JID& jid, const std::string& id) const; + + void addIncomingSessionHandler(IncomingJingleSessionHandler* handler); + void removeIncomingSessionHandler(IncomingJingleSessionHandler* handler); + + void registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref); + protected: + void handleIncomingSession(const JID& initiator, const JID& recipient, JingleSessionImpl::ref, const std::vector<JingleContentPayload::ref>& contents); + + private: + IQRouter* router; + JingleResponder* responder; + std::vector<IncomingJingleSessionHandler*> incomingSessionHandlers; + struct JIDSession { + JIDSession(const JID& initiator, const std::string& session) : initiator(initiator), session(session) {} + bool operator<(const JIDSession& o) const { + return initiator == o.initiator ? session < o.session : initiator < o.initiator; + } + JID initiator; + std::string session; + }; + typedef std::map<JIDSession, JingleSessionImpl::ref> SessionMap; + SessionMap sessions; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp index 98038e1..a1bdb3e 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp @@ -15,47 +15,47 @@ namespace Swift { void AvahiBrowseQuery::startBrowsing() { - std::cout << "Start browsing" << std::endl; - assert(!browser); - avahi_threaded_poll_lock(querier->getThreadedPoll()); - browser = avahi_service_browser_new(querier->getClient(), AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_presence._tcp", NULL, static_cast<AvahiLookupFlags>(0), &handleServiceDiscoveredStatic, this); - if (!browser) { - std::cout << "Error" << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); - } - avahi_threaded_poll_unlock(querier->getThreadedPoll()); + std::cout << "Start browsing" << std::endl; + assert(!browser); + avahi_threaded_poll_lock(querier->getThreadedPoll()); + browser = avahi_service_browser_new(querier->getClient(), AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_presence._tcp", NULL, static_cast<AvahiLookupFlags>(0), &handleServiceDiscoveredStatic, this); + if (!browser) { + std::cout << "Error" << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); + } + avahi_threaded_poll_unlock(querier->getThreadedPoll()); } void AvahiBrowseQuery::stopBrowsing() { - std::cout << "Stop browsing" << std::endl; - avahi_threaded_poll_lock(querier->getThreadedPoll()); - avahi_service_browser_free(browser); - browser = NULL; - avahi_threaded_poll_unlock(querier->getThreadedPoll()); + std::cout << "Stop browsing" << std::endl; + avahi_threaded_poll_lock(querier->getThreadedPoll()); + avahi_service_browser_free(browser); + browser = NULL; + avahi_threaded_poll_unlock(querier->getThreadedPoll()); } void AvahiBrowseQuery::handleServiceDiscovered(AvahiServiceBrowser *, AvahiIfIndex interfaceIndex, AvahiProtocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags) { - switch (event) { - case AVAHI_BROWSER_FAILURE: - std::cout << "Service browse error" << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); - break; - case AVAHI_BROWSER_NEW: { - DNSSDServiceID service(name, domain, type, interfaceIndex); - std::cout << "Service discovered " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this()); - break; - } - case AVAHI_BROWSER_REMOVE: { - std::cout << "Service went away " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl; - DNSSDServiceID service(name, domain, type, interfaceIndex); - eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this()); - break; - } - case AVAHI_BROWSER_ALL_FOR_NOW: - case AVAHI_BROWSER_CACHE_EXHAUSTED: - break; - } + switch (event) { + case AVAHI_BROWSER_FAILURE: + std::cout << "Service browse error" << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); + break; + case AVAHI_BROWSER_NEW: { + DNSSDServiceID service(name, domain, type, interfaceIndex); + std::cout << "Service discovered " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this()); + break; + } + case AVAHI_BROWSER_REMOVE: { + std::cout << "Service went away " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl; + DNSSDServiceID service(name, domain, type, interfaceIndex); + eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this()); + break; + } + case AVAHI_BROWSER_ALL_FOR_NOW: + case AVAHI_BROWSER_CACHE_EXHAUSTED: + break; + } } } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h index d473534..767ee1d 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h @@ -13,25 +13,25 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h> namespace Swift { - class AvahiQuerier; + class AvahiQuerier; - class AvahiBrowseQuery : public DNSSDBrowseQuery, public AvahiQuery { - public: - AvahiBrowseQuery(boost::shared_ptr<AvahiQuerier> q, EventLoop* eventLoop) : AvahiQuery(q, eventLoop), browser(NULL) { - } + class AvahiBrowseQuery : public DNSSDBrowseQuery, public AvahiQuery { + public: + AvahiBrowseQuery(boost::shared_ptr<AvahiQuerier> q, EventLoop* eventLoop) : AvahiQuery(q, eventLoop), browser(NULL) { + } - void startBrowsing(); - void stopBrowsing(); + void startBrowsing(); + void stopBrowsing(); - private: - static void handleServiceDiscoveredStatic(AvahiServiceBrowser *b, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags flags, void* context) { - static_cast<AvahiBrowseQuery*>(context)->handleServiceDiscovered(b, interfaceIndex, protocol, event, name, type, domain, flags); - } + private: + static void handleServiceDiscoveredStatic(AvahiServiceBrowser *b, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags flags, void* context) { + static_cast<AvahiBrowseQuery*>(context)->handleServiceDiscovered(b, interfaceIndex, protocol, event, name, type, domain, flags); + } - void handleServiceDiscovered(AvahiServiceBrowser *, AvahiIfIndex interfaceIndex, AvahiProtocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags); + void handleServiceDiscovered(AvahiServiceBrowser *, AvahiIfIndex interfaceIndex, AvahiProtocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags); - private: - AvahiServiceBrowser* browser; - - }; + private: + AvahiServiceBrowser* browser; + + }; } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp index c9449ff..11f1650 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp @@ -22,45 +22,45 @@ AvahiQuerier::~AvahiQuerier() { } boost::shared_ptr<DNSSDBrowseQuery> AvahiQuerier::createBrowseQuery() { - return boost::shared_ptr<DNSSDBrowseQuery>(new AvahiBrowseQuery(shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDBrowseQuery>(new AvahiBrowseQuery(shared_from_this(), eventLoop)); } boost::shared_ptr<DNSSDRegisterQuery> AvahiQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) { - return boost::shared_ptr<DNSSDRegisterQuery>(new AvahiRegisterQuery(name, port, info, shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDRegisterQuery>(new AvahiRegisterQuery(name, port, info, shared_from_this(), eventLoop)); } boost::shared_ptr<DNSSDResolveServiceQuery> AvahiQuerier::createResolveServiceQuery(const DNSSDServiceID& service) { - return boost::shared_ptr<DNSSDResolveServiceQuery>(new AvahiResolveServiceQuery(service, shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDResolveServiceQuery>(new AvahiResolveServiceQuery(service, shared_from_this(), eventLoop)); } boost::shared_ptr<DNSSDResolveHostnameQuery> AvahiQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) { - return boost::shared_ptr<DNSSDResolveHostnameQuery>(new AvahiResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDResolveHostnameQuery>(new AvahiResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop)); } void AvahiQuerier::start() { - std::cout << "Starrting querier" << std::endl; - assert(!threadedPoll); - threadedPoll = avahi_threaded_poll_new(); - int error; - assert(!client); - client = avahi_client_new( - avahi_threaded_poll_get(threadedPoll), - static_cast<AvahiClientFlags>(0), NULL, this, &error); // TODO - if (!client) { - // TODO - std::cerr << "Avahi Error: " << avahi_strerror(error) << std::endl; - return; - } - std::cout << "Starrting event loop" << std::endl; - avahi_threaded_poll_start(threadedPoll); + std::cout << "Starrting querier" << std::endl; + assert(!threadedPoll); + threadedPoll = avahi_threaded_poll_new(); + int error; + assert(!client); + client = avahi_client_new( + avahi_threaded_poll_get(threadedPoll), + static_cast<AvahiClientFlags>(0), NULL, this, &error); // TODO + if (!client) { + // TODO + std::cerr << "Avahi Error: " << avahi_strerror(error) << std::endl; + return; + } + std::cout << "Starrting event loop" << std::endl; + avahi_threaded_poll_start(threadedPoll); } void AvahiQuerier::stop() { - assert(threadedPoll); - avahi_threaded_poll_stop(threadedPoll); - assert(client); - avahi_client_free(client); - avahi_threaded_poll_free(threadedPoll); + assert(threadedPoll); + avahi_threaded_poll_stop(threadedPoll); + assert(client); + avahi_client_free(client); + avahi_threaded_poll_free(threadedPoll); } } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h index 3176536..fa9580e 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h @@ -20,37 +20,37 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h> namespace Swift { - class EventLoop; - - class AvahiQuerier : - public DNSSDQuerier, - public boost::enable_shared_from_this<AvahiQuerier> { - public: - AvahiQuerier(EventLoop* eventLoop); - ~AvahiQuerier(); - - boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); - boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info); - boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( - const DNSSDServiceID&); - boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( - const std::string& hostname, int interfaceIndex); - - void start(); - void stop(); - - AvahiThreadedPoll* getThreadedPoll() const { - return threadedPoll; - } - - AvahiClient* getClient() const { - return client; - } - - private: - EventLoop* eventLoop; - AvahiClient* client; - AvahiThreadedPoll* threadedPoll; - }; + class EventLoop; + + class AvahiQuerier : + public DNSSDQuerier, + public boost::enable_shared_from_this<AvahiQuerier> { + public: + AvahiQuerier(EventLoop* eventLoop); + ~AvahiQuerier(); + + boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); + boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( + const std::string& name, int port, const ByteArray& info); + boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( + const DNSSDServiceID&); + boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( + const std::string& hostname, int interfaceIndex); + + void start(); + void stop(); + + AvahiThreadedPoll* getThreadedPoll() const { + return threadedPoll; + } + + AvahiClient* getClient() const { + return client; + } + + private: + EventLoop* eventLoop; + AvahiClient* client; + AvahiThreadedPoll* threadedPoll; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h index c2d745c..5752003 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h @@ -12,19 +12,19 @@ #include <Swiften/EventLoop/EventOwner.h> namespace Swift { - class AvahiQuerier; - class EventLoop; + class AvahiQuerier; + class EventLoop; - class AvahiQuery : - public EventOwner, - public boost::enable_shared_from_this<AvahiQuery> { - public: - AvahiQuery(boost::shared_ptr<AvahiQuerier>, EventLoop* eventLoop); - virtual ~AvahiQuery(); - - protected: - boost::shared_ptr<AvahiQuerier> querier; - EventLoop* eventLoop; - }; + class AvahiQuery : + public EventOwner, + public boost::enable_shared_from_this<AvahiQuery> { + public: + AvahiQuery(boost::shared_ptr<AvahiQuerier>, EventLoop* eventLoop); + virtual ~AvahiQuery(); + + protected: + boost::shared_ptr<AvahiQuerier> querier; + EventLoop* eventLoop; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp index 48fe17d..04790d5 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp @@ -15,87 +15,87 @@ namespace Swift { void AvahiRegisterQuery::registerService() { - std::cout << "Registering service " << name << ":" << port << std::endl; - avahi_threaded_poll_lock(querier->getThreadedPoll()); - if (!group) { - std::cout << "Creating entry group" << std::endl; - group = avahi_entry_group_new(querier->getClient(), handleEntryGroupChange, this); - if (!group) { - std::cout << "Error ceating entry group" << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); - } - } - - doRegisterService(); - avahi_threaded_poll_unlock(querier->getThreadedPoll()); + std::cout << "Registering service " << name << ":" << port << std::endl; + avahi_threaded_poll_lock(querier->getThreadedPoll()); + if (!group) { + std::cout << "Creating entry group" << std::endl; + group = avahi_entry_group_new(querier->getClient(), handleEntryGroupChange, this); + if (!group) { + std::cout << "Error ceating entry group" << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); + } + } + + doRegisterService(); + avahi_threaded_poll_unlock(querier->getThreadedPoll()); } void AvahiRegisterQuery::unregisterService() { - if (group) { - avahi_entry_group_free(group); - group = NULL; - } + if (group) { + avahi_entry_group_free(group); + group = NULL; + } } void AvahiRegisterQuery::updateServiceInfo(const ByteArray& txtRecord) { - this->txtRecord = txtRecord; - avahi_threaded_poll_lock(querier->getThreadedPoll()); - assert(group); - avahi_entry_group_reset(group); - doRegisterService(); - avahi_threaded_poll_unlock(querier->getThreadedPoll()); + this->txtRecord = txtRecord; + avahi_threaded_poll_lock(querier->getThreadedPoll()); + assert(group); + avahi_entry_group_reset(group); + doRegisterService(); + avahi_threaded_poll_unlock(querier->getThreadedPoll()); } void AvahiRegisterQuery::doRegisterService() { - AvahiStringList* txtList; - avahi_string_list_parse(vecptr(txtRecord), txtRecord.size(), &txtList); - - int result = avahi_entry_group_add_service_strlst(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, static_cast<AvahiPublishFlags>(0), name.c_str(), "_presence._tcp", NULL, NULL, port, txtList); - if (result < 0) { - std::cout << "Error registering service: " << avahi_strerror(result) << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); - } - result = avahi_entry_group_commit(group); - if (result < 0) { - std::cout << "Error registering service: " << avahi_strerror(result) << std::endl; - } + AvahiStringList* txtList; + avahi_string_list_parse(vecptr(txtRecord), txtRecord.size(), &txtList); + + int result = avahi_entry_group_add_service_strlst(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, static_cast<AvahiPublishFlags>(0), name.c_str(), "_presence._tcp", NULL, NULL, port, txtList); + if (result < 0) { + std::cout << "Error registering service: " << avahi_strerror(result) << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); + } + result = avahi_entry_group_commit(group); + if (result < 0) { + std::cout << "Error registering service: " << avahi_strerror(result) << std::endl; + } } void AvahiRegisterQuery::handleEntryGroupChange(AvahiEntryGroup* g, AvahiEntryGroupState state) { - std::cout << "ENtry group callback: " << state << std::endl; - switch (state) { - case AVAHI_ENTRY_GROUP_ESTABLISHED : - // Domain is a hack! - eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, "local", "_presence._tcp", 0))), shared_from_this()); - std::cout << "Entry group established" << std::endl; - break; - case AVAHI_ENTRY_GROUP_COLLISION : { - std::cout << "Entry group collision" << std::endl; - /*char *n; - n = avahi_alternative_service_name(name); - avahi_free(name); - name = n;*/ - break; - } - - case AVAHI_ENTRY_GROUP_FAILURE : - std::cout << "Entry group failure " << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))) << std::endl; - break; - - case AVAHI_ENTRY_GROUP_UNCOMMITED: - case AVAHI_ENTRY_GROUP_REGISTERING: - ; - - /* - DNSServiceErrorType result = DNSServiceRegister( - &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, port, - txtRecord.getSize(), txtRecord.getData(), - &AvahiRegisterQuery::handleServiceRegisteredStatic, this); - if (result != kDNSServiceErr_NoError) { - sdRef = NULL; - }*/ - //eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); - } + std::cout << "ENtry group callback: " << state << std::endl; + switch (state) { + case AVAHI_ENTRY_GROUP_ESTABLISHED : + // Domain is a hack! + eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, "local", "_presence._tcp", 0))), shared_from_this()); + std::cout << "Entry group established" << std::endl; + break; + case AVAHI_ENTRY_GROUP_COLLISION : { + std::cout << "Entry group collision" << std::endl; + /*char *n; + n = avahi_alternative_service_name(name); + avahi_free(name); + name = n;*/ + break; + } + + case AVAHI_ENTRY_GROUP_FAILURE : + std::cout << "Entry group failure " << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))) << std::endl; + break; + + case AVAHI_ENTRY_GROUP_UNCOMMITED: + case AVAHI_ENTRY_GROUP_REGISTERING: + ; + + /* + DNSServiceErrorType result = DNSServiceRegister( + &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, port, + txtRecord.getSize(), txtRecord.getData(), + &AvahiRegisterQuery::handleServiceRegisteredStatic, this); + if (result != kDNSServiceErr_NoError) { + sdRef = NULL; + }*/ + //eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); + } } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h index 4da9bfd..5570559 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h @@ -14,44 +14,44 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h> namespace Swift { - class AvahiQuerier; + class AvahiQuerier; - class AvahiRegisterQuery : public DNSSDRegisterQuery, public AvahiQuery { - public: - AvahiRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), name(name), port(port), txtRecord(txtRecord), group(0) { - } + class AvahiRegisterQuery : public DNSSDRegisterQuery, public AvahiQuery { + public: + AvahiRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), name(name), port(port), txtRecord(txtRecord), group(0) { + } - void registerService(); - void unregisterService(); - void updateServiceInfo(const ByteArray& txtRecord); + void registerService(); + void unregisterService(); + void updateServiceInfo(const ByteArray& txtRecord); - private: - void doRegisterService(); + private: + void doRegisterService(); - static void handleEntryGroupChange(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) { - static_cast<AvahiRegisterQuery*>(userdata)->handleEntryGroupChange(g, state); - } + static void handleEntryGroupChange(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) { + static_cast<AvahiRegisterQuery*>(userdata)->handleEntryGroupChange(g, state); + } - void handleEntryGroupChange(AvahiEntryGroup* g, AvahiEntryGroupState state); + void handleEntryGroupChange(AvahiEntryGroup* g, AvahiEntryGroupState state); /* - static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) { - static_cast<AvahiRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain); - } - - void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) { - if (errorCode != kDNSServiceErr_NoError) { - eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); - } - else { - } - } - */ - - private: - std::string name; - int port; - ByteArray txtRecord; - AvahiEntryGroup* group; - }; + static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) { + static_cast<AvahiRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain); + } + + void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) { + if (errorCode != kDNSServiceErr_NoError) { + eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); + } + else { + } + } + */ + + private: + std::string name; + int port; + ByteArray txtRecord; + AvahiEntryGroup* group; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp index a9910a3..af1a048 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp @@ -13,11 +13,11 @@ namespace Swift { AvahiResolveHostnameQuery::AvahiResolveHostnameQuery(const std::string& hostname, int, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), hostname(hostname) { - std::cout << "Resolving hostname " << hostname << std::endl; + std::cout << "Resolving hostname " << hostname << std::endl; } void AvahiResolveHostnameQuery::run() { - eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>(HostAddress(hostname))), shared_from_this()); + eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>(HostAddress(hostname))), shared_from_this()); } } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h index 000d966..9d21bf9 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h @@ -16,19 +16,19 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class AvahiQuerier; + class AvahiQuerier; - class AvahiResolveHostnameQuery : public DNSSDResolveHostnameQuery, public AvahiQuery { - public: - AvahiResolveHostnameQuery(const std::string& hostname, int, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop); + class AvahiResolveHostnameQuery : public DNSSDResolveHostnameQuery, public AvahiQuery { + public: + AvahiResolveHostnameQuery(const std::string& hostname, int, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop); - void run(); + void run(); - void finish() { - } + void finish() { + } - private: - HostAddress hostAddress; - std::string hostname; - }; + private: + HostAddress hostAddress; + std::string hostname; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp index 470e165..a5e52b2 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp @@ -15,52 +15,52 @@ namespace Swift { void AvahiResolveServiceQuery::start() { - std::cout << "Start resolving " << service.getName() << " " << service.getType() << " " << service.getDomain() << std::endl; - avahi_threaded_poll_lock(querier->getThreadedPoll()); - assert(!resolver); - resolver = avahi_service_resolver_new(querier->getClient(), service.getNetworkInterfaceID(), AVAHI_PROTO_UNSPEC, service.getName().c_str(), service.getType().c_str(), service.getDomain().c_str(), AVAHI_PROTO_UNSPEC, static_cast<AvahiLookupFlags>(0), handleServiceResolvedStatic, this); - if (!resolver) { - std::cout << "Error starting resolver" << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); - } - avahi_threaded_poll_unlock(querier->getThreadedPoll()); + std::cout << "Start resolving " << service.getName() << " " << service.getType() << " " << service.getDomain() << std::endl; + avahi_threaded_poll_lock(querier->getThreadedPoll()); + assert(!resolver); + resolver = avahi_service_resolver_new(querier->getClient(), service.getNetworkInterfaceID(), AVAHI_PROTO_UNSPEC, service.getName().c_str(), service.getType().c_str(), service.getDomain().c_str(), AVAHI_PROTO_UNSPEC, static_cast<AvahiLookupFlags>(0), handleServiceResolvedStatic, this); + if (!resolver) { + std::cout << "Error starting resolver" << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); + } + avahi_threaded_poll_unlock(querier->getThreadedPoll()); } void AvahiResolveServiceQuery::stop() { - std::cout << "Stop resolving" << std::endl; - avahi_threaded_poll_lock(querier->getThreadedPoll()); - avahi_service_resolver_free(resolver); - resolver = NULL; - avahi_threaded_poll_unlock(querier->getThreadedPoll()); + std::cout << "Stop resolving" << std::endl; + avahi_threaded_poll_lock(querier->getThreadedPoll()); + avahi_service_resolver_free(resolver); + resolver = NULL; + avahi_threaded_poll_unlock(querier->getThreadedPoll()); } void AvahiResolveServiceQuery::handleServiceResolved(AvahiServiceResolver* resolver, AvahiIfIndex, AvahiProtocol, AvahiResolverEvent event, const char *name, const char * type, const char* domain, const char * /*host_name*/, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags) { - std::cout << "Resolve finished" << std::endl; - switch(event) { - case AVAHI_RESOLVER_FAILURE: - std::cout << "Resolve error " << avahi_strerror(avahi_client_errno(avahi_service_resolver_get_client(resolver))) << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); - break; - case AVAHI_RESOLVER_FOUND: { - std::cout << "Success" << std::endl; - char a[AVAHI_ADDRESS_STR_MAX]; - avahi_address_snprint(a, sizeof(a), address); + std::cout << "Resolve finished" << std::endl; + switch(event) { + case AVAHI_RESOLVER_FAILURE: + std::cout << "Resolve error " << avahi_strerror(avahi_client_errno(avahi_service_resolver_get_client(resolver))) << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); + break; + case AVAHI_RESOLVER_FOUND: { + std::cout << "Success" << std::endl; + char a[AVAHI_ADDRESS_STR_MAX]; + avahi_address_snprint(a, sizeof(a), address); - ByteArray txtRecord; - txtRecord.resize(1024); - avahi_string_list_serialize(txt, vecptr(txtRecord), txtRecord.size()); + ByteArray txtRecord; + txtRecord.resize(1024); + avahi_string_list_serialize(txt, vecptr(txtRecord), txtRecord.size()); - // FIXME: Probably not accurate - std::string fullname = std::string(name) + "." + std::string(type) + "." + std::string(domain) + "."; - std::cout << "Result: " << fullname << "->" << std::string(a) << ":" << port << std::endl; - eventLoop->postEvent( - boost::bind( - boost::ref(onServiceResolved), - Result(fullname, std::string(a), port, txtRecord)), - shared_from_this()); - break; - } - } + // FIXME: Probably not accurate + std::string fullname = std::string(name) + "." + std::string(type) + "." + std::string(domain) + "."; + std::cout << "Result: " << fullname << "->" << std::string(a) << ":" << port << std::endl; + eventLoop->postEvent( + boost::bind( + boost::ref(onServiceResolved), + Result(fullname, std::string(a), port, txtRecord)), + shared_from_this()); + break; + } + } } } diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h index 90c2fda..c95d131 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h @@ -15,25 +15,25 @@ #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> namespace Swift { - class AvahiQuerier; + class AvahiQuerier; - class AvahiResolveServiceQuery : public DNSSDResolveServiceQuery, public AvahiQuery { - public: - AvahiResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), service(service), resolver(NULL) { - } + class AvahiResolveServiceQuery : public DNSSDResolveServiceQuery, public AvahiQuery { + public: + AvahiResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), service(service), resolver(NULL) { + } - void start(); - void stop(); + void start(); + void stop(); - private: - static void handleServiceResolvedStatic(AvahiServiceResolver* resolver, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiResolverEvent event, const char *name, const char *type, const char *domain, const char *host_name, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags, void* context) { - static_cast<AvahiResolveServiceQuery*>(context)->handleServiceResolved(resolver, interfaceIndex, protocol, event, name, type, domain, host_name, address, port, txt, flags); - } + private: + static void handleServiceResolvedStatic(AvahiServiceResolver* resolver, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiResolverEvent event, const char *name, const char *type, const char *domain, const char *host_name, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags, void* context) { + static_cast<AvahiResolveServiceQuery*>(context)->handleServiceResolved(resolver, interfaceIndex, protocol, event, name, type, domain, host_name, address, port, txt, flags); + } - void handleServiceResolved(AvahiServiceResolver* resolver, AvahiIfIndex, AvahiProtocol, AvahiResolverEvent event, const char *name, const char * type, const char* domain, const char * /*host_name*/, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags); + void handleServiceResolved(AvahiServiceResolver* resolver, AvahiIfIndex, AvahiProtocol, AvahiResolverEvent event, const char *name, const char * type, const char* domain, const char * /*host_name*/, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags); - private: - DNSSDServiceID service; - AvahiServiceResolver* resolver; - }; + private: + DNSSDServiceID service; + AvahiServiceResolver* resolver; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h index 60b5dee..6cfaf22 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h @@ -13,51 +13,51 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h> namespace Swift { - class BonjourQuerier; - - class BonjourBrowseQuery : public DNSSDBrowseQuery, public BonjourQuery { - public: - BonjourBrowseQuery(boost::shared_ptr<BonjourQuerier> q, EventLoop* eventLoop) : BonjourQuery(q, eventLoop) { - DNSServiceErrorType result = DNSServiceBrowse( - &sdRef, 0, 0, "_presence._tcp", 0, - &BonjourBrowseQuery::handleServiceDiscoveredStatic, this); - if (result != kDNSServiceErr_NoError) { - sdRef = NULL; - } - } - - void startBrowsing() { - if (!sdRef) { - eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); - } - else { - run(); - } - } - - void stopBrowsing() { - finish(); - } - - private: - static void handleServiceDiscoveredStatic(DNSServiceRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain, void *context) { - static_cast<BonjourBrowseQuery*>(context)->handleServiceDiscovered(flags, interfaceIndex, errorCode, name, type, domain); - } - - void handleServiceDiscovered(DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain) { - if (errorCode != kDNSServiceErr_NoError) { - eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); - } - else { - //std::cout << "Discovered service: name:" << name << " domain:" << domain << " type: " << type << std::endl; - DNSSDServiceID service(name, domain, type, boost::numeric_cast<int>(interfaceIndex)); - if (flags & kDNSServiceFlagsAdd) { - eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this()); - } - else { - eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this()); - } - } - } - }; + class BonjourQuerier; + + class BonjourBrowseQuery : public DNSSDBrowseQuery, public BonjourQuery { + public: + BonjourBrowseQuery(boost::shared_ptr<BonjourQuerier> q, EventLoop* eventLoop) : BonjourQuery(q, eventLoop) { + DNSServiceErrorType result = DNSServiceBrowse( + &sdRef, 0, 0, "_presence._tcp", 0, + &BonjourBrowseQuery::handleServiceDiscoveredStatic, this); + if (result != kDNSServiceErr_NoError) { + sdRef = NULL; + } + } + + void startBrowsing() { + if (!sdRef) { + eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); + } + else { + run(); + } + } + + void stopBrowsing() { + finish(); + } + + private: + static void handleServiceDiscoveredStatic(DNSServiceRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain, void *context) { + static_cast<BonjourBrowseQuery*>(context)->handleServiceDiscovered(flags, interfaceIndex, errorCode, name, type, domain); + } + + void handleServiceDiscovered(DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain) { + if (errorCode != kDNSServiceErr_NoError) { + eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); + } + else { + //std::cout << "Discovered service: name:" << name << " domain:" << domain << " type: " << type << std::endl; + DNSSDServiceID service(name, domain, type, boost::numeric_cast<int>(interfaceIndex)); + if (flags & kDNSServiceFlagsAdd) { + eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this()); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this()); + } + } + } + }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp index ac62b49..19ebae3 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp @@ -20,117 +20,117 @@ namespace Swift { BonjourQuerier::BonjourQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), thread(0) { - int fds[2]; - int result = pipe(fds); - assert(result == 0); - (void) result; - interruptSelectReadSocket = fds[0]; - fcntl(interruptSelectReadSocket, F_SETFL, fcntl(interruptSelectReadSocket, F_GETFL)|O_NONBLOCK); - interruptSelectWriteSocket = fds[1]; + int fds[2]; + int result = pipe(fds); + assert(result == 0); + (void) result; + interruptSelectReadSocket = fds[0]; + fcntl(interruptSelectReadSocket, F_SETFL, fcntl(interruptSelectReadSocket, F_GETFL)|O_NONBLOCK); + interruptSelectWriteSocket = fds[1]; } BonjourQuerier::~BonjourQuerier() { - assert(!thread); + assert(!thread); } boost::shared_ptr<DNSSDBrowseQuery> BonjourQuerier::createBrowseQuery() { - return boost::shared_ptr<DNSSDBrowseQuery>(new BonjourBrowseQuery(shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDBrowseQuery>(new BonjourBrowseQuery(shared_from_this(), eventLoop)); } boost::shared_ptr<DNSSDRegisterQuery> BonjourQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) { - return boost::shared_ptr<DNSSDRegisterQuery>(new BonjourRegisterQuery(name, port, info, shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDRegisterQuery>(new BonjourRegisterQuery(name, port, info, shared_from_this(), eventLoop)); } boost::shared_ptr<DNSSDResolveServiceQuery> BonjourQuerier::createResolveServiceQuery(const DNSSDServiceID& service) { - return boost::shared_ptr<DNSSDResolveServiceQuery>(new BonjourResolveServiceQuery(service, shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDResolveServiceQuery>(new BonjourResolveServiceQuery(service, shared_from_this(), eventLoop)); } boost::shared_ptr<DNSSDResolveHostnameQuery> BonjourQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) { - return boost::shared_ptr<DNSSDResolveHostnameQuery>(new BonjourResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop)); + return boost::shared_ptr<DNSSDResolveHostnameQuery>(new BonjourResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop)); } void BonjourQuerier::addRunningQuery(boost::shared_ptr<BonjourQuery> query) { - { - boost::lock_guard<boost::mutex> lock(runningQueriesMutex); - runningQueries.push_back(query); - } - runningQueriesAvailableEvent.notify_one(); - interruptSelect(); + { + boost::lock_guard<boost::mutex> lock(runningQueriesMutex); + runningQueries.push_back(query); + } + runningQueriesAvailableEvent.notify_one(); + interruptSelect(); } void BonjourQuerier::removeRunningQuery(boost::shared_ptr<BonjourQuery> query) { - { - boost::lock_guard<boost::mutex> lock(runningQueriesMutex); - erase(runningQueries, query); - } + { + boost::lock_guard<boost::mutex> lock(runningQueriesMutex); + erase(runningQueries, query); + } } void BonjourQuerier::interruptSelect() { - char c = 0; - write(interruptSelectWriteSocket, &c, 1); + char c = 0; + write(interruptSelectWriteSocket, &c, 1); } void BonjourQuerier::start() { - assert(!thread); - thread = new boost::thread(boost::bind(&BonjourQuerier::run, shared_from_this())); + assert(!thread); + thread = new boost::thread(boost::bind(&BonjourQuerier::run, shared_from_this())); } void BonjourQuerier::stop() { - if (thread) { - stopRequested = true; - assert(runningQueries.empty()); - runningQueriesAvailableEvent.notify_one(); - interruptSelect(); - thread->join(); - delete thread; - thread = NULL; - stopRequested = false; - } + if (thread) { + stopRequested = true; + assert(runningQueries.empty()); + runningQueriesAvailableEvent.notify_one(); + interruptSelect(); + thread->join(); + delete thread; + thread = NULL; + stopRequested = false; + } } void BonjourQuerier::run() { - while (!stopRequested) { - fd_set fdSet; - int maxSocket; - { - boost::unique_lock<boost::mutex> lock(runningQueriesMutex); - if (runningQueries.empty()) { - runningQueriesAvailableEvent.wait(lock); - if (runningQueries.empty()) { - continue; - } - } - - // Run all running queries - FD_ZERO(&fdSet); - maxSocket = interruptSelectReadSocket; - FD_SET(interruptSelectReadSocket, &fdSet); - - foreach(const boost::shared_ptr<BonjourQuery>& query, runningQueries) { - int socketID = query->getSocketID(); - maxSocket = std::max(maxSocket, socketID); - FD_SET(socketID, &fdSet); - } - } - - if (select(maxSocket+1, &fdSet, NULL, NULL, 0) <= 0) { - continue; - } - - if (FD_ISSET(interruptSelectReadSocket, &fdSet)) { - char dummy; - while (read(interruptSelectReadSocket, &dummy, 1) > 0) {} - } - - { - boost::lock_guard<boost::mutex> lock(runningQueriesMutex); - foreach(boost::shared_ptr<BonjourQuery> query, runningQueries) { - if (FD_ISSET(query->getSocketID(), &fdSet)) { - query->processResult(); - } - } - } - } + while (!stopRequested) { + fd_set fdSet; + int maxSocket; + { + boost::unique_lock<boost::mutex> lock(runningQueriesMutex); + if (runningQueries.empty()) { + runningQueriesAvailableEvent.wait(lock); + if (runningQueries.empty()) { + continue; + } + } + + // Run all running queries + FD_ZERO(&fdSet); + maxSocket = interruptSelectReadSocket; + FD_SET(interruptSelectReadSocket, &fdSet); + + foreach(const boost::shared_ptr<BonjourQuery>& query, runningQueries) { + int socketID = query->getSocketID(); + maxSocket = std::max(maxSocket, socketID); + FD_SET(socketID, &fdSet); + } + } + + if (select(maxSocket+1, &fdSet, NULL, NULL, 0) <= 0) { + continue; + } + + if (FD_ISSET(interruptSelectReadSocket, &fdSet)) { + char dummy; + while (read(interruptSelectReadSocket, &dummy, 1) > 0) {} + } + + { + boost::lock_guard<boost::mutex> lock(runningQueriesMutex); + foreach(boost::shared_ptr<BonjourQuery> query, runningQueries) { + if (FD_ISSET(query->getSocketID(), &fdSet)) { + query->processResult(); + } + } + } + } } } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h index 532c73e..74140ac 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h @@ -18,40 +18,40 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h> namespace Swift { - class BonjourQuerier : - public DNSSDQuerier, - public boost::enable_shared_from_this<BonjourQuerier> { - public: - BonjourQuerier(EventLoop* eventLoop); - ~BonjourQuerier(); - - boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); - boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info); - boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( - const DNSSDServiceID&); - boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( - const std::string& hostname, int interfaceIndex); - - void start(); - void stop(); - - private: - friend class BonjourQuery; - - void addRunningQuery(boost::shared_ptr<BonjourQuery>); - void removeRunningQuery(boost::shared_ptr<BonjourQuery>); - void interruptSelect(); - void run(); - - private: - EventLoop* eventLoop; - bool stopRequested; - boost::thread* thread; - boost::mutex runningQueriesMutex; - std::list< boost::shared_ptr<BonjourQuery> > runningQueries; - int interruptSelectReadSocket; - int interruptSelectWriteSocket; - boost::condition_variable runningQueriesAvailableEvent; - }; + class BonjourQuerier : + public DNSSDQuerier, + public boost::enable_shared_from_this<BonjourQuerier> { + public: + BonjourQuerier(EventLoop* eventLoop); + ~BonjourQuerier(); + + boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); + boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( + const std::string& name, int port, const ByteArray& info); + boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( + const DNSSDServiceID&); + boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( + const std::string& hostname, int interfaceIndex); + + void start(); + void stop(); + + private: + friend class BonjourQuery; + + void addRunningQuery(boost::shared_ptr<BonjourQuery>); + void removeRunningQuery(boost::shared_ptr<BonjourQuery>); + void interruptSelect(); + void run(); + + private: + EventLoop* eventLoop; + bool stopRequested; + boost::thread* thread; + boost::mutex runningQueriesMutex; + std::list< boost::shared_ptr<BonjourQuery> > runningQueries; + int interruptSelectReadSocket; + int interruptSelectWriteSocket; + boost::condition_variable runningQueriesAvailableEvent; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp index a4036e9..c2a69b4 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp @@ -14,25 +14,25 @@ BonjourQuery::BonjourQuery(boost::shared_ptr<BonjourQuerier> q, EventLoop* event } BonjourQuery::~BonjourQuery() { - DNSServiceRefDeallocate(sdRef); + DNSServiceRefDeallocate(sdRef); } void BonjourQuery::processResult() { - boost::lock_guard<boost::mutex> lock(sdRefMutex); - DNSServiceProcessResult(sdRef); + boost::lock_guard<boost::mutex> lock(sdRefMutex); + DNSServiceProcessResult(sdRef); } int BonjourQuery::getSocketID() const { - boost::lock_guard<boost::mutex> lock(sdRefMutex); - return DNSServiceRefSockFD(sdRef); + boost::lock_guard<boost::mutex> lock(sdRefMutex); + return DNSServiceRefSockFD(sdRef); } void BonjourQuery::run() { - querier->addRunningQuery(shared_from_this()); + querier->addRunningQuery(shared_from_this()); } void BonjourQuery::finish() { - querier->removeRunningQuery(shared_from_this()); + querier->removeRunningQuery(shared_from_this()); } } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h index 5e62965..2e3eb80 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h @@ -15,27 +15,27 @@ #include <Swiften/EventLoop/EventOwner.h> namespace Swift { - class BonjourQuerier; - class EventLoop; - - class BonjourQuery : - public EventOwner, - public boost::enable_shared_from_this<BonjourQuery> { - public: - BonjourQuery(boost::shared_ptr<BonjourQuerier>, EventLoop* eventLoop); - virtual ~BonjourQuery(); - - void processResult(); - int getSocketID() const; - - protected: - void run(); - void finish(); - - protected: - EventLoop* eventLoop; - boost::shared_ptr<BonjourQuerier> querier; - mutable boost::mutex sdRefMutex; - DNSServiceRef sdRef; - }; + class BonjourQuerier; + class EventLoop; + + class BonjourQuery : + public EventOwner, + public boost::enable_shared_from_this<BonjourQuery> { + public: + BonjourQuery(boost::shared_ptr<BonjourQuerier>, EventLoop* eventLoop); + virtual ~BonjourQuery(); + + void processResult(); + int getSocketID() const; + + protected: + void run(); + void finish(); + + protected: + EventLoop* eventLoop; + boost::shared_ptr<BonjourQuerier> querier; + mutable boost::mutex sdRefMutex; + DNSServiceRef sdRef; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h index b48fbf4..58b6fdd 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h @@ -15,50 +15,50 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h> namespace Swift { - class BonjourQuerier; + class BonjourQuerier; - class BonjourRegisterQuery : public DNSSDRegisterQuery, public BonjourQuery { - public: - BonjourRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { - DNSServiceErrorType result = DNSServiceRegister( - &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, boost::numeric_cast<unsigned short>(port), - boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), - &BonjourRegisterQuery::handleServiceRegisteredStatic, this); - if (result != kDNSServiceErr_NoError) { - sdRef = NULL; - } - } + class BonjourRegisterQuery : public DNSSDRegisterQuery, public BonjourQuery { + public: + BonjourRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { + DNSServiceErrorType result = DNSServiceRegister( + &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, boost::numeric_cast<unsigned short>(port), + boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), + &BonjourRegisterQuery::handleServiceRegisteredStatic, this); + if (result != kDNSServiceErr_NoError) { + sdRef = NULL; + } + } - void registerService() { - if (sdRef) { - run(); - } - else { - eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); - } - } + void registerService() { + if (sdRef) { + run(); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); + } + } - void unregisterService() { - finish(); - } + void unregisterService() { + finish(); + } - void updateServiceInfo(const ByteArray& txtRecord) { - boost::lock_guard<boost::mutex> lock(sdRefMutex); - DNSServiceUpdateRecord(sdRef, NULL, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0); - } + void updateServiceInfo(const ByteArray& txtRecord) { + boost::lock_guard<boost::mutex> lock(sdRefMutex); + DNSServiceUpdateRecord(sdRef, NULL, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0); + } - private: - static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) { - static_cast<BonjourRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain); - } + private: + static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) { + static_cast<BonjourRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain); + } - void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) { - if (errorCode != kDNSServiceErr_NoError) { - eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); - } - else { - eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, domain, regtype, 0))), shared_from_this()); - } - } - }; + void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) { + if (errorCode != kDNSServiceErr_NoError) { + eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, domain, regtype, 0))), shared_from_this()); + } + } + }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h index 5da9f75..755984c 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h @@ -18,55 +18,55 @@ #include <netinet/in.h> namespace Swift { - class BonjourQuerier; + class BonjourQuerier; - class BonjourResolveHostnameQuery : public DNSSDResolveHostnameQuery, public BonjourQuery { - public: - BonjourResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { - DNSServiceErrorType result = DNSServiceGetAddrInfo( - &sdRef, 0, boost::numeric_cast<unsigned int>(interfaceIndex), kDNSServiceProtocol_IPv4, - hostname.c_str(), - &BonjourResolveHostnameQuery::handleHostnameResolvedStatic, this); - if (result != kDNSServiceErr_NoError) { - sdRef = NULL; - } - } + class BonjourResolveHostnameQuery : public DNSSDResolveHostnameQuery, public BonjourQuery { + public: + BonjourResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { + DNSServiceErrorType result = DNSServiceGetAddrInfo( + &sdRef, 0, boost::numeric_cast<unsigned int>(interfaceIndex), kDNSServiceProtocol_IPv4, + hostname.c_str(), + &BonjourResolveHostnameQuery::handleHostnameResolvedStatic, this); + if (result != kDNSServiceErr_NoError) { + sdRef = NULL; + } + } - //void DNSSDResolveHostnameQuery::run() { - void run() { - if (sdRef) { - BonjourQuery::run(); - } - else { - eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>()), shared_from_this()); - } - } + //void DNSSDResolveHostnameQuery::run() { + void run() { + if (sdRef) { + BonjourQuery::run(); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>()), shared_from_this()); + } + } - void finish() { - BonjourQuery::finish(); - } + void finish() { + BonjourQuery::finish(); + } - private: - static void handleHostnameResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char*, const struct sockaddr *address, uint32_t, void *context) { - static_cast<BonjourResolveHostnameQuery*>(context)->handleHostnameResolved(errorCode, address); - } + private: + static void handleHostnameResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char*, const struct sockaddr *address, uint32_t, void *context) { + static_cast<BonjourResolveHostnameQuery*>(context)->handleHostnameResolved(errorCode, address); + } - void handleHostnameResolved(DNSServiceErrorType errorCode, const struct sockaddr *rawAddress) { - if (errorCode) { - eventLoop->postEvent( - boost::bind(boost::ref(onHostnameResolved), - boost::optional<HostAddress>()), - shared_from_this()); - } - else { - assert(rawAddress->sa_family == AF_INET); - const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(rawAddress); - uint32_t address = ntohl(sa->sin_addr.s_addr); - eventLoop->postEvent(boost::bind( - boost::ref(onHostnameResolved), - HostAddress(reinterpret_cast<unsigned char*>(&address), 4)), - shared_from_this()); - } - } - }; + void handleHostnameResolved(DNSServiceErrorType errorCode, const struct sockaddr *rawAddress) { + if (errorCode) { + eventLoop->postEvent( + boost::bind(boost::ref(onHostnameResolved), + boost::optional<HostAddress>()), + shared_from_this()); + } + else { + assert(rawAddress->sa_family == AF_INET); + const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(rawAddress); + uint32_t address = ntohl(sa->sin_addr.s_addr); + eventLoop->postEvent(boost::bind( + boost::ref(onHostnameResolved), + HostAddress(reinterpret_cast<unsigned char*>(&address), 4)), + shared_from_this()); + } + } + }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h index ecb6864..7833641 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h @@ -13,52 +13,52 @@ #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> namespace Swift { - class BonjourQuerier; + class BonjourQuerier; - class BonjourResolveServiceQuery : public DNSSDResolveServiceQuery, public BonjourQuery { - public: - BonjourResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { - DNSServiceErrorType result = DNSServiceResolve( - &sdRef, 0, boost::numeric_cast<unsigned int>(service.getNetworkInterfaceID()), - service.getName().c_str(), service.getType().c_str(), - service.getDomain().c_str(), - &BonjourResolveServiceQuery::handleServiceResolvedStatic, this); - if (result != kDNSServiceErr_NoError) { - sdRef = NULL; - } - } + class BonjourResolveServiceQuery : public DNSSDResolveServiceQuery, public BonjourQuery { + public: + BonjourResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { + DNSServiceErrorType result = DNSServiceResolve( + &sdRef, 0, boost::numeric_cast<unsigned int>(service.getNetworkInterfaceID()), + service.getName().c_str(), service.getType().c_str(), + service.getDomain().c_str(), + &BonjourResolveServiceQuery::handleServiceResolvedStatic, this); + if (result != kDNSServiceErr_NoError) { + sdRef = NULL; + } + } - void start() { - if (sdRef) { - run(); - } - else { - eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); - } - } + void start() { + if (sdRef) { + run(); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); + } + } - void stop() { - finish(); - } + void stop() { + finish(); + } - private: - static void handleServiceResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char *fullname, const char *hosttarget, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord, void *context) { - static_cast<BonjourResolveServiceQuery*>(context)->handleServiceResolved(errorCode, fullname, hosttarget, port, txtLen, txtRecord); - } + private: + static void handleServiceResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char *fullname, const char *hosttarget, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord, void *context) { + static_cast<BonjourResolveServiceQuery*>(context)->handleServiceResolved(errorCode, fullname, hosttarget, port, txtLen, txtRecord); + } - void handleServiceResolved(DNSServiceErrorType errorCode, const char* fullName, const char* host, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord) { - if (errorCode != kDNSServiceErr_NoError) { - eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); - } - else { - //std::cout << "Service resolved: name:" << fullName << " host:" << host << " port:" << port << std::endl; - eventLoop->postEvent( - boost::bind( - boost::ref(onServiceResolved), - Result(std::string(fullName), std::string(host), port, - createByteArray(reinterpret_cast<const char*>(txtRecord), txtLen))), - shared_from_this()); - } - } - }; + void handleServiceResolved(DNSServiceErrorType errorCode, const char* fullName, const char* host, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord) { + if (errorCode != kDNSServiceErr_NoError) { + eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this()); + } + else { + //std::cout << "Service resolved: name:" << fullName << " host:" << host << " port:" << port << std::endl; + eventLoop->postEvent( + boost::bind( + boost::ref(onServiceResolved), + Result(std::string(fullName), std::string(host), port, + createByteArray(reinterpret_cast<const char*>(txtRecord), txtLen))), + shared_from_this()); + } + } + }; } diff --git a/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h index d02490c..5502678 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h @@ -10,15 +10,15 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h> namespace Swift { - class DNSSDBrowseQuery { - public: - virtual ~DNSSDBrowseQuery(); + class DNSSDBrowseQuery { + public: + virtual ~DNSSDBrowseQuery(); - virtual void startBrowsing() = 0; - virtual void stopBrowsing() = 0; + virtual void startBrowsing() = 0; + virtual void stopBrowsing() = 0; - boost::signal<void (const DNSSDServiceID&)> onServiceAdded; - boost::signal<void (const DNSSDServiceID&)> onServiceRemoved; - boost::signal<void ()> onError; - }; + boost::signal<void (const DNSSDServiceID&)> onServiceAdded; + boost::signal<void (const DNSSDServiceID&)> onServiceRemoved; + boost::signal<void ()> onError; + }; } diff --git a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h index 924b7c9..85051fe 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h @@ -11,25 +11,25 @@ #include <Swiften/Base/ByteArray.h> namespace Swift { - class DNSSDServiceID; - class DNSSDBrowseQuery; - class DNSSDRegisterQuery; - class DNSSDResolveServiceQuery; - class DNSSDResolveHostnameQuery; + class DNSSDServiceID; + class DNSSDBrowseQuery; + class DNSSDRegisterQuery; + class DNSSDResolveServiceQuery; + class DNSSDResolveHostnameQuery; - class DNSSDQuerier { - public: - virtual ~DNSSDQuerier(); + class DNSSDQuerier { + public: + virtual ~DNSSDQuerier(); - virtual void start() = 0; - virtual void stop() = 0; + virtual void start() = 0; + virtual void stop() = 0; - virtual boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery() = 0; - virtual boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info) = 0; - virtual boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( - const DNSSDServiceID&) = 0; - virtual boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( - const std::string& hostname, int interfaceIndex) = 0; - }; + virtual boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery() = 0; + virtual boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( + const std::string& name, int port, const ByteArray& info) = 0; + virtual boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( + const DNSSDServiceID&) = 0; + virtual boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( + const std::string& hostname, int interfaceIndex) = 0; + }; } diff --git a/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h index 08e4608..e8e07bd 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h @@ -13,14 +13,14 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h> namespace Swift { - class DNSSDRegisterQuery { - public: - virtual ~DNSSDRegisterQuery(); + class DNSSDRegisterQuery { + public: + virtual ~DNSSDRegisterQuery(); - virtual void registerService() = 0; - virtual void unregisterService() = 0; - virtual void updateServiceInfo(const ByteArray& info) = 0; + virtual void registerService() = 0; + virtual void unregisterService() = 0; + virtual void updateServiceInfo(const ByteArray& info) = 0; - boost::signal<void (boost::optional<DNSSDServiceID>)> onRegisterFinished; - }; + boost::signal<void (boost::optional<DNSSDServiceID>)> onRegisterFinished; + }; } diff --git a/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h index f8ad3de..a4f818c 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h @@ -12,13 +12,13 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class DNSSDResolveHostnameQuery { - public: - virtual ~DNSSDResolveHostnameQuery(); + class DNSSDResolveHostnameQuery { + public: + virtual ~DNSSDResolveHostnameQuery(); - virtual void run() = 0; - virtual void finish() = 0; + virtual void run() = 0; + virtual void finish() = 0; - boost::signal<void (const boost::optional<HostAddress>&)> onHostnameResolved; - }; + boost::signal<void (const boost::optional<HostAddress>&)> onHostnameResolved; + }; } diff --git a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h index 4728927..4d25075 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h @@ -13,22 +13,22 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h> namespace Swift { - class DNSSDResolveServiceQuery { - public: - struct Result { - Result(const std::string& fullName, const std::string& host, int port, const ByteArray& info) : - fullName(fullName), host(host), port(port), info(info) {} - std::string fullName; - std::string host; - int port; - ByteArray info; - }; + class DNSSDResolveServiceQuery { + public: + struct Result { + Result(const std::string& fullName, const std::string& host, int port, const ByteArray& info) : + fullName(fullName), host(host), port(port), info(info) {} + std::string fullName; + std::string host; + int port; + ByteArray info; + }; - virtual ~DNSSDResolveServiceQuery(); + virtual ~DNSSDResolveServiceQuery(); - virtual void start() = 0; - virtual void stop() = 0; + virtual void start() = 0; + virtual void stop() = 0; - boost::signal<void (const boost::optional<Result>&)> onServiceResolved; - }; + boost::signal<void (const boost::optional<Result>&)> onServiceResolved; + }; } diff --git a/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h b/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h index a7dc0ee..5f8c2eb 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h @@ -11,64 +11,64 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API DNSSDServiceID { - public: - static const char* PresenceServiceType; + class SWIFTEN_API DNSSDServiceID { + public: + static const char* PresenceServiceType; - DNSSDServiceID( - const std::string& name, - const std::string& domain, - const std::string& type = PresenceServiceType, - int networkInterface = -1) : - name(name), - domain(domain), - type(type), - networkInterface(networkInterface) { - } + DNSSDServiceID( + const std::string& name, + const std::string& domain, + const std::string& type = PresenceServiceType, + int networkInterface = -1) : + name(name), + domain(domain), + type(type), + networkInterface(networkInterface) { + } - bool operator==(const DNSSDServiceID& o) const { - return name == o.name && domain == o.domain && type == o.type && (networkInterface != 0 && o.networkInterface != 0 ? networkInterface == o.networkInterface : true); - } + bool operator==(const DNSSDServiceID& o) const { + return name == o.name && domain == o.domain && type == o.type && (networkInterface != 0 && o.networkInterface != 0 ? networkInterface == o.networkInterface : true); + } - bool operator<(const DNSSDServiceID& o) const { - if (o.name == name) { - if (o.domain == domain) { - if (o.type == type) { - return networkInterface < o.networkInterface; - } - else { - return type < o.type; - } - } - else { - return domain < o.domain; - } - } - else { - return o.name < name; - } - } + bool operator<(const DNSSDServiceID& o) const { + if (o.name == name) { + if (o.domain == domain) { + if (o.type == type) { + return networkInterface < o.networkInterface; + } + else { + return type < o.type; + } + } + else { + return domain < o.domain; + } + } + else { + return o.name < name; + } + } - const std::string& getName() const { - return name; - } + const std::string& getName() const { + return name; + } - const std::string& getDomain() const { - return domain; - } + const std::string& getDomain() const { + return domain; + } - const std::string& getType() const { - return type; - } + const std::string& getType() const { + return type; + } - int getNetworkInterfaceID() const { - return networkInterface; - } + int getNetworkInterfaceID() const { + return networkInterface; + } - private: - std::string name; - std::string domain; - std::string type; - int networkInterface; - }; + private: + std::string name; + std::string domain; + std::string type; + int networkInterface; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h index 07ed44c..860de41 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h @@ -10,19 +10,19 @@ #include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h> namespace Swift { - class FakeDNSSDQuerier; + class FakeDNSSDQuerier; - class FakeDNSSDBrowseQuery : public DNSSDBrowseQuery, public FakeDNSSDQuery { - public: - FakeDNSSDBrowseQuery(boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier) { - } + class FakeDNSSDBrowseQuery : public DNSSDBrowseQuery, public FakeDNSSDQuery { + public: + FakeDNSSDBrowseQuery(boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier) { + } - void startBrowsing() { - run(); - } + void startBrowsing() { + run(); + } - void stopBrowsing() { - finish(); - } - }; + void stopBrowsing() { + finish(); + } + }; } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp index 74c152e..89698a6 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp @@ -24,117 +24,117 @@ FakeDNSSDQuerier::FakeDNSSDQuerier(const std::string& domain, EventLoop* eventLo } FakeDNSSDQuerier::~FakeDNSSDQuerier() { - if (!runningQueries.empty()) { - std::cerr << "FakeDNSSDQuerier: Running queries not empty at destruction time" << std::endl; - } + if (!runningQueries.empty()) { + std::cerr << "FakeDNSSDQuerier: Running queries not empty at destruction time" << std::endl; + } } boost::shared_ptr<DNSSDBrowseQuery> FakeDNSSDQuerier::createBrowseQuery() { - return boost::shared_ptr<DNSSDBrowseQuery>(new FakeDNSSDBrowseQuery(shared_from_this())); + return boost::shared_ptr<DNSSDBrowseQuery>(new FakeDNSSDBrowseQuery(shared_from_this())); } boost::shared_ptr<DNSSDRegisterQuery> FakeDNSSDQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) { - return boost::shared_ptr<DNSSDRegisterQuery>(new FakeDNSSDRegisterQuery(name, port, info, shared_from_this())); + return boost::shared_ptr<DNSSDRegisterQuery>(new FakeDNSSDRegisterQuery(name, port, info, shared_from_this())); } boost::shared_ptr<DNSSDResolveServiceQuery> FakeDNSSDQuerier::createResolveServiceQuery(const DNSSDServiceID& service) { - return boost::shared_ptr<DNSSDResolveServiceQuery>(new FakeDNSSDResolveServiceQuery(service, shared_from_this())); + return boost::shared_ptr<DNSSDResolveServiceQuery>(new FakeDNSSDResolveServiceQuery(service, shared_from_this())); } boost::shared_ptr<DNSSDResolveHostnameQuery> FakeDNSSDQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) { - return boost::shared_ptr<DNSSDResolveHostnameQuery>(new FakeDNSSDResolveHostnameQuery(hostname, interfaceIndex, shared_from_this())); + return boost::shared_ptr<DNSSDResolveHostnameQuery>(new FakeDNSSDResolveHostnameQuery(hostname, interfaceIndex, shared_from_this())); } void FakeDNSSDQuerier::addRunningQuery(boost::shared_ptr<FakeDNSSDQuery> query) { - runningQueries.push_back(query); - allQueriesEverRun.push_back(query); - if (boost::shared_ptr<FakeDNSSDBrowseQuery> browseQuery = boost::dynamic_pointer_cast<FakeDNSSDBrowseQuery>(query)) { - foreach(const DNSSDServiceID& service, services) { - eventLoop->postEvent(boost::bind(boost::ref(browseQuery->onServiceAdded), service), shared_from_this()); - } - } - else if (boost::shared_ptr<FakeDNSSDResolveServiceQuery> resolveQuery = boost::dynamic_pointer_cast<FakeDNSSDResolveServiceQuery>(query)) { - for(ServiceInfoMap::const_iterator i = serviceInfo.begin(); i != serviceInfo.end(); ++i) { - if (i->first == resolveQuery->service) { - eventLoop->postEvent(boost::bind(boost::ref(resolveQuery->onServiceResolved), i->second), shared_from_this()); - } - } - } - else if (boost::shared_ptr<FakeDNSSDRegisterQuery> registerQuery = boost::dynamic_pointer_cast<FakeDNSSDRegisterQuery>(query)) { - DNSSDServiceID service(registerQuery->name, domain); - eventLoop->postEvent(boost::bind(boost::ref(registerQuery->onRegisterFinished), service), shared_from_this()); - } - else if (boost::shared_ptr<FakeDNSSDResolveHostnameQuery> resolveHostnameQuery = boost::dynamic_pointer_cast<FakeDNSSDResolveHostnameQuery>(query)) { - std::map<std::string,boost::optional<HostAddress> >::const_iterator i = addresses.find(resolveHostnameQuery->hostname); - if (i != addresses.end()) { - eventLoop->postEvent( - boost::bind( - boost::ref(resolveHostnameQuery->onHostnameResolved), i->second), - shared_from_this()); - } - } + runningQueries.push_back(query); + allQueriesEverRun.push_back(query); + if (boost::shared_ptr<FakeDNSSDBrowseQuery> browseQuery = boost::dynamic_pointer_cast<FakeDNSSDBrowseQuery>(query)) { + foreach(const DNSSDServiceID& service, services) { + eventLoop->postEvent(boost::bind(boost::ref(browseQuery->onServiceAdded), service), shared_from_this()); + } + } + else if (boost::shared_ptr<FakeDNSSDResolveServiceQuery> resolveQuery = boost::dynamic_pointer_cast<FakeDNSSDResolveServiceQuery>(query)) { + for(ServiceInfoMap::const_iterator i = serviceInfo.begin(); i != serviceInfo.end(); ++i) { + if (i->first == resolveQuery->service) { + eventLoop->postEvent(boost::bind(boost::ref(resolveQuery->onServiceResolved), i->second), shared_from_this()); + } + } + } + else if (boost::shared_ptr<FakeDNSSDRegisterQuery> registerQuery = boost::dynamic_pointer_cast<FakeDNSSDRegisterQuery>(query)) { + DNSSDServiceID service(registerQuery->name, domain); + eventLoop->postEvent(boost::bind(boost::ref(registerQuery->onRegisterFinished), service), shared_from_this()); + } + else if (boost::shared_ptr<FakeDNSSDResolveHostnameQuery> resolveHostnameQuery = boost::dynamic_pointer_cast<FakeDNSSDResolveHostnameQuery>(query)) { + std::map<std::string,boost::optional<HostAddress> >::const_iterator i = addresses.find(resolveHostnameQuery->hostname); + if (i != addresses.end()) { + eventLoop->postEvent( + boost::bind( + boost::ref(resolveHostnameQuery->onHostnameResolved), i->second), + shared_from_this()); + } + } } void FakeDNSSDQuerier::removeRunningQuery(boost::shared_ptr<FakeDNSSDQuery> query) { - erase(runningQueries, query); + erase(runningQueries, query); } void FakeDNSSDQuerier::addService(const DNSSDServiceID& id) { - services.insert(id); - foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) { - eventLoop->postEvent(boost::bind(boost::ref(query->onServiceAdded), id), shared_from_this()); - } + services.insert(id); + foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) { + eventLoop->postEvent(boost::bind(boost::ref(query->onServiceAdded), id), shared_from_this()); + } } void FakeDNSSDQuerier::removeService(const DNSSDServiceID& id) { - services.erase(id); - serviceInfo.erase(id); - foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) { - eventLoop->postEvent(boost::bind(boost::ref(query->onServiceRemoved), id), shared_from_this()); - } + services.erase(id); + serviceInfo.erase(id); + foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) { + eventLoop->postEvent(boost::bind(boost::ref(query->onServiceRemoved), id), shared_from_this()); + } } void FakeDNSSDQuerier::setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info) { - std::pair<ServiceInfoMap::iterator, bool> r = serviceInfo.insert(std::make_pair(id, info)); - if (!r.second) { - r.first->second = info; - } - foreach(const boost::shared_ptr<FakeDNSSDResolveServiceQuery>& query, getQueries<FakeDNSSDResolveServiceQuery>()) { - if (query->service == id) { - eventLoop->postEvent(boost::bind(boost::ref(query->onServiceResolved), info), shared_from_this()); - } - } + std::pair<ServiceInfoMap::iterator, bool> r = serviceInfo.insert(std::make_pair(id, info)); + if (!r.second) { + r.first->second = info; + } + foreach(const boost::shared_ptr<FakeDNSSDResolveServiceQuery>& query, getQueries<FakeDNSSDResolveServiceQuery>()) { + if (query->service == id) { + eventLoop->postEvent(boost::bind(boost::ref(query->onServiceResolved), info), shared_from_this()); + } + } } bool FakeDNSSDQuerier::isServiceRegistered(const std::string& name, int port, const ByteArray& info) { - foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) { - if (query->name == name && query->port == port && query->info == info) { - return true; - } - } - return false; + foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) { + if (query->name == name && query->port == port && query->info == info) { + return true; + } + } + return false; } void FakeDNSSDQuerier::setBrowseError() { - foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) { - eventLoop->postEvent(boost::ref(query->onError), shared_from_this()); - } + foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) { + eventLoop->postEvent(boost::ref(query->onError), shared_from_this()); + } } void FakeDNSSDQuerier::setRegisterError() { - foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) { - eventLoop->postEvent(boost::bind(boost::ref(query->onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); - } + foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) { + eventLoop->postEvent(boost::bind(boost::ref(query->onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); + } } void FakeDNSSDQuerier::setAddress(const std::string& hostname, boost::optional<HostAddress> address) { - addresses[hostname] = address; - foreach(const boost::shared_ptr<FakeDNSSDResolveHostnameQuery>& query, getQueries<FakeDNSSDResolveHostnameQuery>()) { - if (query->hostname == hostname) { - eventLoop->postEvent(boost::bind( - boost::ref(query->onHostnameResolved), address), shared_from_this()); - } - } + addresses[hostname] = address; + foreach(const boost::shared_ptr<FakeDNSSDResolveHostnameQuery>& query, getQueries<FakeDNSSDResolveHostnameQuery>()) { + if (query->hostname == hostname) { + eventLoop->postEvent(boost::bind( + boost::ref(query->onHostnameResolved), address), shared_from_this()); + } + } } } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h index e68c36d..536bf90 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h @@ -21,78 +21,78 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class FakeDNSSDQuery; - class FakeDNSSDBrowseQuery; - class EventLoop; + class FakeDNSSDQuery; + class FakeDNSSDBrowseQuery; + class EventLoop; - class SWIFTEN_API FakeDNSSDQuerier : - public DNSSDQuerier, - public EventOwner, - public boost::enable_shared_from_this<FakeDNSSDQuerier> { - public: - FakeDNSSDQuerier(const std::string& domain, EventLoop* eventLoop); - ~FakeDNSSDQuerier(); + class SWIFTEN_API FakeDNSSDQuerier : + public DNSSDQuerier, + public EventOwner, + public boost::enable_shared_from_this<FakeDNSSDQuerier> { + public: + FakeDNSSDQuerier(const std::string& domain, EventLoop* eventLoop); + ~FakeDNSSDQuerier(); - void start() {} - void stop() {} + void start() {} + void stop() {} - void clearAllQueriesEverRun() { - allQueriesEverRun.clear(); - } + void clearAllQueriesEverRun() { + allQueriesEverRun.clear(); + } - boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); - boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info); - boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( - const DNSSDServiceID&); - boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( - const std::string& hostname, int interfaceIndex); + boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); + boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( + const std::string& name, int port, const ByteArray& info); + boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( + const DNSSDServiceID&); + boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( + const std::string& hostname, int interfaceIndex); - void addRunningQuery(boost::shared_ptr<FakeDNSSDQuery>); - void removeRunningQuery(boost::shared_ptr<FakeDNSSDQuery>); + void addRunningQuery(boost::shared_ptr<FakeDNSSDQuery>); + void removeRunningQuery(boost::shared_ptr<FakeDNSSDQuery>); - void addService(const DNSSDServiceID& id); - void removeService(const DNSSDServiceID& id); - void setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info); - bool isServiceRegistered(const std::string& name, int port, const ByteArray& info); - void setAddress(const std::string& hostname, boost::optional<HostAddress> address); + void addService(const DNSSDServiceID& id); + void removeService(const DNSSDServiceID& id); + void setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info); + bool isServiceRegistered(const std::string& name, int port, const ByteArray& info); + void setAddress(const std::string& hostname, boost::optional<HostAddress> address); - void setBrowseError(); - void setRegisterError(); + void setBrowseError(); + void setRegisterError(); - public: - template<typename T> - std::vector< boost::shared_ptr<T> > getAllQueriesEverRun() const { - std::vector< boost::shared_ptr<T> > result; - for (QueryList::const_iterator i = allQueriesEverRun.begin(); i != allQueriesEverRun.end(); ++i) { - if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) { - result.push_back(resultQuery); - } - } - return result; - } + public: + template<typename T> + std::vector< boost::shared_ptr<T> > getAllQueriesEverRun() const { + std::vector< boost::shared_ptr<T> > result; + for (QueryList::const_iterator i = allQueriesEverRun.begin(); i != allQueriesEverRun.end(); ++i) { + if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) { + result.push_back(resultQuery); + } + } + return result; + } - private: - template<typename T> - std::vector< boost::shared_ptr<T> > getQueries() const { - std::vector< boost::shared_ptr<T> > result; - for (QueryList::const_iterator i = runningQueries.begin(); i != runningQueries.end(); ++i) { - if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) { - result.push_back(resultQuery); - } - } - return result; - } + private: + template<typename T> + std::vector< boost::shared_ptr<T> > getQueries() const { + std::vector< boost::shared_ptr<T> > result; + for (QueryList::const_iterator i = runningQueries.begin(); i != runningQueries.end(); ++i) { + if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) { + result.push_back(resultQuery); + } + } + return result; + } - private: - std::string domain; - EventLoop* eventLoop; - typedef std::list< boost::shared_ptr<FakeDNSSDQuery> > QueryList; - QueryList runningQueries; - QueryList allQueriesEverRun; - std::set<DNSSDServiceID> services; - typedef std::map<DNSSDServiceID,DNSSDResolveServiceQuery::Result> ServiceInfoMap; - ServiceInfoMap serviceInfo; - std::map<std::string, boost::optional<HostAddress> > addresses; - }; + private: + std::string domain; + EventLoop* eventLoop; + typedef std::list< boost::shared_ptr<FakeDNSSDQuery> > QueryList; + QueryList runningQueries; + QueryList allQueriesEverRun; + std::set<DNSSDServiceID> services; + typedef std::map<DNSSDServiceID,DNSSDResolveServiceQuery::Result> ServiceInfoMap; + ServiceInfoMap serviceInfo; + std::map<std::string, boost::optional<HostAddress> > addresses; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp index a6456d9..980b757 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp @@ -17,11 +17,11 @@ FakeDNSSDQuery::~FakeDNSSDQuery() { } void FakeDNSSDQuery::run() { - querier->addRunningQuery(shared_from_this()); + querier->addRunningQuery(shared_from_this()); } void FakeDNSSDQuery::finish() { - querier->removeRunningQuery(shared_from_this()); + querier->removeRunningQuery(shared_from_this()); } } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h index 22fa982..0d7dedc 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h @@ -12,20 +12,20 @@ #include <Swiften/EventLoop/EventOwner.h> namespace Swift { - class FakeDNSSDQuerier; + class FakeDNSSDQuerier; - class FakeDNSSDQuery : - public EventOwner, - public boost::enable_shared_from_this<FakeDNSSDQuery> { - public: - FakeDNSSDQuery(boost::shared_ptr<FakeDNSSDQuerier>); - virtual ~FakeDNSSDQuery(); - - protected: - void run(); - void finish(); - - protected: - boost::shared_ptr<FakeDNSSDQuerier> querier; - }; + class FakeDNSSDQuery : + public EventOwner, + public boost::enable_shared_from_this<FakeDNSSDQuery> { + public: + FakeDNSSDQuery(boost::shared_ptr<FakeDNSSDQuerier>); + virtual ~FakeDNSSDQuery(); + + protected: + void run(); + void finish(); + + protected: + boost::shared_ptr<FakeDNSSDQuerier> querier; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h index 5e6fe7d..484b2c2 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h @@ -13,27 +13,27 @@ #include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h> namespace Swift { - class FakeDNSSDQuerier; + class FakeDNSSDQuerier; - class FakeDNSSDRegisterQuery : public DNSSDRegisterQuery, public FakeDNSSDQuery { - public: - FakeDNSSDRegisterQuery(const std::string& name, int port, const ByteArray& info, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), name(name), port(port), info(info) { - } + class FakeDNSSDRegisterQuery : public DNSSDRegisterQuery, public FakeDNSSDQuery { + public: + FakeDNSSDRegisterQuery(const std::string& name, int port, const ByteArray& info, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), name(name), port(port), info(info) { + } - void registerService() { - run(); - } + void registerService() { + run(); + } - void updateServiceInfo(const ByteArray& i) { - info = i; - } + void updateServiceInfo(const ByteArray& i) { + info = i; + } - void unregisterService() { - finish(); - } + void unregisterService() { + finish(); + } - std::string name; - int port; - ByteArray info; - }; + std::string name; + int port; + ByteArray info; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h index 77da7ae..0b6a95d 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h @@ -13,22 +13,22 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class FakeDNSSDQuerier; + class FakeDNSSDQuerier; - class FakeDNSSDResolveHostnameQuery : public DNSSDResolveHostnameQuery, public FakeDNSSDQuery { - public: - FakeDNSSDResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), hostname(hostname), interfaceIndex(interfaceIndex) { - } + class FakeDNSSDResolveHostnameQuery : public DNSSDResolveHostnameQuery, public FakeDNSSDQuery { + public: + FakeDNSSDResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), hostname(hostname), interfaceIndex(interfaceIndex) { + } - void run() { - FakeDNSSDQuery::run(); - } + void run() { + FakeDNSSDQuery::run(); + } - void finish() { - FakeDNSSDQuery::finish(); - } + void finish() { + FakeDNSSDQuery::finish(); + } - std::string hostname; - int interfaceIndex; - }; + std::string hostname; + int interfaceIndex; + }; } diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h index a20cc16..180fbb2 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h @@ -11,21 +11,21 @@ #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> namespace Swift { - class FakeDNSSDQuerier; + class FakeDNSSDQuerier; - class FakeDNSSDResolveServiceQuery : public DNSSDResolveServiceQuery, public FakeDNSSDQuery { - public: - FakeDNSSDResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), service(service) { - } + class FakeDNSSDResolveServiceQuery : public DNSSDResolveServiceQuery, public FakeDNSSDQuery { + public: + FakeDNSSDResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), service(service) { + } - void start() { - run(); - } + void start() { + run(); + } - void stop() { - finish(); - } + void stop() { + finish(); + } - DNSSDServiceID service; - }; + DNSSDServiceID service; + }; } diff --git a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp index ee7194f..f2bfa2e 100644 --- a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp +++ b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp @@ -20,20 +20,20 @@ PlatformDNSSDQuerierFactory::PlatformDNSSDQuerierFactory(EventLoop* eventLoop) : boost::shared_ptr<DNSSDQuerier> PlatformDNSSDQuerierFactory::createQuerier() { #if defined(HAVE_BONJOUR) - return boost::shared_ptr<DNSSDQuerier>(new BonjourQuerier(eventLoop)); + return boost::shared_ptr<DNSSDQuerier>(new BonjourQuerier(eventLoop)); #elif defined(HAVE_AVAHI) - return boost::shared_ptr<DNSSDQuerier>(new AvahiQuerier(eventLoop)); + return boost::shared_ptr<DNSSDQuerier>(new AvahiQuerier(eventLoop)); #else - (void)eventLoop; - return boost::shared_ptr<DNSSDQuerier>(); + (void)eventLoop; + return boost::shared_ptr<DNSSDQuerier>(); #endif } bool PlatformDNSSDQuerierFactory::canCreate() { #if defined(HAVE_BONJOUR) || defined(HAVE_AVAHI) - return true; + return true; #else - return false; + return false; #endif } diff --git a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h index 2ba8b25..dc40d01 100644 --- a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h +++ b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h @@ -11,18 +11,18 @@ #include <Swiften/Base/API.h> namespace Swift { - class DNSSDQuerier; - class EventLoop; + class DNSSDQuerier; + class EventLoop; - class SWIFTEN_API PlatformDNSSDQuerierFactory { - public: - PlatformDNSSDQuerierFactory(EventLoop* eventLoop); + class SWIFTEN_API PlatformDNSSDQuerierFactory { + public: + PlatformDNSSDQuerierFactory(EventLoop* eventLoop); - boost::shared_ptr<DNSSDQuerier> createQuerier(); + boost::shared_ptr<DNSSDQuerier> createQuerier(); - bool canCreate(); + bool canCreate(); - private: - EventLoop* eventLoop; - }; + private: + EventLoop* eventLoop; + }; } diff --git a/Swiften/LinkLocal/IncomingLinkLocalSession.cpp b/Swiften/LinkLocal/IncomingLinkLocalSession.cpp index e39b32b..435b065 100644 --- a/Swiften/LinkLocal/IncomingLinkLocalSession.cpp +++ b/Swiften/LinkLocal/IncomingLinkLocalSession.cpp @@ -20,49 +20,49 @@ namespace Swift { IncomingLinkLocalSession::IncomingLinkLocalSession( - const JID& localJID, - boost::shared_ptr<Connection> connection, - PayloadParserFactoryCollection* payloadParserFactories, - PayloadSerializerCollection* payloadSerializers, - XMLParserFactory* xmlParserFactory) : - Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory), - initialized(false) { - setLocalJID(localJID); + const JID& localJID, + boost::shared_ptr<Connection> connection, + PayloadParserFactoryCollection* payloadParserFactories, + PayloadSerializerCollection* payloadSerializers, + XMLParserFactory* xmlParserFactory) : + Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory), + initialized(false) { + setLocalJID(localJID); } void IncomingLinkLocalSession::handleStreamStart(const ProtocolHeader& incomingHeader) { - setRemoteJID(JID(incomingHeader.getFrom())); - if (!getRemoteJID().isValid()) { - finishSession(); - return; - } + setRemoteJID(JID(incomingHeader.getFrom())); + if (!getRemoteJID().isValid()) { + finishSession(); + return; + } - ProtocolHeader header; - header.setFrom(getLocalJID()); - getXMPPLayer()->writeHeader(header); + ProtocolHeader header; + header.setFrom(getLocalJID()); + getXMPPLayer()->writeHeader(header); - if (incomingHeader.getVersion() == "1.0") { - getXMPPLayer()->writeElement(boost::make_shared<StreamFeatures>()); - } - else { - setInitialized(); - } + if (incomingHeader.getVersion() == "1.0") { + getXMPPLayer()->writeElement(boost::make_shared<StreamFeatures>()); + } + else { + setInitialized(); + } } void IncomingLinkLocalSession::handleElement(boost::shared_ptr<ToplevelElement> element) { - boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element); - // If we get our first stanza before streamfeatures, our session is implicitly - // initialized - if (stanza && !isInitialized()) { - setInitialized(); - } - - onElementReceived(element); + boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element); + // If we get our first stanza before streamfeatures, our session is implicitly + // initialized + if (stanza && !isInitialized()) { + setInitialized(); + } + + onElementReceived(element); } void IncomingLinkLocalSession::setInitialized() { - initialized = true; - onSessionStarted(); + initialized = true; + onSessionStarted(); } diff --git a/Swiften/LinkLocal/IncomingLinkLocalSession.h b/Swiften/LinkLocal/IncomingLinkLocalSession.h index 9ac6bac..44a8719 100644 --- a/Swiften/LinkLocal/IncomingLinkLocalSession.h +++ b/Swiften/LinkLocal/IncomingLinkLocalSession.h @@ -15,31 +15,31 @@ #include <Swiften/Session/Session.h> namespace Swift { - class ProtocolHeader; - class XMLParserFactory; - class ToplevelElement; - class PayloadParserFactoryCollection; - class PayloadSerializerCollection; - - class SWIFTEN_API IncomingLinkLocalSession : public Session { - public: - IncomingLinkLocalSession( - const JID& localJID, - boost::shared_ptr<Connection> connection, - PayloadParserFactoryCollection* payloadParserFactories, - PayloadSerializerCollection* payloadSerializers, - XMLParserFactory* xmlParserFactory); - - boost::signal<void ()> onSessionStarted; - - private: - void handleElement(boost::shared_ptr<ToplevelElement>); - void handleStreamStart(const ProtocolHeader&); - void setInitialized(); - bool isInitialized() const { - return initialized; - } - - bool initialized; - }; + class ProtocolHeader; + class XMLParserFactory; + class ToplevelElement; + class PayloadParserFactoryCollection; + class PayloadSerializerCollection; + + class SWIFTEN_API IncomingLinkLocalSession : public Session { + public: + IncomingLinkLocalSession( + const JID& localJID, + boost::shared_ptr<Connection> connection, + PayloadParserFactoryCollection* payloadParserFactories, + PayloadSerializerCollection* payloadSerializers, + XMLParserFactory* xmlParserFactory); + + boost::signal<void ()> onSessionStarted; + + private: + void handleElement(boost::shared_ptr<ToplevelElement>); + void handleStreamStart(const ProtocolHeader&); + void setInitialized(); + bool isInitialized() const { + return initialized; + } + + bool initialized; + }; } diff --git a/Swiften/LinkLocal/LinkLocalConnector.cpp b/Swiften/LinkLocal/LinkLocalConnector.cpp index 7533f24..9123e8e 100644 --- a/Swiften/LinkLocal/LinkLocalConnector.cpp +++ b/Swiften/LinkLocal/LinkLocalConnector.cpp @@ -18,61 +18,61 @@ namespace Swift { LinkLocalConnector::LinkLocalConnector( - const LinkLocalService& service, - boost::shared_ptr<DNSSDQuerier> querier, - boost::shared_ptr<Connection> connection) : - service(service), - querier(querier), - connection(connection) { + const LinkLocalService& service, + boost::shared_ptr<DNSSDQuerier> querier, + boost::shared_ptr<Connection> connection) : + service(service), + querier(querier), + connection(connection) { } LinkLocalConnector::~LinkLocalConnector() { - assert(!resolveQuery); + assert(!resolveQuery); } void LinkLocalConnector::connect() { - resolveQuery = querier->createResolveHostnameQuery( - service.getHostname(), - service.getID().getNetworkInterfaceID()); - resolveQueryHostNameResolvedConnection = resolveQuery->onHostnameResolved.connect(boost::bind( - &LinkLocalConnector::handleHostnameResolved, - boost::dynamic_pointer_cast<LinkLocalConnector>(shared_from_this()), - _1)); - resolveQuery->run(); + resolveQuery = querier->createResolveHostnameQuery( + service.getHostname(), + service.getID().getNetworkInterfaceID()); + resolveQueryHostNameResolvedConnection = resolveQuery->onHostnameResolved.connect(boost::bind( + &LinkLocalConnector::handleHostnameResolved, + boost::dynamic_pointer_cast<LinkLocalConnector>(shared_from_this()), + _1)); + resolveQuery->run(); } void LinkLocalConnector::cancel() { - if (resolveQuery) { - resolveQuery->finish(); - resolveQueryHostNameResolvedConnection.disconnect(); - resolveQuery.reset(); - } - connectionConnectFinishedConnection.disconnect(); - connection->disconnect(); + if (resolveQuery) { + resolveQuery->finish(); + resolveQueryHostNameResolvedConnection.disconnect(); + resolveQuery.reset(); + } + connectionConnectFinishedConnection.disconnect(); + connection->disconnect(); } void LinkLocalConnector::handleHostnameResolved(const boost::optional<HostAddress>& address) { - resolveQuery->finish(); - resolveQueryHostNameResolvedConnection.disconnect(); - resolveQuery.reset(); - if (address) { - connectionConnectFinishedConnection = connection->onConnectFinished.connect( - boost::bind(&LinkLocalConnector::handleConnected, shared_from_this(), _1)); - connection->connect(HostAddressPort(*address, service.getPort())); - } - else { - onConnectFinished(true); - } + resolveQuery->finish(); + resolveQueryHostNameResolvedConnection.disconnect(); + resolveQuery.reset(); + if (address) { + connectionConnectFinishedConnection = connection->onConnectFinished.connect( + boost::bind(&LinkLocalConnector::handleConnected, shared_from_this(), _1)); + connection->connect(HostAddressPort(*address, service.getPort())); + } + else { + onConnectFinished(true); + } } void LinkLocalConnector::handleConnected(bool error) { - onConnectFinished(error); - assert(connectionConnectFinishedConnection.connected()); - connectionConnectFinishedConnection.disconnect(); + onConnectFinished(error); + assert(connectionConnectFinishedConnection.connected()); + connectionConnectFinishedConnection.disconnect(); } void LinkLocalConnector::queueElement(boost::shared_ptr<ToplevelElement> element) { - queuedElements.push_back(element); + queuedElements.push_back(element); } diff --git a/Swiften/LinkLocal/LinkLocalConnector.h b/Swiften/LinkLocal/LinkLocalConnector.h index 363ae4b..4e05dce 100644 --- a/Swiften/LinkLocal/LinkLocalConnector.h +++ b/Swiften/LinkLocal/LinkLocalConnector.h @@ -17,51 +17,51 @@ #include <Swiften/Network/Connection.h> namespace Swift { - class ConnectionFactory; - class HostAddress; - class ToplevelElement; - class PayloadParserFactoryCollection; - class PayloadSerializerCollection; - class DNSSDQuerier; - class DNSSDResolveHostnameQuery; + class ConnectionFactory; + class HostAddress; + class ToplevelElement; + class PayloadParserFactoryCollection; + class PayloadSerializerCollection; + class DNSSDQuerier; + class DNSSDResolveHostnameQuery; - class SWIFTEN_API LinkLocalConnector : public boost::enable_shared_from_this<LinkLocalConnector> { - public: - LinkLocalConnector( - const LinkLocalService& service, - boost::shared_ptr<DNSSDQuerier> querier, - boost::shared_ptr<Connection> connection); - ~LinkLocalConnector(); + class SWIFTEN_API LinkLocalConnector : public boost::enable_shared_from_this<LinkLocalConnector> { + public: + LinkLocalConnector( + const LinkLocalService& service, + boost::shared_ptr<DNSSDQuerier> querier, + boost::shared_ptr<Connection> connection); + ~LinkLocalConnector(); - const LinkLocalService& getService() const { - return service; - } + const LinkLocalService& getService() const { + return service; + } - void connect(); - void cancel(); - void queueElement(boost::shared_ptr<ToplevelElement> element); + void connect(); + void cancel(); + void queueElement(boost::shared_ptr<ToplevelElement> element); - const std::vector<boost::shared_ptr<ToplevelElement> >& getQueuedElements() const { - return queuedElements; - } + const std::vector<boost::shared_ptr<ToplevelElement> >& getQueuedElements() const { + return queuedElements; + } - boost::shared_ptr<Connection> getConnection() const { - return connection; - } + boost::shared_ptr<Connection> getConnection() const { + return connection; + } - boost::signal<void (bool)> onConnectFinished; + boost::signal<void (bool)> onConnectFinished; - private: - void handleHostnameResolved(const boost::optional<HostAddress>& address); - void handleConnected(bool error); + private: + void handleHostnameResolved(const boost::optional<HostAddress>& address); + void handleConnected(bool error); - private: - LinkLocalService service; - boost::shared_ptr<DNSSDQuerier> querier; - boost::shared_ptr<DNSSDResolveHostnameQuery> resolveQuery; - boost::bsignals::connection resolveQueryHostNameResolvedConnection; - boost::shared_ptr<Connection> connection; - boost::bsignals::connection connectionConnectFinishedConnection; - std::vector<boost::shared_ptr<ToplevelElement> > queuedElements; - }; + private: + LinkLocalService service; + boost::shared_ptr<DNSSDQuerier> querier; + boost::shared_ptr<DNSSDResolveHostnameQuery> resolveQuery; + boost::bsignals::connection resolveQueryHostNameResolvedConnection; + boost::shared_ptr<Connection> connection; + boost::bsignals::connection connectionConnectFinishedConnection; + std::vector<boost::shared_ptr<ToplevelElement> > queuedElements; + }; } diff --git a/Swiften/LinkLocal/LinkLocalService.cpp b/Swiften/LinkLocal/LinkLocalService.cpp index ecf3ea1..636362e 100644 --- a/Swiften/LinkLocal/LinkLocalService.cpp +++ b/Swiften/LinkLocal/LinkLocalService.cpp @@ -9,25 +9,25 @@ namespace Swift { std::string LinkLocalService::getDescription() const { - LinkLocalServiceInfo info = getInfo(); - if (!info.getNick().empty()) { - return info.getNick(); - } - else if (!info.getFirstName().empty()) { - std::string result = info.getFirstName(); - if (!info.getLastName().empty()) { - result += " " + info.getLastName(); - } - return result; - } - else if (!info.getLastName().empty()) { - return info.getLastName(); - } - return getName(); + LinkLocalServiceInfo info = getInfo(); + if (!info.getNick().empty()) { + return info.getNick(); + } + else if (!info.getFirstName().empty()) { + std::string result = info.getFirstName(); + if (!info.getLastName().empty()) { + result += " " + info.getLastName(); + } + return result; + } + else if (!info.getLastName().empty()) { + return info.getLastName(); + } + return getName(); } JID LinkLocalService::getJID() const { - return JID(getName()); + return JID(getName()); } } diff --git a/Swiften/LinkLocal/LinkLocalService.h b/Swiften/LinkLocal/LinkLocalService.h index d8096b1..9b0e2ab 100644 --- a/Swiften/LinkLocal/LinkLocalService.h +++ b/Swiften/LinkLocal/LinkLocalService.h @@ -15,40 +15,40 @@ #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> namespace Swift { - class SWIFTEN_API LinkLocalService { - public: - LinkLocalService( - const DNSSDServiceID& id, - const DNSSDResolveServiceQuery::Result& info) : - id(id), - info(info) {} - - const DNSSDServiceID& getID() const { - return id; - } - - const std::string& getName() const { - return id.getName(); - } - - int getPort() const { - return info.port; - } - - const std::string& getHostname() const { - return info.host; - } - - LinkLocalServiceInfo getInfo() const { - return LinkLocalServiceInfo::createFromTXTRecord(info.info); - } - - std::string getDescription() const; - - JID getJID() const; - - private: - DNSSDServiceID id; - DNSSDResolveServiceQuery::Result info; - }; + class SWIFTEN_API LinkLocalService { + public: + LinkLocalService( + const DNSSDServiceID& id, + const DNSSDResolveServiceQuery::Result& info) : + id(id), + info(info) {} + + const DNSSDServiceID& getID() const { + return id; + } + + const std::string& getName() const { + return id.getName(); + } + + int getPort() const { + return info.port; + } + + const std::string& getHostname() const { + return info.host; + } + + LinkLocalServiceInfo getInfo() const { + return LinkLocalServiceInfo::createFromTXTRecord(info.info); + } + + std::string getDescription() const; + + JID getJID() const; + + private: + DNSSDServiceID id; + DNSSDResolveServiceQuery::Result info; + }; } diff --git a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp index ab2834d..d9dfd64 100644 --- a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp +++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp @@ -19,139 +19,139 @@ LinkLocalServiceBrowser::LinkLocalServiceBrowser(boost::shared_ptr<DNSSDQuerier> } LinkLocalServiceBrowser::~LinkLocalServiceBrowser() { - if (isRunning()) { - std::cerr << "WARNING: LinkLocalServiceBrowser still running on destruction" << std::endl; - } + if (isRunning()) { + std::cerr << "WARNING: LinkLocalServiceBrowser still running on destruction" << std::endl; + } } void LinkLocalServiceBrowser::start() { - assert(!isRunning()); - haveError = false; - browseQuery = querier->createBrowseQuery(); - browseQuery->onServiceAdded.connect( - boost::bind(&LinkLocalServiceBrowser::handleServiceAdded, this, _1)); - browseQuery->onServiceRemoved.connect( - boost::bind(&LinkLocalServiceBrowser::handleServiceRemoved, this, _1)); - browseQuery->onError.connect( - boost::bind(&LinkLocalServiceBrowser::handleBrowseError, this)); - browseQuery->startBrowsing(); + assert(!isRunning()); + haveError = false; + browseQuery = querier->createBrowseQuery(); + browseQuery->onServiceAdded.connect( + boost::bind(&LinkLocalServiceBrowser::handleServiceAdded, this, _1)); + browseQuery->onServiceRemoved.connect( + boost::bind(&LinkLocalServiceBrowser::handleServiceRemoved, this, _1)); + browseQuery->onError.connect( + boost::bind(&LinkLocalServiceBrowser::handleBrowseError, this)); + browseQuery->startBrowsing(); } void LinkLocalServiceBrowser::stop() { - assert(isRunning()); - if (isRegistered()) { - unregisterService(); - } - for (ResolveQueryMap::const_iterator i = resolveQueries.begin(); i != resolveQueries.end(); ++i) { - i->second->stop(); - } - resolveQueries.clear(); - services.clear(); - browseQuery->stopBrowsing(); - browseQuery.reset(); - onStopped(haveError); + assert(isRunning()); + if (isRegistered()) { + unregisterService(); + } + for (ResolveQueryMap::const_iterator i = resolveQueries.begin(); i != resolveQueries.end(); ++i) { + i->second->stop(); + } + resolveQueries.clear(); + services.clear(); + browseQuery->stopBrowsing(); + browseQuery.reset(); + onStopped(haveError); } bool LinkLocalServiceBrowser::isRunning() const { - return !!browseQuery; + return !!browseQuery; } bool LinkLocalServiceBrowser::hasError() const { - return haveError; + return haveError; } bool LinkLocalServiceBrowser::isRegistered() const { - return !!registerQuery; + return !!registerQuery; } void LinkLocalServiceBrowser::registerService(const std::string& name, int port, const LinkLocalServiceInfo& info) { - assert(!registerQuery); - registerQuery = querier->createRegisterQuery(name, port, info.toTXTRecord()); - registerQuery->onRegisterFinished.connect( - boost::bind(&LinkLocalServiceBrowser::handleRegisterFinished, this, _1)); - registerQuery->registerService(); + assert(!registerQuery); + registerQuery = querier->createRegisterQuery(name, port, info.toTXTRecord()); + registerQuery->onRegisterFinished.connect( + boost::bind(&LinkLocalServiceBrowser::handleRegisterFinished, this, _1)); + registerQuery->registerService(); } void LinkLocalServiceBrowser::updateService(const LinkLocalServiceInfo& info) { - assert(registerQuery); - registerQuery->updateServiceInfo(info.toTXTRecord()); + assert(registerQuery); + registerQuery->updateServiceInfo(info.toTXTRecord()); } void LinkLocalServiceBrowser::unregisterService() { - assert(registerQuery); - registerQuery->unregisterService(); - registerQuery.reset(); - selfService.reset(); + assert(registerQuery); + registerQuery->unregisterService(); + registerQuery.reset(); + selfService.reset(); } std::vector<LinkLocalService> LinkLocalServiceBrowser::getServices() const { - std::vector<LinkLocalService> result; - for (ServiceMap::const_iterator i = services.begin(); i != services.end(); ++i) { - result.push_back(LinkLocalService(i->first, i->second)); - } - return result; + std::vector<LinkLocalService> result; + for (ServiceMap::const_iterator i = services.begin(); i != services.end(); ++i) { + result.push_back(LinkLocalService(i->first, i->second)); + } + return result; } void LinkLocalServiceBrowser::handleServiceAdded(const DNSSDServiceID& service) { - if (selfService && service == *selfService) { - return; - } + if (selfService && service == *selfService) { + return; + } - std::pair<ResolveQueryMap::iterator, bool> r = resolveQueries.insert(std::make_pair(service, boost::shared_ptr<DNSSDResolveServiceQuery>())); - if (r.second) { - // There was no existing query yet. Start a new query. - boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(service); - resolveQuery->onServiceResolved.connect( - boost::bind(&LinkLocalServiceBrowser::handleServiceResolved, this, service, _1)); - r.first->second = resolveQuery; - resolveQuery->start(); - } + std::pair<ResolveQueryMap::iterator, bool> r = resolveQueries.insert(std::make_pair(service, boost::shared_ptr<DNSSDResolveServiceQuery>())); + if (r.second) { + // There was no existing query yet. Start a new query. + boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(service); + resolveQuery->onServiceResolved.connect( + boost::bind(&LinkLocalServiceBrowser::handleServiceResolved, this, service, _1)); + r.first->second = resolveQuery; + resolveQuery->start(); + } } void LinkLocalServiceBrowser::handleServiceRemoved(const DNSSDServiceID& service) { - ResolveQueryMap::iterator i = resolveQueries.find(service); - if (i == resolveQueries.end()) { - // Can happen after an unregister(), when getting the old 'self' - // service remove notification. - return; - } - i->second->stop(); - resolveQueries.erase(i); - ServiceMap::iterator j = services.find(service); - assert(j != services.end()); - LinkLocalService linkLocalService(j->first, j->second); - services.erase(j); - onServiceRemoved(linkLocalService); + ResolveQueryMap::iterator i = resolveQueries.find(service); + if (i == resolveQueries.end()) { + // Can happen after an unregister(), when getting the old 'self' + // service remove notification. + return; + } + i->second->stop(); + resolveQueries.erase(i); + ServiceMap::iterator j = services.find(service); + assert(j != services.end()); + LinkLocalService linkLocalService(j->first, j->second); + services.erase(j); + onServiceRemoved(linkLocalService); } void LinkLocalServiceBrowser::handleServiceResolved(const DNSSDServiceID& service, const boost::optional<DNSSDResolveServiceQuery::Result>& result) { - if (result) { - std::pair<ServiceMap::iterator, bool> r = services.insert(std::make_pair(service, *result)); - if (r.second) { - onServiceAdded(LinkLocalService(r.first->first, r.first->second)); - } - else { - r.first->second = *result; - onServiceChanged(LinkLocalService(r.first->first, r.first->second)); - } - } + if (result) { + std::pair<ServiceMap::iterator, bool> r = services.insert(std::make_pair(service, *result)); + if (r.second) { + onServiceAdded(LinkLocalService(r.first->first, r.first->second)); + } + else { + r.first->second = *result; + onServiceChanged(LinkLocalService(r.first->first, r.first->second)); + } + } } void LinkLocalServiceBrowser::handleRegisterFinished(const boost::optional<DNSSDServiceID>& result) { - if (result) { - selfService = result; - onServiceRegistered(*result); - } - else { - haveError = true; - stop(); - } + if (result) { + selfService = result; + onServiceRegistered(*result); + } + else { + haveError = true; + stop(); + } } void LinkLocalServiceBrowser::handleBrowseError() { - haveError = true; - stop(); + haveError = true; + stop(); } } diff --git a/Swiften/LinkLocal/LinkLocalServiceBrowser.h b/Swiften/LinkLocal/LinkLocalServiceBrowser.h index 7bd4818..3795258 100644 --- a/Swiften/LinkLocal/LinkLocalServiceBrowser.h +++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.h @@ -23,54 +23,54 @@ #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> namespace Swift { - class SWIFTEN_API LinkLocalServiceBrowser { - public: - LinkLocalServiceBrowser(boost::shared_ptr<DNSSDQuerier> querier); - ~LinkLocalServiceBrowser(); + class SWIFTEN_API LinkLocalServiceBrowser { + public: + LinkLocalServiceBrowser(boost::shared_ptr<DNSSDQuerier> querier); + ~LinkLocalServiceBrowser(); - void start(); - void stop(); - bool isRunning() const; - bool hasError() const; + void start(); + void stop(); + bool isRunning() const; + bool hasError() const; - void registerService( - const std::string& name, - int port, - const LinkLocalServiceInfo& info = LinkLocalServiceInfo()); - void updateService( - const LinkLocalServiceInfo& info = LinkLocalServiceInfo()); - void unregisterService(); - bool isRegistered() const; + void registerService( + const std::string& name, + int port, + const LinkLocalServiceInfo& info = LinkLocalServiceInfo()); + void updateService( + const LinkLocalServiceInfo& info = LinkLocalServiceInfo()); + void unregisterService(); + bool isRegistered() const; - std::vector<LinkLocalService> getServices() const; + std::vector<LinkLocalService> getServices() const; - // FIXME: Ugly that we need this - boost::shared_ptr<DNSSDQuerier> getQuerier() const { - return querier; - } + // FIXME: Ugly that we need this + boost::shared_ptr<DNSSDQuerier> getQuerier() const { + return querier; + } - boost::signal<void (const LinkLocalService&)> onServiceAdded; - boost::signal<void (const LinkLocalService&)> onServiceChanged; - boost::signal<void (const LinkLocalService&)> onServiceRemoved; - boost::signal<void (const DNSSDServiceID&)> onServiceRegistered; - boost::signal<void (bool)> onStopped; + boost::signal<void (const LinkLocalService&)> onServiceAdded; + boost::signal<void (const LinkLocalService&)> onServiceChanged; + boost::signal<void (const LinkLocalService&)> onServiceRemoved; + boost::signal<void (const DNSSDServiceID&)> onServiceRegistered; + boost::signal<void (bool)> onStopped; - private: - void handleServiceAdded(const DNSSDServiceID&); - void handleServiceRemoved(const DNSSDServiceID&); - void handleServiceResolved(const DNSSDServiceID& service, const boost::optional<DNSSDResolveServiceQuery::Result>& result); - void handleRegisterFinished(const boost::optional<DNSSDServiceID>&); - void handleBrowseError(); + private: + void handleServiceAdded(const DNSSDServiceID&); + void handleServiceRemoved(const DNSSDServiceID&); + void handleServiceResolved(const DNSSDServiceID& service, const boost::optional<DNSSDResolveServiceQuery::Result>& result); + void handleRegisterFinished(const boost::optional<DNSSDServiceID>&); + void handleBrowseError(); - private: - boost::shared_ptr<DNSSDQuerier> querier; - boost::optional<DNSSDServiceID> selfService; - boost::shared_ptr<DNSSDBrowseQuery> browseQuery; - boost::shared_ptr<DNSSDRegisterQuery> registerQuery; - typedef std::map<DNSSDServiceID, boost::shared_ptr<DNSSDResolveServiceQuery> > ResolveQueryMap; - ResolveQueryMap resolveQueries; - typedef std::map<DNSSDServiceID, DNSSDResolveServiceQuery::Result> ServiceMap; - ServiceMap services; - bool haveError; - }; + private: + boost::shared_ptr<DNSSDQuerier> querier; + boost::optional<DNSSDServiceID> selfService; + boost::shared_ptr<DNSSDBrowseQuery> browseQuery; + boost::shared_ptr<DNSSDRegisterQuery> registerQuery; + typedef std::map<DNSSDServiceID, boost::shared_ptr<DNSSDResolveServiceQuery> > ResolveQueryMap; + ResolveQueryMap resolveQueries; + typedef std::map<DNSSDServiceID, DNSSDResolveServiceQuery::Result> ServiceMap; + ServiceMap services; + bool haveError; + }; } diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp index df341f4..7a7ed3b 100644 --- a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp +++ b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp @@ -15,110 +15,110 @@ namespace Swift { ByteArray LinkLocalServiceInfo::toTXTRecord() const { - ByteArray result(getEncoded("txtvers=1")); - if (!firstName.empty()) { - append(result, getEncoded("1st=" + firstName)); - } - if (!lastName.empty()) { - append(result, getEncoded("last=" + lastName)); - } - if (!email.empty()) { - append(result, getEncoded("email=" + email)); - } - if (jid.isValid()) { - append(result, getEncoded("jid=" + jid.toString())); - } - if (!message.empty()) { - append(result, getEncoded("msg=" + message)); - } - if (!nick.empty()) { - append(result, getEncoded("nick=" + nick)); - } - if (port) { - append(result, getEncoded("port.p2pj=" + std::string(boost::lexical_cast<std::string>(*port)))); - } + ByteArray result(getEncoded("txtvers=1")); + if (!firstName.empty()) { + append(result, getEncoded("1st=" + firstName)); + } + if (!lastName.empty()) { + append(result, getEncoded("last=" + lastName)); + } + if (!email.empty()) { + append(result, getEncoded("email=" + email)); + } + if (jid.isValid()) { + append(result, getEncoded("jid=" + jid.toString())); + } + if (!message.empty()) { + append(result, getEncoded("msg=" + message)); + } + if (!nick.empty()) { + append(result, getEncoded("nick=" + nick)); + } + if (port) { + append(result, getEncoded("port.p2pj=" + std::string(boost::lexical_cast<std::string>(*port)))); + } - switch (status) { - case Available: append(result, getEncoded("status=avail")); break; - case Away: append(result, getEncoded("status=away")); break; - case DND: append(result, getEncoded("status=dnd")); break; - } + switch (status) { + case Available: append(result, getEncoded("status=avail")); break; + case Away: append(result, getEncoded("status=away")); break; + case DND: append(result, getEncoded("status=dnd")); break; + } - return result; + return result; } ByteArray LinkLocalServiceInfo::getEncoded(const std::string& s) { - ByteArray sizeByte; - sizeByte.resize(1); - sizeByte[0] = boost::numeric_cast<unsigned char>(s.size()); - return concat(sizeByte, createByteArray(s)); + ByteArray sizeByte; + sizeByte.resize(1); + sizeByte[0] = boost::numeric_cast<unsigned char>(s.size()); + return concat(sizeByte, createByteArray(s)); } LinkLocalServiceInfo LinkLocalServiceInfo::createFromTXTRecord(const ByteArray& record) { - LinkLocalServiceInfo info; - size_t i = 0; - size_t recordCount = record.size(); - while (i < recordCount) { - std::pair<std::string,std::string> entry = readEntry(record, &i); - if (entry.first.empty()) { - break; - } - else if (entry.first == "1st") { - info.setFirstName(entry.second); - } - else if (entry.first == "last") { - info.setLastName(entry.second); - } - else if (entry.first == "email") { - info.setEMail(entry.second); - } - else if (entry.first == "jid") { - info.setJID(JID(entry.second)); - } - else if (entry.first == "msg") { - info.setMessage(entry.second); - } - else if (entry.first == "nick") { - info.setNick(entry.second); - } - else if (entry.first == "port.p2pj") { - info.setPort(boost::lexical_cast<int>(entry.second)); - } - else if (entry.first == "status") { - if (entry.second == "away") { - info.setStatus(Away); - } - else if (entry.second == "dnd") { - info.setStatus(DND); - } - } - } - return info; + LinkLocalServiceInfo info; + size_t i = 0; + size_t recordCount = record.size(); + while (i < recordCount) { + std::pair<std::string,std::string> entry = readEntry(record, &i); + if (entry.first.empty()) { + break; + } + else if (entry.first == "1st") { + info.setFirstName(entry.second); + } + else if (entry.first == "last") { + info.setLastName(entry.second); + } + else if (entry.first == "email") { + info.setEMail(entry.second); + } + else if (entry.first == "jid") { + info.setJID(JID(entry.second)); + } + else if (entry.first == "msg") { + info.setMessage(entry.second); + } + else if (entry.first == "nick") { + info.setNick(entry.second); + } + else if (entry.first == "port.p2pj") { + info.setPort(boost::lexical_cast<int>(entry.second)); + } + else if (entry.first == "status") { + if (entry.second == "away") { + info.setStatus(Away); + } + else if (entry.second == "dnd") { + info.setStatus(DND); + } + } + } + return info; } std::pair<std::string,std::string> LinkLocalServiceInfo::readEntry(const ByteArray& record, size_t* index) { - size_t& i = *index; - std::string key; - std::string value; + size_t& i = *index; + std::string key; + std::string value; - size_t entryEnd = i + 1 + record[i]; - ++i; - bool inKey = true; - while (i < entryEnd && i < record.size()) { - if (inKey) { - if (record[i] == '=') { - inKey = false; - } - else { - key += static_cast<char>(record[i]); - } - } - else { - value += static_cast<char>(record[i]); - } - ++i; - } - return std::make_pair(key, value); + size_t entryEnd = i + 1 + record[i]; + ++i; + bool inKey = true; + while (i < entryEnd && i < record.size()) { + if (inKey) { + if (record[i] == '=') { + inKey = false; + } + else { + key += static_cast<char>(record[i]); + } + } + else { + value += static_cast<char>(record[i]); + } + ++i; + } + return std::make_pair(key, value); } } diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.h b/Swiften/LinkLocal/LinkLocalServiceInfo.h index c6e4af3..9f15c6e 100644 --- a/Swiften/LinkLocal/LinkLocalServiceInfo.h +++ b/Swiften/LinkLocal/LinkLocalServiceInfo.h @@ -16,52 +16,52 @@ namespace Swift { - class SWIFTEN_API LinkLocalServiceInfo { - public: - enum Status { Available, Away, DND }; + class SWIFTEN_API LinkLocalServiceInfo { + public: + enum Status { Available, Away, DND }; - LinkLocalServiceInfo() : status(Available) {} + LinkLocalServiceInfo() : status(Available) {} - const std::string& getFirstName() const { return firstName; } - void setFirstName(const std::string& f) { firstName = f; } + const std::string& getFirstName() const { return firstName; } + void setFirstName(const std::string& f) { firstName = f; } - const std::string& getLastName() const { return lastName; } - void setLastName(const std::string& l) { lastName = l; } + const std::string& getLastName() const { return lastName; } + void setLastName(const std::string& l) { lastName = l; } - const std::string& getEMail() const { return email; } - void setEMail(const std::string& e) { email = e; } + const std::string& getEMail() const { return email; } + void setEMail(const std::string& e) { email = e; } - const JID& getJID() const { return jid; } - void setJID(const JID& j) { jid = j; } + const JID& getJID() const { return jid; } + void setJID(const JID& j) { jid = j; } - const std::string& getMessage() const { return message; } - void setMessage(const std::string& m) { message = m; } + const std::string& getMessage() const { return message; } + void setMessage(const std::string& m) { message = m; } - const std::string& getNick() const { return nick; } - void setNick(const std::string& n) { nick = n; } + const std::string& getNick() const { return nick; } + void setNick(const std::string& n) { nick = n; } - Status getStatus() const { return status; } - void setStatus(Status s) { status = s; } + Status getStatus() const { return status; } + void setStatus(Status s) { status = s; } - boost::optional<int> getPort() const { return port; } - void setPort(int p) { port = p; } + boost::optional<int> getPort() const { return port; } + void setPort(int p) { port = p; } - ByteArray toTXTRecord() const; + ByteArray toTXTRecord() const; - static LinkLocalServiceInfo createFromTXTRecord(const ByteArray& record); + static LinkLocalServiceInfo createFromTXTRecord(const ByteArray& record); - private: - static ByteArray getEncoded(const std::string&); - static std::pair<std::string,std::string> readEntry(const ByteArray&, size_t*); + private: + static ByteArray getEncoded(const std::string&); + static std::pair<std::string,std::string> readEntry(const ByteArray&, size_t*); - private: - std::string firstName; - std::string lastName; - std::string email; - JID jid; - std::string message; - std::string nick; - Status status; - boost::optional<int> port; - }; + private: + std::string firstName; + std::string lastName; + std::string email; + JID jid; + std::string message; + std::string nick; + Status status; + boost::optional<int> port; + }; } diff --git a/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp b/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp index 47ab116..89d0e89 100644 --- a/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp +++ b/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp @@ -17,36 +17,36 @@ namespace Swift { OutgoingLinkLocalSession::OutgoingLinkLocalSession( - const JID& localJID, - const JID& remoteJID, - boost::shared_ptr<Connection> connection, - PayloadParserFactoryCollection* payloadParserFactories, - PayloadSerializerCollection* payloadSerializers, - XMLParserFactory* xmlParserFactory) : - Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory) { - setLocalJID(localJID); - setRemoteJID(remoteJID); + const JID& localJID, + const JID& remoteJID, + boost::shared_ptr<Connection> connection, + PayloadParserFactoryCollection* payloadParserFactories, + PayloadSerializerCollection* payloadSerializers, + XMLParserFactory* xmlParserFactory) : + Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory) { + setLocalJID(localJID); + setRemoteJID(remoteJID); } void OutgoingLinkLocalSession::handleSessionStarted() { - ProtocolHeader header; - header.setFrom(getLocalJID()); - getXMPPLayer()->writeHeader(header); + ProtocolHeader header; + header.setFrom(getLocalJID()); + getXMPPLayer()->writeHeader(header); } void OutgoingLinkLocalSession::handleStreamStart(const ProtocolHeader&) { - foreach(const boost::shared_ptr<ToplevelElement>& stanza, queuedElements_) { - sendElement(stanza); - } - queuedElements_.clear(); + foreach(const boost::shared_ptr<ToplevelElement>& stanza, queuedElements_) { + sendElement(stanza); + } + queuedElements_.clear(); } void OutgoingLinkLocalSession::handleElement(boost::shared_ptr<ToplevelElement> element) { - onElementReceived(element); + onElementReceived(element); } void OutgoingLinkLocalSession::queueElement(boost::shared_ptr<ToplevelElement> element) { - queuedElements_.push_back(element); + queuedElements_.push_back(element); } diff --git a/Swiften/LinkLocal/OutgoingLinkLocalSession.h b/Swiften/LinkLocal/OutgoingLinkLocalSession.h index 7227aba..b467918 100644 --- a/Swiften/LinkLocal/OutgoingLinkLocalSession.h +++ b/Swiften/LinkLocal/OutgoingLinkLocalSession.h @@ -17,30 +17,30 @@ #include <Swiften/Session/Session.h> namespace Swift { - class ConnectionFactory; - class XMLParserFactory; - class ToplevelElement; - class PayloadParserFactoryCollection; - class PayloadSerializerCollection; - - class SWIFTEN_API OutgoingLinkLocalSession : public Session { - public: - OutgoingLinkLocalSession( - const JID& localJID, - const JID& remoteJID, - boost::shared_ptr<Connection> connection, - PayloadParserFactoryCollection* payloadParserFactories, - PayloadSerializerCollection* payloadSerializers, - XMLParserFactory* xmlParserFactory); - - void queueElement(boost::shared_ptr<ToplevelElement> element); - - private: - void handleSessionStarted(); - void handleElement(boost::shared_ptr<ToplevelElement>); - void handleStreamStart(const ProtocolHeader&); - - private: - std::vector<boost::shared_ptr<ToplevelElement> > queuedElements_; - }; + class ConnectionFactory; + class XMLParserFactory; + class ToplevelElement; + class PayloadParserFactoryCollection; + class PayloadSerializerCollection; + + class SWIFTEN_API OutgoingLinkLocalSession : public Session { + public: + OutgoingLinkLocalSession( + const JID& localJID, + const JID& remoteJID, + boost::shared_ptr<Connection> connection, + PayloadParserFactoryCollection* payloadParserFactories, + PayloadSerializerCollection* payloadSerializers, + XMLParserFactory* xmlParserFactory); + + void queueElement(boost::shared_ptr<ToplevelElement> element); + + private: + void handleSessionStarted(); + void handleElement(boost::shared_ptr<ToplevelElement>); + void handleStreamStart(const ProtocolHeader&); + + private: + std::vector<boost::shared_ptr<ToplevelElement> > queuedElements_; + }; } diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp index 617e625..3511f90 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp @@ -20,124 +20,124 @@ using namespace Swift; class LinkLocalConnectorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LinkLocalConnectorTest); - CPPUNIT_TEST(testConnect); - CPPUNIT_TEST(testConnect_UnableToResolve); - CPPUNIT_TEST(testConnect_UnableToConnect); - CPPUNIT_TEST(testCancel_DuringResolve); - CPPUNIT_TEST(testCancel_DuringConnect); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - eventLoop = new DummyEventLoop(); - querier = boost::make_shared<FakeDNSSDQuerier>("rabbithole.local", eventLoop); - connection = boost::make_shared<FakeConnection>(eventLoop); - connectFinished = false; - } - - void tearDown() { - querier->clearAllQueriesEverRun(); - delete eventLoop; - } - - void testConnect() { - boost::shared_ptr<LinkLocalConnector> - testling(createConnector("rabbithole.local", 1234)); - querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); - - testling->connect(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(connectFinished); - CPPUNIT_ASSERT(!connectError); - CPPUNIT_ASSERT(connection->connectedTo); - CPPUNIT_ASSERT_EQUAL(std::string(connection->connectedTo->getAddress().toString()), std::string("192.168.1.1")); - CPPUNIT_ASSERT_EQUAL(connection->connectedTo->getPort(), 1234); - } - - void testConnect_UnableToResolve() { - boost::shared_ptr<LinkLocalConnector> - testling(createConnector("rabbithole.local", 1234)); - querier->setAddress("rabbithole.local", boost::optional<HostAddress>()); - - testling->connect(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(connectFinished); - CPPUNIT_ASSERT(connectError); - CPPUNIT_ASSERT(!connection->connectedTo); - } - - void testConnect_UnableToConnect() { - boost::shared_ptr<LinkLocalConnector> - testling(createConnector("rabbithole.local", 1234)); - querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); - connection->setError(Connection::ReadError); - - testling->connect(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(connectFinished); - CPPUNIT_ASSERT(connectError); - CPPUNIT_ASSERT(!connection->connectedTo); - } - - void testCancel_DuringResolve() { - boost::shared_ptr<LinkLocalConnector> - testling(createConnector("rabbithole.local", 1234)); - testling->connect(); - eventLoop->processEvents(); - CPPUNIT_ASSERT(!connectFinished); - - testling->cancel(); - eventLoop->processEvents(); - querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state); - } - - void testCancel_DuringConnect() { - boost::shared_ptr<LinkLocalConnector> - testling(createConnector("rabbithole.local", 1234)); - querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); - connection->setDelayConnect(); - testling->connect(); - eventLoop->processEvents(); - CPPUNIT_ASSERT(FakeConnection::Connecting == connection->state); - - testling->cancel(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state); - } - - private: - boost::shared_ptr<LinkLocalConnector> createConnector(const std::string& hostname, int port) { - LinkLocalService service( - DNSSDServiceID("myname", "local."), - DNSSDResolveServiceQuery::Result( - "myname._presence._tcp.local", hostname, port, - LinkLocalServiceInfo().toTXTRecord())); - boost::shared_ptr<LinkLocalConnector> result( - new LinkLocalConnector(service, querier, connection)); - result->onConnectFinished.connect( - boost::bind(&LinkLocalConnectorTest::handleConnected, this, _1)); - return result; - } - - void handleConnected(bool e) { - connectFinished = true; - connectError = e; - } - - private: - DummyEventLoop* eventLoop; - boost::shared_ptr<FakeDNSSDQuerier> querier; - boost::shared_ptr<FakeConnection> connection; - bool connectFinished; - bool connectError; + CPPUNIT_TEST_SUITE(LinkLocalConnectorTest); + CPPUNIT_TEST(testConnect); + CPPUNIT_TEST(testConnect_UnableToResolve); + CPPUNIT_TEST(testConnect_UnableToConnect); + CPPUNIT_TEST(testCancel_DuringResolve); + CPPUNIT_TEST(testCancel_DuringConnect); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + eventLoop = new DummyEventLoop(); + querier = boost::make_shared<FakeDNSSDQuerier>("rabbithole.local", eventLoop); + connection = boost::make_shared<FakeConnection>(eventLoop); + connectFinished = false; + } + + void tearDown() { + querier->clearAllQueriesEverRun(); + delete eventLoop; + } + + void testConnect() { + boost::shared_ptr<LinkLocalConnector> + testling(createConnector("rabbithole.local", 1234)); + querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); + + testling->connect(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(connectFinished); + CPPUNIT_ASSERT(!connectError); + CPPUNIT_ASSERT(connection->connectedTo); + CPPUNIT_ASSERT_EQUAL(std::string(connection->connectedTo->getAddress().toString()), std::string("192.168.1.1")); + CPPUNIT_ASSERT_EQUAL(connection->connectedTo->getPort(), 1234); + } + + void testConnect_UnableToResolve() { + boost::shared_ptr<LinkLocalConnector> + testling(createConnector("rabbithole.local", 1234)); + querier->setAddress("rabbithole.local", boost::optional<HostAddress>()); + + testling->connect(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(connectFinished); + CPPUNIT_ASSERT(connectError); + CPPUNIT_ASSERT(!connection->connectedTo); + } + + void testConnect_UnableToConnect() { + boost::shared_ptr<LinkLocalConnector> + testling(createConnector("rabbithole.local", 1234)); + querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); + connection->setError(Connection::ReadError); + + testling->connect(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(connectFinished); + CPPUNIT_ASSERT(connectError); + CPPUNIT_ASSERT(!connection->connectedTo); + } + + void testCancel_DuringResolve() { + boost::shared_ptr<LinkLocalConnector> + testling(createConnector("rabbithole.local", 1234)); + testling->connect(); + eventLoop->processEvents(); + CPPUNIT_ASSERT(!connectFinished); + + testling->cancel(); + eventLoop->processEvents(); + querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state); + } + + void testCancel_DuringConnect() { + boost::shared_ptr<LinkLocalConnector> + testling(createConnector("rabbithole.local", 1234)); + querier->setAddress("rabbithole.local", HostAddress("192.168.1.1")); + connection->setDelayConnect(); + testling->connect(); + eventLoop->processEvents(); + CPPUNIT_ASSERT(FakeConnection::Connecting == connection->state); + + testling->cancel(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state); + } + + private: + boost::shared_ptr<LinkLocalConnector> createConnector(const std::string& hostname, int port) { + LinkLocalService service( + DNSSDServiceID("myname", "local."), + DNSSDResolveServiceQuery::Result( + "myname._presence._tcp.local", hostname, port, + LinkLocalServiceInfo().toTXTRecord())); + boost::shared_ptr<LinkLocalConnector> result( + new LinkLocalConnector(service, querier, connection)); + result->onConnectFinished.connect( + boost::bind(&LinkLocalConnectorTest::handleConnected, this, _1)); + return result; + } + + void handleConnected(bool e) { + connectFinished = true; + connectError = e; + } + + private: + DummyEventLoop* eventLoop; + boost::shared_ptr<FakeDNSSDQuerier> querier; + boost::shared_ptr<FakeConnection> connection; + bool connectFinished; + bool connectError; }; CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalConnectorTest); diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp index 8533b33..6d8ba97 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp @@ -23,392 +23,392 @@ using namespace Swift; class LinkLocalServiceBrowserTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LinkLocalServiceBrowserTest); - CPPUNIT_TEST(testConstructor); - CPPUNIT_TEST(testStart); - CPPUNIT_TEST(testServiceAdded); - CPPUNIT_TEST(testServiceAdded_NoServiceInfo); - CPPUNIT_TEST(testServiceAdded_RegisteredService); - CPPUNIT_TEST(testServiceAdded_UnregisteredService); - CPPUNIT_TEST(testServiceAdded_Twice); - CPPUNIT_TEST(testServiceChanged); - CPPUNIT_TEST(testServiceRemoved); - CPPUNIT_TEST(testServiceRemoved_UnregisteredService); - CPPUNIT_TEST(testError_BrowseErrorAfterStart); - CPPUNIT_TEST(testError_BrowseErrorAfterResolve); - CPPUNIT_TEST(testRegisterService); - CPPUNIT_TEST(testRegisterService_Error); - CPPUNIT_TEST(testRegisterService_Reregister); - CPPUNIT_TEST(testUpdateService); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - eventLoop = new DummyEventLoop(); - querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop); - aliceServiceID = new DNSSDServiceID("alice", "wonderland.lit"); - aliceServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.wonderland.lit", "xmpp.wonderland.lit", 1234, LinkLocalServiceInfo().toTXTRecord()); - testServiceID = new DNSSDServiceID("foo", "bar.local"); - testServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.bar.local", "xmpp.bar.local", 1234, LinkLocalServiceInfo().toTXTRecord()); - testServiceInfo2 = new DNSSDResolveServiceQuery::Result("_presence.tcp.bar.local", "xmpp.foo.local", 2345, LinkLocalServiceInfo().toTXTRecord()); - errorStopReceived = false; - normalStopReceived = false; - } - - void tearDown() { - querier->clearAllQueriesEverRun(); - addedServices.clear(); - removedServices.clear(); - changedServices.clear(); - - delete aliceServiceID; - delete aliceServiceInfo; - delete testServiceInfo2; - delete testServiceInfo; - delete testServiceID; - delete eventLoop; - } - - void testConstructor() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - - CPPUNIT_ASSERT(!testling->isRunning()); - CPPUNIT_ASSERT(!testling->hasError()); - } - - void testStart() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - - CPPUNIT_ASSERT(testling->isRunning()); - CPPUNIT_ASSERT(!testling->hasError()); - - testling->stop(); - } - - void testServiceAdded() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - - querier->setServiceInfo(*testServiceID,*testServiceInfo); - querier->addService(*testServiceID); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); - CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); - std::vector<LinkLocalService> services = testling->getServices(); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); - CPPUNIT_ASSERT(*testServiceID == services[0].getID()); - CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort()); - CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname()); - - testling->stop(); - } - - void testServiceAdded_NoServiceInfo() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - - querier->addService(*testServiceID); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); - - testling->stop(); - } - - void testServiceAdded_RegisteredService() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - - testling->registerService("alice", 1234, LinkLocalServiceInfo()); - eventLoop->processEvents(); - querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo); - querier->addService(*aliceServiceID); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); - - testling->stop(); - } - - void testServiceAdded_UnregisteredService() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - testling->registerService("alice", 1234, LinkLocalServiceInfo()); - eventLoop->processEvents(); - testling->unregisterService(); - eventLoop->processEvents(); - - querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo); - querier->addService(*aliceServiceID); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); - CPPUNIT_ASSERT(addedServices[0].getID() == *aliceServiceID); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); - std::vector<LinkLocalService> services = testling->getServices(); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); - CPPUNIT_ASSERT(*aliceServiceID == services[0].getID()); - CPPUNIT_ASSERT(aliceServiceInfo->port == services[0].getPort()); - CPPUNIT_ASSERT(aliceServiceInfo->host == services[0].getHostname()); - - testling->stop(); - } - - void testServiceRemoved_UnregisteredService() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - testling->registerService("alice", 1234, LinkLocalServiceInfo()); - eventLoop->processEvents(); - testling->unregisterService(); - eventLoop->processEvents(); - - querier->removeService(*aliceServiceID); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); - - testling->stop(); - } - - void testServiceAdded_Twice() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - - querier->setServiceInfo(*testServiceID,*testServiceInfo); - querier->addService(*testServiceID); - querier->addService(*testServiceID); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(querier->getAllQueriesEverRun<FakeDNSSDResolveServiceQuery>().size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); - CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); - std::vector<LinkLocalService> services = testling->getServices(); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); - CPPUNIT_ASSERT(*testServiceID == services[0].getID()); - CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort()); - CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname()); - - testling->stop(); - } - - - void testServiceChanged() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - querier->setServiceInfo(*testServiceID,*testServiceInfo); - querier->addService(*testServiceID); - eventLoop->processEvents(); - - querier->setServiceInfo(*testServiceID,*testServiceInfo2); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changedServices.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); - CPPUNIT_ASSERT(changedServices[0].getID() == *testServiceID); - std::vector<LinkLocalService> services = testling->getServices(); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); - CPPUNIT_ASSERT(*testServiceID == services[0].getID()); - CPPUNIT_ASSERT(testServiceInfo2->port == services[0].getPort()); - CPPUNIT_ASSERT(testServiceInfo2->host == services[0].getHostname()); - - testling->stop(); - } - - void testServiceRemoved() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - querier->setServiceInfo(*testServiceID,*testServiceInfo); - querier->addService(*testServiceID); - eventLoop->processEvents(); - - querier->removeService(*testServiceID); - eventLoop->processEvents(); - querier->setServiceInfo(*testServiceID,*testServiceInfo2); - eventLoop->processEvents(); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(removedServices.size())); - CPPUNIT_ASSERT(removedServices[0].getID() == *testServiceID); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); - - testling->stop(); - } - - void testError_BrowseErrorAfterStart() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - - querier->setBrowseError(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(!testling->isRunning()); - CPPUNIT_ASSERT(testling->hasError()); - CPPUNIT_ASSERT(errorStopReceived); - } - - void testError_BrowseErrorAfterResolve() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - querier->setServiceInfo(*testServiceID,*testServiceInfo); - querier->addService(*testServiceID); - eventLoop->processEvents(); - - querier->setBrowseError(); - eventLoop->processEvents(); - querier->setServiceInfo(*testServiceID,*testServiceInfo2); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(!testling->isRunning()); - CPPUNIT_ASSERT(testling->hasError()); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); - CPPUNIT_ASSERT(errorStopReceived); - } - - void testRegisterService() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - - LinkLocalServiceInfo info; - info.setFirstName("Foo"); - testling->registerService("foo@bar", 1234, info); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(registeredServices.size())); - CPPUNIT_ASSERT(registeredServices[0] == DNSSDServiceID("foo@bar", "wonderland.lit")); - testling->stop(); - } - - void testRegisterService_Error() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - LinkLocalServiceInfo info; - testling->registerService("foo@bar", 1234, info); - eventLoop->processEvents(); - - querier->setRegisterError(); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(!testling->isRunning()); - CPPUNIT_ASSERT(testling->hasError()); - CPPUNIT_ASSERT(errorStopReceived); - CPPUNIT_ASSERT(!querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); - } - - void testRegisterService_Reregister() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - LinkLocalServiceInfo info; - info.setFirstName("Foo"); - testling->registerService("foo@bar", 1234, info); - eventLoop->processEvents(); - testling->unregisterService(); - eventLoop->processEvents(); - - info.setFirstName("Bar"); - testling->registerService("bar@baz", 3456, info); - eventLoop->processEvents(); - - CPPUNIT_ASSERT(querier->isServiceRegistered("bar@baz", 3456, info.toTXTRecord())); - - testling->stop(); - } - - void testUpdateService() { - boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); - testling->start(); - eventLoop->processEvents(); - - LinkLocalServiceInfo info; - info.setFirstName("Foo"); - testling->registerService("foo@bar", 1234, info); - eventLoop->processEvents(); - info.setFirstName("Bar"); - testling->updateService(info); - - CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); - - testling->stop(); - } - - private: - boost::shared_ptr<LinkLocalServiceBrowser> createTestling() { - boost::shared_ptr<LinkLocalServiceBrowser> testling( - new LinkLocalServiceBrowser(querier)); - testling->onServiceAdded.connect(boost::bind( - &LinkLocalServiceBrowserTest::handleServiceAdded, this, _1)); - testling->onServiceChanged.connect(boost::bind( - &LinkLocalServiceBrowserTest::handleServiceChanged, this, _1)); - testling->onServiceRemoved.connect(boost::bind( - &LinkLocalServiceBrowserTest::handleServiceRemoved, this, _1)); - testling->onServiceRegistered.connect(boost::bind( - &LinkLocalServiceBrowserTest::handleServiceRegistered, this, _1)); - testling->onStopped.connect(boost::bind( - &LinkLocalServiceBrowserTest::handleStopped, this, _1)); - return testling; - } - - void handleServiceAdded(const LinkLocalService& service) { - addedServices.push_back(service); - } - - void handleServiceRemoved(const LinkLocalService& service) { - removedServices.push_back(service); - } - - void handleServiceChanged(const LinkLocalService& service) { - changedServices.push_back(service); - } - - void handleServiceRegistered(const DNSSDServiceID& service) { - registeredServices.push_back(service); - } - - void handleStopped(bool error) { - CPPUNIT_ASSERT(!errorStopReceived); - CPPUNIT_ASSERT(!normalStopReceived); - if (error) { - errorStopReceived = true; - } - else { - normalStopReceived = true; - } - } - - private: - DummyEventLoop* eventLoop; - boost::shared_ptr<FakeDNSSDQuerier> querier; - std::vector<LinkLocalService> addedServices; - std::vector<LinkLocalService> changedServices; - std::vector<LinkLocalService> removedServices; - std::vector<DNSSDServiceID> registeredServices; - DNSSDServiceID* aliceServiceID; - DNSSDResolveServiceQuery::Result* aliceServiceInfo; - DNSSDServiceID* testServiceID; - DNSSDResolveServiceQuery::Result* testServiceInfo; - DNSSDResolveServiceQuery::Result* testServiceInfo2; - bool errorStopReceived; - bool normalStopReceived; + CPPUNIT_TEST_SUITE(LinkLocalServiceBrowserTest); + CPPUNIT_TEST(testConstructor); + CPPUNIT_TEST(testStart); + CPPUNIT_TEST(testServiceAdded); + CPPUNIT_TEST(testServiceAdded_NoServiceInfo); + CPPUNIT_TEST(testServiceAdded_RegisteredService); + CPPUNIT_TEST(testServiceAdded_UnregisteredService); + CPPUNIT_TEST(testServiceAdded_Twice); + CPPUNIT_TEST(testServiceChanged); + CPPUNIT_TEST(testServiceRemoved); + CPPUNIT_TEST(testServiceRemoved_UnregisteredService); + CPPUNIT_TEST(testError_BrowseErrorAfterStart); + CPPUNIT_TEST(testError_BrowseErrorAfterResolve); + CPPUNIT_TEST(testRegisterService); + CPPUNIT_TEST(testRegisterService_Error); + CPPUNIT_TEST(testRegisterService_Reregister); + CPPUNIT_TEST(testUpdateService); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + eventLoop = new DummyEventLoop(); + querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop); + aliceServiceID = new DNSSDServiceID("alice", "wonderland.lit"); + aliceServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.wonderland.lit", "xmpp.wonderland.lit", 1234, LinkLocalServiceInfo().toTXTRecord()); + testServiceID = new DNSSDServiceID("foo", "bar.local"); + testServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.bar.local", "xmpp.bar.local", 1234, LinkLocalServiceInfo().toTXTRecord()); + testServiceInfo2 = new DNSSDResolveServiceQuery::Result("_presence.tcp.bar.local", "xmpp.foo.local", 2345, LinkLocalServiceInfo().toTXTRecord()); + errorStopReceived = false; + normalStopReceived = false; + } + + void tearDown() { + querier->clearAllQueriesEverRun(); + addedServices.clear(); + removedServices.clear(); + changedServices.clear(); + + delete aliceServiceID; + delete aliceServiceInfo; + delete testServiceInfo2; + delete testServiceInfo; + delete testServiceID; + delete eventLoop; + } + + void testConstructor() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + + CPPUNIT_ASSERT(!testling->isRunning()); + CPPUNIT_ASSERT(!testling->hasError()); + } + + void testStart() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + + CPPUNIT_ASSERT(testling->isRunning()); + CPPUNIT_ASSERT(!testling->hasError()); + + testling->stop(); + } + + void testServiceAdded() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + + querier->setServiceInfo(*testServiceID,*testServiceInfo); + querier->addService(*testServiceID); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); + CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); + std::vector<LinkLocalService> services = testling->getServices(); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); + CPPUNIT_ASSERT(*testServiceID == services[0].getID()); + CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort()); + CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname()); + + testling->stop(); + } + + void testServiceAdded_NoServiceInfo() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + + querier->addService(*testServiceID); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); + + testling->stop(); + } + + void testServiceAdded_RegisteredService() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + + testling->registerService("alice", 1234, LinkLocalServiceInfo()); + eventLoop->processEvents(); + querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo); + querier->addService(*aliceServiceID); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); + + testling->stop(); + } + + void testServiceAdded_UnregisteredService() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + testling->registerService("alice", 1234, LinkLocalServiceInfo()); + eventLoop->processEvents(); + testling->unregisterService(); + eventLoop->processEvents(); + + querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo); + querier->addService(*aliceServiceID); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); + CPPUNIT_ASSERT(addedServices[0].getID() == *aliceServiceID); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); + std::vector<LinkLocalService> services = testling->getServices(); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); + CPPUNIT_ASSERT(*aliceServiceID == services[0].getID()); + CPPUNIT_ASSERT(aliceServiceInfo->port == services[0].getPort()); + CPPUNIT_ASSERT(aliceServiceInfo->host == services[0].getHostname()); + + testling->stop(); + } + + void testServiceRemoved_UnregisteredService() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + testling->registerService("alice", 1234, LinkLocalServiceInfo()); + eventLoop->processEvents(); + testling->unregisterService(); + eventLoop->processEvents(); + + querier->removeService(*aliceServiceID); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); + + testling->stop(); + } + + void testServiceAdded_Twice() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + + querier->setServiceInfo(*testServiceID,*testServiceInfo); + querier->addService(*testServiceID); + querier->addService(*testServiceID); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(querier->getAllQueriesEverRun<FakeDNSSDResolveServiceQuery>().size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); + CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); + std::vector<LinkLocalService> services = testling->getServices(); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); + CPPUNIT_ASSERT(*testServiceID == services[0].getID()); + CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort()); + CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname()); + + testling->stop(); + } + + + void testServiceChanged() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + querier->setServiceInfo(*testServiceID,*testServiceInfo); + querier->addService(*testServiceID); + eventLoop->processEvents(); + + querier->setServiceInfo(*testServiceID,*testServiceInfo2); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changedServices.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size())); + CPPUNIT_ASSERT(changedServices[0].getID() == *testServiceID); + std::vector<LinkLocalService> services = testling->getServices(); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size())); + CPPUNIT_ASSERT(*testServiceID == services[0].getID()); + CPPUNIT_ASSERT(testServiceInfo2->port == services[0].getPort()); + CPPUNIT_ASSERT(testServiceInfo2->host == services[0].getHostname()); + + testling->stop(); + } + + void testServiceRemoved() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + querier->setServiceInfo(*testServiceID,*testServiceInfo); + querier->addService(*testServiceID); + eventLoop->processEvents(); + + querier->removeService(*testServiceID); + eventLoop->processEvents(); + querier->setServiceInfo(*testServiceID,*testServiceInfo2); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(removedServices.size())); + CPPUNIT_ASSERT(removedServices[0].getID() == *testServiceID); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); + + testling->stop(); + } + + void testError_BrowseErrorAfterStart() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + + querier->setBrowseError(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(!testling->isRunning()); + CPPUNIT_ASSERT(testling->hasError()); + CPPUNIT_ASSERT(errorStopReceived); + } + + void testError_BrowseErrorAfterResolve() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + querier->setServiceInfo(*testServiceID,*testServiceInfo); + querier->addService(*testServiceID); + eventLoop->processEvents(); + + querier->setBrowseError(); + eventLoop->processEvents(); + querier->setServiceInfo(*testServiceID,*testServiceInfo2); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(!testling->isRunning()); + CPPUNIT_ASSERT(testling->hasError()); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size())); + CPPUNIT_ASSERT(errorStopReceived); + } + + void testRegisterService() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + + LinkLocalServiceInfo info; + info.setFirstName("Foo"); + testling->registerService("foo@bar", 1234, info); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(registeredServices.size())); + CPPUNIT_ASSERT(registeredServices[0] == DNSSDServiceID("foo@bar", "wonderland.lit")); + testling->stop(); + } + + void testRegisterService_Error() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + LinkLocalServiceInfo info; + testling->registerService("foo@bar", 1234, info); + eventLoop->processEvents(); + + querier->setRegisterError(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(!testling->isRunning()); + CPPUNIT_ASSERT(testling->hasError()); + CPPUNIT_ASSERT(errorStopReceived); + CPPUNIT_ASSERT(!querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); + } + + void testRegisterService_Reregister() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + LinkLocalServiceInfo info; + info.setFirstName("Foo"); + testling->registerService("foo@bar", 1234, info); + eventLoop->processEvents(); + testling->unregisterService(); + eventLoop->processEvents(); + + info.setFirstName("Bar"); + testling->registerService("bar@baz", 3456, info); + eventLoop->processEvents(); + + CPPUNIT_ASSERT(querier->isServiceRegistered("bar@baz", 3456, info.toTXTRecord())); + + testling->stop(); + } + + void testUpdateService() { + boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); + testling->start(); + eventLoop->processEvents(); + + LinkLocalServiceInfo info; + info.setFirstName("Foo"); + testling->registerService("foo@bar", 1234, info); + eventLoop->processEvents(); + info.setFirstName("Bar"); + testling->updateService(info); + + CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); + + testling->stop(); + } + + private: + boost::shared_ptr<LinkLocalServiceBrowser> createTestling() { + boost::shared_ptr<LinkLocalServiceBrowser> testling( + new LinkLocalServiceBrowser(querier)); + testling->onServiceAdded.connect(boost::bind( + &LinkLocalServiceBrowserTest::handleServiceAdded, this, _1)); + testling->onServiceChanged.connect(boost::bind( + &LinkLocalServiceBrowserTest::handleServiceChanged, this, _1)); + testling->onServiceRemoved.connect(boost::bind( + &LinkLocalServiceBrowserTest::handleServiceRemoved, this, _1)); + testling->onServiceRegistered.connect(boost::bind( + &LinkLocalServiceBrowserTest::handleServiceRegistered, this, _1)); + testling->onStopped.connect(boost::bind( + &LinkLocalServiceBrowserTest::handleStopped, this, _1)); + return testling; + } + + void handleServiceAdded(const LinkLocalService& service) { + addedServices.push_back(service); + } + + void handleServiceRemoved(const LinkLocalService& service) { + removedServices.push_back(service); + } + + void handleServiceChanged(const LinkLocalService& service) { + changedServices.push_back(service); + } + + void handleServiceRegistered(const DNSSDServiceID& service) { + registeredServices.push_back(service); + } + + void handleStopped(bool error) { + CPPUNIT_ASSERT(!errorStopReceived); + CPPUNIT_ASSERT(!normalStopReceived); + if (error) { + errorStopReceived = true; + } + else { + normalStopReceived = true; + } + } + + private: + DummyEventLoop* eventLoop; + boost::shared_ptr<FakeDNSSDQuerier> querier; + std::vector<LinkLocalService> addedServices; + std::vector<LinkLocalService> changedServices; + std::vector<LinkLocalService> removedServices; + std::vector<DNSSDServiceID> registeredServices; + DNSSDServiceID* aliceServiceID; + DNSSDResolveServiceQuery::Result* aliceServiceInfo; + DNSSDServiceID* testServiceID; + DNSSDResolveServiceQuery::Result* testServiceInfo; + DNSSDResolveServiceQuery::Result* testServiceInfo2; + bool errorStopReceived; + bool normalStopReceived; }; CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceBrowserTest); diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp index 55fdfb3..0a94a98 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp @@ -15,58 +15,58 @@ using namespace Swift; class LinkLocalServiceInfoTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LinkLocalServiceInfoTest); - CPPUNIT_TEST(testGetTXTRecord); - CPPUNIT_TEST(testCreateFromTXTRecord); - CPPUNIT_TEST(testCreateFromTXTRecord_InvalidSize); - CPPUNIT_TEST(testGetTXTRecordCreateFromTXTRecord_RoundTrip); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(LinkLocalServiceInfoTest); + CPPUNIT_TEST(testGetTXTRecord); + CPPUNIT_TEST(testCreateFromTXTRecord); + CPPUNIT_TEST(testCreateFromTXTRecord_InvalidSize); + CPPUNIT_TEST(testGetTXTRecordCreateFromTXTRecord_RoundTrip); + CPPUNIT_TEST_SUITE_END(); - public: - void testGetTXTRecord() { - LinkLocalServiceInfo info; - info.setFirstName("Remko"); - info.setLastName("Tron\xc3\xe7on"); - info.setStatus(LinkLocalServiceInfo::Away); + public: + void testGetTXTRecord() { + LinkLocalServiceInfo info; + info.setFirstName("Remko"); + info.setLastName("Tron\xc3\xe7on"); + info.setStatus(LinkLocalServiceInfo::Away); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")), info.toTXTRecord()); - } + CPPUNIT_ASSERT_EQUAL(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")), info.toTXTRecord()); + } - void testCreateFromTXTRecord() { - LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away"))); + void testCreateFromTXTRecord() { + LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away"))); - CPPUNIT_ASSERT_EQUAL(std::string("Remko"), info.getFirstName()); - CPPUNIT_ASSERT_EQUAL(std::string("Tron\xc3\xe7on"), info.getLastName()); - CPPUNIT_ASSERT_EQUAL(LinkLocalServiceInfo::Away, info.getStatus()); - } + CPPUNIT_ASSERT_EQUAL(std::string("Remko"), info.getFirstName()); + CPPUNIT_ASSERT_EQUAL(std::string("Tron\xc3\xe7on"), info.getLastName()); + CPPUNIT_ASSERT_EQUAL(LinkLocalServiceInfo::Away, info.getStatus()); + } - void testCreateFromTXTRecord_InvalidSize() { - LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x10last=a")); + void testCreateFromTXTRecord_InvalidSize() { + LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x10last=a")); - CPPUNIT_ASSERT_EQUAL(std::string("a"), info.getLastName()); - } + CPPUNIT_ASSERT_EQUAL(std::string("a"), info.getLastName()); + } - void testGetTXTRecordCreateFromTXTRecord_RoundTrip() { - LinkLocalServiceInfo info; - info.setFirstName("Remko"); - info.setLastName("Tron\xc3\xe7on"); - info.setEMail("remko-email@swift.im"); - info.setJID(JID("remko-jid@swift.im")); - info.setMessage("I'm busy"); - info.setNick("el-tramo"); - info.setStatus(LinkLocalServiceInfo::DND); - info.setPort(1234); + void testGetTXTRecordCreateFromTXTRecord_RoundTrip() { + LinkLocalServiceInfo info; + info.setFirstName("Remko"); + info.setLastName("Tron\xc3\xe7on"); + info.setEMail("remko-email@swift.im"); + info.setJID(JID("remko-jid@swift.im")); + info.setMessage("I'm busy"); + info.setNick("el-tramo"); + info.setStatus(LinkLocalServiceInfo::DND); + info.setPort(1234); - LinkLocalServiceInfo info2 = LinkLocalServiceInfo::createFromTXTRecord(info.toTXTRecord()); - CPPUNIT_ASSERT_EQUAL(info.getFirstName(), info2.getFirstName()); - CPPUNIT_ASSERT_EQUAL(info.getLastName(), info2.getLastName()); - CPPUNIT_ASSERT_EQUAL(info.getEMail(), info2.getEMail()); - CPPUNIT_ASSERT_EQUAL(info.getJID(), info2.getJID()); - CPPUNIT_ASSERT_EQUAL(info.getMessage(), info2.getMessage()); - CPPUNIT_ASSERT_EQUAL(info.getNick(), info2.getNick()); - CPPUNIT_ASSERT(info.getStatus() == info2.getStatus()); - CPPUNIT_ASSERT(info.getPort() == info2.getPort()); - } + LinkLocalServiceInfo info2 = LinkLocalServiceInfo::createFromTXTRecord(info.toTXTRecord()); + CPPUNIT_ASSERT_EQUAL(info.getFirstName(), info2.getFirstName()); + CPPUNIT_ASSERT_EQUAL(info.getLastName(), info2.getLastName()); + CPPUNIT_ASSERT_EQUAL(info.getEMail(), info2.getEMail()); + CPPUNIT_ASSERT_EQUAL(info.getJID(), info2.getJID()); + CPPUNIT_ASSERT_EQUAL(info.getMessage(), info2.getMessage()); + CPPUNIT_ASSERT_EQUAL(info.getNick(), info2.getNick()); + CPPUNIT_ASSERT(info.getStatus() == info2.getStatus()); + CPPUNIT_ASSERT(info.getPort() == info2.getPort()); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceInfoTest); diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp index 0eb2464..206d824 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp @@ -12,57 +12,57 @@ using namespace Swift; class LinkLocalServiceTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LinkLocalServiceTest); - CPPUNIT_TEST(testGetDescription_WithNick); - CPPUNIT_TEST(testGetDescription_WithFirstName); - CPPUNIT_TEST(testGetDescription_WithLastName); - CPPUNIT_TEST(testGetDescription_WithFirstAndLastName); - CPPUNIT_TEST(testGetDescription_NoInfo); - CPPUNIT_TEST_SUITE_END(); - - public: - void testGetDescription_WithNick() { - LinkLocalService testling = createService("alice@wonderland", "Alice", "Alice In", "Wonderland"); - - CPPUNIT_ASSERT_EQUAL(std::string("Alice"), testling.getDescription()); - } - - void testGetDescription_WithFirstName() { - LinkLocalService testling = createService("alice@wonderland", "", "Alice In"); - - CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), testling.getDescription()); - } - - void testGetDescription_WithLastName() { - LinkLocalService testling = createService("alice@wonderland", "", "", "Wonderland"); - - CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), testling.getDescription()); - } - - void testGetDescription_WithFirstAndLastName() { - LinkLocalService testling = createService("alice@wonderland", "", "Alice In", "Wonderland"); - - CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), testling.getDescription()); - } - - void testGetDescription_NoInfo() { - LinkLocalService testling = createService("alice@wonderland"); - - CPPUNIT_ASSERT_EQUAL(std::string("alice@wonderland"), testling.getDescription()); - } - - private: - LinkLocalService createService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) { - DNSSDServiceID service(name, "local."); - LinkLocalServiceInfo info; - info.setFirstName(firstName); - info.setLastName(lastName); - info.setNick(nickName); - return LinkLocalService(service, - DNSSDResolveServiceQuery::Result( - name + "._presence._tcp.local", "rabbithole.local", 1234, - info.toTXTRecord())); - } + CPPUNIT_TEST_SUITE(LinkLocalServiceTest); + CPPUNIT_TEST(testGetDescription_WithNick); + CPPUNIT_TEST(testGetDescription_WithFirstName); + CPPUNIT_TEST(testGetDescription_WithLastName); + CPPUNIT_TEST(testGetDescription_WithFirstAndLastName); + CPPUNIT_TEST(testGetDescription_NoInfo); + CPPUNIT_TEST_SUITE_END(); + + public: + void testGetDescription_WithNick() { + LinkLocalService testling = createService("alice@wonderland", "Alice", "Alice In", "Wonderland"); + + CPPUNIT_ASSERT_EQUAL(std::string("Alice"), testling.getDescription()); + } + + void testGetDescription_WithFirstName() { + LinkLocalService testling = createService("alice@wonderland", "", "Alice In"); + + CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), testling.getDescription()); + } + + void testGetDescription_WithLastName() { + LinkLocalService testling = createService("alice@wonderland", "", "", "Wonderland"); + + CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), testling.getDescription()); + } + + void testGetDescription_WithFirstAndLastName() { + LinkLocalService testling = createService("alice@wonderland", "", "Alice In", "Wonderland"); + + CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), testling.getDescription()); + } + + void testGetDescription_NoInfo() { + LinkLocalService testling = createService("alice@wonderland"); + + CPPUNIT_ASSERT_EQUAL(std::string("alice@wonderland"), testling.getDescription()); + } + + private: + LinkLocalService createService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) { + DNSSDServiceID service(name, "local."); + LinkLocalServiceInfo info; + info.setFirstName(firstName); + info.setLastName(lastName); + info.setNick(nickName); + return LinkLocalService(service, + DNSSDResolveServiceQuery::Result( + name + "._presence._tcp.local", "rabbithole.local", 1234, + info.toTXTRecord())); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceTest); diff --git a/Swiften/MUC/MUC.h b/Swiften/MUC/MUC.h index fbd7be6..e8f953e 100644 --- a/Swiften/MUC/MUC.h +++ b/Swiften/MUC/MUC.h @@ -24,77 +24,77 @@ #include <Swiften/MUC/MUCRegistry.h> namespace Swift { - class StanzaChannel; - class IQRouter; - class DirectedPresenceSender; + class StanzaChannel; + class IQRouter; + class DirectedPresenceSender; - class SWIFTEN_API MUC { - public: - typedef boost::shared_ptr<MUC> ref; + class SWIFTEN_API MUC { + public: + typedef boost::shared_ptr<MUC> ref; - enum JoinResult { JoinSucceeded, JoinFailed }; - enum LeavingType { LeavePart, LeaveKick, LeaveBan, LeaveDestroy, LeaveNotMember, Disconnect }; + enum JoinResult { JoinSucceeded, JoinFailed }; + enum LeavingType { LeavePart, LeaveKick, LeaveBan, LeaveDestroy, LeaveNotMember, Disconnect }; - public: - virtual ~MUC(); + public: + virtual ~MUC(); - /** - * Returns the (bare) JID of the MUC. - */ - virtual JID getJID() const = 0; + /** + * Returns the (bare) JID of the MUC. + */ + virtual JID getJID() const = 0; - /** - * Returns if the room is unlocked and other people can join the room. - * @return True if joinable by others; false otherwise. - */ - virtual bool isUnlocked() const = 0; + /** + * Returns if the room is unlocked and other people can join the room. + * @return True if joinable by others; false otherwise. + */ + virtual bool isUnlocked() const = 0; - virtual void joinAs(const std::string &nick) = 0; - virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since) = 0; - /*virtual void queryRoomInfo(); */ - /*virtual void queryRoomItems(); */ - /*virtual std::string getCurrentNick() = 0; */ - virtual std::map<std::string, MUCOccupant> getOccupants() const = 0; - virtual void changeNickname(const std::string& newNickname) = 0; - virtual void part() = 0; - /*virtual void handleIncomingMessage(Message::ref message) = 0; */ - /** Expose public so it can be called when e.g. user goes offline */ - virtual void handleUserLeft(LeavingType) = 0; - /** Get occupant information*/ - virtual const MUCOccupant& getOccupant(const std::string& nick) = 0; - virtual bool hasOccupant(const std::string& nick) = 0; - virtual void kickOccupant(const JID& jid) = 0; - virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role) = 0; - virtual void requestAffiliationList(MUCOccupant::Affiliation) = 0; - virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation) = 0; - virtual void changeSubject(const std::string& subject) = 0; - virtual void requestConfigurationForm() = 0; - virtual void configureRoom(Form::ref) = 0; - virtual void cancelConfigureRoom() = 0; - virtual void destroyRoom() = 0; - /** Send an invite for the person to join the MUC */ - virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false) = 0; - virtual void setCreateAsReservedIfNew() = 0; - virtual void setPassword(const boost::optional<std::string>& password) = 0; + virtual void joinAs(const std::string &nick) = 0; + virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since) = 0; + /*virtual void queryRoomInfo(); */ + /*virtual void queryRoomItems(); */ + /*virtual std::string getCurrentNick() = 0; */ + virtual std::map<std::string, MUCOccupant> getOccupants() const = 0; + virtual void changeNickname(const std::string& newNickname) = 0; + virtual void part() = 0; + /*virtual void handleIncomingMessage(Message::ref message) = 0; */ + /** Expose public so it can be called when e.g. user goes offline */ + virtual void handleUserLeft(LeavingType) = 0; + /** Get occupant information*/ + virtual const MUCOccupant& getOccupant(const std::string& nick) = 0; + virtual bool hasOccupant(const std::string& nick) = 0; + virtual void kickOccupant(const JID& jid) = 0; + virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role) = 0; + virtual void requestAffiliationList(MUCOccupant::Affiliation) = 0; + virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation) = 0; + virtual void changeSubject(const std::string& subject) = 0; + virtual void requestConfigurationForm() = 0; + virtual void configureRoom(Form::ref) = 0; + virtual void cancelConfigureRoom() = 0; + virtual void destroyRoom() = 0; + /** Send an invite for the person to join the MUC */ + virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false) = 0; + virtual void setCreateAsReservedIfNew() = 0; + virtual void setPassword(const boost::optional<std::string>& password) = 0; - public: - boost::signal<void (const std::string& /*nick*/)> onJoinComplete; - boost::signal<void (ErrorPayload::ref)> onJoinFailed; - boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Role)> onRoleChangeFailed; - boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Affiliation)> onAffiliationChangeFailed; - boost::signal<void (ErrorPayload::ref)> onConfigurationFailed; - boost::signal<void (ErrorPayload::ref)> onAffiliationListFailed; - boost::signal<void (Presence::ref)> onOccupantPresenceChange; - boost::signal<void (const std::string&, const MUCOccupant& /*now*/, const MUCOccupant::Role& /*old*/)> onOccupantRoleChanged; - boost::signal<void (const std::string&, const MUCOccupant::Affiliation& /*new*/, const MUCOccupant::Affiliation& /*old*/)> onOccupantAffiliationChanged; - boost::signal<void (const MUCOccupant&)> onOccupantJoined; - boost::signal<void (const std::string& /*oldNickname*/, const std::string& /*newNickname*/ )> onOccupantNicknameChanged; - boost::signal<void (const MUCOccupant&, LeavingType, const std::string& /*reason*/)> onOccupantLeft; - boost::signal<void (Form::ref)> onConfigurationFormReceived; - boost::signal<void (MUCOccupant::Affiliation, const std::vector<JID>&)> onAffiliationListReceived; - boost::signal<void ()> onUnlocked; - /* boost::signal<void (const MUCInfo&)> onInfoResult; */ - /* boost::signal<void (const blah&)> onItemsResult; */ + public: + boost::signal<void (const std::string& /*nick*/)> onJoinComplete; + boost::signal<void (ErrorPayload::ref)> onJoinFailed; + boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Role)> onRoleChangeFailed; + boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Affiliation)> onAffiliationChangeFailed; + boost::signal<void (ErrorPayload::ref)> onConfigurationFailed; + boost::signal<void (ErrorPayload::ref)> onAffiliationListFailed; + boost::signal<void (Presence::ref)> onOccupantPresenceChange; + boost::signal<void (const std::string&, const MUCOccupant& /*now*/, const MUCOccupant::Role& /*old*/)> onOccupantRoleChanged; + boost::signal<void (const std::string&, const MUCOccupant::Affiliation& /*new*/, const MUCOccupant::Affiliation& /*old*/)> onOccupantAffiliationChanged; + boost::signal<void (const MUCOccupant&)> onOccupantJoined; + boost::signal<void (const std::string& /*oldNickname*/, const std::string& /*newNickname*/ )> onOccupantNicknameChanged; + boost::signal<void (const MUCOccupant&, LeavingType, const std::string& /*reason*/)> onOccupantLeft; + boost::signal<void (Form::ref)> onConfigurationFormReceived; + boost::signal<void (MUCOccupant::Affiliation, const std::vector<JID>&)> onAffiliationListReceived; + boost::signal<void ()> onUnlocked; + /* boost::signal<void (const MUCInfo&)> onInfoResult; */ + /* boost::signal<void (const blah&)> onItemsResult; */ - }; + }; } diff --git a/Swiften/MUC/MUCBookmark.h b/Swiften/MUC/MUCBookmark.h index 1f54a8f..92050f1 100644 --- a/Swiften/MUC/MUCBookmark.h +++ b/Swiften/MUC/MUCBookmark.h @@ -15,76 +15,76 @@ #include <Swiften/JID/JID.h> namespace Swift { - class SWIFTEN_API MUCBookmark { - public: - MUCBookmark(const Storage::Room& room) { - name_ = room.name; - room_ = room.jid; - nick_ = room.nick; - password_ = room.password; - autojoin_ = room.autoJoin; - } - - MUCBookmark(const JID& room, const std::string& bookmarkName) : room_(room), name_(bookmarkName), autojoin_(false) { - } - - void setAutojoin(bool enabled) { - autojoin_ = enabled; - } - - bool getAutojoin() const { - return autojoin_; - } - - void setNick(const boost::optional<std::string>& nick) { - nick_ = nick; - } - - void setPassword(const boost::optional<std::string>& password) { - password_ = password; - } - - const boost::optional<std::string>& getNick() const { - return nick_; - } - - const boost::optional<std::string>& getPassword() const { - return password_; - } - - const std::string& getName() const { - return name_; - } - - const JID& getRoom() const { - return room_; - } - - bool operator==(const MUCBookmark& rhs) const { - /* FIXME: not checking passwords for equality - which might make sense, perhaps */ - return rhs.room_ == room_ && rhs.name_ == name_ && rhs.nick_ == nick_ /*&& rhs.password_ == password_*/ && rhs.autojoin_ == autojoin_; - } - - Storage::Room toStorage() const { - Storage::Room room; - room.name = name_; - room.jid = room_; - if (nick_) { - room.nick = *nick_; - } - if (password_) { - room.password = *password_; - } - room.autoJoin = autojoin_; - return room; - } - - private: - JID room_; - std::string name_; - boost::optional<std::string> nick_; - boost::optional<std::string> password_; - bool autojoin_; - }; + class SWIFTEN_API MUCBookmark { + public: + MUCBookmark(const Storage::Room& room) { + name_ = room.name; + room_ = room.jid; + nick_ = room.nick; + password_ = room.password; + autojoin_ = room.autoJoin; + } + + MUCBookmark(const JID& room, const std::string& bookmarkName) : room_(room), name_(bookmarkName), autojoin_(false) { + } + + void setAutojoin(bool enabled) { + autojoin_ = enabled; + } + + bool getAutojoin() const { + return autojoin_; + } + + void setNick(const boost::optional<std::string>& nick) { + nick_ = nick; + } + + void setPassword(const boost::optional<std::string>& password) { + password_ = password; + } + + const boost::optional<std::string>& getNick() const { + return nick_; + } + + const boost::optional<std::string>& getPassword() const { + return password_; + } + + const std::string& getName() const { + return name_; + } + + const JID& getRoom() const { + return room_; + } + + bool operator==(const MUCBookmark& rhs) const { + /* FIXME: not checking passwords for equality - which might make sense, perhaps */ + return rhs.room_ == room_ && rhs.name_ == name_ && rhs.nick_ == nick_ /*&& rhs.password_ == password_*/ && rhs.autojoin_ == autojoin_; + } + + Storage::Room toStorage() const { + Storage::Room room; + room.name = name_; + room.jid = room_; + if (nick_) { + room.nick = *nick_; + } + if (password_) { + room.password = *password_; + } + room.autoJoin = autojoin_; + return room; + } + + private: + JID room_; + std::string name_; + boost::optional<std::string> nick_; + boost::optional<std::string> password_; + bool autojoin_; + }; } diff --git a/Swiften/MUC/MUCBookmarkManager.cpp b/Swiften/MUC/MUCBookmarkManager.cpp index b109be2..1d8c2aa 100644 --- a/Swiften/MUC/MUCBookmarkManager.cpp +++ b/Swiften/MUC/MUCBookmarkManager.cpp @@ -19,103 +19,103 @@ namespace Swift { MUCBookmarkManager::MUCBookmarkManager(IQRouter* iqRouter) { - iqRouter_ = iqRouter; - ready_ = false; - GetPrivateStorageRequest<Storage>::ref request = GetPrivateStorageRequest<Storage>::create(iqRouter_); - request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksReceived, this, _1, _2)); - request->send(); + iqRouter_ = iqRouter; + ready_ = false; + GetPrivateStorageRequest<Storage>::ref request = GetPrivateStorageRequest<Storage>::create(iqRouter_); + request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksReceived, this, _1, _2)); + request->send(); } void MUCBookmarkManager::handleBookmarksReceived(boost::shared_ptr<Storage> payload, ErrorPayload::ref error) { - if (error) { - return; - } - - ready_ = true; - onBookmarksReady(); - - storage = payload; - - std::vector<MUCBookmark> receivedBookmarks; - foreach (Storage::Room room, payload->getRooms()) { - receivedBookmarks.push_back(MUCBookmark(room)); - } - - std::vector<MUCBookmark> newBookmarks; - foreach (const MUCBookmark& oldBookmark, bookmarks_) { - if (containsEquivalent(receivedBookmarks, oldBookmark)) { - newBookmarks.push_back(oldBookmark); - } else { - onBookmarkRemoved(oldBookmark); - } - } - - foreach (const MUCBookmark& newBookmark, receivedBookmarks) { - if (!containsEquivalent(bookmarks_, newBookmark)) { - newBookmarks.push_back(newBookmark); - onBookmarkAdded(newBookmark); - } - } - bookmarks_ = newBookmarks; + if (error) { + return; + } + + ready_ = true; + onBookmarksReady(); + + storage = payload; + + std::vector<MUCBookmark> receivedBookmarks; + foreach (Storage::Room room, payload->getRooms()) { + receivedBookmarks.push_back(MUCBookmark(room)); + } + + std::vector<MUCBookmark> newBookmarks; + foreach (const MUCBookmark& oldBookmark, bookmarks_) { + if (containsEquivalent(receivedBookmarks, oldBookmark)) { + newBookmarks.push_back(oldBookmark); + } else { + onBookmarkRemoved(oldBookmark); + } + } + + foreach (const MUCBookmark& newBookmark, receivedBookmarks) { + if (!containsEquivalent(bookmarks_, newBookmark)) { + newBookmarks.push_back(newBookmark); + onBookmarkAdded(newBookmark); + } + } + bookmarks_ = newBookmarks; } bool MUCBookmarkManager::containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark) { - return std::find(list.begin(), list.end(), bookmark) != list.end(); + return std::find(list.begin(), list.end(), bookmark) != list.end(); } void MUCBookmarkManager::replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) { - if (!ready_) return; - for (size_t i = 0; i < bookmarks_.size(); i++) { - if (bookmarks_[i] == oldBookmark) { - bookmarks_[i] = newBookmark; - flush(); - onBookmarkRemoved(oldBookmark); - onBookmarkAdded(newBookmark); - return; - } - } + if (!ready_) return; + for (size_t i = 0; i < bookmarks_.size(); i++) { + if (bookmarks_[i] == oldBookmark) { + bookmarks_[i] = newBookmark; + flush(); + onBookmarkRemoved(oldBookmark); + onBookmarkAdded(newBookmark); + return; + } + } } void MUCBookmarkManager::addBookmark(const MUCBookmark& bookmark) { - if (!ready_) return; - bookmarks_.push_back(bookmark); - onBookmarkAdded(bookmark); - flush(); + if (!ready_) return; + bookmarks_.push_back(bookmark); + onBookmarkAdded(bookmark); + flush(); } void MUCBookmarkManager::removeBookmark(const MUCBookmark& bookmark) { - if (!ready_) return; - std::vector<MUCBookmark>::iterator it; - for (it = bookmarks_.begin(); it != bookmarks_.end(); ++it) { - if ((*it) == bookmark) { - bookmarks_.erase(it); - onBookmarkRemoved(bookmark); - break; - } - } - flush(); + if (!ready_) return; + std::vector<MUCBookmark>::iterator it; + for (it = bookmarks_.begin(); it != bookmarks_.end(); ++it) { + if ((*it) == bookmark) { + bookmarks_.erase(it); + onBookmarkRemoved(bookmark); + break; + } + } + flush(); } void MUCBookmarkManager::flush() { - if (!storage) { - storage = boost::make_shared<Storage>(); - } - // Update the storage element - storage->clearRooms(); - foreach(const MUCBookmark& bookmark, bookmarks_) { - storage->addRoom(bookmark.toStorage()); - } - - // Send an iq to save the storage element - SetPrivateStorageRequest<Storage>::ref request = SetPrivateStorageRequest<Storage>::create(storage, iqRouter_); - // FIXME: We should care about the result - //request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksSet, this, _1, _2)); - request->send(); + if (!storage) { + storage = boost::make_shared<Storage>(); + } + // Update the storage element + storage->clearRooms(); + foreach(const MUCBookmark& bookmark, bookmarks_) { + storage->addRoom(bookmark.toStorage()); + } + + // Send an iq to save the storage element + SetPrivateStorageRequest<Storage>::ref request = SetPrivateStorageRequest<Storage>::create(storage, iqRouter_); + // FIXME: We should care about the result + //request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksSet, this, _1, _2)); + request->send(); } const std::vector<MUCBookmark>& MUCBookmarkManager::getBookmarks() const { - return bookmarks_; + return bookmarks_; } } diff --git a/Swiften/MUC/MUCBookmarkManager.h b/Swiften/MUC/MUCBookmarkManager.h index fb5d9f1..18dd677 100644 --- a/Swiften/MUC/MUCBookmarkManager.h +++ b/Swiften/MUC/MUCBookmarkManager.h @@ -18,35 +18,35 @@ #include <Swiften/MUC/MUCBookmark.h> namespace Swift { - class IQRouter; - - class SWIFTEN_API MUCBookmarkManager { - public: - MUCBookmarkManager(IQRouter* iqRouter); - - void addBookmark(const MUCBookmark& bookmark); - void removeBookmark(const MUCBookmark& bookmark); - void replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark); - - const std::vector<MUCBookmark>& getBookmarks() const; - - public: - boost::signal<void (const MUCBookmark&)> onBookmarkAdded; - boost::signal<void (const MUCBookmark&)> onBookmarkRemoved; - /** - * When server bookmarks are ready to be used (request response has been received). - */ - boost::signal<void ()> onBookmarksReady; - - private: - bool containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark); - void handleBookmarksReceived(boost::shared_ptr<Storage> payload, ErrorPayload::ref error); - void flush(); - - private: - bool ready_; - std::vector<MUCBookmark> bookmarks_; - IQRouter* iqRouter_; - boost::shared_ptr<Storage> storage; - }; + class IQRouter; + + class SWIFTEN_API MUCBookmarkManager { + public: + MUCBookmarkManager(IQRouter* iqRouter); + + void addBookmark(const MUCBookmark& bookmark); + void removeBookmark(const MUCBookmark& bookmark); + void replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark); + + const std::vector<MUCBookmark>& getBookmarks() const; + + public: + boost::signal<void (const MUCBookmark&)> onBookmarkAdded; + boost::signal<void (const MUCBookmark&)> onBookmarkRemoved; + /** + * When server bookmarks are ready to be used (request response has been received). + */ + boost::signal<void ()> onBookmarksReady; + + private: + bool containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark); + void handleBookmarksReceived(boost::shared_ptr<Storage> payload, ErrorPayload::ref error); + void flush(); + + private: + bool ready_; + std::vector<MUCBookmark> bookmarks_; + IQRouter* iqRouter_; + boost::shared_ptr<Storage> storage; + }; } diff --git a/Swiften/MUC/MUCImpl.cpp b/Swiften/MUC/MUCImpl.cpp index 774bf7a..8562ec8 100644 --- a/Swiften/MUC/MUCImpl.cpp +++ b/Swiften/MUC/MUCImpl.cpp @@ -31,7 +31,7 @@ namespace Swift { typedef std::pair<std::string, MUCOccupant> StringMUCOccupantPair; MUCImpl::MUCImpl(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, const JID &muc, MUCRegistry* mucRegistry) : ownMUCJID(muc), stanzaChannel(stanzaChannel), iqRouter_(iqRouter), presenceSender(presenceSender), mucRegistry(mucRegistry), createAsReservedIfNew(false), unlocking(false), isUnlocked_(false) { - scopedConnection_ = stanzaChannel->onPresenceReceived.connect(boost::bind(&MUCImpl::handleIncomingPresence, this, _1)); + scopedConnection_ = stanzaChannel->onPresenceReceived.connect(boost::bind(&MUCImpl::handleIncomingPresence, this, _1)); } MUCImpl::~MUCImpl() @@ -44,427 +44,427 @@ MUCImpl::~MUCImpl() * Join the MUC with default context. */ void MUCImpl::joinAs(const std::string &nick) { - joinSince_ = boost::posix_time::not_a_date_time; - internalJoin(nick); + joinSince_ = boost::posix_time::not_a_date_time; + internalJoin(nick); } /** * Set the password used for entering the room. */ void MUCImpl::setPassword(const boost::optional<std::string>& newPassword) { - password = newPassword; + password = newPassword; } /** * Join the MUC with context since date. */ void MUCImpl::joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since) { - joinSince_ = since; - internalJoin(nick); + joinSince_ = since; + internalJoin(nick); } std::map<std::string, MUCOccupant> MUCImpl::getOccupants() const { - return occupants; + return occupants; } bool MUCImpl::isEqualExceptID(const Presence& lhs, const Presence& rhs) { - bool isEqual = false; - if (lhs.getFrom() == rhs.getFrom() && lhs.getTo() == rhs.getTo() && lhs.getStatus() == rhs.getStatus() && lhs.getShow() == rhs.getShow()) { - CapsInfo::ref lhsCaps = lhs.getPayload<CapsInfo>(); - CapsInfo::ref rhsCaps = rhs.getPayload<CapsInfo>(); - - if (!!lhsCaps && !!rhsCaps) { - isEqual = (*lhsCaps == *rhsCaps); - } - else { - isEqual = (!lhsCaps && !rhsCaps); - } - } - return isEqual; + bool isEqual = false; + if (lhs.getFrom() == rhs.getFrom() && lhs.getTo() == rhs.getTo() && lhs.getStatus() == rhs.getStatus() && lhs.getShow() == rhs.getShow()) { + CapsInfo::ref lhsCaps = lhs.getPayload<CapsInfo>(); + CapsInfo::ref rhsCaps = rhs.getPayload<CapsInfo>(); + + if (!!lhsCaps && !!rhsCaps) { + isEqual = (*lhsCaps == *rhsCaps); + } + else { + isEqual = (!lhsCaps && !rhsCaps); + } + } + return isEqual; } void MUCImpl::internalJoin(const std::string &nick) { - //TODO: history request - joinComplete_ = false; - joinSucceeded_ = false; - - mucRegistry->addMUC(getJID()); - - ownMUCJID = JID(ownMUCJID.getNode(), ownMUCJID.getDomain(), nick); - - Presence::ref joinPresence = presenceSender->getLastSentUndirectedPresence() ? (*presenceSender->getLastSentUndirectedPresence())->clone() : boost::make_shared<Presence>(); - assert(joinPresence->getType() == Presence::Available); - joinPresence->setTo(ownMUCJID); - MUCPayload::ref mucPayload = boost::make_shared<MUCPayload>(); - if (joinSince_ != boost::posix_time::not_a_date_time) { - mucPayload->setSince(joinSince_); - } - if (password) { - mucPayload->setPassword(*password); - } - joinPresence->addPayload(mucPayload); - joinRequestPresence_ = joinPresence; - presenceSender->sendPresence(joinPresence); + //TODO: history request + joinComplete_ = false; + joinSucceeded_ = false; + + mucRegistry->addMUC(getJID()); + + ownMUCJID = JID(ownMUCJID.getNode(), ownMUCJID.getDomain(), nick); + + Presence::ref joinPresence = presenceSender->getLastSentUndirectedPresence() ? (*presenceSender->getLastSentUndirectedPresence())->clone() : boost::make_shared<Presence>(); + assert(joinPresence->getType() == Presence::Available); + joinPresence->setTo(ownMUCJID); + MUCPayload::ref mucPayload = boost::make_shared<MUCPayload>(); + if (joinSince_ != boost::posix_time::not_a_date_time) { + mucPayload->setSince(joinSince_); + } + if (password) { + mucPayload->setPassword(*password); + } + joinPresence->addPayload(mucPayload); + joinRequestPresence_ = joinPresence; + presenceSender->sendPresence(joinPresence); } void MUCImpl::changeNickname(const std::string& newNickname) { - Presence::ref changeNicknamePresence = boost::make_shared<Presence>(); - changeNicknamePresence->setTo(ownMUCJID.toBare().toString() + std::string("/") + newNickname); - presenceSender->sendPresence(changeNicknamePresence); + Presence::ref changeNicknamePresence = boost::make_shared<Presence>(); + changeNicknamePresence->setTo(ownMUCJID.toBare().toString() + std::string("/") + newNickname); + presenceSender->sendPresence(changeNicknamePresence); } void MUCImpl::part() { - presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); - mucRegistry->removeMUC(getJID()); + presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); + mucRegistry->removeMUC(getJID()); } void MUCImpl::handleUserLeft(LeavingType type) { - std::map<std::string,MUCOccupant>::iterator i = occupants.find(ownMUCJID.getResource()); - if (i != occupants.end()) { - MUCOccupant me = i->second; - occupants.erase(i); - onOccupantLeft(me, type, ""); - } - occupants.clear(); - joinComplete_ = false; - joinSucceeded_ = false; - isUnlocked_ = false; - presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); + std::map<std::string,MUCOccupant>::iterator i = occupants.find(ownMUCJID.getResource()); + if (i != occupants.end()) { + MUCOccupant me = i->second; + occupants.erase(i); + onOccupantLeft(me, type, ""); + } + occupants.clear(); + joinComplete_ = false; + joinSucceeded_ = false; + isUnlocked_ = false; + presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); } void MUCImpl::handleIncomingPresence(Presence::ref presence) { - if (!isFromMUC(presence->getFrom())) { - return; - } - - MUCUserPayload::ref mucPayload; - foreach (MUCUserPayload::ref payload, presence->getPayloads<MUCUserPayload>()) { - if (!payload->getItems().empty() || !payload->getStatusCodes().empty()) { - mucPayload = payload; - } - } - - // On the first incoming presence, check if our join has succeeded - // (i.e. we start getting non-error presence from the MUC) or not - if (!joinSucceeded_) { - if (presence->getType() == Presence::Error) { - std::string reason; - onJoinFailed(presence->getPayload<ErrorPayload>()); - return; - } - else { - joinSucceeded_ = true; - presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); - if (presenceSender->getLastSentUndirectedPresence() && !isEqualExceptID(**(presenceSender->getLastSentUndirectedPresence()), *joinRequestPresence_)) { - // our presence changed between join request and join complete, send current presence to MUC - Presence::ref latestPresence = boost::make_shared<Presence>(**presenceSender->getLastSentUndirectedPresence()); - latestPresence->setTo(ownMUCJID); - presenceSender->sendPresence(latestPresence); - } - } - } - - std::string nick = presence->getFrom().getResource(); - if (nick.empty()) { - return; - } - MUCOccupant::Role role(MUCOccupant::NoRole); - MUCOccupant::Affiliation affiliation(MUCOccupant::NoAffiliation); - boost::optional<JID> realJID; - if (mucPayload && mucPayload->getItems().size() > 0) { - role = mucPayload->getItems()[0].role ? mucPayload->getItems()[0].role.get() : MUCOccupant::NoRole; - affiliation = mucPayload->getItems()[0].affiliation ? mucPayload->getItems()[0].affiliation.get() : MUCOccupant::NoAffiliation; - realJID = mucPayload->getItems()[0].realJID; - } - - //100 is non-anonymous - //TODO: 100 may also be specified in a <message/> - //170 is room logging to http - //TODO: Nick changes - if (presence->getType() == Presence::Unavailable) { - LeavingType type = LeavePart; - boost::optional<std::string> newNickname; - if (mucPayload) { - if (boost::dynamic_pointer_cast<MUCDestroyPayload>(mucPayload->getPayload())) { - type = LeaveDestroy; - } - else foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) { - if (status.code == 307) { - type = LeaveKick; - } - else if (status.code == 301) { - type = LeaveBan; - } - else if (status.code == 321) { - type = LeaveNotMember; - } - else if (status.code == 303) { - if (mucPayload->getItems().size() == 1) { - newNickname = mucPayload->getItems()[0].nick; - } - } - } - } - if (newNickname) { - std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick); - if (i != occupants.end()) { - MUCOccupant occupant = i->second; - occupants.erase(i); - occupant.setNick(newNickname.get()); - occupants.insert(std::make_pair(newNickname.get(), occupant)); - onOccupantNicknameChanged(nick, newNickname.get()); - } - } - else { - if (presence->getFrom() == ownMUCJID) { - handleUserLeft(type); - return; - } - else { - std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick); - if (i != occupants.end()) { - //TODO: part type - MUCOccupant occupant = i->second; - occupants.erase(i); - onOccupantLeft(occupant, type, ""); - } - } - } - } - else if (presence->getType() == Presence::Available) { - std::map<std::string, MUCOccupant>::iterator it = occupants.find(nick); - MUCOccupant occupant(nick, role, affiliation); - bool isJoin = true; - if (realJID) { - occupant.setRealJID(realJID.get()); - } - if (it != occupants.end()) { - isJoin = false; - MUCOccupant oldOccupant = it->second; - if (oldOccupant.getRole() != role) { - onOccupantRoleChanged(nick, occupant, oldOccupant.getRole()); - } - if (oldOccupant.getAffiliation() != affiliation) { - onOccupantAffiliationChanged(nick, affiliation, oldOccupant.getAffiliation()); - } - occupants.erase(it); - } - std::pair<std::map<std::string, MUCOccupant>::iterator, bool> result = occupants.insert(std::make_pair(nick, occupant)); - if (isJoin) { - onOccupantJoined(result.first->second); - } - onOccupantPresenceChange(presence); - } - if (mucPayload && !joinComplete_) { - bool isLocked = false; - foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) { - if (status.code == 110) { - /* Simply knowing this is your presence is enough, 210 doesn't seem to be necessary. */ - joinComplete_ = true; - if (ownMUCJID != presence->getFrom()) { - presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); - ownMUCJID = presence->getFrom(); - presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); - } - } - // MUC status 201: a new room has been created - if (status.code == 201) { - isLocked = true; - /* Room is created and locked */ - /* Currently deal with this by making an instant room */ - if (ownMUCJID != presence->getFrom()) { - presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); - ownMUCJID = presence->getFrom(); - presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); - } - if (createAsReservedIfNew) { - unlocking = true; - requestConfigurationForm(); - } - else { - // Accept default room configuration and create an instant room http://xmpp.org/extensions/xep-0045.html#createroom-instant - MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); - presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); - mucPayload->setPayload(boost::make_shared<Form>(Form::SubmitType)); - boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared< GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); - request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2)); - request->send(); - } - } - } - if (joinComplete_ && !isLocked) { - onJoinComplete(getOwnNick()); - } - if (!isLocked && !isUnlocked_ && (presence->getFrom() == ownMUCJID)) { - isUnlocked_ = true; - onUnlocked(); - } - } + if (!isFromMUC(presence->getFrom())) { + return; + } + + MUCUserPayload::ref mucPayload; + foreach (MUCUserPayload::ref payload, presence->getPayloads<MUCUserPayload>()) { + if (!payload->getItems().empty() || !payload->getStatusCodes().empty()) { + mucPayload = payload; + } + } + + // On the first incoming presence, check if our join has succeeded + // (i.e. we start getting non-error presence from the MUC) or not + if (!joinSucceeded_) { + if (presence->getType() == Presence::Error) { + std::string reason; + onJoinFailed(presence->getPayload<ErrorPayload>()); + return; + } + else { + joinSucceeded_ = true; + presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); + if (presenceSender->getLastSentUndirectedPresence() && !isEqualExceptID(**(presenceSender->getLastSentUndirectedPresence()), *joinRequestPresence_)) { + // our presence changed between join request and join complete, send current presence to MUC + Presence::ref latestPresence = boost::make_shared<Presence>(**presenceSender->getLastSentUndirectedPresence()); + latestPresence->setTo(ownMUCJID); + presenceSender->sendPresence(latestPresence); + } + } + } + + std::string nick = presence->getFrom().getResource(); + if (nick.empty()) { + return; + } + MUCOccupant::Role role(MUCOccupant::NoRole); + MUCOccupant::Affiliation affiliation(MUCOccupant::NoAffiliation); + boost::optional<JID> realJID; + if (mucPayload && mucPayload->getItems().size() > 0) { + role = mucPayload->getItems()[0].role ? mucPayload->getItems()[0].role.get() : MUCOccupant::NoRole; + affiliation = mucPayload->getItems()[0].affiliation ? mucPayload->getItems()[0].affiliation.get() : MUCOccupant::NoAffiliation; + realJID = mucPayload->getItems()[0].realJID; + } + + //100 is non-anonymous + //TODO: 100 may also be specified in a <message/> + //170 is room logging to http + //TODO: Nick changes + if (presence->getType() == Presence::Unavailable) { + LeavingType type = LeavePart; + boost::optional<std::string> newNickname; + if (mucPayload) { + if (boost::dynamic_pointer_cast<MUCDestroyPayload>(mucPayload->getPayload())) { + type = LeaveDestroy; + } + else foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) { + if (status.code == 307) { + type = LeaveKick; + } + else if (status.code == 301) { + type = LeaveBan; + } + else if (status.code == 321) { + type = LeaveNotMember; + } + else if (status.code == 303) { + if (mucPayload->getItems().size() == 1) { + newNickname = mucPayload->getItems()[0].nick; + } + } + } + } + if (newNickname) { + std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick); + if (i != occupants.end()) { + MUCOccupant occupant = i->second; + occupants.erase(i); + occupant.setNick(newNickname.get()); + occupants.insert(std::make_pair(newNickname.get(), occupant)); + onOccupantNicknameChanged(nick, newNickname.get()); + } + } + else { + if (presence->getFrom() == ownMUCJID) { + handleUserLeft(type); + return; + } + else { + std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick); + if (i != occupants.end()) { + //TODO: part type + MUCOccupant occupant = i->second; + occupants.erase(i); + onOccupantLeft(occupant, type, ""); + } + } + } + } + else if (presence->getType() == Presence::Available) { + std::map<std::string, MUCOccupant>::iterator it = occupants.find(nick); + MUCOccupant occupant(nick, role, affiliation); + bool isJoin = true; + if (realJID) { + occupant.setRealJID(realJID.get()); + } + if (it != occupants.end()) { + isJoin = false; + MUCOccupant oldOccupant = it->second; + if (oldOccupant.getRole() != role) { + onOccupantRoleChanged(nick, occupant, oldOccupant.getRole()); + } + if (oldOccupant.getAffiliation() != affiliation) { + onOccupantAffiliationChanged(nick, affiliation, oldOccupant.getAffiliation()); + } + occupants.erase(it); + } + std::pair<std::map<std::string, MUCOccupant>::iterator, bool> result = occupants.insert(std::make_pair(nick, occupant)); + if (isJoin) { + onOccupantJoined(result.first->second); + } + onOccupantPresenceChange(presence); + } + if (mucPayload && !joinComplete_) { + bool isLocked = false; + foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) { + if (status.code == 110) { + /* Simply knowing this is your presence is enough, 210 doesn't seem to be necessary. */ + joinComplete_ = true; + if (ownMUCJID != presence->getFrom()) { + presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); + ownMUCJID = presence->getFrom(); + presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); + } + } + // MUC status 201: a new room has been created + if (status.code == 201) { + isLocked = true; + /* Room is created and locked */ + /* Currently deal with this by making an instant room */ + if (ownMUCJID != presence->getFrom()) { + presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); + ownMUCJID = presence->getFrom(); + presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); + } + if (createAsReservedIfNew) { + unlocking = true; + requestConfigurationForm(); + } + else { + // Accept default room configuration and create an instant room http://xmpp.org/extensions/xep-0045.html#createroom-instant + MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); + presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence); + mucPayload->setPayload(boost::make_shared<Form>(Form::SubmitType)); + boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared< GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2)); + request->send(); + } + } + } + if (joinComplete_ && !isLocked) { + onJoinComplete(getOwnNick()); + } + if (!isLocked && !isUnlocked_ && (presence->getFrom() == ownMUCJID)) { + isUnlocked_ = true; + onUnlocked(); + } + } } void MUCImpl::handleCreationConfigResponse(MUCOwnerPayload::ref /*unused*/, ErrorPayload::ref error) { - unlocking = false; - if (error) { - presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); - onJoinFailed(error); - } else { - onJoinComplete(getOwnNick()); /* Previously, this wasn't needed here, as the presence duplication bug caused an emit elsewhere. */ - isUnlocked_ = true; - onUnlocked(); - } + unlocking = false; + if (error) { + presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence); + onJoinFailed(error); + } else { + onJoinComplete(getOwnNick()); /* Previously, this wasn't needed here, as the presence duplication bug caused an emit elsewhere. */ + isUnlocked_ = true; + onUnlocked(); + } } bool MUCImpl::hasOccupant(const std::string& nick) { - return occupants.find(nick) != occupants.end(); + return occupants.find(nick) != occupants.end(); } const MUCOccupant& MUCImpl::getOccupant(const std::string& nick) { - return occupants.find(nick)->second; + return occupants.find(nick)->second; } void MUCImpl::kickOccupant(const JID& jid) { - changeOccupantRole(jid, MUCOccupant::NoRole); + changeOccupantRole(jid, MUCOccupant::NoRole); } /** * Call with the room JID, not the real JID. */ void MUCImpl::changeOccupantRole(const JID& jid, MUCOccupant::Role role) { - MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>(); - MUCItem item; - item.role = role; - item.nick = jid.getResource(); - mucPayload->addItem(item); - boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); - request->onResponse.connect(boost::bind(&MUCImpl::handleOccupantRoleChangeResponse, this, _1, _2, jid, role)); - request->send(); - + MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>(); + MUCItem item; + item.role = role; + item.nick = jid.getResource(); + mucPayload->addItem(item); + boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MUCImpl::handleOccupantRoleChangeResponse, this, _1, _2, jid, role)); + request->send(); + } void MUCImpl::handleOccupantRoleChangeResponse(MUCAdminPayload::ref /*unused*/, ErrorPayload::ref error, const JID& jid, MUCOccupant::Role role) { - if (error) { - onRoleChangeFailed(error, jid, role); - } + if (error) { + onRoleChangeFailed(error, jid, role); + } } void MUCImpl::requestAffiliationList(MUCOccupant::Affiliation affiliation) { - MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>(); - MUCItem item; - item.affiliation = affiliation; - mucPayload->addItem(item); - boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared< GenericRequest<MUCAdminPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_); - request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationListResponse, this, _1, _2, affiliation)); - request->send(); + MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>(); + MUCItem item; + item.affiliation = affiliation; + mucPayload->addItem(item); + boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared< GenericRequest<MUCAdminPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationListResponse, this, _1, _2, affiliation)); + request->send(); } /** * Must be called with the real JID, not the room JID. */ void MUCImpl::changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation) { - MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>(); - MUCItem item; - item.affiliation = affiliation; - item.realJID = jid.toBare(); - mucPayload->addItem(item); - boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); - request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationChangeResponse, this, _1, _2, jid, affiliation)); - request->send(); + MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>(); + MUCItem item; + item.affiliation = affiliation; + item.realJID = jid.toBare(); + mucPayload->addItem(item); + boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationChangeResponse, this, _1, _2, jid, affiliation)); + request->send(); } void MUCImpl::handleAffiliationListResponse(MUCAdminPayload::ref payload, ErrorPayload::ref error, MUCOccupant::Affiliation affiliation) { - if (error) { - onAffiliationListFailed(error); - } - else { - std::vector<JID> jids; - foreach (MUCItem item, payload->getItems()) { - if (item.realJID) { - jids.push_back(*item.realJID); - } - } - onAffiliationListReceived(affiliation, jids); - } + if (error) { + onAffiliationListFailed(error); + } + else { + std::vector<JID> jids; + foreach (MUCItem item, payload->getItems()) { + if (item.realJID) { + jids.push_back(*item.realJID); + } + } + onAffiliationListReceived(affiliation, jids); + } } void MUCImpl::handleAffiliationChangeResponse(MUCAdminPayload::ref /*unused*/, ErrorPayload::ref error, const JID& jid, MUCOccupant::Affiliation affiliation) { - if (error) { - onAffiliationChangeFailed(error, jid, affiliation); - } + if (error) { + onAffiliationChangeFailed(error, jid, affiliation); + } } void MUCImpl::changeSubject(const std::string& subject) { - Message::ref message = boost::make_shared<Message>(); - message->setSubject(subject); - message->setType(Message::Groupchat); - message->setTo(ownMUCJID.toBare()); - stanzaChannel->sendMessage(message); + Message::ref message = boost::make_shared<Message>(); + message->setSubject(subject); + message->setType(Message::Groupchat); + message->setTo(ownMUCJID.toBare()); + stanzaChannel->sendMessage(message); } void MUCImpl::requestConfigurationForm() { - MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); - boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_); - request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationFormReceived, this, _1, _2)); - request->send(); + MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); + boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationFormReceived, this, _1, _2)); + request->send(); } void MUCImpl::cancelConfigureRoom() { - MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); - mucPayload->setPayload(boost::make_shared<Form>(Form::CancelType)); - boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); - request->send(); + MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); + mucPayload->setPayload(boost::make_shared<Form>(Form::CancelType)); + boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); + request->send(); } void MUCImpl::handleConfigurationFormReceived(MUCOwnerPayload::ref payload, ErrorPayload::ref error) { - Form::ref form; - if (payload) { - form = payload->getForm(); - } - if (error || !form) { - onConfigurationFailed(error); - } else { - onConfigurationFormReceived(form); - } + Form::ref form; + if (payload) { + form = payload->getForm(); + } + if (error || !form) { + onConfigurationFailed(error); + } else { + onConfigurationFormReceived(form); + } } void MUCImpl::handleConfigurationResultReceived(MUCOwnerPayload::ref /*payload*/, ErrorPayload::ref error) { - if (error) { - onConfigurationFailed(error); - } + if (error) { + onConfigurationFailed(error); + } } void MUCImpl::configureRoom(Form::ref form) { - MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); - mucPayload->setPayload(form); - boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); - if (unlocking) { - request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2)); - } - else { - request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2)); - } - request->send(); + MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload()); + mucPayload->setPayload(form); + boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); + if (unlocking) { + request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2)); + } + else { + request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2)); + } + request->send(); } void MUCImpl::destroyRoom() { - MUCOwnerPayload::ref mucPayload = boost::make_shared<MUCOwnerPayload>(); - MUCDestroyPayload::ref mucDestroyPayload = boost::make_shared<MUCDestroyPayload>(); - mucPayload->setPayload(mucDestroyPayload); - boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); - request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2)); - request->send(); + MUCOwnerPayload::ref mucPayload = boost::make_shared<MUCOwnerPayload>(); + MUCDestroyPayload::ref mucDestroyPayload = boost::make_shared<MUCDestroyPayload>(); + mucPayload->setPayload(mucDestroyPayload); + boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2)); + request->send(); } void MUCImpl::invitePerson(const JID& person, const std::string& reason, bool isImpromptu, bool isReuseChat) { - Message::ref message = boost::make_shared<Message>(); - message->setTo(person); - message->setType(Message::Normal); - MUCInvitationPayload::ref invite = boost::make_shared<MUCInvitationPayload>(); - invite->setReason(reason); - invite->setJID(ownMUCJID.toBare()); - invite->setIsImpromptu(isImpromptu); - invite->setIsContinuation(isReuseChat); - message->addPayload(invite); - stanzaChannel->sendMessage(message); + Message::ref message = boost::make_shared<Message>(); + message->setTo(person); + message->setType(Message::Normal); + MUCInvitationPayload::ref invite = boost::make_shared<MUCInvitationPayload>(); + invite->setReason(reason); + invite->setJID(ownMUCJID.toBare()); + invite->setIsImpromptu(isImpromptu); + invite->setIsContinuation(isReuseChat); + message->addPayload(invite); + stanzaChannel->sendMessage(message); } //TODO: Invites(direct/mediated) diff --git a/Swiften/MUC/MUCImpl.h b/Swiften/MUC/MUCImpl.h index 8103e69..9b4377a 100644 --- a/Swiften/MUC/MUCImpl.h +++ b/Swiften/MUC/MUCImpl.h @@ -25,106 +25,106 @@ #include <Swiften/MUC/MUCRegistry.h> namespace Swift { - class StanzaChannel; - class IQRouter; - class DirectedPresenceSender; - - class SWIFTEN_API MUCImpl : public MUC { - public: - typedef boost::shared_ptr<MUCImpl> ref; - - public: - MUCImpl(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, const JID &muc, MUCRegistry* mucRegistry); - virtual ~MUCImpl(); - - /** - * Returns the (bare) JID of the MUC. - */ - virtual JID getJID() const { - return ownMUCJID.toBare(); - } - - /** - * Returns if the room is unlocked and other people can join the room. - * @return True if joinable by others; false otherwise. - */ - virtual bool isUnlocked() const { - return isUnlocked_; - } - - virtual void joinAs(const std::string &nick); - virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since); - /*virtual void queryRoomInfo(); */ - /*virtual void queryRoomItems(); */ - /*virtual std::string getCurrentNick(); */ - virtual std::map<std::string, MUCOccupant> getOccupants() const; - - /** - * Send a new presence to the MUC indicating a nickname change. Any custom status the user had in the is cleared. - * @param newNickname The nickname to change to. - */ - virtual void changeNickname(const std::string& newNickname); - virtual void part(); - /*virtual void handleIncomingMessage(Message::ref message); */ - /** Expose public so it can be called when e.g. user goes offline */ - virtual void handleUserLeft(LeavingType); - /** Get occupant information*/ - virtual const MUCOccupant& getOccupant(const std::string& nick); - virtual bool hasOccupant(const std::string& nick); - virtual void kickOccupant(const JID& jid); - virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role); - virtual void requestAffiliationList(MUCOccupant::Affiliation); - virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation); - virtual void changeSubject(const std::string& subject); - virtual void requestConfigurationForm(); - virtual void configureRoom(Form::ref); - virtual void cancelConfigureRoom(); - virtual void destroyRoom(); - /** Send an invite for the person to join the MUC */ - virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false); - virtual void setCreateAsReservedIfNew() {createAsReservedIfNew = true;} - virtual void setPassword(const boost::optional<std::string>& password); - - private: - bool isFromMUC(const JID& j) const { - return ownMUCJID.equals(j, JID::WithoutResource); - } - - const std::string& getOwnNick() const { - return ownMUCJID.getResource(); - } - - /** - * This function compares two Presence elements for equality based on to, from, status, show and entity capability information. - * @return True if equal; else otherwise. - */ - static bool isEqualExceptID(const Presence& lhs, const Presence& rhs); - - private: - void handleIncomingPresence(Presence::ref presence); - void internalJoin(const std::string& nick); - void handleCreationConfigResponse(MUCOwnerPayload::ref, ErrorPayload::ref); - void handleOccupantRoleChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Role); - void handleAffiliationChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Affiliation); - void handleAffiliationListResponse(MUCAdminPayload::ref, ErrorPayload::ref, MUCOccupant::Affiliation); - void handleConfigurationFormReceived(MUCOwnerPayload::ref, ErrorPayload::ref); - void handleConfigurationResultReceived(MUCOwnerPayload::ref, ErrorPayload::ref); - - private: - JID ownMUCJID; - StanzaChannel* stanzaChannel; - IQRouter* iqRouter_; - DirectedPresenceSender* presenceSender; - MUCRegistry* mucRegistry; - std::map<std::string, MUCOccupant> occupants; - bool joinSucceeded_; - bool joinComplete_; - boost::bsignals::scoped_connection scopedConnection_; - boost::posix_time::ptime joinSince_; - bool createAsReservedIfNew; - bool unlocking; - bool isUnlocked_; - boost::optional<std::string> password; - Presence::ref joinRequestPresence_; - }; + class StanzaChannel; + class IQRouter; + class DirectedPresenceSender; + + class SWIFTEN_API MUCImpl : public MUC { + public: + typedef boost::shared_ptr<MUCImpl> ref; + + public: + MUCImpl(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, const JID &muc, MUCRegistry* mucRegistry); + virtual ~MUCImpl(); + + /** + * Returns the (bare) JID of the MUC. + */ + virtual JID getJID() const { + return ownMUCJID.toBare(); + } + + /** + * Returns if the room is unlocked and other people can join the room. + * @return True if joinable by others; false otherwise. + */ + virtual bool isUnlocked() const { + return isUnlocked_; + } + + virtual void joinAs(const std::string &nick); + virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since); + /*virtual void queryRoomInfo(); */ + /*virtual void queryRoomItems(); */ + /*virtual std::string getCurrentNick(); */ + virtual std::map<std::string, MUCOccupant> getOccupants() const; + + /** + * Send a new presence to the MUC indicating a nickname change. Any custom status the user had in the is cleared. + * @param newNickname The nickname to change to. + */ + virtual void changeNickname(const std::string& newNickname); + virtual void part(); + /*virtual void handleIncomingMessage(Message::ref message); */ + /** Expose public so it can be called when e.g. user goes offline */ + virtual void handleUserLeft(LeavingType); + /** Get occupant information*/ + virtual const MUCOccupant& getOccupant(const std::string& nick); + virtual bool hasOccupant(const std::string& nick); + virtual void kickOccupant(const JID& jid); + virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role); + virtual void requestAffiliationList(MUCOccupant::Affiliation); + virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation); + virtual void changeSubject(const std::string& subject); + virtual void requestConfigurationForm(); + virtual void configureRoom(Form::ref); + virtual void cancelConfigureRoom(); + virtual void destroyRoom(); + /** Send an invite for the person to join the MUC */ + virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false); + virtual void setCreateAsReservedIfNew() {createAsReservedIfNew = true;} + virtual void setPassword(const boost::optional<std::string>& password); + + private: + bool isFromMUC(const JID& j) const { + return ownMUCJID.equals(j, JID::WithoutResource); + } + + const std::string& getOwnNick() const { + return ownMUCJID.getResource(); + } + + /** + * This function compares two Presence elements for equality based on to, from, status, show and entity capability information. + * @return True if equal; else otherwise. + */ + static bool isEqualExceptID(const Presence& lhs, const Presence& rhs); + + private: + void handleIncomingPresence(Presence::ref presence); + void internalJoin(const std::string& nick); + void handleCreationConfigResponse(MUCOwnerPayload::ref, ErrorPayload::ref); + void handleOccupantRoleChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Role); + void handleAffiliationChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Affiliation); + void handleAffiliationListResponse(MUCAdminPayload::ref, ErrorPayload::ref, MUCOccupant::Affiliation); + void handleConfigurationFormReceived(MUCOwnerPayload::ref, ErrorPayload::ref); + void handleConfigurationResultReceived(MUCOwnerPayload::ref, ErrorPayload::ref); + + private: + JID ownMUCJID; + StanzaChannel* stanzaChannel; + IQRouter* iqRouter_; + DirectedPresenceSender* presenceSender; + MUCRegistry* mucRegistry; + std::map<std::string, MUCOccupant> occupants; + bool joinSucceeded_; + bool joinComplete_; + boost::bsignals::scoped_connection scopedConnection_; + boost::posix_time::ptime joinSince_; + bool createAsReservedIfNew; + bool unlocking; + bool isUnlocked_; + boost::optional<std::string> password; + Presence::ref joinRequestPresence_; + }; } diff --git a/Swiften/MUC/MUCManager.cpp b/Swiften/MUC/MUCManager.cpp index 58a9a15..b4e3b00 100644 --- a/Swiften/MUC/MUCManager.cpp +++ b/Swiften/MUC/MUCManager.cpp @@ -14,7 +14,7 @@ MUCManager::MUCManager(StanzaChannel* stanzaChannel, IQRouter* iqRouter, Directe } MUC::ref MUCManager::createMUC(const JID& jid) { - return boost::make_shared<MUCImpl>(stanzaChannel, iqRouter, presenceSender, jid, mucRegistry); + return boost::make_shared<MUCImpl>(stanzaChannel, iqRouter, presenceSender, jid, mucRegistry); } } diff --git a/Swiften/MUC/MUCManager.h b/Swiften/MUC/MUCManager.h index 5e237f5..c1f0f61 100644 --- a/Swiften/MUC/MUCManager.h +++ b/Swiften/MUC/MUCManager.h @@ -10,21 +10,21 @@ #include <Swiften/MUC/MUC.h> namespace Swift { - class IQRouter; - class StanzaChannel; - class DirectedPresenceSender; - class MUCRegistry; + class IQRouter; + class StanzaChannel; + class DirectedPresenceSender; + class MUCRegistry; - class SWIFTEN_API MUCManager { - public: - MUCManager(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, MUCRegistry* mucRegistry); + class SWIFTEN_API MUCManager { + public: + MUCManager(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, MUCRegistry* mucRegistry); - MUC::ref createMUC(const JID&); + MUC::ref createMUC(const JID&); - private: - StanzaChannel* stanzaChannel; - IQRouter* iqRouter; - DirectedPresenceSender* presenceSender; - MUCRegistry* mucRegistry; - }; + private: + StanzaChannel* stanzaChannel; + IQRouter* iqRouter; + DirectedPresenceSender* presenceSender; + MUCRegistry* mucRegistry; + }; } diff --git a/Swiften/MUC/MUCRegistry.cpp b/Swiften/MUC/MUCRegistry.cpp index 38433a7..9315173 100644 --- a/Swiften/MUC/MUCRegistry.cpp +++ b/Swiften/MUC/MUCRegistry.cpp @@ -14,15 +14,15 @@ MUCRegistry::~MUCRegistry() { } bool MUCRegistry::isMUC(const JID& j) const { - return std::find(mucs.begin(), mucs.end(), j) != mucs.end(); + return std::find(mucs.begin(), mucs.end(), j) != mucs.end(); } void MUCRegistry::addMUC(const JID& j) { - mucs.push_back(j); + mucs.push_back(j); } void MUCRegistry::removeMUC(const JID& j) { - erase(mucs, j); + erase(mucs, j); } diff --git a/Swiften/MUC/MUCRegistry.h b/Swiften/MUC/MUCRegistry.h index e69cdb5..3f61c71 100644 --- a/Swiften/MUC/MUCRegistry.h +++ b/Swiften/MUC/MUCRegistry.h @@ -12,17 +12,17 @@ #include <Swiften/JID/JID.h> namespace Swift { - class JID; + class JID; - class SWIFTEN_API MUCRegistry { - public: - ~MUCRegistry(); + class SWIFTEN_API MUCRegistry { + public: + ~MUCRegistry(); - bool isMUC(const JID& j) const; - void addMUC(const JID& j); - void removeMUC(const JID& j); + bool isMUC(const JID& j) const; + void addMUC(const JID& j); + void removeMUC(const JID& j); - private: - std::vector<JID> mucs; - }; + private: + std::vector<JID> mucs; + }; } diff --git a/Swiften/MUC/UnitTest/MUCTest.cpp b/Swiften/MUC/UnitTest/MUCTest.cpp index a422c12..548617c 100644 --- a/Swiften/MUC/UnitTest/MUCTest.cpp +++ b/Swiften/MUC/UnitTest/MUCTest.cpp @@ -24,254 +24,254 @@ using namespace Swift; class MUCTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(MUCTest); - CPPUNIT_TEST(testJoin); - CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess); - CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess); - CPPUNIT_TEST(testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess); - CPPUNIT_TEST(testCreateInstant); - CPPUNIT_TEST(testReplicateBug); - CPPUNIT_TEST(testNicknameChange); - /*CPPUNIT_TEST(testJoin_Success); - CPPUNIT_TEST(testJoin_Fail);*/ - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - channel = new DummyStanzaChannel(); - router = new IQRouter(channel); - mucRegistry = new MUCRegistry(); - stanzaChannelPresenceSender = new StanzaChannelPresenceSender(channel); - presenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender); - nickChanges = 0; - } - - void tearDown() { - delete presenceSender; - delete stanzaChannelPresenceSender; - delete mucRegistry; - delete router; - delete channel; - } - - void testJoin() { - MUC::ref testling = createMUC(JID("foo@bar.com")); - testling->joinAs("Alice"); - - CPPUNIT_ASSERT(mucRegistry->isMUC(JID("foo@bar.com"))); - Presence::ref p = channel->getStanzaAtIndex<Presence>(0); - CPPUNIT_ASSERT(p); - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo()); - } - - void testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess() { - MUC::ref testling = createMUC(JID("foo@bar.com")); - testling->joinAs("Alice"); - - presenceSender->sendPresence(Presence::create("Test")); - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size())); - } - - void testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess() { - MUC::ref testling = createMUC(JID("foo@bar.com")); - testling->joinAs("Alice"); - - presenceSender->sendPresence(Presence::create("Test")); - receivePresence(JID("foo@bar.com/Rabbit"), "Here"); - - CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size())); - Presence::ref p = channel->getStanzaAtIndex<Presence>(2); - CPPUNIT_ASSERT(p); - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo()); - CPPUNIT_ASSERT_EQUAL(std::string("Test"), p->getStatus()); - } - - void testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess() { - MUC::ref testling = createMUC(JID("foo@bar.com")); - testling->joinAs("Alice"); - - receivePresence(JID("foo@bar.com/Rabbit"), "Here"); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size())); - Presence::ref p = channel->getStanzaAtIndex<Presence>(0); - CPPUNIT_ASSERT(p); - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo()); - CPPUNIT_ASSERT_EQUAL(std::string(""), p->getStatus()); - } - - void testCreateInstant() { - MUC::ref testling = createMUC(JID("rabbithole@wonderland.lit")); - testling->joinAs("Alice"); - Presence::ref serverRespondsLocked = boost::make_shared<Presence>(); - serverRespondsLocked->setFrom(JID("rabbithole@wonderland.lit/Alice")); - MUCUserPayload::ref mucPayload(new MUCUserPayload()); - MUCItem myItem; - myItem.affiliation = MUCOccupant::Owner; - myItem.role = MUCOccupant::Moderator; - mucPayload->addItem(myItem); - mucPayload->addStatusCode(MUCUserPayload::StatusCode(110)); - mucPayload->addStatusCode(MUCUserPayload::StatusCode(201)); - serverRespondsLocked->addPayload(mucPayload); - channel->onPresenceReceived(serverRespondsLocked); - CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size())); - IQ::ref iq = channel->getStanzaAtIndex<IQ>(1); - CPPUNIT_ASSERT(iq); - CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()); - CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm()); - CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType()); - } - - void testReplicateBug() { - Presence::ref initialPresence = boost::make_shared<Presence>(); - initialPresence->setStatus(""); - VCard::ref vcard = boost::make_shared<VCard>(); - vcard->setPhoto(createByteArray("15c30080ae98ec48be94bf0e191d43edd06e500a")); - initialPresence->addPayload(vcard); - CapsInfo::ref caps = boost::make_shared<CapsInfo>(); - caps->setNode("http://swift.im"); - caps->setVersion("p2UP0DrcVgKM6jJqYN/B92DKK0o="); - initialPresence->addPayload(caps); - channel->sendPresence(initialPresence); - - MUC::ref testling = createMUC(JID("test@rooms.swift.im")); - testling->joinAs("Test"); - Presence::ref serverRespondsLocked = boost::make_shared<Presence>(); - serverRespondsLocked->setFrom(JID("test@rooms.swift.im/Test")); - serverRespondsLocked->setTo(JID("test@swift.im/6913d576d55f0b67")); - serverRespondsLocked->addPayload(vcard); - serverRespondsLocked->addPayload(caps); - serverRespondsLocked->setStatus(""); - MUCUserPayload::ref mucPayload(new MUCUserPayload()); - MUCItem myItem; - myItem.affiliation = MUCOccupant::Owner; - myItem.role = MUCOccupant::Moderator; - mucPayload->addItem(myItem); - mucPayload->addStatusCode(MUCUserPayload::StatusCode(201)); - serverRespondsLocked->addPayload(mucPayload); - channel->onPresenceReceived(serverRespondsLocked); - CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size())); - IQ::ref iq = channel->getStanzaAtIndex<IQ>(2); - CPPUNIT_ASSERT(iq); - CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()); - CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm()); - CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType()); - } - - void testNicknameChange() { - MUC::ref testling = createMUC(JID("foo@bar.com")); - // Join as Rabbit - testling->joinAs("Rabbit"); - - // Rabbit joins - Presence::ref rabbitJoins = boost::make_shared<Presence>(); - rabbitJoins->setTo("test@swift.im/6913d576d55f0b67"); - rabbitJoins->setFrom(testling->getJID().toString() + "/Rabbit"); - channel->onPresenceReceived(rabbitJoins); - CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Rabbit")); - - // Alice joins - Presence::ref aliceJoins = boost::make_shared<Presence>(); - aliceJoins->setTo("test@swift.im/6913d576d55f0b67"); - aliceJoins->setFrom(testling->getJID().toString() + "/Alice"); - channel->onPresenceReceived(aliceJoins); - CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice")); - - // Change nick to Dodo - testling->changeNickname("Dodo"); - Presence::ref stanza = channel->getStanzaAtIndex<Presence>(1); - CPPUNIT_ASSERT(stanza); - CPPUNIT_ASSERT_EQUAL(std::string("Dodo"), stanza->getTo().getResource()); - - // Alice changes nick to Alice2 - stanza = boost::make_shared<Presence>(); - stanza->setFrom(JID("foo@bar.com/Alice")); - stanza->setTo(JID(router->getJID())); - stanza->setType(Presence::Unavailable); - MUCUserPayload::ref mucPayload(new MUCUserPayload()); - MUCItem myItem; - myItem.affiliation = MUCOccupant::Member; - myItem.nick = "Alice2"; - myItem.role = MUCOccupant::Participant; - mucPayload->addItem(myItem); - mucPayload->addStatusCode(303); - stanza->addPayload(mucPayload); - channel->onPresenceReceived(stanza); - CPPUNIT_ASSERT_EQUAL(1, nickChanges); - CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Alice")); - CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice2")); - - // We (Rabbit) change nick to Robot - stanza = boost::make_shared<Presence>(); - stanza->setFrom(JID("foo@bar.com/Rabbit")); - stanza->setTo(JID(router->getJID())); - stanza->setType(Presence::Unavailable); - mucPayload = MUCUserPayload::ref(new MUCUserPayload()); - myItem.affiliation = MUCOccupant::Member; - myItem.nick = "Robot"; - myItem.role = MUCOccupant::Participant; - mucPayload->addItem(myItem); - mucPayload->addStatusCode(303); - stanza->addPayload(mucPayload); - channel->onPresenceReceived(stanza); - CPPUNIT_ASSERT_EQUAL(2, nickChanges); - CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Rabbit")); - CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Robot")); - } - - /*void testJoin_Success() { - MUC::ref testling = createMUC(JID("foo@bar.com")); - testling->onJoinFinished.connect(boost::bind(&MUCTest::handleJoinFinished, this, _1, _2)); - testling->joinAs("Alice"); - receivePresence(JID("foo@bar.com/Rabbit"), "Here"); - - CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(joinResults.size())); - CPPUNIT_ASSERT_EQUAL(std::string("Alice"), joinResults[0].nick); - CPPUNIT_ASSERT(joinResults[0].error); - } - - void testJoin_Fail() { - //CPPUNIT_ASSERT(!mucRegistry->isMUC(JID("foo@bar.com"))); - }*/ - - private: - MUC::ref createMUC(const JID& jid) { - MUC::ref muc = boost::make_shared<MUCImpl>(channel, router, presenceSender, jid, mucRegistry); - muc->onOccupantNicknameChanged.connect(boost::bind(&MUCTest::handleOccupantNicknameChanged, this, _1, _2)); - return muc; - } - - void handleJoinFinished(const std::string& nick, ErrorPayload::ref error) { - JoinResult r; - r.nick = nick; - r.error = error; - joinResults.push_back(r); - } - - void receivePresence(const JID& jid, const std::string& status) { - Presence::ref p = Presence::create(status); - p->setFrom(jid); - //MUCUserPayload::ref mucUserPayload = boost::make_shared<MUCUserPayload>(); - //mucUserPayload->addItem(item); - //p->addPayload(mucUserPayload); - channel->onPresenceReceived(p); - } - - void handleOccupantNicknameChanged(const std::string&, const std::string&) { - nickChanges++; - } - - private: - DummyStanzaChannel* channel; - IQRouter* router; - MUCRegistry* mucRegistry; - StanzaChannelPresenceSender* stanzaChannelPresenceSender; - DirectedPresenceSender* presenceSender; - struct JoinResult { - std::string nick; - ErrorPayload::ref error; - }; - std::vector<JoinResult> joinResults; - int nickChanges; + CPPUNIT_TEST_SUITE(MUCTest); + CPPUNIT_TEST(testJoin); + CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess); + CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess); + CPPUNIT_TEST(testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess); + CPPUNIT_TEST(testCreateInstant); + CPPUNIT_TEST(testReplicateBug); + CPPUNIT_TEST(testNicknameChange); + /*CPPUNIT_TEST(testJoin_Success); + CPPUNIT_TEST(testJoin_Fail);*/ + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + channel = new DummyStanzaChannel(); + router = new IQRouter(channel); + mucRegistry = new MUCRegistry(); + stanzaChannelPresenceSender = new StanzaChannelPresenceSender(channel); + presenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender); + nickChanges = 0; + } + + void tearDown() { + delete presenceSender; + delete stanzaChannelPresenceSender; + delete mucRegistry; + delete router; + delete channel; + } + + void testJoin() { + MUC::ref testling = createMUC(JID("foo@bar.com")); + testling->joinAs("Alice"); + + CPPUNIT_ASSERT(mucRegistry->isMUC(JID("foo@bar.com"))); + Presence::ref p = channel->getStanzaAtIndex<Presence>(0); + CPPUNIT_ASSERT(p); + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo()); + } + + void testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess() { + MUC::ref testling = createMUC(JID("foo@bar.com")); + testling->joinAs("Alice"); + + presenceSender->sendPresence(Presence::create("Test")); + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size())); + } + + void testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess() { + MUC::ref testling = createMUC(JID("foo@bar.com")); + testling->joinAs("Alice"); + + presenceSender->sendPresence(Presence::create("Test")); + receivePresence(JID("foo@bar.com/Rabbit"), "Here"); + + CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size())); + Presence::ref p = channel->getStanzaAtIndex<Presence>(2); + CPPUNIT_ASSERT(p); + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo()); + CPPUNIT_ASSERT_EQUAL(std::string("Test"), p->getStatus()); + } + + void testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess() { + MUC::ref testling = createMUC(JID("foo@bar.com")); + testling->joinAs("Alice"); + + receivePresence(JID("foo@bar.com/Rabbit"), "Here"); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size())); + Presence::ref p = channel->getStanzaAtIndex<Presence>(0); + CPPUNIT_ASSERT(p); + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo()); + CPPUNIT_ASSERT_EQUAL(std::string(""), p->getStatus()); + } + + void testCreateInstant() { + MUC::ref testling = createMUC(JID("rabbithole@wonderland.lit")); + testling->joinAs("Alice"); + Presence::ref serverRespondsLocked = boost::make_shared<Presence>(); + serverRespondsLocked->setFrom(JID("rabbithole@wonderland.lit/Alice")); + MUCUserPayload::ref mucPayload(new MUCUserPayload()); + MUCItem myItem; + myItem.affiliation = MUCOccupant::Owner; + myItem.role = MUCOccupant::Moderator; + mucPayload->addItem(myItem); + mucPayload->addStatusCode(MUCUserPayload::StatusCode(110)); + mucPayload->addStatusCode(MUCUserPayload::StatusCode(201)); + serverRespondsLocked->addPayload(mucPayload); + channel->onPresenceReceived(serverRespondsLocked); + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size())); + IQ::ref iq = channel->getStanzaAtIndex<IQ>(1); + CPPUNIT_ASSERT(iq); + CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()); + CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm()); + CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType()); + } + + void testReplicateBug() { + Presence::ref initialPresence = boost::make_shared<Presence>(); + initialPresence->setStatus(""); + VCard::ref vcard = boost::make_shared<VCard>(); + vcard->setPhoto(createByteArray("15c30080ae98ec48be94bf0e191d43edd06e500a")); + initialPresence->addPayload(vcard); + CapsInfo::ref caps = boost::make_shared<CapsInfo>(); + caps->setNode("http://swift.im"); + caps->setVersion("p2UP0DrcVgKM6jJqYN/B92DKK0o="); + initialPresence->addPayload(caps); + channel->sendPresence(initialPresence); + + MUC::ref testling = createMUC(JID("test@rooms.swift.im")); + testling->joinAs("Test"); + Presence::ref serverRespondsLocked = boost::make_shared<Presence>(); + serverRespondsLocked->setFrom(JID("test@rooms.swift.im/Test")); + serverRespondsLocked->setTo(JID("test@swift.im/6913d576d55f0b67")); + serverRespondsLocked->addPayload(vcard); + serverRespondsLocked->addPayload(caps); + serverRespondsLocked->setStatus(""); + MUCUserPayload::ref mucPayload(new MUCUserPayload()); + MUCItem myItem; + myItem.affiliation = MUCOccupant::Owner; + myItem.role = MUCOccupant::Moderator; + mucPayload->addItem(myItem); + mucPayload->addStatusCode(MUCUserPayload::StatusCode(201)); + serverRespondsLocked->addPayload(mucPayload); + channel->onPresenceReceived(serverRespondsLocked); + CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size())); + IQ::ref iq = channel->getStanzaAtIndex<IQ>(2); + CPPUNIT_ASSERT(iq); + CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()); + CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm()); + CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType()); + } + + void testNicknameChange() { + MUC::ref testling = createMUC(JID("foo@bar.com")); + // Join as Rabbit + testling->joinAs("Rabbit"); + + // Rabbit joins + Presence::ref rabbitJoins = boost::make_shared<Presence>(); + rabbitJoins->setTo("test@swift.im/6913d576d55f0b67"); + rabbitJoins->setFrom(testling->getJID().toString() + "/Rabbit"); + channel->onPresenceReceived(rabbitJoins); + CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Rabbit")); + + // Alice joins + Presence::ref aliceJoins = boost::make_shared<Presence>(); + aliceJoins->setTo("test@swift.im/6913d576d55f0b67"); + aliceJoins->setFrom(testling->getJID().toString() + "/Alice"); + channel->onPresenceReceived(aliceJoins); + CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice")); + + // Change nick to Dodo + testling->changeNickname("Dodo"); + Presence::ref stanza = channel->getStanzaAtIndex<Presence>(1); + CPPUNIT_ASSERT(stanza); + CPPUNIT_ASSERT_EQUAL(std::string("Dodo"), stanza->getTo().getResource()); + + // Alice changes nick to Alice2 + stanza = boost::make_shared<Presence>(); + stanza->setFrom(JID("foo@bar.com/Alice")); + stanza->setTo(JID(router->getJID())); + stanza->setType(Presence::Unavailable); + MUCUserPayload::ref mucPayload(new MUCUserPayload()); + MUCItem myItem; + myItem.affiliation = MUCOccupant::Member; + myItem.nick = "Alice2"; + myItem.role = MUCOccupant::Participant; + mucPayload->addItem(myItem); + mucPayload->addStatusCode(303); + stanza->addPayload(mucPayload); + channel->onPresenceReceived(stanza); + CPPUNIT_ASSERT_EQUAL(1, nickChanges); + CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Alice")); + CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice2")); + + // We (Rabbit) change nick to Robot + stanza = boost::make_shared<Presence>(); + stanza->setFrom(JID("foo@bar.com/Rabbit")); + stanza->setTo(JID(router->getJID())); + stanza->setType(Presence::Unavailable); + mucPayload = MUCUserPayload::ref(new MUCUserPayload()); + myItem.affiliation = MUCOccupant::Member; + myItem.nick = "Robot"; + myItem.role = MUCOccupant::Participant; + mucPayload->addItem(myItem); + mucPayload->addStatusCode(303); + stanza->addPayload(mucPayload); + channel->onPresenceReceived(stanza); + CPPUNIT_ASSERT_EQUAL(2, nickChanges); + CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Rabbit")); + CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Robot")); + } + + /*void testJoin_Success() { + MUC::ref testling = createMUC(JID("foo@bar.com")); + testling->onJoinFinished.connect(boost::bind(&MUCTest::handleJoinFinished, this, _1, _2)); + testling->joinAs("Alice"); + receivePresence(JID("foo@bar.com/Rabbit"), "Here"); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(joinResults.size())); + CPPUNIT_ASSERT_EQUAL(std::string("Alice"), joinResults[0].nick); + CPPUNIT_ASSERT(joinResults[0].error); + } + + void testJoin_Fail() { + //CPPUNIT_ASSERT(!mucRegistry->isMUC(JID("foo@bar.com"))); + }*/ + + private: + MUC::ref createMUC(const JID& jid) { + MUC::ref muc = boost::make_shared<MUCImpl>(channel, router, presenceSender, jid, mucRegistry); + muc->onOccupantNicknameChanged.connect(boost::bind(&MUCTest::handleOccupantNicknameChanged, this, _1, _2)); + return muc; + } + + void handleJoinFinished(const std::string& nick, ErrorPayload::ref error) { + JoinResult r; + r.nick = nick; + r.error = error; + joinResults.push_back(r); + } + + void receivePresence(const JID& jid, const std::string& status) { + Presence::ref p = Presence::create(status); + p->setFrom(jid); + //MUCUserPayload::ref mucUserPayload = boost::make_shared<MUCUserPayload>(); + //mucUserPayload->addItem(item); + //p->addPayload(mucUserPayload); + channel->onPresenceReceived(p); + } + + void handleOccupantNicknameChanged(const std::string&, const std::string&) { + nickChanges++; + } + + private: + DummyStanzaChannel* channel; + IQRouter* router; + MUCRegistry* mucRegistry; + StanzaChannelPresenceSender* stanzaChannelPresenceSender; + DirectedPresenceSender* presenceSender; + struct JoinResult { + std::string nick; + ErrorPayload::ref error; + }; + std::vector<JoinResult> joinResults; + int nickChanges; }; CPPUNIT_TEST_SUITE_REGISTRATION(MUCTest); diff --git a/Swiften/MUC/UnitTest/MockMUC.cpp b/Swiften/MUC/UnitTest/MockMUC.cpp index 6131183..93e7d0b 100644 --- a/Swiften/MUC/UnitTest/MockMUC.cpp +++ b/Swiften/MUC/UnitTest/MockMUC.cpp @@ -18,34 +18,34 @@ MockMUC::~MockMUC() { void MockMUC::insertOccupant(const MUCOccupant& occupant) { - occupants_.insert(std::make_pair(occupant.getNick(), occupant)); - onOccupantJoined(occupant); + occupants_.insert(std::make_pair(occupant.getNick(), occupant)); + onOccupantJoined(occupant); } const MUCOccupant& MockMUC::getOccupant(const std::string& nick) { - return occupants_.find(nick)->second; + return occupants_.find(nick)->second; } bool MockMUC::hasOccupant(const std::string& nick) { - return occupants_.find(nick) != occupants_.end(); + return occupants_.find(nick) != occupants_.end(); } void MockMUC::changeAffiliation(const JID &jid, MUCOccupant::Affiliation newAffilation) { - std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource()); - if (i != occupants_.end()) { - const MUCOccupant old = i->second; - i->second = MUCOccupant(old.getNick(), old.getRole(), newAffilation); - onOccupantAffiliationChanged(i->first, newAffilation, old.getAffiliation()); - } + std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource()); + if (i != occupants_.end()) { + const MUCOccupant old = i->second; + i->second = MUCOccupant(old.getNick(), old.getRole(), newAffilation); + onOccupantAffiliationChanged(i->first, newAffilation, old.getAffiliation()); + } } void MockMUC::changeOccupantRole(const JID &jid, MUCOccupant::Role newRole) { - std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource()); - if (i != occupants_.end()) { - const MUCOccupant old = i->second; - i->second = MUCOccupant(old.getNick(), newRole, old.getAffiliation()); - onOccupantRoleChanged(i->first, i->second, old.getRole()); - } + std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource()); + if (i != occupants_.end()) { + const MUCOccupant old = i->second; + i->second = MUCOccupant(old.getNick(), newRole, old.getAffiliation()); + onOccupantRoleChanged(i->first, i->second, old.getRole()); + } } } diff --git a/Swiften/MUC/UnitTest/MockMUC.h b/Swiften/MUC/UnitTest/MockMUC.h index c54e738..c61f8a9 100644 --- a/Swiften/MUC/UnitTest/MockMUC.h +++ b/Swiften/MUC/UnitTest/MockMUC.h @@ -25,74 +25,74 @@ #include <Swiften/MUC/MUCRegistry.h> namespace Swift { - class StanzaChannel; - class IQRouter; - class DirectedPresenceSender; + class StanzaChannel; + class IQRouter; + class DirectedPresenceSender; - class SWIFTEN_API MockMUC : public MUC{ - public: - typedef boost::shared_ptr<MockMUC> ref; + class SWIFTEN_API MockMUC : public MUC{ + public: + typedef boost::shared_ptr<MockMUC> ref; - public: - MockMUC(const JID &muc); - virtual ~MockMUC(); + public: + MockMUC(const JID &muc); + virtual ~MockMUC(); - /** - * Cause a user to appear to have entered the room. For testing only. - */ - void insertOccupant(const MUCOccupant& occupant); + /** + * Cause a user to appear to have entered the room. For testing only. + */ + void insertOccupant(const MUCOccupant& occupant); - /** - * Returns the (bare) JID of the MUC. - */ - virtual JID getJID() const { - return ownMUCJID.toBare(); - } - /** - * Returns if the room is unlocked and other people can join the room. - * @return True if joinable by others; false otherwise. - */ - virtual bool isUnlocked() const { return true; } + /** + * Returns the (bare) JID of the MUC. + */ + virtual JID getJID() const { + return ownMUCJID.toBare(); + } + /** + * Returns if the room is unlocked and other people can join the room. + * @return True if joinable by others; false otherwise. + */ + virtual bool isUnlocked() const { return true; } - virtual void joinAs(const std::string&) {} - virtual void joinWithContextSince(const std::string&, const boost::posix_time::ptime&) {} - /*virtual void queryRoomInfo(); */ - /*virtual void queryRoomItems(); */ - /*virtual std::string getCurrentNick() = 0; */ - virtual std::map<std::string, MUCOccupant> getOccupants() const { return occupants_; } - virtual void changeNickname(const std::string&) { } - virtual void part() {} - /*virtual void handleIncomingMessage(Message::ref message) = 0; */ - /** Expose public so it can be called when e.g. user goes offline */ - virtual void handleUserLeft(LeavingType) {} - /** Get occupant information*/ - virtual const MUCOccupant& getOccupant(const std::string&); - virtual bool hasOccupant(const std::string&); - virtual void kickOccupant(const JID&) {} - virtual void changeOccupantRole(const JID&, MUCOccupant::Role); - virtual void requestAffiliationList(MUCOccupant::Affiliation) {} - virtual void changeAffiliation(const JID&, MUCOccupant::Affiliation); - virtual void changeSubject(const std::string&) {} - virtual void requestConfigurationForm() {} - virtual void configureRoom(Form::ref) {} - virtual void cancelConfigureRoom() {} - virtual void destroyRoom() {} - /** Send an invite for the person to join the MUC */ - virtual void invitePerson(const JID&, const std::string&, bool, bool) {} - virtual void setCreateAsReservedIfNew() {} - virtual void setPassword(const boost::optional<std::string>&) {} + virtual void joinAs(const std::string&) {} + virtual void joinWithContextSince(const std::string&, const boost::posix_time::ptime&) {} + /*virtual void queryRoomInfo(); */ + /*virtual void queryRoomItems(); */ + /*virtual std::string getCurrentNick() = 0; */ + virtual std::map<std::string, MUCOccupant> getOccupants() const { return occupants_; } + virtual void changeNickname(const std::string&) { } + virtual void part() {} + /*virtual void handleIncomingMessage(Message::ref message) = 0; */ + /** Expose public so it can be called when e.g. user goes offline */ + virtual void handleUserLeft(LeavingType) {} + /** Get occupant information*/ + virtual const MUCOccupant& getOccupant(const std::string&); + virtual bool hasOccupant(const std::string&); + virtual void kickOccupant(const JID&) {} + virtual void changeOccupantRole(const JID&, MUCOccupant::Role); + virtual void requestAffiliationList(MUCOccupant::Affiliation) {} + virtual void changeAffiliation(const JID&, MUCOccupant::Affiliation); + virtual void changeSubject(const std::string&) {} + virtual void requestConfigurationForm() {} + virtual void configureRoom(Form::ref) {} + virtual void cancelConfigureRoom() {} + virtual void destroyRoom() {} + /** Send an invite for the person to join the MUC */ + virtual void invitePerson(const JID&, const std::string&, bool, bool) {} + virtual void setCreateAsReservedIfNew() {} + virtual void setPassword(const boost::optional<std::string>&) {} - protected: - virtual bool isFromMUC(const JID& j) const { - return ownMUCJID.equals(j, JID::WithoutResource); - } + protected: + virtual bool isFromMUC(const JID& j) const { + return ownMUCJID.equals(j, JID::WithoutResource); + } - virtual const std::string& getOwnNick() const { - return ownMUCJID.getResource(); - } + virtual const std::string& getOwnNick() const { + return ownMUCJID.getResource(); + } - private: - JID ownMUCJID; - std::map<std::string, MUCOccupant> occupants_; - }; + private: + JID ownMUCJID; + std::map<std::string, MUCOccupant> occupants_; + }; } diff --git a/Swiften/Network/BOSHConnection.cpp b/Swiften/Network/BOSHConnection.cpp index b04609f..887a5f0 100644 --- a/Swiften/Network/BOSHConnection.cpp +++ b/Swiften/Network/BOSHConnection.cpp @@ -32,63 +32,63 @@ namespace Swift { BOSHConnection::BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions) - : boshURL_(boshURL), - connector_(connector), - parserFactory_(parserFactory), - sid_(), - waitingForStartResponse_(false), - rid_(~0ULL), - pending_(false), - connectionReady_(false) + : boshURL_(boshURL), + connector_(connector), + parserFactory_(parserFactory), + sid_(), + waitingForStartResponse_(false), + rid_(~0ULL), + pending_(false), + connectionReady_(false) { - if (boshURL_.getScheme() == "https") { - tlsLayer_ = boost::make_shared<TLSLayer>(tlsContextFactory, tlsOptions); - // The following dummyLayer_ is needed as the TLSLayer will pass the decrypted data to its parent layer. - // The dummyLayer_ will serve as the parent layer. - dummyLayer_ = boost::make_shared<DummyStreamLayer>(tlsLayer_.get()); - } + if (boshURL_.getScheme() == "https") { + tlsLayer_ = boost::make_shared<TLSLayer>(tlsContextFactory, tlsOptions); + // The following dummyLayer_ is needed as the TLSLayer will pass the decrypted data to its parent layer. + // The dummyLayer_ will serve as the parent layer. + dummyLayer_ = boost::make_shared<DummyStreamLayer>(tlsLayer_.get()); + } } BOSHConnection::~BOSHConnection() { - cancelConnector(); - if (connection_) { - connection_->onDataRead.disconnect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1)); - connection_->onDisconnected.disconnect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); - } - BOSHConnection::disconnect(); + cancelConnector(); + if (connection_) { + connection_->onDataRead.disconnect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1)); + connection_->onDisconnected.disconnect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); + } + BOSHConnection::disconnect(); } void BOSHConnection::connect() { - connector_->onConnectFinished.connect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1)); - connector_->start(); + connector_->onConnectFinished.connect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1)); + connector_->start(); } void BOSHConnection::cancelConnector() { - if (connector_) { - connector_->onConnectFinished.disconnect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1)); - connector_->stop(); - connector_.reset(); - } + if (connector_) { + connector_->onConnectFinished.disconnect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1)); + connector_->stop(); + connector_.reset(); + } } void BOSHConnection::handleTLSConnected() { - SWIFT_LOG(debug) << std::endl; - onConnectFinished(false); + SWIFT_LOG(debug) << std::endl; + onConnectFinished(false); } void BOSHConnection::handleTLSApplicationDataRead(const SafeByteArray& data) { - SWIFT_LOG(debug) << std::endl; - handleDataRead(boost::make_shared<SafeByteArray>(data)); + SWIFT_LOG(debug) << std::endl; + handleDataRead(boost::make_shared<SafeByteArray>(data)); } void BOSHConnection::handleTLSNetowrkDataWriteRequest(const SafeByteArray& data) { - SWIFT_LOG(debug) << std::endl; - connection_->write(data); + SWIFT_LOG(debug) << std::endl; + connection_->write(data); } void BOSHConnection::handleRawDataRead(boost::shared_ptr<SafeByteArray> data) { - SWIFT_LOG(debug) << std::endl; - tlsLayer_->handleDataRead(*data.get()); + SWIFT_LOG(debug) << std::endl; + tlsLayer_->handleDataRead(*data.get()); } void BOSHConnection::handleTLSError(boost::shared_ptr<TLSError> /* error */) { @@ -96,298 +96,298 @@ void BOSHConnection::handleTLSError(boost::shared_ptr<TLSError> /* error */) { } void BOSHConnection::writeData(const SafeByteArray& data) { - if (tlsLayer_) { - tlsLayer_->writeData(data); - } - else { - connection_->write(data); - } + if (tlsLayer_) { + tlsLayer_->writeData(data); + } + else { + connection_->write(data); + } } void BOSHConnection::disconnect() { - if (connection_) { - connection_->disconnect(); - sid_ = ""; - } - else { - /* handleDisconnected takes care of the connector_ as well */ - handleDisconnected(boost::optional<Connection::Error>()); - } + if (connection_) { + connection_->disconnect(); + sid_ = ""; + } + else { + /* handleDisconnected takes care of the connector_ as well */ + handleDisconnected(boost::optional<Connection::Error>()); + } } void BOSHConnection::restartStream() { - write(createSafeByteArray(""), true, false); + write(createSafeByteArray(""), true, false); } bool BOSHConnection::setClientCertificate(CertificateWithKey::ref cert) { - if (tlsLayer_) { - SWIFT_LOG(debug) << "set client certificate" << std::endl; - return tlsLayer_->setClientCertificate(cert); - } - else { - return false; - } + if (tlsLayer_) { + SWIFT_LOG(debug) << "set client certificate" << std::endl; + return tlsLayer_->setClientCertificate(cert); + } + else { + return false; + } } Certificate::ref BOSHConnection::getPeerCertificate() const { - Certificate::ref peerCertificate; - if (tlsLayer_) { - peerCertificate = tlsLayer_->getPeerCertificate(); - } - return peerCertificate; + Certificate::ref peerCertificate; + if (tlsLayer_) { + peerCertificate = tlsLayer_->getPeerCertificate(); + } + return peerCertificate; } std::vector<Certificate::ref> BOSHConnection::getPeerCertificateChain() const { - std::vector<Certificate::ref> peerCertificateChain; - if (tlsLayer_) { - peerCertificateChain = tlsLayer_->getPeerCertificateChain(); - } - return peerCertificateChain; + std::vector<Certificate::ref> peerCertificateChain; + if (tlsLayer_) { + peerCertificateChain = tlsLayer_->getPeerCertificateChain(); + } + return peerCertificateChain; } CertificateVerificationError::ref BOSHConnection::getPeerCertificateVerificationError() const { - CertificateVerificationError::ref verificationError; - if (tlsLayer_) { - verificationError = tlsLayer_->getPeerCertificateVerificationError(); - } - return verificationError; + CertificateVerificationError::ref verificationError; + if (tlsLayer_) { + verificationError = tlsLayer_->getPeerCertificateVerificationError(); + } + return verificationError; } void BOSHConnection::terminateStream() { - write(createSafeByteArray(""), false, true); + write(createSafeByteArray(""), false, true); } void BOSHConnection::write(const SafeByteArray& data) { - write(data, false, false); + write(data, false, false); } std::pair<SafeByteArray, size_t> BOSHConnection::createHTTPRequest(const SafeByteArray& data, bool streamRestart, bool terminate, unsigned long long rid, const std::string& sid, const URL& boshURL) { - size_t size; - std::stringstream content; - SafeByteArray contentTail = createSafeByteArray("</body>"); - std::stringstream header; - - content << "<body rid='" << rid << "' sid='" << sid << "'"; - if (streamRestart) { - content << " xmpp:restart='true' xmlns:xmpp='urn:xmpp:xbosh'"; - } - if (terminate) { - content << " type='terminate'"; - } - content << " xmlns='http://jabber.org/protocol/httpbind'>"; - - SafeByteArray safeContent = createSafeByteArray(content.str()); - safeContent.insert(safeContent.end(), data.begin(), data.end()); - safeContent.insert(safeContent.end(), contentTail.begin(), contentTail.end()); - - size = safeContent.size(); - - header << "POST " << boshURL.getPath() << " HTTP/1.1\r\n" - << "Host: " << boshURL.getHost(); - if (boshURL.getPort()) { - header << ":" << *boshURL.getPort(); - } - header << "\r\n" - // << "Accept-Encoding: deflate\r\n" - << "Content-Type: text/xml; charset=utf-8\r\n" - << "Content-Length: " << size << "\r\n\r\n"; - - SafeByteArray safeHeader = createSafeByteArray(header.str()); - safeHeader.insert(safeHeader.end(), safeContent.begin(), safeContent.end()); - - return std::pair<SafeByteArray, size_t>(safeHeader, size); + size_t size; + std::stringstream content; + SafeByteArray contentTail = createSafeByteArray("</body>"); + std::stringstream header; + + content << "<body rid='" << rid << "' sid='" << sid << "'"; + if (streamRestart) { + content << " xmpp:restart='true' xmlns:xmpp='urn:xmpp:xbosh'"; + } + if (terminate) { + content << " type='terminate'"; + } + content << " xmlns='http://jabber.org/protocol/httpbind'>"; + + SafeByteArray safeContent = createSafeByteArray(content.str()); + safeContent.insert(safeContent.end(), data.begin(), data.end()); + safeContent.insert(safeContent.end(), contentTail.begin(), contentTail.end()); + + size = safeContent.size(); + + header << "POST " << boshURL.getPath() << " HTTP/1.1\r\n" + << "Host: " << boshURL.getHost(); + if (boshURL.getPort()) { + header << ":" << *boshURL.getPort(); + } + header << "\r\n" + // << "Accept-Encoding: deflate\r\n" + << "Content-Type: text/xml; charset=utf-8\r\n" + << "Content-Length: " << size << "\r\n\r\n"; + + SafeByteArray safeHeader = createSafeByteArray(header.str()); + safeHeader.insert(safeHeader.end(), safeContent.begin(), safeContent.end()); + + return std::pair<SafeByteArray, size_t>(safeHeader, size); } void BOSHConnection::write(const SafeByteArray& data, bool streamRestart, bool terminate) { - assert(connectionReady_); - assert(!sid_.empty()); + assert(connectionReady_); + assert(!sid_.empty()); - SafeByteArray safeHeader = createHTTPRequest(data, streamRestart, terminate, rid_, sid_, boshURL_).first; + SafeByteArray safeHeader = createHTTPRequest(data, streamRestart, terminate, rid_, sid_, boshURL_).first; - onBOSHDataWritten(safeHeader); - writeData(safeHeader); - pending_ = true; + onBOSHDataWritten(safeHeader); + writeData(safeHeader); + pending_ = true; - SWIFT_LOG(debug) << "write data: " << safeByteArrayToString(safeHeader) << std::endl; + SWIFT_LOG(debug) << "write data: " << safeByteArrayToString(safeHeader) << std::endl; } void BOSHConnection::handleConnectFinished(Connection::ref connection) { - cancelConnector(); - connectionReady_ = !!connection; - if (connectionReady_) { - connection_ = connection; - if (tlsLayer_) { - connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleRawDataRead, shared_from_this(), _1)); - connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); - - tlsLayer_->getContext()->onDataForNetwork.connect(boost::bind(&BOSHConnection::handleTLSNetowrkDataWriteRequest, shared_from_this(), _1)); - tlsLayer_->getContext()->onDataForApplication.connect(boost::bind(&BOSHConnection::handleTLSApplicationDataRead, shared_from_this(), _1)); - tlsLayer_->onConnected.connect(boost::bind(&BOSHConnection::handleTLSConnected, shared_from_this())); - tlsLayer_->onError.connect(boost::bind(&BOSHConnection::handleTLSError, shared_from_this(), _1)); - tlsLayer_->connect(); - } - else { - connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1)); - connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); - } - } - - if (!connectionReady_ || !tlsLayer_) { - onConnectFinished(!connectionReady_); - } + cancelConnector(); + connectionReady_ = !!connection; + if (connectionReady_) { + connection_ = connection; + if (tlsLayer_) { + connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleRawDataRead, shared_from_this(), _1)); + connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); + + tlsLayer_->getContext()->onDataForNetwork.connect(boost::bind(&BOSHConnection::handleTLSNetowrkDataWriteRequest, shared_from_this(), _1)); + tlsLayer_->getContext()->onDataForApplication.connect(boost::bind(&BOSHConnection::handleTLSApplicationDataRead, shared_from_this(), _1)); + tlsLayer_->onConnected.connect(boost::bind(&BOSHConnection::handleTLSConnected, shared_from_this())); + tlsLayer_->onError.connect(boost::bind(&BOSHConnection::handleTLSError, shared_from_this(), _1)); + tlsLayer_->connect(); + } + else { + connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1)); + connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); + } + } + + if (!connectionReady_ || !tlsLayer_) { + onConnectFinished(!connectionReady_); + } } void BOSHConnection::startStream(const std::string& to, unsigned long long rid) { - assert(connectionReady_); - // Session Creation Request - std::stringstream content; - std::stringstream header; - - content << "<body content='text/xml; charset=utf-8'" - << " hold='1'" - << " to='" << to << "'" - << " rid='" << rid << "'" - << " ver='1.6'" - << " wait='60'" /* FIXME: we probably want this configurable*/ - // << " ack='0'" FIXME: support acks - << " xml:lang='en'" - << " xmlns:xmpp='urn:xmpp:bosh'" - << " xmpp:version='1.0'" - << " xmlns='http://jabber.org/protocol/httpbind' />"; - - std::string contentString = content.str(); - - header << "POST " << boshURL_.getPath() << " HTTP/1.1\r\n" - << "Host: " << boshURL_.getHost(); - if (boshURL_.getPort()) { - header << ":" << *boshURL_.getPort(); - } - header << "\r\n" - // << "Accept-Encoding: deflate\r\n" - << "Content-Type: text/xml; charset=utf-8\r\n" - << "Content-Length: " << contentString.size() << "\r\n\r\n" - << contentString; - - waitingForStartResponse_ = true; - SafeByteArray safeHeader = createSafeByteArray(header.str()); - onBOSHDataWritten(safeHeader); - writeData(safeHeader); - SWIFT_LOG(debug) << "write stream header: " << safeByteArrayToString(safeHeader) << std::endl; + assert(connectionReady_); + // Session Creation Request + std::stringstream content; + std::stringstream header; + + content << "<body content='text/xml; charset=utf-8'" + << " hold='1'" + << " to='" << to << "'" + << " rid='" << rid << "'" + << " ver='1.6'" + << " wait='60'" /* FIXME: we probably want this configurable*/ + // << " ack='0'" FIXME: support acks + << " xml:lang='en'" + << " xmlns:xmpp='urn:xmpp:bosh'" + << " xmpp:version='1.0'" + << " xmlns='http://jabber.org/protocol/httpbind' />"; + + std::string contentString = content.str(); + + header << "POST " << boshURL_.getPath() << " HTTP/1.1\r\n" + << "Host: " << boshURL_.getHost(); + if (boshURL_.getPort()) { + header << ":" << *boshURL_.getPort(); + } + header << "\r\n" + // << "Accept-Encoding: deflate\r\n" + << "Content-Type: text/xml; charset=utf-8\r\n" + << "Content-Length: " << contentString.size() << "\r\n\r\n" + << contentString; + + waitingForStartResponse_ = true; + SafeByteArray safeHeader = createSafeByteArray(header.str()); + onBOSHDataWritten(safeHeader); + writeData(safeHeader); + SWIFT_LOG(debug) << "write stream header: " << safeByteArrayToString(safeHeader) << std::endl; } void BOSHConnection::handleDataRead(boost::shared_ptr<SafeByteArray> data) { - onBOSHDataRead(*data); - buffer_ = concat(buffer_, *data); - std::string response = safeByteArrayToString(buffer_); - if (response.find("\r\n\r\n") == std::string::npos) { - onBOSHDataRead(createSafeByteArray("[[Previous read incomplete, pending]]")); - return; - } - - std::string httpCode = response.substr(response.find(" ") + 1, 3); - if (httpCode != "200") { - onHTTPError(httpCode); - return; - } - - BOSHBodyExtractor parser(parserFactory_, createByteArray(response.substr(response.find("\r\n\r\n") + 4))); - if (parser.getBody()) { - if (parser.getBody()->attributes.getAttribute("type") == "terminate") { - BOSHError::Type errorType = parseTerminationCondition(parser.getBody()->attributes.getAttribute("condition")); - onSessionTerminated(errorType == BOSHError::NoError ? boost::shared_ptr<BOSHError>() : boost::make_shared<BOSHError>(errorType)); - } - buffer_.clear(); - if (waitingForStartResponse_) { - waitingForStartResponse_ = false; - sid_ = parser.getBody()->attributes.getAttribute("sid"); - std::string requestsString = parser.getBody()->attributes.getAttribute("requests"); - size_t requests = 2; - if (!requestsString.empty()) { - try { - requests = boost::lexical_cast<size_t>(requestsString); - } - catch (const boost::bad_lexical_cast&) { - } - } - onSessionStarted(sid_, requests); - } - SafeByteArray payload = createSafeByteArray(parser.getBody()->content); - /* Say we're good to go again, so don't add anything after here in the method */ - pending_ = false; - onXMPPDataRead(payload); - } + onBOSHDataRead(*data); + buffer_ = concat(buffer_, *data); + std::string response = safeByteArrayToString(buffer_); + if (response.find("\r\n\r\n") == std::string::npos) { + onBOSHDataRead(createSafeByteArray("[[Previous read incomplete, pending]]")); + return; + } + + std::string httpCode = response.substr(response.find(" ") + 1, 3); + if (httpCode != "200") { + onHTTPError(httpCode); + return; + } + + BOSHBodyExtractor parser(parserFactory_, createByteArray(response.substr(response.find("\r\n\r\n") + 4))); + if (parser.getBody()) { + if (parser.getBody()->attributes.getAttribute("type") == "terminate") { + BOSHError::Type errorType = parseTerminationCondition(parser.getBody()->attributes.getAttribute("condition")); + onSessionTerminated(errorType == BOSHError::NoError ? boost::shared_ptr<BOSHError>() : boost::make_shared<BOSHError>(errorType)); + } + buffer_.clear(); + if (waitingForStartResponse_) { + waitingForStartResponse_ = false; + sid_ = parser.getBody()->attributes.getAttribute("sid"); + std::string requestsString = parser.getBody()->attributes.getAttribute("requests"); + size_t requests = 2; + if (!requestsString.empty()) { + try { + requests = boost::lexical_cast<size_t>(requestsString); + } + catch (const boost::bad_lexical_cast&) { + } + } + onSessionStarted(sid_, requests); + } + SafeByteArray payload = createSafeByteArray(parser.getBody()->content); + /* Say we're good to go again, so don't add anything after here in the method */ + pending_ = false; + onXMPPDataRead(payload); + } } BOSHError::Type BOSHConnection::parseTerminationCondition(const std::string& text) { - BOSHError::Type condition = BOSHError::UndefinedCondition; - if (text == "bad-request") { - condition = BOSHError::BadRequest; - } - else if (text == "host-gone") { - condition = BOSHError::HostGone; - } - else if (text == "host-unknown") { - condition = BOSHError::HostUnknown; - } - else if (text == "improper-addressing") { - condition = BOSHError::ImproperAddressing; - } - else if (text == "internal-server-error") { - condition = BOSHError::InternalServerError; - } - else if (text == "item-not-found") { - condition = BOSHError::ItemNotFound; - } - else if (text == "other-request") { - condition = BOSHError::OtherRequest; - } - else if (text == "policy-violation") { - condition = BOSHError::PolicyViolation; - } - else if (text == "remote-connection-failed") { - condition = BOSHError::RemoteConnectionFailed; - } - else if (text == "remote-stream-error") { - condition = BOSHError::RemoteStreamError; - } - else if (text == "see-other-uri") { - condition = BOSHError::SeeOtherURI; - } - else if (text == "system-shutdown") { - condition = BOSHError::SystemShutdown; - } - else if (text == "") { - condition = BOSHError::NoError; - } - return condition; + BOSHError::Type condition = BOSHError::UndefinedCondition; + if (text == "bad-request") { + condition = BOSHError::BadRequest; + } + else if (text == "host-gone") { + condition = BOSHError::HostGone; + } + else if (text == "host-unknown") { + condition = BOSHError::HostUnknown; + } + else if (text == "improper-addressing") { + condition = BOSHError::ImproperAddressing; + } + else if (text == "internal-server-error") { + condition = BOSHError::InternalServerError; + } + else if (text == "item-not-found") { + condition = BOSHError::ItemNotFound; + } + else if (text == "other-request") { + condition = BOSHError::OtherRequest; + } + else if (text == "policy-violation") { + condition = BOSHError::PolicyViolation; + } + else if (text == "remote-connection-failed") { + condition = BOSHError::RemoteConnectionFailed; + } + else if (text == "remote-stream-error") { + condition = BOSHError::RemoteStreamError; + } + else if (text == "see-other-uri") { + condition = BOSHError::SeeOtherURI; + } + else if (text == "system-shutdown") { + condition = BOSHError::SystemShutdown; + } + else if (text == "") { + condition = BOSHError::NoError; + } + return condition; } const std::string& BOSHConnection::getSID() { - return sid_; + return sid_; } void BOSHConnection::setRID(unsigned long long rid) { - rid_ = rid; + rid_ = rid; } void BOSHConnection::setSID(const std::string& sid) { - sid_ = sid; + sid_ = sid; } void BOSHConnection::handleDisconnected(const boost::optional<Connection::Error>& error) { - cancelConnector(); - onDisconnected(error ? true : false); - sid_ = ""; - connectionReady_ = false; + cancelConnector(); + onDisconnected(error ? true : false); + sid_ = ""; + connectionReady_ = false; } bool BOSHConnection::isReadyToSend() { - /* Without pipelining you need to not send more without first receiving the response */ - /* With pipelining you can. Assuming we can't, here */ - return connectionReady_ && !pending_ && !waitingForStartResponse_ && !sid_.empty(); + /* Without pipelining you need to not send more without first receiving the response */ + /* With pipelining you can. Assuming we can't, here */ + return connectionReady_ && !pending_ && !waitingForStartResponse_ && !sid_.empty(); } } diff --git a/Swiften/Network/BOSHConnection.h b/Swiften/Network/BOSHConnection.h index da43e71..dc0f3a5 100644 --- a/Swiften/Network/BOSHConnection.h +++ b/Swiften/Network/BOSHConnection.h @@ -26,101 +26,101 @@ #include <Swiften/TLS/TLSError.h> namespace boost { - class thread; - namespace system { - class error_code; - } + class thread; + namespace system { + class error_code; + } } class BOSHConnectionTest; namespace Swift { - class XMLParserFactory; - class TLSContextFactory; - class TLSLayer; - struct TLSOptions; - class HighLayer; - - class SWIFTEN_API BOSHError : public SessionStream::SessionStreamError { - public: - enum Type { - BadRequest, HostGone, HostUnknown, ImproperAddressing, - InternalServerError, ItemNotFound, OtherRequest, PolicyViolation, - RemoteConnectionFailed, RemoteStreamError, SeeOtherURI, SystemShutdown, UndefinedCondition, - NoError}; - - BOSHError(Type type) : SessionStream::SessionStreamError(SessionStream::SessionStreamError::ConnectionReadError), type(type) {} - Type getType() {return type;} - typedef boost::shared_ptr<BOSHError> ref; - - private: - Type type; - }; - - class SWIFTEN_API BOSHConnection : public boost::enable_shared_from_this<BOSHConnection> { - public: - typedef boost::shared_ptr<BOSHConnection> ref; - static ref create(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions) { - return ref(new BOSHConnection(boshURL, connector, parserFactory, tlsContextFactory, tlsOptions)); - } - virtual ~BOSHConnection(); - virtual void connect(); - virtual void disconnect(); - virtual void write(const SafeByteArray& data); - - const std::string& getSID(); - void setRID(unsigned long long rid); - void setSID(const std::string& sid); - void startStream(const std::string& to, unsigned long long rid); - void terminateStream(); - bool isReadyToSend(); - void restartStream(); - - bool setClientCertificate(CertificateWithKey::ref cert); - Certificate::ref getPeerCertificate() const; - std::vector<Certificate::ref> getPeerCertificateChain() const; - CertificateVerificationError::ref getPeerCertificateVerificationError() const; - - boost::signal<void (bool /* error */)> onConnectFinished; - boost::signal<void (bool /* error */)> onDisconnected; - boost::signal<void (BOSHError::ref)> onSessionTerminated; - boost::signal<void (const std::string& /*sid*/, size_t /*requests*/)> onSessionStarted; - boost::signal<void (const SafeByteArray&)> onXMPPDataRead; - boost::signal<void (const SafeByteArray&)> onBOSHDataRead; - boost::signal<void (const SafeByteArray&)> onBOSHDataWritten; - boost::signal<void (const std::string&)> onHTTPError; - - private: - friend class ::BOSHConnectionTest; - - BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions); - - static std::pair<SafeByteArray, size_t> createHTTPRequest(const SafeByteArray& data, bool streamRestart, bool terminate, unsigned long long rid, const std::string& sid, const URL& boshURL); - void handleConnectFinished(Connection::ref); - void handleDataRead(boost::shared_ptr<SafeByteArray> data); - void handleDisconnected(const boost::optional<Connection::Error>& error); - void write(const SafeByteArray& data, bool streamRestart, bool terminate); /* FIXME: refactor */ - BOSHError::Type parseTerminationCondition(const std::string& text); - void cancelConnector(); - - void handleTLSConnected(); - void handleTLSApplicationDataRead(const SafeByteArray& data); - void handleTLSNetowrkDataWriteRequest(const SafeByteArray& data); - void handleRawDataRead(boost::shared_ptr<SafeByteArray> data); - void handleTLSError(boost::shared_ptr<TLSError> error); - void writeData(const SafeByteArray& data); - - URL boshURL_; - Connector::ref connector_; - XMLParserFactory* parserFactory_; - boost::shared_ptr<Connection> connection_; - boost::shared_ptr<HighLayer> dummyLayer_; - boost::shared_ptr<TLSLayer> tlsLayer_; - std::string sid_; - bool waitingForStartResponse_; - unsigned long long rid_; - SafeByteArray buffer_; - bool pending_; - bool connectionReady_; - }; + class XMLParserFactory; + class TLSContextFactory; + class TLSLayer; + struct TLSOptions; + class HighLayer; + + class SWIFTEN_API BOSHError : public SessionStream::SessionStreamError { + public: + enum Type { + BadRequest, HostGone, HostUnknown, ImproperAddressing, + InternalServerError, ItemNotFound, OtherRequest, PolicyViolation, + RemoteConnectionFailed, RemoteStreamError, SeeOtherURI, SystemShutdown, UndefinedCondition, + NoError}; + + BOSHError(Type type) : SessionStream::SessionStreamError(SessionStream::SessionStreamError::ConnectionReadError), type(type) {} + Type getType() {return type;} + typedef boost::shared_ptr<BOSHError> ref; + + private: + Type type; + }; + + class SWIFTEN_API BOSHConnection : public boost::enable_shared_from_this<BOSHConnection> { + public: + typedef boost::shared_ptr<BOSHConnection> ref; + static ref create(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions) { + return ref(new BOSHConnection(boshURL, connector, parserFactory, tlsContextFactory, tlsOptions)); + } + virtual ~BOSHConnection(); + virtual void connect(); + virtual void disconnect(); + virtual void write(const SafeByteArray& data); + + const std::string& getSID(); + void setRID(unsigned long long rid); + void setSID(const std::string& sid); + void startStream(const std::string& to, unsigned long long rid); + void terminateStream(); + bool isReadyToSend(); + void restartStream(); + + bool setClientCertificate(CertificateWithKey::ref cert); + Certificate::ref getPeerCertificate() const; + std::vector<Certificate::ref> getPeerCertificateChain() const; + CertificateVerificationError::ref getPeerCertificateVerificationError() const; + + boost::signal<void (bool /* error */)> onConnectFinished; + boost::signal<void (bool /* error */)> onDisconnected; + boost::signal<void (BOSHError::ref)> onSessionTerminated; + boost::signal<void (const std::string& /*sid*/, size_t /*requests*/)> onSessionStarted; + boost::signal<void (const SafeByteArray&)> onXMPPDataRead; + boost::signal<void (const SafeByteArray&)> onBOSHDataRead; + boost::signal<void (const SafeByteArray&)> onBOSHDataWritten; + boost::signal<void (const std::string&)> onHTTPError; + + private: + friend class ::BOSHConnectionTest; + + BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions); + + static std::pair<SafeByteArray, size_t> createHTTPRequest(const SafeByteArray& data, bool streamRestart, bool terminate, unsigned long long rid, const std::string& sid, const URL& boshURL); + void handleConnectFinished(Connection::ref); + void handleDataRead(boost::shared_ptr<SafeByteArray> data); + void handleDisconnected(const boost::optional<Connection::Error>& error); + void write(const SafeByteArray& data, bool streamRestart, bool terminate); /* FIXME: refactor */ + BOSHError::Type parseTerminationCondition(const std::string& text); + void cancelConnector(); + + void handleTLSConnected(); + void handleTLSApplicationDataRead(const SafeByteArray& data); + void handleTLSNetowrkDataWriteRequest(const SafeByteArray& data); + void handleRawDataRead(boost::shared_ptr<SafeByteArray> data); + void handleTLSError(boost::shared_ptr<TLSError> error); + void writeData(const SafeByteArray& data); + + URL boshURL_; + Connector::ref connector_; + XMLParserFactory* parserFactory_; + boost::shared_ptr<Connection> connection_; + boost::shared_ptr<HighLayer> dummyLayer_; + boost::shared_ptr<TLSLayer> tlsLayer_; + std::string sid_; + bool waitingForStartResponse_; + unsigned long long rid_; + SafeByteArray buffer_; + bool pending_; + bool connectionReady_; + }; } diff --git a/Swiften/Network/BOSHConnectionPool.cpp b/Swiften/Network/BOSHConnectionPool.cpp index 57c1bcc..7d5c164 100644 --- a/Swiften/Network/BOSHConnectionPool.cpp +++ b/Swiften/Network/BOSHConnectionPool.cpp @@ -18,284 +18,284 @@ namespace Swift { BOSHConnectionPool::BOSHConnectionPool(const URL& boshURL, DomainNameResolver* realResolver, ConnectionFactory* connectionFactoryParameter, XMLParserFactory* parserFactory, TLSContextFactory* tlsFactory, TimerFactory* timerFactory, EventLoop* eventLoop, const std::string& to, unsigned long long initialRID, const URL& boshHTTPConnectProxyURL, const SafeString& boshHTTPConnectProxyAuthID, const SafeString& boshHTTPConnectProxyAuthPassword, const TLSOptions& tlsOptions, boost::shared_ptr<HTTPTrafficFilter> trafficFilter) : - boshURL(boshURL), - connectionFactory(connectionFactoryParameter), - xmlParserFactory(parserFactory), - timerFactory(timerFactory), - rid(initialRID), - pendingTerminate(false), - to(to), - requestLimit(2), - restartCount(0), - pendingRestart(false), - tlsContextFactory_(tlsFactory), - tlsOptions_(tlsOptions) { - - if (!boshHTTPConnectProxyURL.isEmpty()) { - connectionFactory = new HTTPConnectProxiedConnectionFactory(realResolver, connectionFactory, timerFactory, boshHTTPConnectProxyURL.getHost(), URL::getPortOrDefaultPort(boshHTTPConnectProxyURL), boshHTTPConnectProxyAuthID, boshHTTPConnectProxyAuthPassword, trafficFilter); - } - resolver = new CachingDomainNameResolver(realResolver, eventLoop); + boshURL(boshURL), + connectionFactory(connectionFactoryParameter), + xmlParserFactory(parserFactory), + timerFactory(timerFactory), + rid(initialRID), + pendingTerminate(false), + to(to), + requestLimit(2), + restartCount(0), + pendingRestart(false), + tlsContextFactory_(tlsFactory), + tlsOptions_(tlsOptions) { + + if (!boshHTTPConnectProxyURL.isEmpty()) { + connectionFactory = new HTTPConnectProxiedConnectionFactory(realResolver, connectionFactory, timerFactory, boshHTTPConnectProxyURL.getHost(), URL::getPortOrDefaultPort(boshHTTPConnectProxyURL), boshHTTPConnectProxyAuthID, boshHTTPConnectProxyAuthPassword, trafficFilter); + } + resolver = new CachingDomainNameResolver(realResolver, eventLoop); } BOSHConnectionPool::~BOSHConnectionPool() { - /* Don't do a normal close here. Instead kill things forcibly, as close() or writeFooter() will already have been called */ - std::vector<BOSHConnection::ref> connectionCopies = connections; - foreach (BOSHConnection::ref connection, connectionCopies) { - if (connection) { - destroyConnection(connection); - connection->disconnect(); - } - } - foreach (ConnectionFactory* factory, myConnectionFactories) { - delete factory; - } - delete resolver; + /* Don't do a normal close here. Instead kill things forcibly, as close() or writeFooter() will already have been called */ + std::vector<BOSHConnection::ref> connectionCopies = connections; + foreach (BOSHConnection::ref connection, connectionCopies) { + if (connection) { + destroyConnection(connection); + connection->disconnect(); + } + } + foreach (ConnectionFactory* factory, myConnectionFactories) { + delete factory; + } + delete resolver; } void BOSHConnectionPool::write(const SafeByteArray& data) { - dataQueue.push_back(data); - tryToSendQueuedData(); + dataQueue.push_back(data); + tryToSendQueuedData(); } void BOSHConnectionPool::handleDataRead(const SafeByteArray& data) { - onXMPPDataRead(data); - tryToSendQueuedData(); /* Will rebalance the connections */ + onXMPPDataRead(data); + tryToSendQueuedData(); /* Will rebalance the connections */ } void BOSHConnectionPool::restartStream() { - BOSHConnection::ref connection = getSuitableConnection(); - if (connection) { - pendingRestart = false; - rid++; - connection->setRID(rid); - connection->restartStream(); - restartCount++; - } - else { - pendingRestart = true; - } + BOSHConnection::ref connection = getSuitableConnection(); + if (connection) { + pendingRestart = false; + rid++; + connection->setRID(rid); + connection->restartStream(); + restartCount++; + } + else { + pendingRestart = true; + } } void BOSHConnectionPool::setTLSCertificate(CertificateWithKey::ref certWithKey) { - clientCertificate = certWithKey; + clientCertificate = certWithKey; } bool BOSHConnectionPool::isTLSEncrypted() const { - return !pinnedCertificateChain_.empty(); + return !pinnedCertificateChain_.empty(); } Certificate::ref BOSHConnectionPool::getPeerCertificate() const { - Certificate::ref peerCertificate; - if (!pinnedCertificateChain_.empty()) { - peerCertificate = pinnedCertificateChain_[0]; - } - return peerCertificate; + Certificate::ref peerCertificate; + if (!pinnedCertificateChain_.empty()) { + peerCertificate = pinnedCertificateChain_[0]; + } + return peerCertificate; } std::vector<Certificate::ref> BOSHConnectionPool::getPeerCertificateChain() const { - return pinnedCertificateChain_; + return pinnedCertificateChain_; } boost::shared_ptr<CertificateVerificationError> BOSHConnectionPool::getPeerCertificateVerificationError() const { - return lastVerificationError_; + return lastVerificationError_; } void BOSHConnectionPool::writeFooter() { - pendingTerminate = true; - tryToSendQueuedData(); + pendingTerminate = true; + tryToSendQueuedData(); } void BOSHConnectionPool::open() { - createConnection(); + createConnection(); } void BOSHConnectionPool::close() { - if (!sid.empty()) { - writeFooter(); - } - else { - pendingTerminate = true; - std::vector<BOSHConnection::ref> connectionCopies = connections; - foreach (BOSHConnection::ref connection, connectionCopies) { - if (connection) { - connection->disconnect(); - } - } - } + if (!sid.empty()) { + writeFooter(); + } + else { + pendingTerminate = true; + std::vector<BOSHConnection::ref> connectionCopies = connections; + foreach (BOSHConnection::ref connection, connectionCopies) { + if (connection) { + connection->disconnect(); + } + } + } } void BOSHConnectionPool::handleSessionStarted(const std::string& sessionID, size_t requests) { - sid = sessionID; - requestLimit = requests; - onSessionStarted(); + sid = sessionID; + requestLimit = requests; + onSessionStarted(); } void BOSHConnectionPool::handleConnectFinished(bool error, BOSHConnection::ref connection) { - if (error) { - onSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); - /*TODO: We can probably manage to not terminate the stream here and use the rid/ack retry - * logic to just swallow the error and try again (some number of tries). - */ - } - else { - if (connection->getPeerCertificate() && pinnedCertificateChain_.empty()) { - pinnedCertificateChain_ = connection->getPeerCertificateChain(); - } - if (!pinnedCertificateChain_.empty()) { - lastVerificationError_ = connection->getPeerCertificateVerificationError(); - } - - if (sid.empty()) { - connection->startStream(to, rid); - } - if (pendingRestart) { - restartStream(); - } - tryToSendQueuedData(); - } + if (error) { + onSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); + /*TODO: We can probably manage to not terminate the stream here and use the rid/ack retry + * logic to just swallow the error and try again (some number of tries). + */ + } + else { + if (connection->getPeerCertificate() && pinnedCertificateChain_.empty()) { + pinnedCertificateChain_ = connection->getPeerCertificateChain(); + } + if (!pinnedCertificateChain_.empty()) { + lastVerificationError_ = connection->getPeerCertificateVerificationError(); + } + + if (sid.empty()) { + connection->startStream(to, rid); + } + if (pendingRestart) { + restartStream(); + } + tryToSendQueuedData(); + } } BOSHConnection::ref BOSHConnectionPool::getSuitableConnection() { - BOSHConnection::ref suitableConnection; - foreach (BOSHConnection::ref connection, connections) { - if (connection->isReadyToSend()) { - suitableConnection = connection; - break; - } - } - - if (!suitableConnection && connections.size() < requestLimit) { - /* This is not a suitable connection because it won't have yet connected and added TLS if needed. */ - BOSHConnection::ref newConnection = createConnection(); - newConnection->setSID(sid); - } - assert(connections.size() <= requestLimit); - assert((!suitableConnection) || suitableConnection->isReadyToSend()); - return suitableConnection; + BOSHConnection::ref suitableConnection; + foreach (BOSHConnection::ref connection, connections) { + if (connection->isReadyToSend()) { + suitableConnection = connection; + break; + } + } + + if (!suitableConnection && connections.size() < requestLimit) { + /* This is not a suitable connection because it won't have yet connected and added TLS if needed. */ + BOSHConnection::ref newConnection = createConnection(); + newConnection->setSID(sid); + } + assert(connections.size() <= requestLimit); + assert((!suitableConnection) || suitableConnection->isReadyToSend()); + return suitableConnection; } void BOSHConnectionPool::tryToSendQueuedData() { - if (sid.empty()) { - /* If we've not got as far as stream start yet, pend */ - return; - } - - BOSHConnection::ref suitableConnection = getSuitableConnection(); - bool toSend = !dataQueue.empty(); - if (suitableConnection) { - if (toSend) { - rid++; - suitableConnection->setRID(rid); - SafeByteArray data; - foreach (const SafeByteArray& datum, dataQueue) { - data.insert(data.end(), datum.begin(), datum.end()); - } - suitableConnection->write(data); - dataQueue.clear(); - } - else if (pendingTerminate) { - rid++; - suitableConnection->setRID(rid); - suitableConnection->terminateStream(); - sid = ""; - close(); - } - } - if (!pendingTerminate) { - /* Ensure there's always a session waiting to read data for us */ - bool pending = false; - foreach (BOSHConnection::ref connection, connections) { - if (connection && !connection->isReadyToSend()) { - pending = true; - } - } - if (!pending) { - if (restartCount >= 1) { - /* Don't open a second connection until we've restarted the stream twice - i.e. we've authed and resource bound.*/ - if (suitableConnection) { - rid++; - suitableConnection->setRID(rid); - suitableConnection->write(createSafeByteArray("")); - } - else { - /* My thought process I went through when writing this, to aid anyone else confused why this can happen... - * - * What to do here? I think this isn't possible. - If you didn't have two connections, suitable would have made one. - If you have two connections and neither is suitable, pending would be true. - If you have a non-pending connection, it's suitable. - - If I decide to do something here, remove assert above. - - Ah! Yes, because there's a period between creating the connection and it being connected. */ - } - } - } - } + if (sid.empty()) { + /* If we've not got as far as stream start yet, pend */ + return; + } + + BOSHConnection::ref suitableConnection = getSuitableConnection(); + bool toSend = !dataQueue.empty(); + if (suitableConnection) { + if (toSend) { + rid++; + suitableConnection->setRID(rid); + SafeByteArray data; + foreach (const SafeByteArray& datum, dataQueue) { + data.insert(data.end(), datum.begin(), datum.end()); + } + suitableConnection->write(data); + dataQueue.clear(); + } + else if (pendingTerminate) { + rid++; + suitableConnection->setRID(rid); + suitableConnection->terminateStream(); + sid = ""; + close(); + } + } + if (!pendingTerminate) { + /* Ensure there's always a session waiting to read data for us */ + bool pending = false; + foreach (BOSHConnection::ref connection, connections) { + if (connection && !connection->isReadyToSend()) { + pending = true; + } + } + if (!pending) { + if (restartCount >= 1) { + /* Don't open a second connection until we've restarted the stream twice - i.e. we've authed and resource bound.*/ + if (suitableConnection) { + rid++; + suitableConnection->setRID(rid); + suitableConnection->write(createSafeByteArray("")); + } + else { + /* My thought process I went through when writing this, to aid anyone else confused why this can happen... + * + * What to do here? I think this isn't possible. + If you didn't have two connections, suitable would have made one. + If you have two connections and neither is suitable, pending would be true. + If you have a non-pending connection, it's suitable. + + If I decide to do something here, remove assert above. + + Ah! Yes, because there's a period between creating the connection and it being connected. */ + } + } + } + } } void BOSHConnectionPool::handleHTTPError(const std::string& /*errorCode*/) { - handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); + handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); } void BOSHConnectionPool::handleConnectionDisconnected(bool/* error*/, BOSHConnection::ref connection) { - destroyConnection(connection); - if (pendingTerminate && sid.empty() && connections.empty()) { - handleSessionTerminated(BOSHError::ref()); - } - //else if (error) { - // handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); - //} - else { - /* We might have just freed up a connection slot to send with */ - tryToSendQueuedData(); - } + destroyConnection(connection); + if (pendingTerminate && sid.empty() && connections.empty()) { + handleSessionTerminated(BOSHError::ref()); + } + //else if (error) { + // handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); + //} + else { + /* We might have just freed up a connection slot to send with */ + tryToSendQueuedData(); + } } boost::shared_ptr<BOSHConnection> BOSHConnectionPool::createConnection() { - Connector::ref connector = Connector::create(boshURL.getHost(), URL::getPortOrDefaultPort(boshURL), boost::optional<std::string>(), resolver, connectionFactory, timerFactory); - BOSHConnection::ref connection = BOSHConnection::create(boshURL, connector, xmlParserFactory, tlsContextFactory_, tlsOptions_); - connection->onXMPPDataRead.connect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1)); - connection->onSessionStarted.connect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2)); - connection->onBOSHDataRead.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1)); - connection->onBOSHDataWritten.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1)); - connection->onDisconnected.connect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection)); - connection->onConnectFinished.connect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection)); - connection->onSessionTerminated.connect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1)); - connection->onHTTPError.connect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1)); - - if (boshURL.getScheme() == "https") { - bool success = connection->setClientCertificate(clientCertificate); - SWIFT_LOG(debug) << "setClientCertificate, success: " << success << std::endl; - } - - connection->connect(); - connections.push_back(connection); - return connection; + Connector::ref connector = Connector::create(boshURL.getHost(), URL::getPortOrDefaultPort(boshURL), boost::optional<std::string>(), resolver, connectionFactory, timerFactory); + BOSHConnection::ref connection = BOSHConnection::create(boshURL, connector, xmlParserFactory, tlsContextFactory_, tlsOptions_); + connection->onXMPPDataRead.connect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1)); + connection->onSessionStarted.connect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2)); + connection->onBOSHDataRead.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1)); + connection->onBOSHDataWritten.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1)); + connection->onDisconnected.connect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection)); + connection->onConnectFinished.connect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection)); + connection->onSessionTerminated.connect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1)); + connection->onHTTPError.connect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1)); + + if (boshURL.getScheme() == "https") { + bool success = connection->setClientCertificate(clientCertificate); + SWIFT_LOG(debug) << "setClientCertificate, success: " << success << std::endl; + } + + connection->connect(); + connections.push_back(connection); + return connection; } void BOSHConnectionPool::destroyConnection(boost::shared_ptr<BOSHConnection> connection) { - connections.erase(std::remove(connections.begin(), connections.end(), connection), connections.end()); - connection->onXMPPDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1)); - connection->onSessionStarted.disconnect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2)); - connection->onBOSHDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1)); - connection->onBOSHDataWritten.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1)); - connection->onDisconnected.disconnect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection)); - connection->onConnectFinished.disconnect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection)); - connection->onSessionTerminated.disconnect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1)); - connection->onHTTPError.disconnect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1)); + connections.erase(std::remove(connections.begin(), connections.end(), connection), connections.end()); + connection->onXMPPDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1)); + connection->onSessionStarted.disconnect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2)); + connection->onBOSHDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1)); + connection->onBOSHDataWritten.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1)); + connection->onDisconnected.disconnect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection)); + connection->onConnectFinished.disconnect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection)); + connection->onSessionTerminated.disconnect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1)); + connection->onHTTPError.disconnect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1)); } void BOSHConnectionPool::handleSessionTerminated(BOSHError::ref error) { - onSessionTerminated(error); + onSessionTerminated(error); } void BOSHConnectionPool::handleBOSHDataRead(const SafeByteArray& data) { - onBOSHDataRead(data); + onBOSHDataRead(data); } void BOSHConnectionPool::handleBOSHDataWritten(const SafeByteArray& data) { - onBOSHDataWritten(data); + onBOSHDataWritten(data); } } diff --git a/Swiften/Network/BOSHConnectionPool.h b/Swiften/Network/BOSHConnectionPool.h index df116ff..5088be6 100644 --- a/Swiften/Network/BOSHConnectionPool.h +++ b/Swiften/Network/BOSHConnectionPool.h @@ -16,73 +16,73 @@ #include <Swiften/TLS/TLSOptions.h> namespace Swift { - class CachingDomainNameResolver; - class EventLoop; - class HTTPConnectProxiedConnectionFactory; - class HTTPTrafficFilter; - class TLSContextFactory; - class CachingDomainNameResolver; - class EventLoop; + class CachingDomainNameResolver; + class EventLoop; + class HTTPConnectProxiedConnectionFactory; + class HTTPTrafficFilter; + class TLSContextFactory; + class CachingDomainNameResolver; + class EventLoop; - class SWIFTEN_API BOSHConnectionPool : public boost::bsignals::trackable { - public: - BOSHConnectionPool(const URL& boshURL, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, XMLParserFactory* parserFactory, TLSContextFactory* tlsFactory, TimerFactory* timerFactory, EventLoop* eventLoop, const std::string& to, unsigned long long initialRID, const URL& boshHTTPConnectProxyURL, const SafeString& boshHTTPConnectProxyAuthID, const SafeString& boshHTTPConnectProxyAuthPassword, const TLSOptions& tlsOptions, boost::shared_ptr<HTTPTrafficFilter> trafficFilter = boost::shared_ptr<HTTPTrafficFilter>()); - ~BOSHConnectionPool(); + class SWIFTEN_API BOSHConnectionPool : public boost::bsignals::trackable { + public: + BOSHConnectionPool(const URL& boshURL, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, XMLParserFactory* parserFactory, TLSContextFactory* tlsFactory, TimerFactory* timerFactory, EventLoop* eventLoop, const std::string& to, unsigned long long initialRID, const URL& boshHTTPConnectProxyURL, const SafeString& boshHTTPConnectProxyAuthID, const SafeString& boshHTTPConnectProxyAuthPassword, const TLSOptions& tlsOptions, boost::shared_ptr<HTTPTrafficFilter> trafficFilter = boost::shared_ptr<HTTPTrafficFilter>()); + ~BOSHConnectionPool(); - void open(); - void write(const SafeByteArray& data); - void writeFooter(); - void close(); - void restartStream(); + void open(); + void write(const SafeByteArray& data); + void writeFooter(); + void close(); + void restartStream(); - void setTLSCertificate(CertificateWithKey::ref certWithKey); - bool isTLSEncrypted() const; - Certificate::ref getPeerCertificate() const; - std::vector<Certificate::ref> getPeerCertificateChain() const; - boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const; + void setTLSCertificate(CertificateWithKey::ref certWithKey); + bool isTLSEncrypted() const; + Certificate::ref getPeerCertificate() const; + std::vector<Certificate::ref> getPeerCertificateChain() const; + boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const; - boost::signal<void (BOSHError::ref)> onSessionTerminated; - boost::signal<void ()> onSessionStarted; - boost::signal<void (const SafeByteArray&)> onXMPPDataRead; - boost::signal<void (const SafeByteArray&)> onBOSHDataRead; - boost::signal<void (const SafeByteArray&)> onBOSHDataWritten; + boost::signal<void (BOSHError::ref)> onSessionTerminated; + boost::signal<void ()> onSessionStarted; + boost::signal<void (const SafeByteArray&)> onXMPPDataRead; + boost::signal<void (const SafeByteArray&)> onBOSHDataRead; + boost::signal<void (const SafeByteArray&)> onBOSHDataWritten; - private: - void handleDataRead(const SafeByteArray& data); - void handleSessionStarted(const std::string& sid, size_t requests); - void handleBOSHDataRead(const SafeByteArray& data); - void handleBOSHDataWritten(const SafeByteArray& data); - void handleSessionTerminated(BOSHError::ref condition); - void handleConnectFinished(bool, BOSHConnection::ref connection); - void handleConnectionDisconnected(bool error, BOSHConnection::ref connection); - void handleHTTPError(const std::string& errorCode); + private: + void handleDataRead(const SafeByteArray& data); + void handleSessionStarted(const std::string& sid, size_t requests); + void handleBOSHDataRead(const SafeByteArray& data); + void handleBOSHDataWritten(const SafeByteArray& data); + void handleSessionTerminated(BOSHError::ref condition); + void handleConnectFinished(bool, BOSHConnection::ref connection); + void handleConnectionDisconnected(bool error, BOSHConnection::ref connection); + void handleHTTPError(const std::string& errorCode); - private: - BOSHConnection::ref createConnection(); - void destroyConnection(BOSHConnection::ref connection); - void tryToSendQueuedData(); - BOSHConnection::ref getSuitableConnection(); + private: + BOSHConnection::ref createConnection(); + void destroyConnection(BOSHConnection::ref connection); + void tryToSendQueuedData(); + BOSHConnection::ref getSuitableConnection(); - private: - URL boshURL; - ConnectionFactory* connectionFactory; - XMLParserFactory* xmlParserFactory; - TimerFactory* timerFactory; - std::vector<BOSHConnection::ref> connections; - std::string sid; - unsigned long long rid; - std::vector<SafeByteArray> dataQueue; - bool pendingTerminate; - std::string to; - size_t requestLimit; - int restartCount; - bool pendingRestart; - std::vector<ConnectionFactory*> myConnectionFactories; - CachingDomainNameResolver* resolver; - CertificateWithKey::ref clientCertificate; - TLSContextFactory* tlsContextFactory_; - TLSOptions tlsOptions_; - std::vector<boost::shared_ptr<Certificate> > pinnedCertificateChain_; - boost::shared_ptr<CertificateVerificationError> lastVerificationError_; - }; + private: + URL boshURL; + ConnectionFactory* connectionFactory; + XMLParserFactory* xmlParserFactory; + TimerFactory* timerFactory; + std::vector<BOSHConnection::ref> connections; + std::string sid; + unsigned long long rid; + std::vector<SafeByteArray> dataQueue; + bool pendingTerminate; + std::string to; + size_t requestLimit; + int restartCount; + bool pendingRestart; + std::vector<ConnectionFactory*> myConnectionFactories; + CachingDomainNameResolver* resolver; + CertificateWithKey::ref clientCertificate; + TLSContextFactory* tlsContextFactory_; + TLSOptions tlsOptions_; + std::vector<boost::shared_ptr<Certificate> > pinnedCertificateChain_; + boost::shared_ptr<CertificateVerificationError> lastVerificationError_; + }; } diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp index a88a739..80cb6b8 100644 --- a/Swiften/Network/BoostConnection.cpp +++ b/Swiften/Network/BoostConnection.cpp @@ -32,147 +32,147 @@ static const size_t BUFFER_SIZE = 4096; // A reference-counted non-modifiable buffer class. class SharedBuffer { - public: - SharedBuffer(const SafeByteArray& data) : - data_(new std::vector<char, SafeAllocator<char> >(data.begin(), data.end())), - buffer_(boost::asio::buffer(*data_)) { - } - - // ConstBufferSequence requirements. - typedef boost::asio::const_buffer value_type; - typedef const boost::asio::const_buffer* const_iterator; - const boost::asio::const_buffer* begin() const { return &buffer_; } - const boost::asio::const_buffer* end() const { return &buffer_ + 1; } - - private: - boost::shared_ptr< std::vector<char, SafeAllocator<char> > > data_; - boost::asio::const_buffer buffer_; + public: + SharedBuffer(const SafeByteArray& data) : + data_(new std::vector<char, SafeAllocator<char> >(data.begin(), data.end())), + buffer_(boost::asio::buffer(*data_)) { + } + + // ConstBufferSequence requirements. + typedef boost::asio::const_buffer value_type; + typedef const boost::asio::const_buffer* const_iterator; + const boost::asio::const_buffer* begin() const { return &buffer_; } + const boost::asio::const_buffer* end() const { return &buffer_ + 1; } + + private: + boost::shared_ptr< std::vector<char, SafeAllocator<char> > > data_; + boost::asio::const_buffer buffer_; }; // ----------------------------------------------------------------------------- BoostConnection::BoostConnection(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : - eventLoop(eventLoop), ioService(ioService), socket_(*ioService), writing_(false), closeSocketAfterNextWrite_(false) { + eventLoop(eventLoop), ioService(ioService), socket_(*ioService), writing_(false), closeSocketAfterNextWrite_(false) { } BoostConnection::~BoostConnection() { } void BoostConnection::listen() { - doRead(); + doRead(); } void BoostConnection::connect(const HostAddressPort& addressPort) { - boost::asio::ip::tcp::endpoint endpoint( - boost::asio::ip::address::from_string(addressPort.getAddress().toString()), boost::numeric_cast<unsigned short>(addressPort.getPort())); - socket_.async_connect( - endpoint, - boost::bind(&BoostConnection::handleConnectFinished, shared_from_this(), boost::asio::placeholders::error)); + boost::asio::ip::tcp::endpoint endpoint( + boost::asio::ip::address::from_string(addressPort.getAddress().toString()), boost::numeric_cast<unsigned short>(addressPort.getPort())); + socket_.async_connect( + endpoint, + boost::bind(&BoostConnection::handleConnectFinished, shared_from_this(), boost::asio::placeholders::error)); } void BoostConnection::disconnect() { - //MainEventLoop::removeEventsFromOwner(shared_from_this()); - - // Mac OS X apparently exhibits a problem where closing a socket during a write could potentially go into uninterruptable sleep. - // See e.g. http://bugs.python.org/issue7401 - // We therefore wait until any pending write finishes, which hopefully should fix our hang on exit during close(). - boost::lock_guard<boost::mutex> lock(writeMutex_); - if (writing_) { - closeSocketAfterNextWrite_ = true; - } else { - closeSocket(); - } + //MainEventLoop::removeEventsFromOwner(shared_from_this()); + + // Mac OS X apparently exhibits a problem where closing a socket during a write could potentially go into uninterruptable sleep. + // See e.g. http://bugs.python.org/issue7401 + // We therefore wait until any pending write finishes, which hopefully should fix our hang on exit during close(). + boost::lock_guard<boost::mutex> lock(writeMutex_); + if (writing_) { + closeSocketAfterNextWrite_ = true; + } else { + closeSocket(); + } } void BoostConnection::closeSocket() { - boost::lock_guard<boost::mutex> lock(readCloseMutex_); - boost::system::error_code errorCode; - socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorCode); - socket_.close(); + boost::lock_guard<boost::mutex> lock(readCloseMutex_); + boost::system::error_code errorCode; + socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorCode); + socket_.close(); } void BoostConnection::write(const SafeByteArray& data) { - boost::lock_guard<boost::mutex> lock(writeMutex_); - if (!writing_) { - writing_ = true; - doWrite(data); - } - else { - append(writeQueue_, data); - } + boost::lock_guard<boost::mutex> lock(writeMutex_); + if (!writing_) { + writing_ = true; + doWrite(data); + } + else { + append(writeQueue_, data); + } } void BoostConnection::doWrite(const SafeByteArray& data) { - boost::asio::async_write(socket_, SharedBuffer(data), - boost::bind(&BoostConnection::handleDataWritten, shared_from_this(), boost::asio::placeholders::error)); + boost::asio::async_write(socket_, SharedBuffer(data), + boost::bind(&BoostConnection::handleDataWritten, shared_from_this(), boost::asio::placeholders::error)); } void BoostConnection::handleConnectFinished(const boost::system::error_code& error) { - SWIFT_LOG(debug) << "Connect finished: " << error << std::endl; - if (!error) { - eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), false), shared_from_this()); - doRead(); - } - else if (error != boost::asio::error::operation_aborted) { - eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), true), shared_from_this()); - } + SWIFT_LOG(debug) << "Connect finished: " << error << std::endl; + if (!error) { + eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), false), shared_from_this()); + doRead(); + } + else if (error != boost::asio::error::operation_aborted) { + eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), true), shared_from_this()); + } } void BoostConnection::doRead() { - readBuffer_ = boost::make_shared<SafeByteArray>(BUFFER_SIZE); - boost::lock_guard<boost::mutex> lock(readCloseMutex_); - socket_.async_read_some( - boost::asio::buffer(*readBuffer_), - boost::bind(&BoostConnection::handleSocketRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); + readBuffer_ = boost::make_shared<SafeByteArray>(BUFFER_SIZE); + boost::lock_guard<boost::mutex> lock(readCloseMutex_); + socket_.async_read_some( + boost::asio::buffer(*readBuffer_), + boost::bind(&BoostConnection::handleSocketRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void BoostConnection::handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred) { - SWIFT_LOG(debug) << "Socket read " << error << std::endl; - if (!error) { - readBuffer_->resize(bytesTransferred); - eventLoop->postEvent(boost::bind(boost::ref(onDataRead), readBuffer_), shared_from_this()); - doRead(); - } - else if (/*error == boost::asio::error::eof ||*/ error == boost::asio::error::operation_aborted) { - eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this()); - } - else { - eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), ReadError), shared_from_this()); - } + SWIFT_LOG(debug) << "Socket read " << error << std::endl; + if (!error) { + readBuffer_->resize(bytesTransferred); + eventLoop->postEvent(boost::bind(boost::ref(onDataRead), readBuffer_), shared_from_this()); + doRead(); + } + else if (/*error == boost::asio::error::eof ||*/ error == boost::asio::error::operation_aborted) { + eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this()); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), ReadError), shared_from_this()); + } } void BoostConnection::handleDataWritten(const boost::system::error_code& error) { - SWIFT_LOG(debug) << "Data written " << error << std::endl; - if (!error) { - eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this()); - } - else if (/*error == boost::asio::error::eof || */error == boost::asio::error::operation_aborted) { - eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this()); - } - else { - eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), WriteError), shared_from_this()); - } - { - boost::lock_guard<boost::mutex> lock(writeMutex_); - if (writeQueue_.empty()) { - writing_ = false; - if (closeSocketAfterNextWrite_) { - closeSocket(); - } - } - else { - doWrite(writeQueue_); - writeQueue_.clear(); - } - } + SWIFT_LOG(debug) << "Data written " << error << std::endl; + if (!error) { + eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this()); + } + else if (/*error == boost::asio::error::eof || */error == boost::asio::error::operation_aborted) { + eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this()); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), WriteError), shared_from_this()); + } + { + boost::lock_guard<boost::mutex> lock(writeMutex_); + if (writeQueue_.empty()) { + writing_ = false; + if (closeSocketAfterNextWrite_) { + closeSocket(); + } + } + else { + doWrite(writeQueue_); + writeQueue_.clear(); + } + } } HostAddressPort BoostConnection::getLocalAddress() const { - return HostAddressPort(socket_.local_endpoint()); + return HostAddressPort(socket_.local_endpoint()); } HostAddressPort BoostConnection::getRemoteAddress() const { - return HostAddressPort(socket_.remote_endpoint()); + return HostAddressPort(socket_.remote_endpoint()); } diff --git a/Swiften/Network/BoostConnection.h b/Swiften/Network/BoostConnection.h index be44d51..9909455 100644 --- a/Swiften/Network/BoostConnection.h +++ b/Swiften/Network/BoostConnection.h @@ -20,62 +20,62 @@ #include <Swiften/TLS/CertificateWithKey.h> namespace boost { - class thread; - namespace system { - class error_code; - } + class thread; + namespace system { + class error_code; + } } namespace Swift { - class EventLoop; - - class SWIFTEN_API BoostConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<BoostConnection> { - public: - typedef boost::shared_ptr<BoostConnection> ref; - - virtual ~BoostConnection(); - - static ref create(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { - return ref(new BoostConnection(ioService, eventLoop)); - } - - virtual void listen(); - virtual void connect(const HostAddressPort& address); - virtual void disconnect(); - virtual void write(const SafeByteArray& data); - - boost::asio::ip::tcp::socket& getSocket() { - return socket_; - } - - virtual HostAddressPort getLocalAddress() const; - virtual HostAddressPort getRemoteAddress() const; - - bool setClientCertificate(CertificateWithKey::ref cert); - - Certificate::ref getPeerCertificate() const; - std::vector<Certificate::ref> getPeerCertificateChain() const; - boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const; - - private: - BoostConnection(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); - - void handleConnectFinished(const boost::system::error_code& error); - void handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred); - void handleDataWritten(const boost::system::error_code& error); - void doRead(); - void doWrite(const SafeByteArray& data); - void closeSocket(); - - private: - EventLoop* eventLoop; - boost::shared_ptr<boost::asio::io_service> ioService; - boost::asio::ip::tcp::socket socket_; - boost::shared_ptr<SafeByteArray> readBuffer_; - boost::mutex writeMutex_; - bool writing_; - SafeByteArray writeQueue_; - bool closeSocketAfterNextWrite_; - boost::mutex readCloseMutex_; - }; + class EventLoop; + + class SWIFTEN_API BoostConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<BoostConnection> { + public: + typedef boost::shared_ptr<BoostConnection> ref; + + virtual ~BoostConnection(); + + static ref create(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { + return ref(new BoostConnection(ioService, eventLoop)); + } + + virtual void listen(); + virtual void connect(const HostAddressPort& address); + virtual void disconnect(); + virtual void write(const SafeByteArray& data); + + boost::asio::ip::tcp::socket& getSocket() { + return socket_; + } + + virtual HostAddressPort getLocalAddress() const; + virtual HostAddressPort getRemoteAddress() const; + + bool setClientCertificate(CertificateWithKey::ref cert); + + Certificate::ref getPeerCertificate() const; + std::vector<Certificate::ref> getPeerCertificateChain() const; + boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const; + + private: + BoostConnection(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); + + void handleConnectFinished(const boost::system::error_code& error); + void handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred); + void handleDataWritten(const boost::system::error_code& error); + void doRead(); + void doWrite(const SafeByteArray& data); + void closeSocket(); + + private: + EventLoop* eventLoop; + boost::shared_ptr<boost::asio::io_service> ioService; + boost::asio::ip::tcp::socket socket_; + boost::shared_ptr<SafeByteArray> readBuffer_; + boost::mutex writeMutex_; + bool writing_; + SafeByteArray writeQueue_; + bool closeSocketAfterNextWrite_; + boost::mutex readCloseMutex_; + }; } diff --git a/Swiften/Network/BoostConnectionFactory.cpp b/Swiften/Network/BoostConnectionFactory.cpp index 4aec324..d22f600 100644 --- a/Swiften/Network/BoostConnectionFactory.cpp +++ b/Swiften/Network/BoostConnectionFactory.cpp @@ -14,7 +14,7 @@ BoostConnectionFactory::BoostConnectionFactory(boost::shared_ptr<boost::asio::io } boost::shared_ptr<Connection> BoostConnectionFactory::createConnection() { - return BoostConnection::create(ioService, eventLoop); + return BoostConnection::create(ioService, eventLoop); } } diff --git a/Swiften/Network/BoostConnectionFactory.h b/Swiften/Network/BoostConnectionFactory.h index c98180c..46502de 100644 --- a/Swiften/Network/BoostConnectionFactory.h +++ b/Swiften/Network/BoostConnectionFactory.h @@ -13,16 +13,16 @@ #include <Swiften/Network/ConnectionFactory.h> namespace Swift { - class BoostConnection; + class BoostConnection; - class SWIFTEN_API BoostConnectionFactory : public ConnectionFactory { - public: - BoostConnectionFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop); + class SWIFTEN_API BoostConnectionFactory : public ConnectionFactory { + public: + BoostConnectionFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop); - virtual boost::shared_ptr<Connection> createConnection(); + virtual boost::shared_ptr<Connection> createConnection(); - private: - boost::shared_ptr<boost::asio::io_service> ioService; - EventLoop* eventLoop; - }; + private: + boost::shared_ptr<boost::asio::io_service> ioService; + EventLoop* eventLoop; + }; } diff --git a/Swiften/Network/BoostConnectionServer.cpp b/Swiften/Network/BoostConnectionServer.cpp index 48b323d..0b20a7f 100644 --- a/Swiften/Network/BoostConnectionServer.cpp +++ b/Swiften/Network/BoostConnectionServer.cpp @@ -26,84 +26,84 @@ BoostConnectionServer::BoostConnectionServer(const HostAddress &address, int por } void BoostConnectionServer::start() { - boost::optional<Error> error = tryStart(); - if (error) { - eventLoop->postEvent(boost::bind(boost::ref(onStopped), *error), shared_from_this()); - } + boost::optional<Error> error = tryStart(); + if (error) { + eventLoop->postEvent(boost::bind(boost::ref(onStopped), *error), shared_from_this()); + } } boost::optional<BoostConnectionServer::Error> BoostConnectionServer::tryStart() { - try { - assert(!acceptor_); - boost::asio::ip::tcp::endpoint endpoint; - if (address_.isValid()) { - endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), boost::numeric_cast<unsigned short>(port_)); - } - else { - endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), boost::numeric_cast<unsigned short>(port_)); - } - acceptor_ = new boost::asio::ip::tcp::acceptor(*ioService_, endpoint); - if (endpoint.protocol() == boost::asio::ip::tcp::v6()) { - boost::system::error_code ec; - acceptor_->set_option(boost::asio::ip::v6_only(false), ec); - SWIFT_LOG_ASSERT(ec, warning) << "IPv4/IPv6 dual-stack support is not supported on this platform." << std::endl; - } - acceptNextConnection(); - } - catch (const boost::system::system_error& e) { - if (e.code() == boost::asio::error::address_in_use) { - return Conflict; - } - else { - return UnknownError; - } - } - return boost::optional<Error>(); + try { + assert(!acceptor_); + boost::asio::ip::tcp::endpoint endpoint; + if (address_.isValid()) { + endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), boost::numeric_cast<unsigned short>(port_)); + } + else { + endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), boost::numeric_cast<unsigned short>(port_)); + } + acceptor_ = new boost::asio::ip::tcp::acceptor(*ioService_, endpoint); + if (endpoint.protocol() == boost::asio::ip::tcp::v6()) { + boost::system::error_code ec; + acceptor_->set_option(boost::asio::ip::v6_only(false), ec); + SWIFT_LOG_ASSERT(ec, warning) << "IPv4/IPv6 dual-stack support is not supported on this platform." << std::endl; + } + acceptNextConnection(); + } + catch (const boost::system::system_error& e) { + if (e.code() == boost::asio::error::address_in_use) { + return Conflict; + } + else { + return UnknownError; + } + } + return boost::optional<Error>(); } void BoostConnectionServer::stop() { - stop(boost::optional<Error>()); + stop(boost::optional<Error>()); } void BoostConnectionServer::stop(boost::optional<Error> e) { - if (acceptor_) { - acceptor_->close(); - delete acceptor_; - acceptor_ = NULL; - } - eventLoop->postEvent(boost::bind(boost::ref(onStopped), e), shared_from_this()); + if (acceptor_) { + acceptor_->close(); + delete acceptor_; + acceptor_ = NULL; + } + eventLoop->postEvent(boost::bind(boost::ref(onStopped), e), shared_from_this()); } void BoostConnectionServer::acceptNextConnection() { - BoostConnection::ref newConnection(BoostConnection::create(ioService_, eventLoop)); - acceptor_->async_accept(newConnection->getSocket(), - boost::bind(&BoostConnectionServer::handleAccept, shared_from_this(), newConnection, boost::asio::placeholders::error)); + BoostConnection::ref newConnection(BoostConnection::create(ioService_, eventLoop)); + acceptor_->async_accept(newConnection->getSocket(), + boost::bind(&BoostConnectionServer::handleAccept, shared_from_this(), newConnection, boost::asio::placeholders::error)); } void BoostConnectionServer::handleAccept(boost::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error) { - if (error) { - eventLoop->postEvent( - boost::bind( - &BoostConnectionServer::stop, shared_from_this(), UnknownError), - shared_from_this()); - } - else { - eventLoop->postEvent( - boost::bind(boost::ref(onNewConnection), newConnection), - shared_from_this()); - newConnection->listen(); - acceptNextConnection(); - } + if (error) { + eventLoop->postEvent( + boost::bind( + &BoostConnectionServer::stop, shared_from_this(), UnknownError), + shared_from_this()); + } + else { + eventLoop->postEvent( + boost::bind(boost::ref(onNewConnection), newConnection), + shared_from_this()); + newConnection->listen(); + acceptNextConnection(); + } } HostAddressPort BoostConnectionServer::getAddressPort() const { - if (acceptor_) { - return HostAddressPort(acceptor_->local_endpoint()); - } - else { - return HostAddressPort(); - } + if (acceptor_) { + return HostAddressPort(acceptor_->local_endpoint()); + } + else { + return HostAddressPort(); + } } } diff --git a/Swiften/Network/BoostConnectionServer.h b/Swiften/Network/BoostConnectionServer.h index 042cc24..8ee2a6d 100644 --- a/Swiften/Network/BoostConnectionServer.h +++ b/Swiften/Network/BoostConnectionServer.h @@ -19,39 +19,39 @@ #include <Swiften/Network/ConnectionServer.h> namespace Swift { - class SWIFTEN_API BoostConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<BoostConnectionServer> { - public: - typedef boost::shared_ptr<BoostConnectionServer> ref; + class SWIFTEN_API BoostConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<BoostConnectionServer> { + public: + typedef boost::shared_ptr<BoostConnectionServer> ref; - static ref create(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { - return ref(new BoostConnectionServer(port, ioService, eventLoop)); - } + static ref create(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { + return ref(new BoostConnectionServer(port, ioService, eventLoop)); + } - static ref create(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { - return ref(new BoostConnectionServer(address, port, ioService, eventLoop)); - } + static ref create(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { + return ref(new BoostConnectionServer(address, port, ioService, eventLoop)); + } - virtual boost::optional<Error> tryStart(); // FIXME: This should become the new start - virtual void start(); - virtual void stop(); + virtual boost::optional<Error> tryStart(); // FIXME: This should become the new start + virtual void start(); + virtual void stop(); - virtual HostAddressPort getAddressPort() const; + virtual HostAddressPort getAddressPort() const; - boost::signal<void (boost::optional<Error>)> onStopped; + boost::signal<void (boost::optional<Error>)> onStopped; - private: - BoostConnectionServer(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); - BoostConnectionServer(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); + private: + BoostConnectionServer(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); + BoostConnectionServer(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); - void stop(boost::optional<Error> e); - void acceptNextConnection(); - void handleAccept(boost::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error); + void stop(boost::optional<Error> e); + void acceptNextConnection(); + void handleAccept(boost::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error); - private: - HostAddress address_; - int port_; - boost::shared_ptr<boost::asio::io_service> ioService_; - EventLoop* eventLoop; - boost::asio::ip::tcp::acceptor* acceptor_; - }; + private: + HostAddress address_; + int port_; + boost::shared_ptr<boost::asio::io_service> ioService_; + EventLoop* eventLoop; + boost::asio::ip::tcp::acceptor* acceptor_; + }; } diff --git a/Swiften/Network/BoostConnectionServerFactory.cpp b/Swiften/Network/BoostConnectionServerFactory.cpp index 12173c3..25afdb6 100644 --- a/Swiften/Network/BoostConnectionServerFactory.cpp +++ b/Swiften/Network/BoostConnectionServerFactory.cpp @@ -20,11 +20,11 @@ BoostConnectionServerFactory::BoostConnectionServerFactory(boost::shared_ptr<boo } boost::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(int port) { - return BoostConnectionServer::create(port, ioService, eventLoop); + return BoostConnectionServer::create(port, ioService, eventLoop); } boost::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(const Swift::HostAddress &hostAddress, int port) { - return BoostConnectionServer::create(hostAddress, port, ioService, eventLoop); + return BoostConnectionServer::create(hostAddress, port, ioService, eventLoop); } } diff --git a/Swiften/Network/BoostConnectionServerFactory.h b/Swiften/Network/BoostConnectionServerFactory.h index 831ab45..1e0daa3 100644 --- a/Swiften/Network/BoostConnectionServerFactory.h +++ b/Swiften/Network/BoostConnectionServerFactory.h @@ -19,18 +19,18 @@ #include <Swiften/Network/ConnectionServerFactory.h> namespace Swift { - class ConnectionServer; + class ConnectionServer; - class SWIFTEN_API BoostConnectionServerFactory : public ConnectionServerFactory { - public: - BoostConnectionServerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop); + class SWIFTEN_API BoostConnectionServerFactory : public ConnectionServerFactory { + public: + BoostConnectionServerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop); - virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port); + virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port); - virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port); + virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port); - private: - boost::shared_ptr<boost::asio::io_service> ioService; - EventLoop* eventLoop; - }; + private: + boost::shared_ptr<boost::asio::io_service> ioService; + EventLoop* eventLoop; + }; } diff --git a/Swiften/Network/BoostIOServiceThread.cpp b/Swiften/Network/BoostIOServiceThread.cpp index af74c85..ba9dd5b 100644 --- a/Swiften/Network/BoostIOServiceThread.cpp +++ b/Swiften/Network/BoostIOServiceThread.cpp @@ -11,27 +11,27 @@ namespace Swift { BoostIOServiceThread::BoostIOServiceThread(boost::shared_ptr<boost::asio::io_service> ioService) { - if (!!ioService) { - ioService_ = ioService; - thread_ = NULL; - } - else { - ioService_ = boost::make_shared<boost::asio::io_service>(); - thread_ = new boost::thread(boost::bind(&BoostIOServiceThread::doRun, this)); - } + if (!!ioService) { + ioService_ = ioService; + thread_ = NULL; + } + else { + ioService_ = boost::make_shared<boost::asio::io_service>(); + thread_ = new boost::thread(boost::bind(&BoostIOServiceThread::doRun, this)); + } } BoostIOServiceThread::~BoostIOServiceThread() { - if (thread_) { - ioService_->stop(); - thread_->join(); - delete thread_; - } + if (thread_) { + ioService_->stop(); + thread_->join(); + delete thread_; + } } void BoostIOServiceThread::doRun() { - boost::asio::io_service::work work(*ioService_); - ioService_->run(); + boost::asio::io_service::work work(*ioService_); + ioService_->run(); } } diff --git a/Swiften/Network/BoostIOServiceThread.h b/Swiften/Network/BoostIOServiceThread.h index f493dfb..54f1840 100644 --- a/Swiften/Network/BoostIOServiceThread.h +++ b/Swiften/Network/BoostIOServiceThread.h @@ -13,28 +13,28 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API BoostIOServiceThread { - public: - /** - * Construct the object. - * @param ioService If this optional parameter is provided, the behaviour - * of this class changes completely - it no longer spawns its own thread - * and instead acts as a simple wrapper of the io_service. Use this if - * you are re-using an io_service from elsewhere (particularly if you - * are using the BoostASIOEventLoop). - */ - BoostIOServiceThread(boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>()); - ~BoostIOServiceThread(); + class SWIFTEN_API BoostIOServiceThread { + public: + /** + * Construct the object. + * @param ioService If this optional parameter is provided, the behaviour + * of this class changes completely - it no longer spawns its own thread + * and instead acts as a simple wrapper of the io_service. Use this if + * you are re-using an io_service from elsewhere (particularly if you + * are using the BoostASIOEventLoop). + */ + BoostIOServiceThread(boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>()); + ~BoostIOServiceThread(); - boost::shared_ptr<boost::asio::io_service> getIOService() const { - return ioService_; - } + boost::shared_ptr<boost::asio::io_service> getIOService() const { + return ioService_; + } - private: - void doRun(); + private: + void doRun(); - private: - boost::shared_ptr<boost::asio::io_service> ioService_; - boost::thread* thread_; - }; + private: + boost::shared_ptr<boost::asio::io_service> ioService_; + boost::thread* thread_; + }; } diff --git a/Swiften/Network/BoostNetworkFactories.cpp b/Swiften/Network/BoostNetworkFactories.cpp index 871a38b..40282f2 100644 --- a/Swiften/Network/BoostNetworkFactories.cpp +++ b/Swiften/Network/BoostNetworkFactories.cpp @@ -29,44 +29,44 @@ namespace Swift { BoostNetworkFactories::BoostNetworkFactories(EventLoop* eventLoop, boost::shared_ptr<boost::asio::io_service> ioService) : ioServiceThread(ioService), eventLoop(eventLoop) { - timerFactory = new BoostTimerFactory(ioServiceThread.getIOService(), eventLoop); - connectionFactory = new BoostConnectionFactory(ioServiceThread.getIOService(), eventLoop); - connectionServerFactory = new BoostConnectionServerFactory(ioServiceThread.getIOService(), eventLoop); + timerFactory = new BoostTimerFactory(ioServiceThread.getIOService(), eventLoop); + connectionFactory = new BoostConnectionFactory(ioServiceThread.getIOService(), eventLoop); + connectionServerFactory = new BoostConnectionServerFactory(ioServiceThread.getIOService(), eventLoop); #ifdef SWIFT_EXPERIMENTAL_FT - natTraverser = new PlatformNATTraversalWorker(eventLoop); + natTraverser = new PlatformNATTraversalWorker(eventLoop); #else - natTraverser = new NullNATTraverser(eventLoop); + natTraverser = new NullNATTraverser(eventLoop); #endif - networkEnvironment = new PlatformNetworkEnvironment(); - xmlParserFactory = new PlatformXMLParserFactory(); - tlsFactories = new PlatformTLSFactories(); - proxyProvider = new PlatformProxyProvider(); - idnConverter = PlatformIDNConverter::create(); + networkEnvironment = new PlatformNetworkEnvironment(); + xmlParserFactory = new PlatformXMLParserFactory(); + tlsFactories = new PlatformTLSFactories(); + proxyProvider = new PlatformProxyProvider(); + idnConverter = PlatformIDNConverter::create(); #ifdef USE_UNBOUND - // TODO: What to do about idnConverter. - domainNameResolver = new UnboundDomainNameResolver(idnConverter, ioServiceThread.getIOService(), eventLoop); + // TODO: What to do about idnConverter. + domainNameResolver = new UnboundDomainNameResolver(idnConverter, ioServiceThread.getIOService(), eventLoop); #else - domainNameResolver = new PlatformDomainNameResolver(idnConverter, eventLoop); + domainNameResolver = new PlatformDomainNameResolver(idnConverter, eventLoop); #endif - cryptoProvider = PlatformCryptoProvider::create(); + cryptoProvider = PlatformCryptoProvider::create(); } BoostNetworkFactories::~BoostNetworkFactories() { - delete cryptoProvider; - delete domainNameResolver; - delete idnConverter; - delete proxyProvider; - delete tlsFactories; - delete xmlParserFactory; - delete networkEnvironment; - delete natTraverser; - delete connectionServerFactory; - delete connectionFactory; - delete timerFactory; + delete cryptoProvider; + delete domainNameResolver; + delete idnConverter; + delete proxyProvider; + delete tlsFactories; + delete xmlParserFactory; + delete networkEnvironment; + delete natTraverser; + delete connectionServerFactory; + delete connectionFactory; + delete timerFactory; } TLSContextFactory* BoostNetworkFactories::getTLSContextFactory() const { - return tlsFactories->getTLSContextFactory(); + return tlsFactories->getTLSContextFactory(); } } diff --git a/Swiften/Network/BoostNetworkFactories.h b/Swiften/Network/BoostNetworkFactories.h index 12755b9..ccacbf0 100644 --- a/Swiften/Network/BoostNetworkFactories.h +++ b/Swiften/Network/BoostNetworkFactories.h @@ -12,83 +12,83 @@ #include <Swiften/Network/NetworkFactories.h> namespace Swift { - class EventLoop; - class NATTraverser; - class PlatformTLSFactories; - - class SWIFTEN_API BoostNetworkFactories : public NetworkFactories { - public: - /** - * Construct the network factories, using the provided EventLoop. - * @param ioService If this optional parameter is provided, it will be - * used for the construction of the BoostIOServiceThread. - */ - BoostNetworkFactories(EventLoop* eventLoop, boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>()); - virtual ~BoostNetworkFactories(); - - virtual TimerFactory* getTimerFactory() const SWIFTEN_OVERRIDE { - return timerFactory; - } - - virtual ConnectionFactory* getConnectionFactory() const SWIFTEN_OVERRIDE { - return connectionFactory; - } - - BoostIOServiceThread* getIOServiceThread() { - return &ioServiceThread; - } - - DomainNameResolver* getDomainNameResolver() const SWIFTEN_OVERRIDE { - return domainNameResolver; - } - - ConnectionServerFactory* getConnectionServerFactory() const SWIFTEN_OVERRIDE { - return connectionServerFactory; - } - - NetworkEnvironment* getNetworkEnvironment() const SWIFTEN_OVERRIDE { - return networkEnvironment; - } - - NATTraverser* getNATTraverser() const SWIFTEN_OVERRIDE { - return natTraverser; - } - - virtual XMLParserFactory* getXMLParserFactory() const SWIFTEN_OVERRIDE { - return xmlParserFactory; - } - - virtual TLSContextFactory* getTLSContextFactory() const SWIFTEN_OVERRIDE; - - virtual ProxyProvider* getProxyProvider() const SWIFTEN_OVERRIDE { - return proxyProvider; - } - - virtual EventLoop* getEventLoop() const SWIFTEN_OVERRIDE { - return eventLoop; - } - - virtual IDNConverter* getIDNConverter() const SWIFTEN_OVERRIDE { - return idnConverter; - } - - virtual CryptoProvider* getCryptoProvider() const SWIFTEN_OVERRIDE { - return cryptoProvider; - } - - private: - BoostIOServiceThread ioServiceThread; - TimerFactory* timerFactory; - ConnectionFactory* connectionFactory; - DomainNameResolver* domainNameResolver; - ConnectionServerFactory* connectionServerFactory; - NATTraverser* natTraverser; - NetworkEnvironment* networkEnvironment; - XMLParserFactory* xmlParserFactory; - PlatformTLSFactories* tlsFactories; - ProxyProvider* proxyProvider; - EventLoop* eventLoop; - IDNConverter* idnConverter; - CryptoProvider* cryptoProvider; - }; + class EventLoop; + class NATTraverser; + class PlatformTLSFactories; + + class SWIFTEN_API BoostNetworkFactories : public NetworkFactories { + public: + /** + * Construct the network factories, using the provided EventLoop. + * @param ioService If this optional parameter is provided, it will be + * used for the construction of the BoostIOServiceThread. + */ + BoostNetworkFactories(EventLoop* eventLoop, boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>()); + virtual ~BoostNetworkFactories(); + + virtual TimerFactory* getTimerFactory() const SWIFTEN_OVERRIDE { + return timerFactory; + } + + virtual ConnectionFactory* getConnectionFactory() const SWIFTEN_OVERRIDE { + return connectionFactory; + } + + BoostIOServiceThread* getIOServiceThread() { + return &ioServiceThread; + } + + DomainNameResolver* getDomainNameResolver() const SWIFTEN_OVERRIDE { + return domainNameResolver; + } + + ConnectionServerFactory* getConnectionServerFactory() const SWIFTEN_OVERRIDE { + return connectionServerFactory; + } + + NetworkEnvironment* getNetworkEnvironment() const SWIFTEN_OVERRIDE { + return networkEnvironment; + } + + NATTraverser* getNATTraverser() const SWIFTEN_OVERRIDE { + return natTraverser; + } + + virtual XMLParserFactory* getXMLParserFactory() const SWIFTEN_OVERRIDE { + return xmlParserFactory; + } + + virtual TLSContextFactory* getTLSContextFactory() const SWIFTEN_OVERRIDE; + + virtual ProxyProvider* getProxyProvider() const SWIFTEN_OVERRIDE { + return proxyProvider; + } + + virtual EventLoop* getEventLoop() const SWIFTEN_OVERRIDE { + return eventLoop; + } + + virtual IDNConverter* getIDNConverter() const SWIFTEN_OVERRIDE { + return idnConverter; + } + + virtual CryptoProvider* getCryptoProvider() const SWIFTEN_OVERRIDE { + return cryptoProvider; + } + + private: + BoostIOServiceThread ioServiceThread; + TimerFactory* timerFactory; + ConnectionFactory* connectionFactory; + DomainNameResolver* domainNameResolver; + ConnectionServerFactory* connectionServerFactory; + NATTraverser* natTraverser; + NetworkEnvironment* networkEnvironment; + XMLParserFactory* xmlParserFactory; + PlatformTLSFactories* tlsFactories; + ProxyProvider* proxyProvider; + EventLoop* eventLoop; + IDNConverter* idnConverter; + CryptoProvider* cryptoProvider; + }; } diff --git a/Swiften/Network/BoostTimer.cpp b/Swiften/Network/BoostTimer.cpp index c30fe32..734a9c8 100644 --- a/Swiften/Network/BoostTimer.cpp +++ b/Swiften/Network/BoostTimer.cpp @@ -15,48 +15,48 @@ namespace Swift { BoostTimer::BoostTimer(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop) : - timeout(milliseconds), ioService(service), eventLoop(eventLoop), shuttingDown(false) { - timer.reset(new boost::asio::deadline_timer(*service)); + timeout(milliseconds), ioService(service), eventLoop(eventLoop), shuttingDown(false) { + timer.reset(new boost::asio::deadline_timer(*service)); } BoostTimer::~BoostTimer() { - { - boost::mutex::scoped_lock lockTimer(timerMutex); - timer.reset(); - } + { + boost::mutex::scoped_lock lockTimer(timerMutex); + timer.reset(); + } } void BoostTimer::start() { - { - boost::mutex::scoped_lock lockTimer(timerMutex); - shuttingDown = false; - timer->expires_from_now(boost::posix_time::milliseconds(timeout)); - timer->async_wait(boost::bind(&BoostTimer::handleTimerTick, shared_from_this(), boost::asio::placeholders::error)); - } + { + boost::mutex::scoped_lock lockTimer(timerMutex); + shuttingDown = false; + timer->expires_from_now(boost::posix_time::milliseconds(timeout)); + timer->async_wait(boost::bind(&BoostTimer::handleTimerTick, shared_from_this(), boost::asio::placeholders::error)); + } } void BoostTimer::stop() { - { - boost::mutex::scoped_lock lockTimer(timerMutex); - shuttingDown = true; - timer->cancel(); - eventLoop->removeEventsFromOwner(shared_from_this()); - } + { + boost::mutex::scoped_lock lockTimer(timerMutex); + shuttingDown = true; + timer->cancel(); + eventLoop->removeEventsFromOwner(shared_from_this()); + } } void BoostTimer::handleTimerTick(const boost::system::error_code& error) { - if (error) { - assert(error == boost::asio::error::operation_aborted); - } - else { - { - boost::mutex::scoped_lock lockTimer(timerMutex); - if (shuttingDown) { - return; - } - eventLoop->postEvent(boost::bind(boost::ref(onTick)), shared_from_this()); - } - } + if (error) { + assert(error == boost::asio::error::operation_aborted); + } + else { + { + boost::mutex::scoped_lock lockTimer(timerMutex); + if (shuttingDown) { + return; + } + eventLoop->postEvent(boost::bind(boost::ref(onTick)), shared_from_this()); + } + } } } diff --git a/Swiften/Network/BoostTimer.h b/Swiften/Network/BoostTimer.h index 3227031..79c71cd 100644 --- a/Swiften/Network/BoostTimer.h +++ b/Swiften/Network/BoostTimer.h @@ -17,32 +17,32 @@ #include <Swiften/Network/Timer.h> namespace Swift { - class EventLoop; + class EventLoop; - class SWIFTEN_API BoostTimer : public Timer, public EventOwner, public boost::enable_shared_from_this<BoostTimer> { - public: - typedef boost::shared_ptr<BoostTimer> ref; + class SWIFTEN_API BoostTimer : public Timer, public EventOwner, public boost::enable_shared_from_this<BoostTimer> { + public: + typedef boost::shared_ptr<BoostTimer> ref; - virtual ~BoostTimer(); + virtual ~BoostTimer(); - static ref create(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop) { - return ref(new BoostTimer(milliseconds, service, eventLoop)); - } + static ref create(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop) { + return ref(new BoostTimer(milliseconds, service, eventLoop)); + } - virtual void start(); - virtual void stop(); + virtual void start(); + virtual void stop(); - private: - BoostTimer(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop); + private: + BoostTimer(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop); - void handleTimerTick(const boost::system::error_code& error); + void handleTimerTick(const boost::system::error_code& error); - private: - int timeout; - boost::shared_ptr<boost::asio::io_service> ioService; - boost::scoped_ptr<boost::asio::deadline_timer> timer; - boost::mutex timerMutex; - EventLoop* eventLoop; - bool shuttingDown; - }; + private: + int timeout; + boost::shared_ptr<boost::asio::io_service> ioService; + boost::scoped_ptr<boost::asio::deadline_timer> timer; + boost::mutex timerMutex; + EventLoop* eventLoop; + bool shuttingDown; + }; } diff --git a/Swiften/Network/BoostTimerFactory.cpp b/Swiften/Network/BoostTimerFactory.cpp index 4281a1f..086eb60 100644 --- a/Swiften/Network/BoostTimerFactory.cpp +++ b/Swiften/Network/BoostTimerFactory.cpp @@ -14,7 +14,7 @@ BoostTimerFactory::BoostTimerFactory(boost::shared_ptr<boost::asio::io_service> } boost::shared_ptr<Timer> BoostTimerFactory::createTimer(int milliseconds) { - return BoostTimer::create(milliseconds, ioService, eventLoop); + return BoostTimer::create(milliseconds, ioService, eventLoop); } } diff --git a/Swiften/Network/BoostTimerFactory.h b/Swiften/Network/BoostTimerFactory.h index 328c64e..4fbabe9 100644 --- a/Swiften/Network/BoostTimerFactory.h +++ b/Swiften/Network/BoostTimerFactory.h @@ -13,17 +13,17 @@ #include <Swiften/Network/TimerFactory.h> namespace Swift { - class BoostTimer; - class EventLoop; + class BoostTimer; + class EventLoop; - class SWIFTEN_API BoostTimerFactory : public TimerFactory { - public: - BoostTimerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop); + class SWIFTEN_API BoostTimerFactory : public TimerFactory { + public: + BoostTimerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop); - virtual boost::shared_ptr<Timer> createTimer(int milliseconds); + virtual boost::shared_ptr<Timer> createTimer(int milliseconds); - private: - boost::shared_ptr<boost::asio::io_service> ioService; - EventLoop* eventLoop; - }; + private: + boost::shared_ptr<boost::asio::io_service> ioService; + EventLoop* eventLoop; + }; } diff --git a/Swiften/Network/CachingDomainNameResolver.cpp b/Swiften/Network/CachingDomainNameResolver.cpp index 8a2336b..d731eb9 100644 --- a/Swiften/Network/CachingDomainNameResolver.cpp +++ b/Swiften/Network/CachingDomainNameResolver.cpp @@ -18,13 +18,13 @@ CachingDomainNameResolver::~CachingDomainNameResolver() { } DomainNameServiceQuery::ref CachingDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) { - //TODO: Cache - return realResolver->createServiceQuery(serviceLookupPrefix, domain); + //TODO: Cache + return realResolver->createServiceQuery(serviceLookupPrefix, domain); } DomainNameAddressQuery::ref CachingDomainNameResolver::createAddressQuery(const std::string& name) { - //TODO: Cache - return realResolver->createAddressQuery(name); + //TODO: Cache + return realResolver->createAddressQuery(name); } } diff --git a/Swiften/Network/CachingDomainNameResolver.h b/Swiften/Network/CachingDomainNameResolver.h index 2a0b1b7..25cb86c 100644 --- a/Swiften/Network/CachingDomainNameResolver.h +++ b/Swiften/Network/CachingDomainNameResolver.h @@ -16,17 +16,17 @@ * FIXME: Does not do any caching yet. */ namespace Swift { - class EventLoop; + class EventLoop; - class SWIFTEN_API CachingDomainNameResolver : public DomainNameResolver { - public: - CachingDomainNameResolver(DomainNameResolver* realResolver, EventLoop* eventLoop); - ~CachingDomainNameResolver(); + class SWIFTEN_API CachingDomainNameResolver : public DomainNameResolver { + public: + CachingDomainNameResolver(DomainNameResolver* realResolver, EventLoop* eventLoop); + ~CachingDomainNameResolver(); - virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); - virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name); + virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); + virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name); - private: - DomainNameResolver* realResolver; - }; + private: + DomainNameResolver* realResolver; + }; } diff --git a/Swiften/Network/ChainedConnector.cpp b/Swiften/Network/ChainedConnector.cpp index 3cc4057..08c4aac 100644 --- a/Swiften/Network/ChainedConnector.cpp +++ b/Swiften/Network/ChainedConnector.cpp @@ -18,79 +18,79 @@ using namespace Swift; ChainedConnector::ChainedConnector( - const std::string& hostname, - int port, - const boost::optional<std::string>& serviceLookupPrefix, - DomainNameResolver* resolver, - const std::vector<ConnectionFactory*>& connectionFactories, - TimerFactory* timerFactory) : - hostname(hostname), - port(port), - serviceLookupPrefix(serviceLookupPrefix), - resolver(resolver), - connectionFactories(connectionFactories), - timerFactory(timerFactory), - timeoutMilliseconds(0) { + const std::string& hostname, + int port, + const boost::optional<std::string>& serviceLookupPrefix, + DomainNameResolver* resolver, + const std::vector<ConnectionFactory*>& connectionFactories, + TimerFactory* timerFactory) : + hostname(hostname), + port(port), + serviceLookupPrefix(serviceLookupPrefix), + resolver(resolver), + connectionFactories(connectionFactories), + timerFactory(timerFactory), + timeoutMilliseconds(0) { } ChainedConnector::~ChainedConnector() { - if (currentConnector) { - currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); - currentConnector->stop(); - currentConnector.reset(); - } + if (currentConnector) { + currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); + currentConnector->stop(); + currentConnector.reset(); + } } void ChainedConnector::setTimeoutMilliseconds(int milliseconds) { - timeoutMilliseconds = milliseconds; + timeoutMilliseconds = milliseconds; } void ChainedConnector::start() { - SWIFT_LOG(debug) << "Starting queued connector for " << hostname << std::endl; + SWIFT_LOG(debug) << "Starting queued connector for " << hostname << std::endl; - connectionFactoryQueue = std::deque<ConnectionFactory*>(connectionFactories.begin(), connectionFactories.end()); - tryNextConnectionFactory(); + connectionFactoryQueue = std::deque<ConnectionFactory*>(connectionFactories.begin(), connectionFactories.end()); + tryNextConnectionFactory(); } void ChainedConnector::stop() { - if (currentConnector) { - currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); - currentConnector->stop(); - currentConnector.reset(); - } - finish(boost::shared_ptr<Connection>(), boost::shared_ptr<Error>()); + if (currentConnector) { + currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); + currentConnector->stop(); + currentConnector.reset(); + } + finish(boost::shared_ptr<Connection>(), boost::shared_ptr<Error>()); } void ChainedConnector::tryNextConnectionFactory() { - assert(!currentConnector); - if (connectionFactoryQueue.empty()) { - SWIFT_LOG(debug) << "No more connection factories" << std::endl; - finish(boost::shared_ptr<Connection>(), lastError); - } - else { - ConnectionFactory* connectionFactory = connectionFactoryQueue.front(); - SWIFT_LOG(debug) << "Trying next connection factory: " << typeid(*connectionFactory).name() << std::endl; - connectionFactoryQueue.pop_front(); - currentConnector = Connector::create(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory); - currentConnector->setTimeoutMilliseconds(timeoutMilliseconds); - currentConnector->onConnectFinished.connect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); - currentConnector->start(); - } + assert(!currentConnector); + if (connectionFactoryQueue.empty()) { + SWIFT_LOG(debug) << "No more connection factories" << std::endl; + finish(boost::shared_ptr<Connection>(), lastError); + } + else { + ConnectionFactory* connectionFactory = connectionFactoryQueue.front(); + SWIFT_LOG(debug) << "Trying next connection factory: " << typeid(*connectionFactory).name() << std::endl; + connectionFactoryQueue.pop_front(); + currentConnector = Connector::create(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory); + currentConnector->setTimeoutMilliseconds(timeoutMilliseconds); + currentConnector->onConnectFinished.connect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); + currentConnector->start(); + } } void ChainedConnector::handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> error) { - SWIFT_LOG(debug) << "Connector finished" << std::endl; - currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); - lastError = error; - currentConnector.reset(); - if (connection) { - finish(connection, error); - } - else { - tryNextConnectionFactory(); - } + SWIFT_LOG(debug) << "Connector finished" << std::endl; + currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); + lastError = error; + currentConnector.reset(); + if (connection) { + finish(connection, error); + } + else { + tryNextConnectionFactory(); + } } void ChainedConnector::finish(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> error) { - onConnectFinished(connection, error); + onConnectFinished(connection, error); } diff --git a/Swiften/Network/ChainedConnector.h b/Swiften/Network/ChainedConnector.h index 9bcc961..416dccb 100644 --- a/Swiften/Network/ChainedConnector.h +++ b/Swiften/Network/ChainedConnector.h @@ -18,38 +18,38 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - class Connection; - class Connector; - class ConnectionFactory; - class TimerFactory; - class DomainNameResolver; - - class SWIFTEN_API ChainedConnector { - public: - ChainedConnector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, const std::vector<ConnectionFactory*>&, TimerFactory*); - ~ChainedConnector(); - - void setTimeoutMilliseconds(int milliseconds); - void start(); - void stop(); - - boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished; - - private: - void finish(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error>); - void tryNextConnectionFactory(); - void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error>); - - private: - std::string hostname; - int port; - boost::optional<std::string> serviceLookupPrefix; - DomainNameResolver* resolver; - std::vector<ConnectionFactory*> connectionFactories; - TimerFactory* timerFactory; - int timeoutMilliseconds; - std::deque<ConnectionFactory*> connectionFactoryQueue; - boost::shared_ptr<Connector> currentConnector; - boost::shared_ptr<Error> lastError; - }; + class Connection; + class Connector; + class ConnectionFactory; + class TimerFactory; + class DomainNameResolver; + + class SWIFTEN_API ChainedConnector { + public: + ChainedConnector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, const std::vector<ConnectionFactory*>&, TimerFactory*); + ~ChainedConnector(); + + void setTimeoutMilliseconds(int milliseconds); + void start(); + void stop(); + + boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished; + + private: + void finish(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error>); + void tryNextConnectionFactory(); + void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error>); + + private: + std::string hostname; + int port; + boost::optional<std::string> serviceLookupPrefix; + DomainNameResolver* resolver; + std::vector<ConnectionFactory*> connectionFactories; + TimerFactory* timerFactory; + int timeoutMilliseconds; + std::deque<ConnectionFactory*> connectionFactoryQueue; + boost::shared_ptr<Connector> currentConnector; + boost::shared_ptr<Error> lastError; + }; } diff --git a/Swiften/Network/Connection.h b/Swiften/Network/Connection.h index 39b63d4..c38b98f 100644 --- a/Swiften/Network/Connection.h +++ b/Swiften/Network/Connection.h @@ -13,32 +13,32 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - class HostAddressPort; - - class SWIFTEN_API Connection { - public: - typedef boost::shared_ptr<Connection> ref; - - enum Error { - ReadError, - WriteError - }; - - Connection(); - virtual ~Connection(); - - virtual void listen() = 0; - virtual void connect(const HostAddressPort& address) = 0; - virtual void disconnect() = 0; - virtual void write(const SafeByteArray& data) = 0; - - virtual HostAddressPort getLocalAddress() const = 0; - virtual HostAddressPort getRemoteAddress() const = 0; - - public: - boost::signal<void (bool /* error */)> onConnectFinished; - boost::signal<void (const boost::optional<Error>&)> onDisconnected; - boost::signal<void (boost::shared_ptr<SafeByteArray>)> onDataRead; - boost::signal<void ()> onDataWritten; - }; + class HostAddressPort; + + class SWIFTEN_API Connection { + public: + typedef boost::shared_ptr<Connection> ref; + + enum Error { + ReadError, + WriteError + }; + + Connection(); + virtual ~Connection(); + + virtual void listen() = 0; + virtual void connect(const HostAddressPort& address) = 0; + virtual void disconnect() = 0; + virtual void write(const SafeByteArray& data) = 0; + + virtual HostAddressPort getLocalAddress() const = 0; + virtual HostAddressPort getRemoteAddress() const = 0; + + public: + boost::signal<void (bool /* error */)> onConnectFinished; + boost::signal<void (const boost::optional<Error>&)> onDisconnected; + boost::signal<void (boost::shared_ptr<SafeByteArray>)> onDataRead; + boost::signal<void ()> onDataWritten; + }; } diff --git a/Swiften/Network/ConnectionFactory.h b/Swiften/Network/ConnectionFactory.h index d8e1b71..fd65908 100644 --- a/Swiften/Network/ConnectionFactory.h +++ b/Swiften/Network/ConnectionFactory.h @@ -11,12 +11,12 @@ #include <Swiften/Base/API.h> namespace Swift { - class Connection; + class Connection; - class SWIFTEN_API ConnectionFactory { - public: - virtual ~ConnectionFactory(); + class SWIFTEN_API ConnectionFactory { + public: + virtual ~ConnectionFactory(); - virtual boost::shared_ptr<Connection> createConnection() = 0; - }; + virtual boost::shared_ptr<Connection> createConnection() = 0; + }; } diff --git a/Swiften/Network/ConnectionServer.h b/Swiften/Network/ConnectionServer.h index 7b0cdd1..a8c77eb 100644 --- a/Swiften/Network/ConnectionServer.h +++ b/Swiften/Network/ConnectionServer.h @@ -15,23 +15,23 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class SWIFTEN_API ConnectionServer { - public: - enum Error { - Conflict, - UnknownError - }; + class SWIFTEN_API ConnectionServer { + public: + enum Error { + Conflict, + UnknownError + }; - virtual ~ConnectionServer(); + virtual ~ConnectionServer(); - virtual HostAddressPort getAddressPort() const = 0; + virtual HostAddressPort getAddressPort() const = 0; - virtual boost::optional<Error> tryStart() = 0; // FIXME: This should become the new start + virtual boost::optional<Error> tryStart() = 0; // FIXME: This should become the new start - virtual void start() = 0; + virtual void start() = 0; - virtual void stop() = 0; + virtual void stop() = 0; - boost::signal<void (boost::shared_ptr<Connection>)> onNewConnection; - }; + boost::signal<void (boost::shared_ptr<Connection>)> onNewConnection; + }; } diff --git a/Swiften/Network/ConnectionServerFactory.h b/Swiften/Network/ConnectionServerFactory.h index 8e488c9..7f988bf 100644 --- a/Swiften/Network/ConnectionServerFactory.h +++ b/Swiften/Network/ConnectionServerFactory.h @@ -17,15 +17,15 @@ #include <Swiften/Base/API.h> namespace Swift { - class ConnectionServer; - class HostAddress; + class ConnectionServer; + class HostAddress; - class SWIFTEN_API ConnectionServerFactory { - public: - virtual ~ConnectionServerFactory(); + class SWIFTEN_API ConnectionServerFactory { + public: + virtual ~ConnectionServerFactory(); - virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) = 0; + virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) = 0; - virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) = 0; - }; + virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) = 0; + }; } diff --git a/Swiften/Network/Connector.cpp b/Swiften/Network/Connector.cpp index 2775c97..bd25e70 100644 --- a/Swiften/Network/Connector.cpp +++ b/Swiften/Network/Connector.cpp @@ -21,174 +21,174 @@ Connector::Connector(const std::string& hostname, int port, const boost::optiona } void Connector::setTimeoutMilliseconds(int milliseconds) { - timeoutMilliseconds = milliseconds; + timeoutMilliseconds = milliseconds; } void Connector::start() { - SWIFT_LOG(debug) << "Starting connector for " << hostname << std::endl; - assert(!currentConnection); - assert(!serviceQuery); - assert(!timer); - queriedAllServices = false; - if (timeoutMilliseconds > 0) { - timer = timerFactory->createTimer(timeoutMilliseconds); - timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this())); - } - if (serviceLookupPrefix) { - serviceQuery = resolver->createServiceQuery(*serviceLookupPrefix, hostname); - serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1)); - serviceQuery->run(); - } - else if (HostAddress(hostname).isValid()) { - // hostname is already a valid address; skip name lookup. - foundSomeDNS = true; - addressQueryResults.push_back(HostAddress(hostname)); - tryNextAddress(); - } else { - queryAddress(hostname); - } + SWIFT_LOG(debug) << "Starting connector for " << hostname << std::endl; + assert(!currentConnection); + assert(!serviceQuery); + assert(!timer); + queriedAllServices = false; + if (timeoutMilliseconds > 0) { + timer = timerFactory->createTimer(timeoutMilliseconds); + timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this())); + } + if (serviceLookupPrefix) { + serviceQuery = resolver->createServiceQuery(*serviceLookupPrefix, hostname); + serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1)); + serviceQuery->run(); + } + else if (HostAddress(hostname).isValid()) { + // hostname is already a valid address; skip name lookup. + foundSomeDNS = true; + addressQueryResults.push_back(HostAddress(hostname)); + tryNextAddress(); + } else { + queryAddress(hostname); + } } void Connector::stop() { - if (currentConnection) { - currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); - currentConnection->disconnect(); - } - finish(boost::shared_ptr<Connection>()); + if (currentConnection) { + currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); + currentConnection->disconnect(); + } + finish(boost::shared_ptr<Connection>()); } void Connector::queryAddress(const std::string& hostname) { - assert(!addressQuery); - addressQuery = resolver->createAddressQuery(hostname); - addressQuery->onResult.connect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2)); - addressQuery->run(); + assert(!addressQuery); + addressQuery = resolver->createAddressQuery(hostname); + addressQuery->onResult.connect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2)); + addressQuery->run(); } void Connector::handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result) { - SWIFT_LOG(debug) << result.size() << " SRV result(s)" << std::endl; - serviceQueryResults = std::deque<DomainNameServiceQuery::Result>(result.begin(), result.end()); - serviceQuery.reset(); - if (!serviceQueryResults.empty()) { - foundSomeDNS = true; - } - tryNextServiceOrFallback(); + SWIFT_LOG(debug) << result.size() << " SRV result(s)" << std::endl; + serviceQueryResults = std::deque<DomainNameServiceQuery::Result>(result.begin(), result.end()); + serviceQuery.reset(); + if (!serviceQueryResults.empty()) { + foundSomeDNS = true; + } + tryNextServiceOrFallback(); } void Connector::tryNextServiceOrFallback() { - if (queriedAllServices) { - SWIFT_LOG(debug) << "Queried all services" << std::endl; - finish(boost::shared_ptr<Connection>()); - } - else if (serviceQueryResults.empty()) { - SWIFT_LOG(debug) << "Falling back on A resolution" << std::endl; - // Fall back on simple address resolving - queriedAllServices = true; - queryAddress(hostname); - } - else { - SWIFT_LOG(debug) << "Querying next address" << std::endl; - queryAddress(serviceQueryResults.front().hostname); - } + if (queriedAllServices) { + SWIFT_LOG(debug) << "Queried all services" << std::endl; + finish(boost::shared_ptr<Connection>()); + } + else if (serviceQueryResults.empty()) { + SWIFT_LOG(debug) << "Falling back on A resolution" << std::endl; + // Fall back on simple address resolving + queriedAllServices = true; + queryAddress(hostname); + } + else { + SWIFT_LOG(debug) << "Querying next address" << std::endl; + queryAddress(serviceQueryResults.front().hostname); + } } void Connector::handleAddressQueryResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error) { - SWIFT_LOG(debug) << addresses.size() << " addresses" << std::endl; - addressQuery.reset(); - if (error || addresses.empty()) { - if (!serviceQueryResults.empty()) { - serviceQueryResults.pop_front(); - } - tryNextServiceOrFallback(); - } - else { - foundSomeDNS = true; - addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end()); - tryNextAddress(); - } + SWIFT_LOG(debug) << addresses.size() << " addresses" << std::endl; + addressQuery.reset(); + if (error || addresses.empty()) { + if (!serviceQueryResults.empty()) { + serviceQueryResults.pop_front(); + } + tryNextServiceOrFallback(); + } + else { + foundSomeDNS = true; + addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end()); + tryNextAddress(); + } } void Connector::tryNextAddress() { - if (addressQueryResults.empty()) { - SWIFT_LOG(debug) << "Done trying addresses. Moving on." << std::endl; - // Done trying all addresses. Move on to the next host. - if (!serviceQueryResults.empty()) { - serviceQueryResults.pop_front(); - } - tryNextServiceOrFallback(); - } - else { - SWIFT_LOG(debug) << "Trying next address" << std::endl; - HostAddress address = addressQueryResults.front(); - addressQueryResults.pop_front(); - - int connectPort = (port == -1 ? 5222 : port); - if (!serviceQueryResults.empty()) { - connectPort = serviceQueryResults.front().port; - } - - tryConnect(HostAddressPort(address, connectPort)); - } + if (addressQueryResults.empty()) { + SWIFT_LOG(debug) << "Done trying addresses. Moving on." << std::endl; + // Done trying all addresses. Move on to the next host. + if (!serviceQueryResults.empty()) { + serviceQueryResults.pop_front(); + } + tryNextServiceOrFallback(); + } + else { + SWIFT_LOG(debug) << "Trying next address" << std::endl; + HostAddress address = addressQueryResults.front(); + addressQueryResults.pop_front(); + + int connectPort = (port == -1 ? 5222 : port); + if (!serviceQueryResults.empty()) { + connectPort = serviceQueryResults.front().port; + } + + tryConnect(HostAddressPort(address, connectPort)); + } } void Connector::tryConnect(const HostAddressPort& target) { - assert(!currentConnection); - SWIFT_LOG(debug) << "Trying to connect to " << target.getAddress().toString() << ":" << target.getPort() << std::endl; - currentConnection = connectionFactory->createConnection(); - currentConnection->onConnectFinished.connect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); - currentConnection->connect(target); - if (timer) { - timer->start(); - } + assert(!currentConnection); + SWIFT_LOG(debug) << "Trying to connect to " << target.getAddress().toString() << ":" << target.getPort() << std::endl; + currentConnection = connectionFactory->createConnection(); + currentConnection->onConnectFinished.connect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); + currentConnection->connect(target); + if (timer) { + timer->start(); + } } void Connector::handleConnectionConnectFinished(bool error) { - SWIFT_LOG(debug) << "ConnectFinished: " << (error ? "error" : "success") << std::endl; - if (timer) { - timer->stop(); - timer.reset(); - } - currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); - if (error) { - currentConnection.reset(); - if (!addressQueryResults.empty()) { - tryNextAddress(); - } - else { - if (!serviceQueryResults.empty()) { - serviceQueryResults.pop_front(); - } - tryNextServiceOrFallback(); - } - } - else { - finish(currentConnection); - } + SWIFT_LOG(debug) << "ConnectFinished: " << (error ? "error" : "success") << std::endl; + if (timer) { + timer->stop(); + timer.reset(); + } + currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); + if (error) { + currentConnection.reset(); + if (!addressQueryResults.empty()) { + tryNextAddress(); + } + else { + if (!serviceQueryResults.empty()) { + serviceQueryResults.pop_front(); + } + tryNextServiceOrFallback(); + } + } + else { + finish(currentConnection); + } } void Connector::finish(boost::shared_ptr<Connection> connection) { - if (timer) { - timer->stop(); - timer->onTick.disconnect(boost::bind(&Connector::handleTimeout, shared_from_this())); - timer.reset(); - } - if (serviceQuery) { - serviceQuery->onResult.disconnect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1)); - serviceQuery.reset(); - } - if (addressQuery) { - addressQuery->onResult.disconnect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2)); - addressQuery.reset(); - } - if (currentConnection) { - currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); - currentConnection.reset(); - } - onConnectFinished(connection, (connection || foundSomeDNS) ? boost::shared_ptr<Error>() : boost::make_shared<DomainNameResolveError>()); + if (timer) { + timer->stop(); + timer->onTick.disconnect(boost::bind(&Connector::handleTimeout, shared_from_this())); + timer.reset(); + } + if (serviceQuery) { + serviceQuery->onResult.disconnect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1)); + serviceQuery.reset(); + } + if (addressQuery) { + addressQuery->onResult.disconnect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2)); + addressQuery.reset(); + } + if (currentConnection) { + currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); + currentConnection.reset(); + } + onConnectFinished(connection, (connection || foundSomeDNS) ? boost::shared_ptr<Error>() : boost::make_shared<DomainNameResolveError>()); } void Connector::handleTimeout() { - SWIFT_LOG(debug) << "Timeout" << std::endl; - handleConnectionConnectFinished(true); + SWIFT_LOG(debug) << "Timeout" << std::endl; + handleConnectionConnectFinished(true); } } diff --git a/Swiften/Network/Connector.h b/Swiften/Network/Connector.h index 3ed76fa..52486b6 100644 --- a/Swiften/Network/Connector.h +++ b/Swiften/Network/Connector.h @@ -21,61 +21,61 @@ #include <Swiften/Network/Timer.h> namespace Swift { - class DomainNameAddressQuery; - class DomainNameResolver; - class ConnectionFactory; - class TimerFactory; + class DomainNameAddressQuery; + class DomainNameResolver; + class ConnectionFactory; + class TimerFactory; - class SWIFTEN_API Connector : public boost::bsignals::trackable, public boost::enable_shared_from_this<Connector> { - public: - typedef boost::shared_ptr<Connector> ref; + class SWIFTEN_API Connector : public boost::bsignals::trackable, public boost::enable_shared_from_this<Connector> { + public: + typedef boost::shared_ptr<Connector> ref; - static Connector::ref create(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { - return ref(new Connector(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory)); - } + static Connector::ref create(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { + return ref(new Connector(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory)); + } - void setTimeoutMilliseconds(int milliseconds); - /** - * Start the connection attempt. - * Note that after calling this method, the caller is responsible for calling #stop() - * if it wants to cancel it. Not doing so can leak references. - */ - void start(); - void stop(); + void setTimeoutMilliseconds(int milliseconds); + /** + * Start the connection attempt. + * Note that after calling this method, the caller is responsible for calling #stop() + * if it wants to cancel it. Not doing so can leak references. + */ + void start(); + void stop(); - boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished; + boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished; - private: - Connector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, ConnectionFactory*, TimerFactory*); + private: + Connector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, ConnectionFactory*, TimerFactory*); - void handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result); - void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error); - void queryAddress(const std::string& hostname); + void handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result); + void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error); + void queryAddress(const std::string& hostname); - void tryNextServiceOrFallback(); - void tryNextAddress(); - void tryConnect(const HostAddressPort& target); + void tryNextServiceOrFallback(); + void tryNextAddress(); + void tryConnect(const HostAddressPort& target); - void handleConnectionConnectFinished(bool error); - void finish(boost::shared_ptr<Connection>); - void handleTimeout(); + void handleConnectionConnectFinished(bool error); + void finish(boost::shared_ptr<Connection>); + void handleTimeout(); - private: - std::string hostname; - int port; - boost::optional<std::string> serviceLookupPrefix; - DomainNameResolver* resolver; - ConnectionFactory* connectionFactory; - TimerFactory* timerFactory; - int timeoutMilliseconds; - boost::shared_ptr<Timer> timer; - boost::shared_ptr<DomainNameServiceQuery> serviceQuery; - std::deque<DomainNameServiceQuery::Result> serviceQueryResults; - boost::shared_ptr<DomainNameAddressQuery> addressQuery; - std::deque<HostAddress> addressQueryResults; - bool queriedAllServices; - boost::shared_ptr<Connection> currentConnection; - bool foundSomeDNS; - }; + private: + std::string hostname; + int port; + boost::optional<std::string> serviceLookupPrefix; + DomainNameResolver* resolver; + ConnectionFactory* connectionFactory; + TimerFactory* timerFactory; + int timeoutMilliseconds; + boost::shared_ptr<Timer> timer; + boost::shared_ptr<DomainNameServiceQuery> serviceQuery; + std::deque<DomainNameServiceQuery::Result> serviceQueryResults; + boost::shared_ptr<DomainNameAddressQuery> addressQuery; + std::deque<HostAddress> addressQueryResults; + bool queriedAllServices; + boost::shared_ptr<Connection> currentConnection; + bool foundSomeDNS; + }; } diff --git a/Swiften/Network/DomainNameAddressQuery.h b/Swiften/Network/DomainNameAddressQuery.h index 7b4b9b0..10bcd5a 100644 --- a/Swiften/Network/DomainNameAddressQuery.h +++ b/Swiften/Network/DomainNameAddressQuery.h @@ -14,14 +14,14 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class DomainNameAddressQuery { - public: - typedef boost::shared_ptr<DomainNameAddressQuery> ref; + class DomainNameAddressQuery { + public: + typedef boost::shared_ptr<DomainNameAddressQuery> ref; - virtual ~DomainNameAddressQuery(); + virtual ~DomainNameAddressQuery(); - virtual void run() = 0; + virtual void run() = 0; - boost::signal<void (const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>)> onResult; - }; + boost::signal<void (const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>)> onResult; + }; } diff --git a/Swiften/Network/DomainNameResolveError.h b/Swiften/Network/DomainNameResolveError.h index c788537..f231f9a 100644 --- a/Swiften/Network/DomainNameResolveError.h +++ b/Swiften/Network/DomainNameResolveError.h @@ -10,8 +10,8 @@ #include <Swiften/Base/Error.h> namespace Swift { - class SWIFTEN_API DomainNameResolveError : public Error { - public: - DomainNameResolveError() {} - }; + class SWIFTEN_API DomainNameResolveError : public Error { + public: + DomainNameResolveError() {} + }; } diff --git a/Swiften/Network/DomainNameResolver.h b/Swiften/Network/DomainNameResolver.h index e398774..97997c9 100644 --- a/Swiften/Network/DomainNameResolver.h +++ b/Swiften/Network/DomainNameResolver.h @@ -13,15 +13,15 @@ #include <Swiften/Base/API.h> namespace Swift { - class DomainNameServiceQuery; - class DomainNameAddressQuery; - + class DomainNameServiceQuery; + class DomainNameAddressQuery; - class SWIFTEN_API DomainNameResolver { - public: - virtual ~DomainNameResolver(); - virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) = 0; - virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name) = 0; - }; + class SWIFTEN_API DomainNameResolver { + public: + virtual ~DomainNameResolver(); + + virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) = 0; + virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name) = 0; + }; } diff --git a/Swiften/Network/DomainNameServiceQuery.cpp b/Swiften/Network/DomainNameServiceQuery.cpp index 4410ed9..708bbce 100644 --- a/Swiften/Network/DomainNameServiceQuery.cpp +++ b/Swiften/Network/DomainNameServiceQuery.cpp @@ -22,11 +22,11 @@ using namespace Swift; namespace lambda = boost::lambda; namespace { - struct ResultPriorityComparator { - bool operator()(const DomainNameServiceQuery::Result& a, const DomainNameServiceQuery::Result& b) const { - return a.priority < b.priority; - } - }; + struct ResultPriorityComparator { + bool operator()(const DomainNameServiceQuery::Result& a, const DomainNameServiceQuery::Result& b) const { + return a.priority < b.priority; + } + }; } namespace Swift { @@ -35,31 +35,31 @@ DomainNameServiceQuery::~DomainNameServiceQuery() { } void DomainNameServiceQuery::sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator) { - ResultPriorityComparator comparator; - std::stable_sort(queries.begin(), queries.end(), comparator); + ResultPriorityComparator comparator; + std::stable_sort(queries.begin(), queries.end(), comparator); - std::vector<DomainNameServiceQuery::Result>::iterator i = queries.begin(); - while (i != queries.end()) { - std::vector<DomainNameServiceQuery::Result>::iterator next = std::upper_bound(i, queries.end(), *i, comparator); - if (std::distance(i, next) > 1) { - std::vector<int> weights; - std::transform(i, next, std::back_inserter(weights), - /* easy hack to account for '0' weights getting at least some weight */ - lambda::bind(&Result::weight, lambda::_1) + 1); - for (int j = 0; j < boost::numeric_cast<int>(weights.size() - 1); ++j) { - std::vector<int> cumulativeWeights; - std::partial_sum( - weights.begin() + j, - weights.end(), - std::back_inserter(cumulativeWeights)); - int randomNumber = generator.generateRandomInteger(cumulativeWeights.back()); - BOOST_AUTO(selectedIndex, std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin()); - std::swap(i[j], i[j + selectedIndex]); - std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]); - } - } - i = next; - } + std::vector<DomainNameServiceQuery::Result>::iterator i = queries.begin(); + while (i != queries.end()) { + std::vector<DomainNameServiceQuery::Result>::iterator next = std::upper_bound(i, queries.end(), *i, comparator); + if (std::distance(i, next) > 1) { + std::vector<int> weights; + std::transform(i, next, std::back_inserter(weights), + /* easy hack to account for '0' weights getting at least some weight */ + lambda::bind(&Result::weight, lambda::_1) + 1); + for (int j = 0; j < boost::numeric_cast<int>(weights.size() - 1); ++j) { + std::vector<int> cumulativeWeights; + std::partial_sum( + weights.begin() + j, + weights.end(), + std::back_inserter(cumulativeWeights)); + int randomNumber = generator.generateRandomInteger(cumulativeWeights.back()); + BOOST_AUTO(selectedIndex, std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin()); + std::swap(i[j], i[j + selectedIndex]); + std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]); + } + } + i = next; + } } diff --git a/Swiften/Network/DomainNameServiceQuery.h b/Swiften/Network/DomainNameServiceQuery.h index 240ae4e..acbccf0 100644 --- a/Swiften/Network/DomainNameServiceQuery.h +++ b/Swiften/Network/DomainNameServiceQuery.h @@ -17,25 +17,25 @@ #include <Swiften/Network/DomainNameResolveError.h> namespace Swift { - class RandomGenerator; + class RandomGenerator; - class SWIFTEN_API DomainNameServiceQuery { - public: - typedef boost::shared_ptr<DomainNameServiceQuery> ref; + class SWIFTEN_API DomainNameServiceQuery { + public: + typedef boost::shared_ptr<DomainNameServiceQuery> ref; - struct Result { - Result(const std::string& hostname = "", int port = -1, int priority = -1, int weight = -1) : hostname(hostname), port(port), priority(priority), weight(weight) {} - std::string hostname; - int port; - int priority; - int weight; - }; + struct Result { + Result(const std::string& hostname = "", int port = -1, int priority = -1, int weight = -1) : hostname(hostname), port(port), priority(priority), weight(weight) {} + std::string hostname; + int port; + int priority; + int weight; + }; - virtual ~DomainNameServiceQuery(); + virtual ~DomainNameServiceQuery(); - virtual void run() = 0; - static void sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator); + virtual void run() = 0; + static void sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator); - boost::signal<void (const std::vector<Result>&)> onResult; - }; + boost::signal<void (const std::vector<Result>&)> onResult; + }; } diff --git a/Swiften/Network/DummyConnection.cpp b/Swiften/Network/DummyConnection.cpp index 53f3db7..a4e5419 100644 --- a/Swiften/Network/DummyConnection.cpp +++ b/Swiften/Network/DummyConnection.cpp @@ -17,15 +17,15 @@ DummyConnection::DummyConnection(EventLoop* eventLoop) : eventLoop(eventLoop) { } void DummyConnection::receive(const SafeByteArray& data) { - eventLoop->postEvent(boost::bind(boost::ref(onDataRead), boost::make_shared<SafeByteArray>(data)), shared_from_this()); + eventLoop->postEvent(boost::bind(boost::ref(onDataRead), boost::make_shared<SafeByteArray>(data)), shared_from_this()); } void DummyConnection::listen() { - assert(false); + assert(false); } void DummyConnection::connect(const HostAddressPort&) { - assert(false); + assert(false); } diff --git a/Swiften/Network/DummyConnection.h b/Swiften/Network/DummyConnection.h index edc2473..fcfdb15 100644 --- a/Swiften/Network/DummyConnection.h +++ b/Swiften/Network/DummyConnection.h @@ -15,36 +15,36 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class SWIFTEN_API DummyConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<DummyConnection> { - public: - DummyConnection(EventLoop* eventLoop); + class SWIFTEN_API DummyConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<DummyConnection> { + public: + DummyConnection(EventLoop* eventLoop); - void listen(); - void connect(const HostAddressPort&); + void listen(); + void connect(const HostAddressPort&); - void disconnect() { - //assert(false); - } + void disconnect() { + //assert(false); + } - void write(const SafeByteArray& data) { - eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this()); - onDataSent(data); - } + void write(const SafeByteArray& data) { + eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this()); + onDataSent(data); + } - void receive(const SafeByteArray& data); + void receive(const SafeByteArray& data); - HostAddressPort getLocalAddress() const { - return localAddress; - } + HostAddressPort getLocalAddress() const { + return localAddress; + } - HostAddressPort getRemoteAddress() const { - return remoteAddress; - } + HostAddressPort getRemoteAddress() const { + return remoteAddress; + } - boost::signal<void (const SafeByteArray&)> onDataSent; + boost::signal<void (const SafeByteArray&)> onDataSent; - EventLoop* eventLoop; - HostAddressPort localAddress; - HostAddressPort remoteAddress; - }; + EventLoop* eventLoop; + HostAddressPort localAddress; + HostAddressPort remoteAddress; + }; } diff --git a/Swiften/Network/DummyConnectionFactory.h b/Swiften/Network/DummyConnectionFactory.h index e8a294e..f861312 100644 --- a/Swiften/Network/DummyConnectionFactory.h +++ b/Swiften/Network/DummyConnectionFactory.h @@ -17,13 +17,13 @@ class EventLoop; class DummyConnectionFactory : public ConnectionFactory { public: - DummyConnectionFactory(EventLoop *eventLoop) : eventLoop(eventLoop) {} - virtual ~DummyConnectionFactory() {} - virtual boost::shared_ptr<Connection> createConnection() { - return boost::make_shared<DummyConnection>(eventLoop); - } + DummyConnectionFactory(EventLoop *eventLoop) : eventLoop(eventLoop) {} + virtual ~DummyConnectionFactory() {} + virtual boost::shared_ptr<Connection> createConnection() { + return boost::make_shared<DummyConnection>(eventLoop); + } private: - EventLoop* eventLoop; + EventLoop* eventLoop; }; } diff --git a/Swiften/Network/DummyConnectionServer.h b/Swiften/Network/DummyConnectionServer.h index 1195cad..0bf7386 100644 --- a/Swiften/Network/DummyConnectionServer.h +++ b/Swiften/Network/DummyConnectionServer.h @@ -15,29 +15,29 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class SWIFTEN_API DummyConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<DummyConnectionServer> { - public: - DummyConnectionServer(EventLoop* /*eventLoop*/, int port) : localAddressPort(HostAddress(), port) {} - DummyConnectionServer(EventLoop* /*eventLoop*/, const Swift::HostAddress& hostAddress, int port) : localAddressPort(hostAddress, port) {} - virtual ~DummyConnectionServer() {} + class SWIFTEN_API DummyConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<DummyConnectionServer> { + public: + DummyConnectionServer(EventLoop* /*eventLoop*/, int port) : localAddressPort(HostAddress(), port) {} + DummyConnectionServer(EventLoop* /*eventLoop*/, const Swift::HostAddress& hostAddress, int port) : localAddressPort(hostAddress, port) {} + virtual ~DummyConnectionServer() {} - virtual HostAddressPort getAddressPort() const { - return localAddressPort; - } + virtual HostAddressPort getAddressPort() const { + return localAddressPort; + } - virtual boost::optional<Error> tryStart() { - return boost::optional<Error>(); - } + virtual boost::optional<Error> tryStart() { + return boost::optional<Error>(); + } - virtual void start() { + virtual void start() { - } + } - virtual void stop() { + virtual void stop() { - } + } - private: - HostAddressPort localAddressPort; - }; + private: + HostAddressPort localAddressPort; + }; } diff --git a/Swiften/Network/DummyConnectionServerFactory.h b/Swiften/Network/DummyConnectionServerFactory.h index 6369452..0952a38 100644 --- a/Swiften/Network/DummyConnectionServerFactory.h +++ b/Swiften/Network/DummyConnectionServerFactory.h @@ -17,19 +17,19 @@ class EventLoop; class DummyConnectionServerFactory : public ConnectionServerFactory { public: - DummyConnectionServerFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {} - virtual ~DummyConnectionServerFactory() {} + DummyConnectionServerFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {} + virtual ~DummyConnectionServerFactory() {} - virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) { - return boost::make_shared<DummyConnectionServer>(eventLoop, port); - } + virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) { + return boost::make_shared<DummyConnectionServer>(eventLoop, port); + } - virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) { - return boost::make_shared<DummyConnectionServer>(eventLoop, hostAddress, port); - } + virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) { + return boost::make_shared<DummyConnectionServer>(eventLoop, hostAddress, port); + } private: - EventLoop* eventLoop; + EventLoop* eventLoop; }; } diff --git a/Swiften/Network/DummyTimerFactory.cpp b/Swiften/Network/DummyTimerFactory.cpp index 6967e92..cae5c84 100644 --- a/Swiften/Network/DummyTimerFactory.cpp +++ b/Swiften/Network/DummyTimerFactory.cpp @@ -14,27 +14,27 @@ namespace Swift { class DummyTimerFactory::DummyTimer : public Timer { - public: - DummyTimer(int timeout, DummyTimerFactory* factory) : timeout(timeout), factory(factory), isRunning(false), startTime(~0) { - } - - virtual void start() { - isRunning = true; - startTime = factory->currentTime; - } - - virtual void stop() { - isRunning = false; - } - - int getAlarmTime() const { - return startTime + timeout; - } - - int timeout; - DummyTimerFactory* factory; - bool isRunning; - int startTime; + public: + DummyTimer(int timeout, DummyTimerFactory* factory) : timeout(timeout), factory(factory), isRunning(false), startTime(~0) { + } + + virtual void start() { + isRunning = true; + startTime = factory->currentTime; + } + + virtual void stop() { + isRunning = false; + } + + int getAlarmTime() const { + return startTime + timeout; + } + + int timeout; + DummyTimerFactory* factory; + bool isRunning; + int startTime; }; @@ -42,19 +42,19 @@ DummyTimerFactory::DummyTimerFactory() : currentTime(0) { } boost::shared_ptr<Timer> DummyTimerFactory::createTimer(int milliseconds) { - boost::shared_ptr<DummyTimer> timer(new DummyTimer(milliseconds, this)); - timers.push_back(timer); - return timer; + boost::shared_ptr<DummyTimer> timer(new DummyTimer(milliseconds, this)); + timers.push_back(timer); + return timer; } void DummyTimerFactory::setTime(int time) { - assert(time > currentTime); - foreach(boost::shared_ptr<DummyTimer> timer, timers) { - if (timer->getAlarmTime() > currentTime && timer->getAlarmTime() <= time && timer->isRunning) { - timer->onTick(); - } - } - currentTime = time; + assert(time > currentTime); + foreach(boost::shared_ptr<DummyTimer> timer, timers) { + if (timer->getAlarmTime() > currentTime && timer->getAlarmTime() <= time && timer->isRunning) { + timer->onTick(); + } + } + currentTime = time; } } diff --git a/Swiften/Network/DummyTimerFactory.h b/Swiften/Network/DummyTimerFactory.h index 2f2ba43..bb2f813 100644 --- a/Swiften/Network/DummyTimerFactory.h +++ b/Swiften/Network/DummyTimerFactory.h @@ -12,18 +12,18 @@ #include <Swiften/Network/TimerFactory.h> namespace Swift { - class SWIFTEN_API DummyTimerFactory : public TimerFactory { - public: - class DummyTimer; + class SWIFTEN_API DummyTimerFactory : public TimerFactory { + public: + class DummyTimer; - DummyTimerFactory(); + DummyTimerFactory(); - virtual boost::shared_ptr<Timer> createTimer(int milliseconds); - void setTime(int time); + virtual boost::shared_ptr<Timer> createTimer(int milliseconds); + void setTime(int time); - private: - friend class DummyTimer; - int currentTime; - std::list<boost::shared_ptr<DummyTimer> > timers; - }; + private: + friend class DummyTimer; + int currentTime; + std::list<boost::shared_ptr<DummyTimer> > timers; + }; } diff --git a/Swiften/Network/EnvironmentProxyProvider.cpp b/Swiften/Network/EnvironmentProxyProvider.cpp index b61a73f..aa8027f 100644 --- a/Swiften/Network/EnvironmentProxyProvider.cpp +++ b/Swiften/Network/EnvironmentProxyProvider.cpp @@ -22,35 +22,35 @@ namespace Swift { EnvironmentProxyProvider::EnvironmentProxyProvider() { - socksProxy = getFromEnv("all_proxy", "socks"); - httpProxy = getFromEnv("http_proxy", "http"); - SWIFT_LOG(debug) << "Environment: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl; + socksProxy = getFromEnv("all_proxy", "socks"); + httpProxy = getFromEnv("http_proxy", "http"); + SWIFT_LOG(debug) << "Environment: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl; } HostAddressPort EnvironmentProxyProvider::getHTTPConnectProxy() const { - return httpProxy; + return httpProxy; } HostAddressPort EnvironmentProxyProvider::getSOCKS5Proxy() const { - return socksProxy; + return socksProxy; } HostAddressPort EnvironmentProxyProvider::getFromEnv(const char* envVarName, std::string proxyProtocol) { - char* envVar = NULL; - std::string address; - int port = 0; + char* envVar = NULL; + std::string address; + int port = 0; - envVar = getenv(envVarName); + envVar = getenv(envVarName); - proxyProtocol += "://"; - address = envVar != NULL ? envVar : "0.0.0.0"; - if(envVar != NULL && address.compare(0, proxyProtocol.length(), proxyProtocol) == 0) { - address = address.substr(proxyProtocol.length(), address.length()); - port = atoi(address.substr(address.find(':') + 1, address.length()).c_str()); - address = address.substr(0, address.find(':')); - } + proxyProtocol += "://"; + address = envVar != NULL ? envVar : "0.0.0.0"; + if(envVar != NULL && address.compare(0, proxyProtocol.length(), proxyProtocol) == 0) { + address = address.substr(proxyProtocol.length(), address.length()); + port = atoi(address.substr(address.find(':') + 1, address.length()).c_str()); + address = address.substr(0, address.find(':')); + } - return HostAddressPort(HostAddress(address), port); + return HostAddressPort(HostAddress(address), port); } } diff --git a/Swiften/Network/EnvironmentProxyProvider.h b/Swiften/Network/EnvironmentProxyProvider.h index 0afad9d..59463ff 100644 --- a/Swiften/Network/EnvironmentProxyProvider.h +++ b/Swiften/Network/EnvironmentProxyProvider.h @@ -16,16 +16,16 @@ #include <Swiften/Network/ProxyProvider.h> namespace Swift { - class SWIFTEN_API EnvironmentProxyProvider : public ProxyProvider { - public: - EnvironmentProxyProvider(); - virtual HostAddressPort getHTTPConnectProxy() const; - virtual HostAddressPort getSOCKS5Proxy() const; - private: - HostAddressPort getFromEnv(const char* envVarName, std::string proxyProtocol); - HostAddressPort socksProxy; - HostAddressPort httpProxy; - }; + class SWIFTEN_API EnvironmentProxyProvider : public ProxyProvider { + public: + EnvironmentProxyProvider(); + virtual HostAddressPort getHTTPConnectProxy() const; + virtual HostAddressPort getSOCKS5Proxy() const; + private: + HostAddressPort getFromEnv(const char* envVarName, std::string proxyProtocol); + HostAddressPort socksProxy; + HostAddressPort httpProxy; + }; } diff --git a/Swiften/Network/FakeConnection.cpp b/Swiften/Network/FakeConnection.cpp index dc19e4b..82b792a 100644 --- a/Swiften/Network/FakeConnection.cpp +++ b/Swiften/Network/FakeConnection.cpp @@ -17,48 +17,48 @@ FakeConnection::~FakeConnection() { } void FakeConnection::listen() { - assert(false); + assert(false); } void FakeConnection::setError(const Error& e) { - error = boost::optional<Error>(e); - state = DisconnectedWithError; - if (connectedTo) { - eventLoop->postEvent( - boost::bind(boost::ref(onDisconnected), error), - shared_from_this()); - } + error = boost::optional<Error>(e); + state = DisconnectedWithError; + if (connectedTo) { + eventLoop->postEvent( + boost::bind(boost::ref(onDisconnected), error), + shared_from_this()); + } } void FakeConnection::connect(const HostAddressPort& address) { - if (delayConnect) { - state = Connecting; - } - else { - if (!error) { - connectedTo = address; - state = Connected; - } - else { - state = DisconnectedWithError; - } - eventLoop->postEvent( - boost::bind(boost::ref(onConnectFinished), error ? true : false), - shared_from_this()); - } + if (delayConnect) { + state = Connecting; + } + else { + if (!error) { + connectedTo = address; + state = Connected; + } + else { + state = DisconnectedWithError; + } + eventLoop->postEvent( + boost::bind(boost::ref(onConnectFinished), error ? true : false), + shared_from_this()); + } } void FakeConnection::disconnect() { - if (!error) { - state = Disconnected; - } - else { - state = DisconnectedWithError; - } - connectedTo.reset(); - eventLoop->postEvent( - boost::bind(boost::ref(onDisconnected), error), - shared_from_this()); + if (!error) { + state = Disconnected; + } + else { + state = DisconnectedWithError; + } + connectedTo.reset(); + eventLoop->postEvent( + boost::bind(boost::ref(onDisconnected), error), + shared_from_this()); } } diff --git a/Swiften/Network/FakeConnection.h b/Swiften/Network/FakeConnection.h index ec62ad7..c7d1f27 100644 --- a/Swiften/Network/FakeConnection.h +++ b/Swiften/Network/FakeConnection.h @@ -18,47 +18,47 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class SWIFTEN_API FakeConnection : - public Connection, - public EventOwner, - public boost::enable_shared_from_this<FakeConnection> { - public: - enum State { - Initial, - Connecting, - Connected, - Disconnected, - DisconnectedWithError - }; + class SWIFTEN_API FakeConnection : + public Connection, + public EventOwner, + public boost::enable_shared_from_this<FakeConnection> { + public: + enum State { + Initial, + Connecting, + Connected, + Disconnected, + DisconnectedWithError + }; - FakeConnection(EventLoop* eventLoop); - virtual ~FakeConnection(); + FakeConnection(EventLoop* eventLoop); + virtual ~FakeConnection(); - virtual void listen(); - virtual HostAddressPort getLocalAddress() const { - return HostAddressPort(); - } - virtual HostAddressPort getRemoteAddress() const { - return HostAddressPort(); - } + virtual void listen(); + virtual HostAddressPort getLocalAddress() const { + return HostAddressPort(); + } + virtual HostAddressPort getRemoteAddress() const { + return HostAddressPort(); + } - void setError(const Error& e); - virtual void connect(const HostAddressPort& address); - virtual void disconnect(); + void setError(const Error& e); + virtual void connect(const HostAddressPort& address); + virtual void disconnect(); - virtual void write(const SafeByteArray& data) { - dataWritten.push_back(data); - } + virtual void write(const SafeByteArray& data) { + dataWritten.push_back(data); + } - void setDelayConnect() { - delayConnect = true; - } + void setDelayConnect() { + delayConnect = true; + } - EventLoop* eventLoop; - boost::optional<HostAddressPort> connectedTo; - std::vector<SafeByteArray> dataWritten; - boost::optional<Error> error; - State state; - bool delayConnect; - }; + EventLoop* eventLoop; + boost::optional<HostAddressPort> connectedTo; + std::vector<SafeByteArray> dataWritten; + boost::optional<Error> error; + State state; + bool delayConnect; + }; } diff --git a/Swiften/Network/GConfProxyProvider.cpp b/Swiften/Network/GConfProxyProvider.cpp index ed9be3c..35303d5 100644 --- a/Swiften/Network/GConfProxyProvider.cpp +++ b/Swiften/Network/GConfProxyProvider.cpp @@ -24,43 +24,43 @@ namespace Swift { GConfProxyProvider::GConfProxyProvider() { - // Ensure static GLib initialization methods are called - static bool glibInitialized = false; - if (!glibInitialized) { - g_type_init(); - glibInitialized = true; - } - - socksProxy = getFromGConf("/system/proxy/socks_host", "/system/proxy/socks_port"); - httpProxy = getFromGConf("/system/http_proxy/host", "/system/http_proxy/port"); - SWIFT_LOG(debug) << "GConf: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl; + // Ensure static GLib initialization methods are called + static bool glibInitialized = false; + if (!glibInitialized) { + g_type_init(); + glibInitialized = true; + } + + socksProxy = getFromGConf("/system/proxy/socks_host", "/system/proxy/socks_port"); + httpProxy = getFromGConf("/system/http_proxy/host", "/system/http_proxy/port"); + SWIFT_LOG(debug) << "GConf: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl; } HostAddressPort GConfProxyProvider::getHTTPConnectProxy() const { - return httpProxy; + return httpProxy; } HostAddressPort GConfProxyProvider::getSOCKS5Proxy() const { - return socksProxy; + return socksProxy; } HostAddressPort GConfProxyProvider::getFromGConf(const char* gcHost, const char* gcPort) { - std::string address; - int port = 0; - gchar* str; + std::string address; + int port = 0; + gchar* str; - GConfClient* client = gconf_client_get_default(); + GConfClient* client = gconf_client_get_default(); - str = gconf_client_get_string(client, gcHost, NULL); - port = static_cast<int> (gconf_client_get_int(client, gcPort, NULL)); + str = gconf_client_get_string(client, gcHost, NULL); + port = static_cast<int> (gconf_client_get_int(client, gcPort, NULL)); - if(str) { - address = static_cast<char*> (str); - g_free(str); - } + if(str) { + address = static_cast<char*> (str); + g_free(str); + } - g_object_unref(client); - return HostAddressPort(HostAddress(address), port); + g_object_unref(client); + return HostAddressPort(HostAddress(address), port); } } diff --git a/Swiften/Network/GConfProxyProvider.h b/Swiften/Network/GConfProxyProvider.h index 31f38a9..826a67b 100644 --- a/Swiften/Network/GConfProxyProvider.h +++ b/Swiften/Network/GConfProxyProvider.h @@ -9,16 +9,16 @@ #include <Swiften/Network/ProxyProvider.h> namespace Swift { - class GConfProxyProvider : public ProxyProvider { - public: - GConfProxyProvider(); - virtual HostAddressPort getHTTPConnectProxy() const; - virtual HostAddressPort getSOCKS5Proxy() const; - private: - HostAddressPort getFromGConf(const char* gcHost, const char* gcPort); - HostAddressPort socksProxy; - HostAddressPort httpProxy; - }; + class GConfProxyProvider : public ProxyProvider { + public: + GConfProxyProvider(); + virtual HostAddressPort getHTTPConnectProxy() const; + virtual HostAddressPort getSOCKS5Proxy() const; + private: + HostAddressPort getFromGConf(const char* gcHost, const char* gcPort); + HostAddressPort socksProxy; + HostAddressPort httpProxy; + }; } diff --git a/Swiften/Network/HTTPConnectProxiedConnection.cpp b/Swiften/Network/HTTPConnectProxiedConnection.cpp index 3ed2ac5..991e815 100644 --- a/Swiften/Network/HTTPConnectProxiedConnection.cpp +++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp @@ -33,16 +33,16 @@ using namespace Swift; HTTPConnectProxiedConnection::HTTPConnectProxiedConnection( - DomainNameResolver* resolver, - ConnectionFactory* connectionFactory, - TimerFactory* timerFactory, - const std::string& proxyHost, - int proxyPort, - const SafeString& authID, - const SafeString& authPassword) : - ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort), - authID_(authID), - authPassword_(authPassword) { + DomainNameResolver* resolver, + ConnectionFactory* connectionFactory, + TimerFactory* timerFactory, + const std::string& proxyHost, + int proxyPort, + const SafeString& authID, + const SafeString& authPassword) : + ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort), + authID_(authID), + authPassword_(authPassword) { } HTTPConnectProxiedConnection::~HTTPConnectProxiedConnection() { @@ -50,116 +50,116 @@ HTTPConnectProxiedConnection::~HTTPConnectProxiedConnection() { } void HTTPConnectProxiedConnection::setHTTPTrafficFilter(boost::shared_ptr<HTTPTrafficFilter> trafficFilter) { - trafficFilter_ = trafficFilter; + trafficFilter_ = trafficFilter; } void HTTPConnectProxiedConnection::initializeProxy() { - httpResponseBuffer_.clear(); - - std::stringstream connect; - connect << "CONNECT " << getServer().getAddress().toString() << ":" << getServer().getPort() << " HTTP/1.1\r\n"; - SafeByteArray data = createSafeByteArray(connect.str()); - if (!authID_.empty() && !authPassword_.empty()) { - append(data, createSafeByteArray("Proxy-Authorization: Basic ")); - SafeByteArray credentials = authID_; - append(credentials, createSafeByteArray(":")); - append(credentials, authPassword_); - append(data, Base64::encode(credentials)); - append(data, createSafeByteArray("\r\n")); - } - else if (!nextHTTPRequestHeaders_.empty()) { - typedef std::pair<std::string, std::string> StringPair; - foreach(const StringPair& headerField, nextHTTPRequestHeaders_) { - append(data, createSafeByteArray(headerField.first)); - append(data, createSafeByteArray(": ")); - append(data, createSafeByteArray(headerField.second)); - append(data, createSafeByteArray("\r\n")); - } - - nextHTTPRequestHeaders_.clear(); - } - append(data, createSafeByteArray("\r\n")); - SWIFT_LOG(debug) << "HTTP Proxy send headers: " << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl; - write(data); + httpResponseBuffer_.clear(); + + std::stringstream connect; + connect << "CONNECT " << getServer().getAddress().toString() << ":" << getServer().getPort() << " HTTP/1.1\r\n"; + SafeByteArray data = createSafeByteArray(connect.str()); + if (!authID_.empty() && !authPassword_.empty()) { + append(data, createSafeByteArray("Proxy-Authorization: Basic ")); + SafeByteArray credentials = authID_; + append(credentials, createSafeByteArray(":")); + append(credentials, authPassword_); + append(data, Base64::encode(credentials)); + append(data, createSafeByteArray("\r\n")); + } + else if (!nextHTTPRequestHeaders_.empty()) { + typedef std::pair<std::string, std::string> StringPair; + foreach(const StringPair& headerField, nextHTTPRequestHeaders_) { + append(data, createSafeByteArray(headerField.first)); + append(data, createSafeByteArray(": ")); + append(data, createSafeByteArray(headerField.second)); + append(data, createSafeByteArray("\r\n")); + } + + nextHTTPRequestHeaders_.clear(); + } + append(data, createSafeByteArray("\r\n")); + SWIFT_LOG(debug) << "HTTP Proxy send headers: " << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl; + write(data); } void HTTPConnectProxiedConnection::parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields) { - std::istringstream dataStream(data); - - // parse status line - std::getline(dataStream, statusLine); - - // parse fields - std::string headerLine; - std::string::size_type splitIndex; - while (std::getline(dataStream, headerLine) && headerLine != "\r") { - splitIndex = headerLine.find(':', 0); - if (splitIndex != std::string::npos) { - headerFields.push_back(std::pair<std::string, std::string>(headerLine.substr(0, splitIndex), headerLine.substr(splitIndex + 1))); - } - } + std::istringstream dataStream(data); + + // parse status line + std::getline(dataStream, statusLine); + + // parse fields + std::string headerLine; + std::string::size_type splitIndex; + while (std::getline(dataStream, headerLine) && headerLine != "\r") { + splitIndex = headerLine.find(':', 0); + if (splitIndex != std::string::npos) { + headerFields.push_back(std::pair<std::string, std::string>(headerLine.substr(0, splitIndex), headerLine.substr(splitIndex + 1))); + } + } } void HTTPConnectProxiedConnection::sendHTTPRequest(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& headerFields) { - typedef std::pair<std::string, std::string> HTTPHeaderField; - std::stringstream request; - - request << statusLine << "\r\n"; - foreach (const HTTPHeaderField& field, headerFields) { - request << field.first << ":" << field.second << "\r\n"; - } - request << "\r\n"; - write(createSafeByteArray(request.str())); + typedef std::pair<std::string, std::string> HTTPHeaderField; + std::stringstream request; + + request << statusLine << "\r\n"; + foreach (const HTTPHeaderField& field, headerFields) { + request << field.first << ":" << field.second << "\r\n"; + } + request << "\r\n"; + write(createSafeByteArray(request.str())); } void HTTPConnectProxiedConnection::handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data) { - std::string dataString = byteArrayToString(ByteArray(data->begin(), data->end())); - SWIFT_LOG(debug) << data << std::endl; - httpResponseBuffer_.append(dataString); - - std::string statusLine; - std::vector<std::pair<std::string, std::string> > headerFields; - - std::string::size_type headerEnd = httpResponseBuffer_.find("\r\n\r\n", 0); - if (headerEnd == std::string::npos) { - if ((httpResponseBuffer_.size() > 4) && (httpResponseBuffer_.substr(0, 4) != "HTTP")) { - setProxyInitializeFinished(false); - } - return; - } - - parseHTTPHeader(httpResponseBuffer_.substr(0, headerEnd), statusLine, headerFields); - - if (trafficFilter_) { - std::vector<std::pair<std::string, std::string> > newHeaderFields = trafficFilter_->filterHTTPResponseHeader(statusLine, headerFields); - if (!newHeaderFields.empty()) { - std::stringstream statusLine; - reconnect(); - nextHTTPRequestHeaders_ = newHeaderFields; - return; - } - } - - std::vector<std::string> tmp = String::split(statusLine, ' '); - if (tmp.size() > 1) { - try { - int status = boost::lexical_cast<int>(tmp[1]); - SWIFT_LOG(debug) << "Proxy Status: " << status << std::endl; - if (status / 100 == 2) { // all 2XX states are OK - setProxyInitializeFinished(true); - } - else { - SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << httpResponseBuffer_ << std::endl; - setProxyInitializeFinished(false); - } - } - catch (boost::bad_lexical_cast&) { - SWIFT_LOG(warning) << "Unexpected response: " << tmp[1] << std::endl; - setProxyInitializeFinished(false); - } - } - else { - setProxyInitializeFinished(false); - } - httpResponseBuffer_.clear(); + std::string dataString = byteArrayToString(ByteArray(data->begin(), data->end())); + SWIFT_LOG(debug) << data << std::endl; + httpResponseBuffer_.append(dataString); + + std::string statusLine; + std::vector<std::pair<std::string, std::string> > headerFields; + + std::string::size_type headerEnd = httpResponseBuffer_.find("\r\n\r\n", 0); + if (headerEnd == std::string::npos) { + if ((httpResponseBuffer_.size() > 4) && (httpResponseBuffer_.substr(0, 4) != "HTTP")) { + setProxyInitializeFinished(false); + } + return; + } + + parseHTTPHeader(httpResponseBuffer_.substr(0, headerEnd), statusLine, headerFields); + + if (trafficFilter_) { + std::vector<std::pair<std::string, std::string> > newHeaderFields = trafficFilter_->filterHTTPResponseHeader(statusLine, headerFields); + if (!newHeaderFields.empty()) { + std::stringstream statusLine; + reconnect(); + nextHTTPRequestHeaders_ = newHeaderFields; + return; + } + } + + std::vector<std::string> tmp = String::split(statusLine, ' '); + if (tmp.size() > 1) { + try { + int status = boost::lexical_cast<int>(tmp[1]); + SWIFT_LOG(debug) << "Proxy Status: " << status << std::endl; + if (status / 100 == 2) { // all 2XX states are OK + setProxyInitializeFinished(true); + } + else { + SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << httpResponseBuffer_ << std::endl; + setProxyInitializeFinished(false); + } + } + catch (boost::bad_lexical_cast&) { + SWIFT_LOG(warning) << "Unexpected response: " << tmp[1] << std::endl; + setProxyInitializeFinished(false); + } + } + else { + setProxyInitializeFinished(false); + } + httpResponseBuffer_.clear(); } diff --git a/Swiften/Network/HTTPConnectProxiedConnection.h b/Swiften/Network/HTTPConnectProxiedConnection.h index 24f36b9..adb8d08 100644 --- a/Swiften/Network/HTTPConnectProxiedConnection.h +++ b/Swiften/Network/HTTPConnectProxiedConnection.h @@ -19,38 +19,38 @@ #include <Swiften/Network/ProxiedConnection.h> namespace Swift { - class ConnectionFactory; - class DomainNameResolver; - class EventLoop; - class HTTPTrafficFilter; - class TimerFactory; + class ConnectionFactory; + class DomainNameResolver; + class EventLoop; + class HTTPTrafficFilter; + class TimerFactory; - class SWIFTEN_API HTTPConnectProxiedConnection : public ProxiedConnection { - public: - typedef boost::shared_ptr<HTTPConnectProxiedConnection> ref; + class SWIFTEN_API HTTPConnectProxiedConnection : public ProxiedConnection { + public: + typedef boost::shared_ptr<HTTPConnectProxiedConnection> ref; - virtual ~HTTPConnectProxiedConnection(); + virtual ~HTTPConnectProxiedConnection(); - static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword) { - return ref(new HTTPConnectProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort, authID, authPassword)); - } + static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword) { + return ref(new HTTPConnectProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort, authID, authPassword)); + } - void setHTTPTrafficFilter(boost::shared_ptr<HTTPTrafficFilter> trafficFilter); + void setHTTPTrafficFilter(boost::shared_ptr<HTTPTrafficFilter> trafficFilter); - private: - HTTPConnectProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword); + private: + HTTPConnectProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword); - virtual void initializeProxy(); - virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data); + virtual void initializeProxy(); + virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data); - void sendHTTPRequest(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& headerFields); - void parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields); + void sendHTTPRequest(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& headerFields); + void parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields); - private: - SafeByteArray authID_; - SafeByteArray authPassword_; - boost::shared_ptr<HTTPTrafficFilter> trafficFilter_; - std::string httpResponseBuffer_; - std::vector<std::pair<std::string, std::string> > nextHTTPRequestHeaders_; - }; + private: + SafeByteArray authID_; + SafeByteArray authPassword_; + boost::shared_ptr<HTTPTrafficFilter> trafficFilter_; + std::string httpResponseBuffer_; + std::vector<std::pair<std::string, std::string> > nextHTTPRequestHeaders_; + }; } diff --git a/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp b/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp index 91b241e..735791f 100644 --- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp +++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp @@ -24,9 +24,9 @@ HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainN } boost::shared_ptr<Connection> HTTPConnectProxiedConnectionFactory::createConnection() { - HTTPConnectProxiedConnection::ref proxyConnection = HTTPConnectProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_, authID_, authPassword_); - proxyConnection->setHTTPTrafficFilter(httpTrafficFilter_); - return proxyConnection; + HTTPConnectProxiedConnection::ref proxyConnection = HTTPConnectProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_, authID_, authPassword_); + proxyConnection->setHTTPTrafficFilter(httpTrafficFilter_); + return proxyConnection; } } diff --git a/Swiften/Network/HTTPConnectProxiedConnectionFactory.h b/Swiften/Network/HTTPConnectProxiedConnectionFactory.h index 05e9447..455fba0 100644 --- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.h +++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.h @@ -18,26 +18,26 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class DomainNameResolver; - class TimerFactory; - class EventLoop; - class HTTPTrafficFilter; + class DomainNameResolver; + class TimerFactory; + class EventLoop; + class HTTPTrafficFilter; - class SWIFTEN_API HTTPConnectProxiedConnectionFactory : public ConnectionFactory { - public: - HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>()); - HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>()); + class SWIFTEN_API HTTPConnectProxiedConnectionFactory : public ConnectionFactory { + public: + HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>()); + HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>()); - virtual boost::shared_ptr<Connection> createConnection(); + virtual boost::shared_ptr<Connection> createConnection(); - private: - DomainNameResolver* resolver_; - ConnectionFactory* connectionFactory_; - TimerFactory* timerFactory_; - std::string proxyHost_; - int proxyPort_; - SafeString authID_; - SafeString authPassword_; - boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter_; - }; + private: + DomainNameResolver* resolver_; + ConnectionFactory* connectionFactory_; + TimerFactory* timerFactory_; + std::string proxyHost_; + int proxyPort_; + SafeString authID_; + SafeString authPassword_; + boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter_; + }; } diff --git a/Swiften/Network/HTTPTrafficFilter.h b/Swiften/Network/HTTPTrafficFilter.h index cc1af21..5c29bd6 100644 --- a/Swiften/Network/HTTPTrafficFilter.h +++ b/Swiften/Network/HTTPTrafficFilter.h @@ -17,15 +17,15 @@ namespace Swift { class SWIFTEN_API HTTPTrafficFilter { - public: - virtual ~HTTPTrafficFilter(); - /** - * @brief This method is called by the HTTPConnectPRoxiedConnection on every incoming HTTP response. - * It can be used to insert additional HTTP requests into the HTTP CONNECT proxy initalization process. - * @return A vector of HTTP header fields to use in a new request. If an empty vector is returned, - * no new request will be send and the normal proxy logic continues. - */ - virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& /* responseHeader */) = 0; + public: + virtual ~HTTPTrafficFilter(); + /** + * @brief This method is called by the HTTPConnectPRoxiedConnection on every incoming HTTP response. + * It can be used to insert additional HTTP requests into the HTTP CONNECT proxy initalization process. + * @return A vector of HTTP header fields to use in a new request. If an empty vector is returned, + * no new request will be send and the normal proxy logic continues. + */ + virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& /* responseHeader */) = 0; }; } diff --git a/Swiften/Network/HostAddress.cpp b/Swiften/Network/HostAddress.cpp index ae1a008..64a4ff6 100644 --- a/Swiften/Network/HostAddress.cpp +++ b/Swiften/Network/HostAddress.cpp @@ -25,48 +25,48 @@ HostAddress::HostAddress() { } HostAddress::HostAddress(const std::string& address) { - try { - address_ = boost::asio::ip::address::from_string(address); - } - catch (const std::exception&) { - } + try { + address_ = boost::asio::ip::address::from_string(address); + } + catch (const std::exception&) { + } } HostAddress::HostAddress(const unsigned char* address, size_t length) { - assert(length == 4 || length == 16); - if (length == 4) { - boost::asio::ip::address_v4::bytes_type data; - for (size_t i = 0; i < length; ++i) { - data[i] = address[i]; - } - address_ = boost::asio::ip::address(boost::asio::ip::address_v4(data)); - } - else { - boost::asio::ip::address_v6::bytes_type data; - for (size_t i = 0; i < length; ++i) { - data[i] = address[i]; - } - address_ = boost::asio::ip::address(boost::asio::ip::address_v6(data)); - } + assert(length == 4 || length == 16); + if (length == 4) { + boost::asio::ip::address_v4::bytes_type data; + for (size_t i = 0; i < length; ++i) { + data[i] = address[i]; + } + address_ = boost::asio::ip::address(boost::asio::ip::address_v4(data)); + } + else { + boost::asio::ip::address_v6::bytes_type data; + for (size_t i = 0; i < length; ++i) { + data[i] = address[i]; + } + address_ = boost::asio::ip::address(boost::asio::ip::address_v6(data)); + } } HostAddress::HostAddress(const boost::asio::ip::address& address) : address_(address) { } std::string HostAddress::toString() const { - return address_.to_string(); + return address_.to_string(); } bool HostAddress::isValid() const { - return !(address_.is_v4() && address_.to_v4().to_ulong() == 0); + return !(address_.is_v4() && address_.to_v4().to_ulong() == 0); } boost::asio::ip::address HostAddress::getRawAddress() const { - return address_; + return address_; } bool HostAddress::isLocalhost() const { - return address_ == localhost4 || address_ == localhost6; + return address_ == localhost4 || address_ == localhost6; } } diff --git a/Swiften/Network/HostAddress.h b/Swiften/Network/HostAddress.h index 91c3e73..00fe9bf 100644 --- a/Swiften/Network/HostAddress.h +++ b/Swiften/Network/HostAddress.h @@ -12,24 +12,24 @@ #include <Swiften/Base/API.h> namespace Swift { - class SWIFTEN_API HostAddress { - public: - HostAddress(); - HostAddress(const std::string&); - HostAddress(const unsigned char* address, size_t length); - HostAddress(const boost::asio::ip::address& address); - - std::string toString() const; - boost::asio::ip::address getRawAddress() const; - - bool operator==(const HostAddress& o) const { - return address_ == o.address_; - } - - bool isValid() const; - bool isLocalhost() const; - - private: - boost::asio::ip::address address_; - }; + class SWIFTEN_API HostAddress { + public: + HostAddress(); + HostAddress(const std::string&); + HostAddress(const unsigned char* address, size_t length); + HostAddress(const boost::asio::ip::address& address); + + std::string toString() const; + boost::asio::ip::address getRawAddress() const; + + bool operator==(const HostAddress& o) const { + return address_ == o.address_; + } + + bool isValid() const; + bool isLocalhost() const; + + private: + boost::asio::ip::address address_; + }; } diff --git a/Swiften/Network/HostAddressPort.cpp b/Swiften/Network/HostAddressPort.cpp index 3229761..a73b2ad 100644 --- a/Swiften/Network/HostAddressPort.cpp +++ b/Swiften/Network/HostAddressPort.cpp @@ -14,10 +14,10 @@ HostAddressPort::HostAddressPort(const HostAddress& address, int port) : address } HostAddressPort::HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint) { - address_ = HostAddress(endpoint.address()); - port_ = endpoint.port(); + address_ = HostAddress(endpoint.address()); + port_ = endpoint.port(); } std::string HostAddressPort::toString() const { - return getAddress().toString() + ":" + boost::lexical_cast<std::string>(getPort()); + return getAddress().toString() + ":" + boost::lexical_cast<std::string>(getPort()); } diff --git a/Swiften/Network/HostAddressPort.h b/Swiften/Network/HostAddressPort.h index f06d4a5..e42e1d1 100644 --- a/Swiften/Network/HostAddressPort.h +++ b/Swiften/Network/HostAddressPort.h @@ -12,31 +12,31 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class SWIFTEN_API HostAddressPort { - public: - HostAddressPort(const HostAddress& address = HostAddress(), int port = -1); - HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint); - - const HostAddress& getAddress() const { - return address_; - } - - int getPort() const { - return port_; - } - - bool operator==(const HostAddressPort& o) const { - return address_ == o.address_ && port_ == o.port_; - } - - bool isValid() const { - return address_.isValid() && port_ > 0; - } - - std::string toString() const; - - private: - HostAddress address_; - int port_; - }; + class SWIFTEN_API HostAddressPort { + public: + HostAddressPort(const HostAddress& address = HostAddress(), int port = -1); + HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint); + + const HostAddress& getAddress() const { + return address_; + } + + int getPort() const { + return port_; + } + + bool operator==(const HostAddressPort& o) const { + return address_ == o.address_ && port_ == o.port_; + } + + bool isValid() const { + return address_.isValid() && port_ > 0; + } + + std::string toString() const; + + private: + HostAddress address_; + int port_; + }; } diff --git a/Swiften/Network/HostNameOrAddress.cpp b/Swiften/Network/HostNameOrAddress.cpp index 8b6e5c5..5c5e5e0 100644 --- a/Swiften/Network/HostNameOrAddress.cpp +++ b/Swiften/Network/HostNameOrAddress.cpp @@ -9,21 +9,21 @@ using namespace Swift; namespace { - struct ToStringVisitor : public boost::static_visitor<std::string> { - std::string operator()(const HostAddress& address) const { - return address.toString(); - } - - std::string operator()(const std::string & str) const { - return str; - } - }; + struct ToStringVisitor : public boost::static_visitor<std::string> { + std::string operator()(const HostAddress& address) const { + return address.toString(); + } + + std::string operator()(const std::string & str) const { + return str; + } + }; } namespace Swift { std::string toString(const HostNameOrAddress& address) { - return boost::apply_visitor(ToStringVisitor(), address); + return boost::apply_visitor(ToStringVisitor(), address); } } diff --git a/Swiften/Network/HostNameOrAddress.h b/Swiften/Network/HostNameOrAddress.h index d6ef439..81c0995 100644 --- a/Swiften/Network/HostNameOrAddress.h +++ b/Swiften/Network/HostNameOrAddress.h @@ -12,7 +12,7 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - typedef boost::variant<std::string, HostAddress> HostNameOrAddress; + typedef boost::variant<std::string, HostAddress> HostNameOrAddress; - std::string toString(const HostNameOrAddress& address); + std::string toString(const HostNameOrAddress& address); } diff --git a/Swiften/Network/MacOSXProxyProvider.cpp b/Swiften/Network/MacOSXProxyProvider.cpp index a489add..858d568 100644 --- a/Swiften/Network/MacOSXProxyProvider.cpp +++ b/Swiften/Network/MacOSXProxyProvider.cpp @@ -29,49 +29,49 @@ using namespace Swift; #ifndef SWIFTEN_PLATFORM_IPHONE static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabledKey, CFStringRef hostKey, CFStringRef portKey) { - CFNumberRef numberValue = NULL; - HostAddressPort ret = HostAddressPort(HostAddress(), 0); - - if(CFDictionaryGetValueIfPresent(dict, reinterpret_cast<const void*> (enabledKey), reinterpret_cast<const void**> (&numberValue)) == true) { - const int i = 0; - CFNumberRef zero = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &i); - CFComparisonResult result = CFNumberCompare(numberValue, zero, NULL); - CFRelease(zero); - - if(result != kCFCompareEqualTo) { - int port = 0; - std::string host = ""; - - try { - CFNumberRef numberValue = reinterpret_cast<CFNumberRef> (CFDictionaryGetValue(dict, portKey)); - if(numberValue != NULL) { - CFNumberGetValue(numberValue, kCFNumberIntType, &port); - } - - CFStringRef stringValue = reinterpret_cast<CFStringRef> (CFDictionaryGetValue(dict, hostKey)); - if(stringValue != NULL) { - std::vector<char> buffer; - // length must be +1 for the ending zero; and the Docu of CFStringGetCString tells it like - // if the string is toby the length must be at least 5. - CFIndex length = CFStringGetLength(stringValue) + 1; - buffer.resize(boost::numeric_cast<size_t>(length)); - if(CFStringGetCString(stringValue, &buffer[0], length, kCFStringEncodingMacRoman)) { - for(std::vector<char>::iterator iter = buffer.begin(); iter != buffer.end(); ++iter) { - host += *iter; - } - } - } - } - catch(...) { - std::cerr << "Exception caught ... " << std::endl; - } - - if(host != "" && port != 0) { - ret = HostAddressPort(HostAddress(host), port); - } - } - } - return ret; + CFNumberRef numberValue = NULL; + HostAddressPort ret = HostAddressPort(HostAddress(), 0); + + if(CFDictionaryGetValueIfPresent(dict, reinterpret_cast<const void*> (enabledKey), reinterpret_cast<const void**> (&numberValue)) == true) { + const int i = 0; + CFNumberRef zero = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &i); + CFComparisonResult result = CFNumberCompare(numberValue, zero, NULL); + CFRelease(zero); + + if(result != kCFCompareEqualTo) { + int port = 0; + std::string host = ""; + + try { + CFNumberRef numberValue = reinterpret_cast<CFNumberRef> (CFDictionaryGetValue(dict, portKey)); + if(numberValue != NULL) { + CFNumberGetValue(numberValue, kCFNumberIntType, &port); + } + + CFStringRef stringValue = reinterpret_cast<CFStringRef> (CFDictionaryGetValue(dict, hostKey)); + if(stringValue != NULL) { + std::vector<char> buffer; + // length must be +1 for the ending zero; and the Docu of CFStringGetCString tells it like + // if the string is toby the length must be at least 5. + CFIndex length = CFStringGetLength(stringValue) + 1; + buffer.resize(boost::numeric_cast<size_t>(length)); + if(CFStringGetCString(stringValue, &buffer[0], length, kCFStringEncodingMacRoman)) { + for(std::vector<char>::iterator iter = buffer.begin(); iter != buffer.end(); ++iter) { + host += *iter; + } + } + } + } + catch(...) { + std::cerr << "Exception caught ... " << std::endl; + } + + if(host != "" && port != 0) { + ret = HostAddressPort(HostAddress(host), port); + } + } + } + return ret; } #endif namespace Swift { @@ -80,27 +80,27 @@ MacOSXProxyProvider::MacOSXProxyProvider() { } HostAddressPort MacOSXProxyProvider::getHTTPConnectProxy() const { - HostAddressPort result; + HostAddressPort result; #ifndef SWIFTEN_PLATFORM_IPHONE - CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); - if(proxies != NULL) { - result = getFromDictionary(proxies, kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort); - CFRelease(proxies); - } + CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); + if(proxies != NULL) { + result = getFromDictionary(proxies, kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort); + CFRelease(proxies); + } #endif - return result; + return result; } HostAddressPort MacOSXProxyProvider::getSOCKS5Proxy() const { - HostAddressPort result; + HostAddressPort result; #ifndef SWIFTEN_PLATFORM_IPHONE - CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); - if(proxies != NULL) { - result = getFromDictionary(proxies, kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort); - CFRelease(proxies); - } + CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); + if(proxies != NULL) { + result = getFromDictionary(proxies, kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort); + CFRelease(proxies); + } #endif - return result; + return result; } } diff --git a/Swiften/Network/MacOSXProxyProvider.h b/Swiften/Network/MacOSXProxyProvider.h index 53a7760..56ffd9f 100644 --- a/Swiften/Network/MacOSXProxyProvider.h +++ b/Swiften/Network/MacOSXProxyProvider.h @@ -17,10 +17,10 @@ #include <Swiften/Network/ProxyProvider.h> namespace Swift { - class MacOSXProxyProvider : public ProxyProvider { - public: - MacOSXProxyProvider(); - virtual HostAddressPort getHTTPConnectProxy() const; - virtual HostAddressPort getSOCKS5Proxy() const; - }; + class MacOSXProxyProvider : public ProxyProvider { + public: + MacOSXProxyProvider(); + virtual HostAddressPort getHTTPConnectProxy() const; + virtual HostAddressPort getSOCKS5Proxy() const; + }; } diff --git a/Swiften/Network/MiniUPnPInterface.cpp b/Swiften/Network/MiniUPnPInterface.cpp index 3ca2ec4..3da6572 100644 --- a/Swiften/Network/MiniUPnPInterface.cpp +++ b/Swiften/Network/MiniUPnPInterface.cpp @@ -24,94 +24,94 @@ namespace Swift { struct MiniUPnPInterface::Private { - bool isValid; - std::string localAddress; - UPNPDev* deviceList; - UPNPUrls urls; - IGDdatas data; + bool isValid; + std::string localAddress; + UPNPDev* deviceList; + UPNPUrls urls; + IGDdatas data; }; MiniUPnPInterface::MiniUPnPInterface() : p(boost::make_shared<Private>()) { - p->isValid = false; - int error = 0; - p->deviceList = upnpDiscover(1500 /* timeout in ms */, 0, 0, 0, 0 /* do IPv6? */, &error); - if (!p->deviceList) { - return; - } - - char lanAddress[64]; - if (!UPNP_GetValidIGD(p->deviceList, &p->urls, &p->data, lanAddress, sizeof(lanAddress))) { - return; - } - p->localAddress = std::string(lanAddress); - p->isValid = true; + p->isValid = false; + int error = 0; + p->deviceList = upnpDiscover(1500 /* timeout in ms */, 0, 0, 0, 0 /* do IPv6? */, &error); + if (!p->deviceList) { + return; + } + + char lanAddress[64]; + if (!UPNP_GetValidIGD(p->deviceList, &p->urls, &p->data, lanAddress, sizeof(lanAddress))) { + return; + } + p->localAddress = std::string(lanAddress); + p->isValid = true; } MiniUPnPInterface::~MiniUPnPInterface() { - if (p->isValid) { - FreeUPNPUrls(&p->urls); - } - freeUPNPDevlist(p->deviceList); + if (p->isValid) { + FreeUPNPUrls(&p->urls); + } + freeUPNPDevlist(p->deviceList); } boost::optional<HostAddress> MiniUPnPInterface::getPublicIP() { - if (!p->isValid) { - return boost::optional<HostAddress>(); - } - char externalIPAddress[40]; - int ret = UPNP_GetExternalIPAddress(p->urls.controlURL, p->data.first.servicetype, externalIPAddress); - if (ret != UPNPCOMMAND_SUCCESS) { - return boost::optional<HostAddress>(); - } - else { - return HostAddress(std::string(externalIPAddress)); - } + if (!p->isValid) { + return boost::optional<HostAddress>(); + } + char externalIPAddress[40]; + int ret = UPNP_GetExternalIPAddress(p->urls.controlURL, p->data.first.servicetype, externalIPAddress); + if (ret != UPNPCOMMAND_SUCCESS) { + return boost::optional<HostAddress>(); + } + else { + return HostAddress(std::string(externalIPAddress)); + } } boost::optional<NATPortMapping> MiniUPnPInterface::addPortForward(int actualLocalPort, int actualPublicPort) { - if (!p->isValid) { - return boost::optional<NATPortMapping>(); - } - - NATPortMapping mapping(actualLocalPort, actualPublicPort, NATPortMapping::TCP); - - std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); - std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); - std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); - - int ret = UPNP_AddPortMapping( - p->urls.controlURL, - p->data.first.servicetype, - publicPort.c_str(), - localPort.c_str(), - p->localAddress.c_str(), - "Swift", - mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", - 0, - leaseSeconds.c_str()); - if (ret == UPNPCOMMAND_SUCCESS) { - return mapping; - } - else { - return boost::optional<NATPortMapping>(); - } + if (!p->isValid) { + return boost::optional<NATPortMapping>(); + } + + NATPortMapping mapping(actualLocalPort, actualPublicPort, NATPortMapping::TCP); + + std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); + std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); + std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); + + int ret = UPNP_AddPortMapping( + p->urls.controlURL, + p->data.first.servicetype, + publicPort.c_str(), + localPort.c_str(), + p->localAddress.c_str(), + "Swift", + mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", + 0, + leaseSeconds.c_str()); + if (ret == UPNPCOMMAND_SUCCESS) { + return mapping; + } + else { + return boost::optional<NATPortMapping>(); + } } bool MiniUPnPInterface::removePortForward(const NATPortMapping& mapping) { - if (!p->isValid) { - return false; - } + if (!p->isValid) { + return false; + } - std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); - std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); - std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); + std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); + std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); + std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); - int ret = UPNP_DeletePortMapping(p->urls.controlURL, p->data.first.servicetype, publicPort.c_str(), mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", 0); - return ret == UPNPCOMMAND_SUCCESS; + int ret = UPNP_DeletePortMapping(p->urls.controlURL, p->data.first.servicetype, publicPort.c_str(), mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", 0); + return ret == UPNPCOMMAND_SUCCESS; } bool MiniUPnPInterface::isAvailable() { - return p->isValid; + return p->isValid; } } diff --git a/Swiften/Network/MiniUPnPInterface.h b/Swiften/Network/MiniUPnPInterface.h index 46e45e5..5253e71 100644 --- a/Swiften/Network/MiniUPnPInterface.h +++ b/Swiften/Network/MiniUPnPInterface.h @@ -14,19 +14,19 @@ #include <Swiften/Network/NATTraversalInterface.h> namespace Swift { - class MiniUPnPInterface : public NATTraversalInterface, boost::noncopyable { - public: - MiniUPnPInterface(); - virtual ~MiniUPnPInterface(); + class MiniUPnPInterface : public NATTraversalInterface, boost::noncopyable { + public: + MiniUPnPInterface(); + virtual ~MiniUPnPInterface(); - virtual bool isAvailable(); + virtual bool isAvailable(); - boost::optional<HostAddress> getPublicIP(); - boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort); - bool removePortForward(const NATPortMapping&); + boost::optional<HostAddress> getPublicIP(); + boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort); + bool removePortForward(const NATPortMapping&); - private: - struct Private; - boost::shared_ptr<Private> p; - }; + private: + struct Private; + boost::shared_ptr<Private> p; + }; } diff --git a/Swiften/Network/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp index e84d6ec..4818170 100644 --- a/Swiften/Network/NATPMPInterface.cpp +++ b/Swiften/Network/NATPMPInterface.cpp @@ -26,117 +26,117 @@ namespace Swift { struct NATPMPInterface::Private { - natpmp_t natpmp; + natpmp_t natpmp; }; NATPMPInterface::NATPMPInterface() : p(boost::make_shared<Private>()) { - initnatpmp(&p->natpmp, 0, 0); + initnatpmp(&p->natpmp, 0, 0); } NATPMPInterface::~NATPMPInterface() { - closenatpmp(&p->natpmp); + closenatpmp(&p->natpmp); } bool NATPMPInterface::isAvailable() { - return getPublicIP() ? true : false; + return getPublicIP() ? true : false; } boost::optional<HostAddress> NATPMPInterface::getPublicIP() { - if (sendpublicaddressrequest(&p->natpmp) < 0) { - SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl; - return boost::optional<HostAddress>(); - } - - int r = 0; - natpmpresp_t response; - do { - fd_set fds; - struct timeval timeout; - FD_ZERO(&fds); - FD_SET(p->natpmp.s, &fds); - getnatpmprequesttimeout(&p->natpmp, &timeout); - - // Limit NAT-PMP timeout to ten seconds. - timeout.tv_sec = 10; - timeout.tv_usec = 0; - - select(FD_SETSIZE, &fds, NULL, NULL, &timeout); - r = readnatpmpresponseorretry(&p->natpmp, &response); - } while (false /*r == NATPMP_TRYAGAIN*/); - - if (r == 0) { - return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4)); - } - else { - SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl; - return boost::optional<HostAddress>(); - } + if (sendpublicaddressrequest(&p->natpmp) < 0) { + SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl; + return boost::optional<HostAddress>(); + } + + int r = 0; + natpmpresp_t response; + do { + fd_set fds; + struct timeval timeout; + FD_ZERO(&fds); + FD_SET(p->natpmp.s, &fds); + getnatpmprequesttimeout(&p->natpmp, &timeout); + + // Limit NAT-PMP timeout to ten seconds. + timeout.tv_sec = 10; + timeout.tv_usec = 0; + + select(FD_SETSIZE, &fds, NULL, NULL, &timeout); + r = readnatpmpresponseorretry(&p->natpmp, &response); + } while (false /*r == NATPMP_TRYAGAIN*/); + + if (r == 0) { + return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4)); + } + else { + SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl; + return boost::optional<HostAddress>(); + } } boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, int publicPort) { - NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); - if (sendnewportmappingrequest( - &p->natpmp, - mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, - boost::numeric_cast<uint16_t>(mapping.getLocalPort()), - boost::numeric_cast<uint16_t>(mapping.getPublicPort()), - boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) { - SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl; - return boost::optional<NATPortMapping>(); - } - - int r = 0; - natpmpresp_t response; - do { - fd_set fds; - struct timeval timeout; - FD_ZERO(&fds); - FD_SET(p->natpmp.s, &fds); - getnatpmprequesttimeout(&p->natpmp, &timeout); - - // Limit NAT-PMP timeout to ten seconds. - timeout.tv_sec = 10; - timeout.tv_usec = 0; - - select(FD_SETSIZE, &fds, NULL, NULL, &timeout); - r = readnatpmpresponseorretry(&p->natpmp, &response); - } while(false /*r == NATPMP_TRYAGAIN*/); - - if (r == 0) { - NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime)); - return result; - } - else { - SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; - return boost::optional<NATPortMapping>(); - } + NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); + if (sendnewportmappingrequest( + &p->natpmp, + mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, + boost::numeric_cast<uint16_t>(mapping.getLocalPort()), + boost::numeric_cast<uint16_t>(mapping.getPublicPort()), + boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) { + SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl; + return boost::optional<NATPortMapping>(); + } + + int r = 0; + natpmpresp_t response; + do { + fd_set fds; + struct timeval timeout; + FD_ZERO(&fds); + FD_SET(p->natpmp.s, &fds); + getnatpmprequesttimeout(&p->natpmp, &timeout); + + // Limit NAT-PMP timeout to ten seconds. + timeout.tv_sec = 10; + timeout.tv_usec = 0; + + select(FD_SETSIZE, &fds, NULL, NULL, &timeout); + r = readnatpmpresponseorretry(&p->natpmp, &response); + } while(false /*r == NATPMP_TRYAGAIN*/); + + if (r == 0) { + NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime)); + return result; + } + else { + SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; + return boost::optional<NATPortMapping>(); + } } bool NATPMPInterface::removePortForward(const NATPortMapping& mapping) { - if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, boost::numeric_cast<uint32_t>(mapping.getLocalPort())) < 0) { - SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl; - return false; - } - - int r = 0; - natpmpresp_t response; - do { - fd_set fds; - struct timeval timeout; - FD_ZERO(&fds); - FD_SET(p->natpmp.s, &fds); - getnatpmprequesttimeout(&p->natpmp, &timeout); - select(FD_SETSIZE, &fds, NULL, NULL, &timeout); - r = readnatpmpresponseorretry(&p->natpmp, &response); - } while(r == NATPMP_TRYAGAIN); - - if (r == 0) { - return true; - } - else { - SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; - return false; - } + if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, boost::numeric_cast<uint32_t>(mapping.getLocalPort())) < 0) { + SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl; + return false; + } + + int r = 0; + natpmpresp_t response; + do { + fd_set fds; + struct timeval timeout; + FD_ZERO(&fds); + FD_SET(p->natpmp.s, &fds); + getnatpmprequesttimeout(&p->natpmp, &timeout); + select(FD_SETSIZE, &fds, NULL, NULL, &timeout); + r = readnatpmpresponseorretry(&p->natpmp, &response); + } while(r == NATPMP_TRYAGAIN); + + if (r == 0) { + return true; + } + else { + SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; + return false; + } } diff --git a/Swiften/Network/NATPMPInterface.h b/Swiften/Network/NATPMPInterface.h index 467ee5c..a4bb816 100644 --- a/Swiften/Network/NATPMPInterface.h +++ b/Swiften/Network/NATPMPInterface.h @@ -14,19 +14,19 @@ #include <Swiften/Network/NATTraversalInterface.h> namespace Swift { - class NATPMPInterface : public NATTraversalInterface, boost::noncopyable { - public: - NATPMPInterface(); - virtual ~NATPMPInterface(); + class NATPMPInterface : public NATTraversalInterface, boost::noncopyable { + public: + NATPMPInterface(); + virtual ~NATPMPInterface(); - virtual bool isAvailable(); + virtual bool isAvailable(); - virtual boost::optional<HostAddress> getPublicIP(); - virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort); - virtual bool removePortForward(const NATPortMapping&); + virtual boost::optional<HostAddress> getPublicIP(); + virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort); + virtual bool removePortForward(const NATPortMapping&); - private: - struct Private; - boost::shared_ptr<Private> p; - }; + private: + struct Private; + boost::shared_ptr<Private> p; + }; } diff --git a/Swiften/Network/NATPortMapping.h b/Swiften/Network/NATPortMapping.h index 3ddf39e..ff8fde3 100644 --- a/Swiften/Network/NATPortMapping.h +++ b/Swiften/Network/NATPortMapping.h @@ -16,38 +16,38 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class SWIFTEN_API NATPortMapping { - public: - enum Protocol { - TCP, - UDP - }; - - NATPortMapping(int localPort, int publicPort, Protocol protocol = TCP, int leaseInSeconds = 60 * 60 * 24) : - publicPort(publicPort), localPort(localPort), protocol(protocol), leaseInSeconds(leaseInSeconds) { - - } - - int getPublicPort() const { - return publicPort; - } - - int getLocalPort() const { - return localPort; - } - - Protocol getProtocol() const { - return protocol; - } - - int getLeaseInSeconds() const { - return leaseInSeconds; - } - - private: - int publicPort; - int localPort; - Protocol protocol; - int leaseInSeconds; - }; + class SWIFTEN_API NATPortMapping { + public: + enum Protocol { + TCP, + UDP + }; + + NATPortMapping(int localPort, int publicPort, Protocol protocol = TCP, int leaseInSeconds = 60 * 60 * 24) : + publicPort(publicPort), localPort(localPort), protocol(protocol), leaseInSeconds(leaseInSeconds) { + + } + + int getPublicPort() const { + return publicPort; + } + + int getLocalPort() const { + return localPort; + } + + Protocol getProtocol() const { + return protocol; + } + + int getLeaseInSeconds() const { + return leaseInSeconds; + } + + private: + int publicPort; + int localPort; + Protocol protocol; + int leaseInSeconds; + }; } diff --git a/Swiften/Network/NATTraversalForwardPortRequest.h b/Swiften/Network/NATTraversalForwardPortRequest.h index 155d30b..0565b4c 100644 --- a/Swiften/Network/NATTraversalForwardPortRequest.h +++ b/Swiften/Network/NATTraversalForwardPortRequest.h @@ -17,13 +17,13 @@ #include <Swiften/Network/NATPortMapping.h> namespace Swift { - class SWIFTEN_API NATTraversalForwardPortRequest { - public: - virtual ~NATTraversalForwardPortRequest(); + class SWIFTEN_API NATTraversalForwardPortRequest { + public: + virtual ~NATTraversalForwardPortRequest(); - virtual void start() = 0; - virtual void stop() = 0; + virtual void start() = 0; + virtual void stop() = 0; - boost::signal<void (boost::optional<NATPortMapping>)> onResult; - }; + boost::signal<void (boost::optional<NATPortMapping>)> onResult; + }; } diff --git a/Swiften/Network/NATTraversalGetPublicIPRequest.h b/Swiften/Network/NATTraversalGetPublicIPRequest.h index 725afd2..8cdc067 100644 --- a/Swiften/Network/NATTraversalGetPublicIPRequest.h +++ b/Swiften/Network/NATTraversalGetPublicIPRequest.h @@ -17,13 +17,13 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class SWIFTEN_API NATTraversalGetPublicIPRequest { - public: - virtual ~NATTraversalGetPublicIPRequest(); + class SWIFTEN_API NATTraversalGetPublicIPRequest { + public: + virtual ~NATTraversalGetPublicIPRequest(); - virtual void start() = 0; - virtual void stop() = 0; + virtual void start() = 0; + virtual void stop() = 0; - boost::signal<void (boost::optional<HostAddress>)> onResult; - }; + boost::signal<void (boost::optional<HostAddress>)> onResult; + }; } diff --git a/Swiften/Network/NATTraversalInterface.h b/Swiften/Network/NATTraversalInterface.h index 4e5f5fc..ea9ed6a 100644 --- a/Swiften/Network/NATTraversalInterface.h +++ b/Swiften/Network/NATTraversalInterface.h @@ -12,14 +12,14 @@ #include <Swiften/Network/NATPortMapping.h> namespace Swift { - class SWIFTEN_API NATTraversalInterface { - public: - virtual ~NATTraversalInterface(); + class SWIFTEN_API NATTraversalInterface { + public: + virtual ~NATTraversalInterface(); - virtual bool isAvailable() = 0; + virtual bool isAvailable() = 0; - virtual boost::optional<HostAddress> getPublicIP() = 0; - virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort) = 0; - virtual bool removePortForward(const NATPortMapping&) = 0; - }; + virtual boost::optional<HostAddress> getPublicIP() = 0; + virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort) = 0; + virtual bool removePortForward(const NATPortMapping&) = 0; + }; } diff --git a/Swiften/Network/NATTraversalRemovePortForwardingRequest.h b/Swiften/Network/NATTraversalRemovePortForwardingRequest.h index efbf6ea..8200197 100644 --- a/Swiften/Network/NATTraversalRemovePortForwardingRequest.h +++ b/Swiften/Network/NATTraversalRemovePortForwardingRequest.h @@ -17,26 +17,26 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class SWIFTEN_API NATTraversalRemovePortForwardingRequest { - public: - struct PortMapping { - enum Protocol { - TCP, - UDP - }; - - unsigned int publicPort; - unsigned int localPort; - Protocol protocol; - unsigned long leaseInSeconds; - }; - - public: - virtual ~NATTraversalRemovePortForwardingRequest(); - - virtual void start() = 0; - virtual void stop() = 0; - - boost::signal<void (boost::optional<bool> /* failure */)> onResult; - }; + class SWIFTEN_API NATTraversalRemovePortForwardingRequest { + public: + struct PortMapping { + enum Protocol { + TCP, + UDP + }; + + unsigned int publicPort; + unsigned int localPort; + Protocol protocol; + unsigned long leaseInSeconds; + }; + + public: + virtual ~NATTraversalRemovePortForwardingRequest(); + + virtual void start() = 0; + virtual void stop() = 0; + + boost::signal<void (boost::optional<bool> /* failure */)> onResult; + }; } diff --git a/Swiften/Network/NATTraverser.h b/Swiften/Network/NATTraverser.h index e86704a..0ff6bb3 100644 --- a/Swiften/Network/NATTraverser.h +++ b/Swiften/Network/NATTraverser.h @@ -11,16 +11,16 @@ #include <Swiften/Base/API.h> namespace Swift { - class NATTraversalGetPublicIPRequest; - class NATTraversalForwardPortRequest; - class NATTraversalRemovePortForwardingRequest; + class NATTraversalGetPublicIPRequest; + class NATTraversalForwardPortRequest; + class NATTraversalRemovePortForwardingRequest; - class SWIFTEN_API NATTraverser { - public: - virtual ~NATTraverser(); + class SWIFTEN_API NATTraverser { + public: + virtual ~NATTraverser(); - virtual boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest() = 0; - virtual boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort) = 0; - virtual boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort) = 0; - }; + virtual boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest() = 0; + virtual boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort) = 0; + virtual boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort) = 0; + }; } diff --git a/Swiften/Network/NetworkEnvironment.cpp b/Swiften/Network/NetworkEnvironment.cpp index dff310e..19f727c 100644 --- a/Swiften/Network/NetworkEnvironment.cpp +++ b/Swiften/Network/NetworkEnvironment.cpp @@ -16,17 +16,17 @@ NetworkEnvironment::~NetworkEnvironment() { } HostAddress NetworkEnvironment::getLocalAddress() const { - std::vector<NetworkInterface> networkInterfaces = getNetworkInterfaces(); - foreach (const NetworkInterface& iface, networkInterfaces) { - if (!iface.isLoopback()) { - foreach (const HostAddress& address, iface.getAddresses()) { - if (address.getRawAddress().is_v4()) { - return address; - } - } - } - } - return HostAddress(); + std::vector<NetworkInterface> networkInterfaces = getNetworkInterfaces(); + foreach (const NetworkInterface& iface, networkInterfaces) { + if (!iface.isLoopback()) { + foreach (const HostAddress& address, iface.getAddresses()) { + if (address.getRawAddress().is_v4()) { + return address; + } + } + } + } + return HostAddress(); } } diff --git a/Swiften/Network/NetworkEnvironment.h b/Swiften/Network/NetworkEnvironment.h index 36a2bde..c98a78f 100644 --- a/Swiften/Network/NetworkEnvironment.h +++ b/Swiften/Network/NetworkEnvironment.h @@ -13,12 +13,12 @@ #include <Swiften/Network/NetworkInterface.h> namespace Swift { - class SWIFTEN_API NetworkEnvironment { - public: - virtual ~NetworkEnvironment(); + class SWIFTEN_API NetworkEnvironment { + public: + virtual ~NetworkEnvironment(); - virtual std::vector<NetworkInterface> getNetworkInterfaces() const = 0; + virtual std::vector<NetworkInterface> getNetworkInterfaces() const = 0; - HostAddress getLocalAddress() const; - }; + HostAddress getLocalAddress() const; + }; } diff --git a/Swiften/Network/NetworkFactories.h b/Swiften/Network/NetworkFactories.h index 81ce0c5..7c76c67 100644 --- a/Swiften/Network/NetworkFactories.h +++ b/Swiften/Network/NetworkFactories.h @@ -9,38 +9,38 @@ #include <Swiften/Base/API.h> namespace Swift { - class TimerFactory; - class ConnectionFactory; - class DomainNameResolver; - class ConnectionServerFactory; - class NATTraverser; - class XMLParserFactory; - class TLSContextFactory; - class CertificateFactory; - class ProxyProvider; - class EventLoop; - class IDNConverter; - class NetworkEnvironment; - class CryptoProvider; + class TimerFactory; + class ConnectionFactory; + class DomainNameResolver; + class ConnectionServerFactory; + class NATTraverser; + class XMLParserFactory; + class TLSContextFactory; + class CertificateFactory; + class ProxyProvider; + class EventLoop; + class IDNConverter; + class NetworkEnvironment; + class CryptoProvider; - /** - * An interface collecting network factories. - */ - class SWIFTEN_API NetworkFactories { - public: - virtual ~NetworkFactories(); + /** + * An interface collecting network factories. + */ + class SWIFTEN_API NetworkFactories { + public: + virtual ~NetworkFactories(); - virtual TimerFactory* getTimerFactory() const = 0; - virtual ConnectionFactory* getConnectionFactory() const = 0; - virtual DomainNameResolver* getDomainNameResolver() const = 0; - virtual ConnectionServerFactory* getConnectionServerFactory() const = 0; - virtual NATTraverser* getNATTraverser() const = 0; - virtual NetworkEnvironment* getNetworkEnvironment() const = 0; - virtual XMLParserFactory* getXMLParserFactory() const = 0; - virtual TLSContextFactory* getTLSContextFactory() const = 0; - virtual ProxyProvider* getProxyProvider() const = 0; - virtual EventLoop* getEventLoop() const = 0; - virtual IDNConverter* getIDNConverter() const = 0; - virtual CryptoProvider* getCryptoProvider() const = 0; - }; + virtual TimerFactory* getTimerFactory() const = 0; + virtual ConnectionFactory* getConnectionFactory() const = 0; + virtual DomainNameResolver* getDomainNameResolver() const = 0; + virtual ConnectionServerFactory* getConnectionServerFactory() const = 0; + virtual NATTraverser* getNATTraverser() const = 0; + virtual NetworkEnvironment* getNetworkEnvironment() const = 0; + virtual XMLParserFactory* getXMLParserFactory() const = 0; + virtual TLSContextFactory* getTLSContextFactory() const = 0; + virtual ProxyProvider* getProxyProvider() const = 0; + virtual EventLoop* getEventLoop() const = 0; + virtual IDNConverter* getIDNConverter() const = 0; + virtual CryptoProvider* getCryptoProvider() const = 0; + }; } diff --git a/Swiften/Network/NetworkInterface.h b/Swiften/Network/NetworkInterface.h index 0c1ba07..91aefc4 100644 --- a/Swiften/Network/NetworkInterface.h +++ b/Swiften/Network/NetworkInterface.h @@ -18,30 +18,30 @@ #include <Swiften/Network/HostAddress.h> namespace Swift { - class SWIFTEN_API NetworkInterface { - public: - NetworkInterface(const std::string& name, bool loopback) : name(name), loopback(loopback) { - } - - void addAddress(const HostAddress& address) { - addresses.push_back(address); - } - - const std::vector<HostAddress>& getAddresses() const { - return addresses; - } - - const std::string& getName() const { - return name; - } - - bool isLoopback() const { - return loopback; - } - - private: - std::string name; - bool loopback; - std::vector<HostAddress> addresses; - }; + class SWIFTEN_API NetworkInterface { + public: + NetworkInterface(const std::string& name, bool loopback) : name(name), loopback(loopback) { + } + + void addAddress(const HostAddress& address) { + addresses.push_back(address); + } + + const std::vector<HostAddress>& getAddresses() const { + return addresses; + } + + const std::string& getName() const { + return name; + } + + bool isLoopback() const { + return loopback; + } + + private: + std::string name; + bool loopback; + std::vector<HostAddress> addresses; + }; } diff --git a/Swiften/Network/NullNATTraversalInterface.h b/Swiften/Network/NullNATTraversalInterface.h index 281dca2..ecbf110 100644 --- a/Swiften/Network/NullNATTraversalInterface.h +++ b/Swiften/Network/NullNATTraversalInterface.h @@ -11,22 +11,22 @@ #include <Swiften/Network/NATTraversalInterface.h> namespace Swift { - class NullNATTraversalInterface : public NATTraversalInterface { - public: - virtual bool isAvailable() { - return true; - } + class NullNATTraversalInterface : public NATTraversalInterface { + public: + virtual bool isAvailable() { + return true; + } - virtual boost::optional<HostAddress> getPublicIP() { - return boost::optional<HostAddress>(); - } + virtual boost::optional<HostAddress> getPublicIP() { + return boost::optional<HostAddress>(); + } - virtual boost::optional<NATPortMapping> addPortForward(int, int) { - return boost::optional<NATPortMapping>(); - } + virtual boost::optional<NATPortMapping> addPortForward(int, int) { + return boost::optional<NATPortMapping>(); + } - virtual bool removePortForward(const NATPortMapping&) { - return false; - } - }; + virtual bool removePortForward(const NATPortMapping&) { + return false; + } + }; } diff --git a/Swiften/Network/NullNATTraverser.cpp b/Swiften/Network/NullNATTraverser.cpp index 3f7b1c1..c4e121b 100644 --- a/Swiften/Network/NullNATTraverser.cpp +++ b/Swiften/Network/NullNATTraverser.cpp @@ -17,66 +17,66 @@ namespace Swift { class NullNATTraversalGetPublicIPRequest : public NATTraversalGetPublicIPRequest { - public: - NullNATTraversalGetPublicIPRequest(EventLoop* eventLoop) : eventLoop(eventLoop) { - } + public: + NullNATTraversalGetPublicIPRequest(EventLoop* eventLoop) : eventLoop(eventLoop) { + } - virtual void start() { - eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<HostAddress>())); - } + virtual void start() { + eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<HostAddress>())); + } - virtual void stop() { - } + virtual void stop() { + } - private: - EventLoop* eventLoop; + private: + EventLoop* eventLoop; }; class NullNATTraversalForwardPortRequest : public NATTraversalForwardPortRequest { - public: - NullNATTraversalForwardPortRequest(EventLoop* eventLoop) : eventLoop(eventLoop) { - } + public: + NullNATTraversalForwardPortRequest(EventLoop* eventLoop) : eventLoop(eventLoop) { + } - virtual void start() { - eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<NATPortMapping>())); - } + virtual void start() { + eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<NATPortMapping>())); + } - virtual void stop() { - } + virtual void stop() { + } - private: - EventLoop* eventLoop; + private: + EventLoop* eventLoop; }; class NullNATTraversalRemovePortForwardingRequest : public NATTraversalRemovePortForwardingRequest { - public: - NullNATTraversalRemovePortForwardingRequest(EventLoop* eventLoop) : eventLoop(eventLoop) { - } + public: + NullNATTraversalRemovePortForwardingRequest(EventLoop* eventLoop) : eventLoop(eventLoop) { + } - virtual void start() { - eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<bool>(true))); - } + virtual void start() { + eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<bool>(true))); + } - virtual void stop() { - } + virtual void stop() { + } - private: - EventLoop* eventLoop; + private: + EventLoop* eventLoop; }; NullNATTraverser::NullNATTraverser(EventLoop* eventLoop) : eventLoop(eventLoop) { } boost::shared_ptr<NATTraversalGetPublicIPRequest> NullNATTraverser::createGetPublicIPRequest() { - return boost::make_shared<NullNATTraversalGetPublicIPRequest>(eventLoop); + return boost::make_shared<NullNATTraversalGetPublicIPRequest>(eventLoop); } boost::shared_ptr<NATTraversalForwardPortRequest> NullNATTraverser::createForwardPortRequest(int, int) { - return boost::make_shared<NullNATTraversalForwardPortRequest>(eventLoop); + return boost::make_shared<NullNATTraversalForwardPortRequest>(eventLoop); } boost::shared_ptr<NATTraversalRemovePortForwardingRequest> NullNATTraverser::createRemovePortForwardingRequest(int, int) { - return boost::make_shared<NullNATTraversalRemovePortForwardingRequest>(eventLoop); + return boost::make_shared<NullNATTraversalRemovePortForwardingRequest>(eventLoop); } } diff --git a/Swiften/Network/NullNATTraverser.h b/Swiften/Network/NullNATTraverser.h index 3e388d9..3492940 100644 --- a/Swiften/Network/NullNATTraverser.h +++ b/Swiften/Network/NullNATTraverser.h @@ -9,17 +9,17 @@ #include <Swiften/Network/NATTraverser.h> namespace Swift { - class EventLoop; + class EventLoop; - class NullNATTraverser : public NATTraverser { - public: - NullNATTraverser(EventLoop* eventLoop); + class NullNATTraverser : public NATTraverser { + public: + NullNATTraverser(EventLoop* eventLoop); - boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest(); - boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort); - boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort); + boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest(); + boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort); + boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort); - private: - EventLoop* eventLoop; - }; + private: + EventLoop* eventLoop; + }; } diff --git a/Swiften/Network/NullProxyProvider.cpp b/Swiften/Network/NullProxyProvider.cpp index 3a04480..32a1b9d 100644 --- a/Swiften/Network/NullProxyProvider.cpp +++ b/Swiften/Network/NullProxyProvider.cpp @@ -12,9 +12,9 @@ NullProxyProvider::NullProxyProvider() { } HostAddressPort NullProxyProvider::getHTTPConnectProxy() const { - return HostAddressPort(); + return HostAddressPort(); } HostAddressPort NullProxyProvider::getSOCKS5Proxy() const { - return HostAddressPort(); + return HostAddressPort(); } diff --git a/Swiften/Network/NullProxyProvider.h b/Swiften/Network/NullProxyProvider.h index 7567505..ae7aaab 100644 --- a/Swiften/Network/NullProxyProvider.h +++ b/Swiften/Network/NullProxyProvider.h @@ -9,11 +9,11 @@ #include <Swiften/Network/ProxyProvider.h> namespace Swift { - class NullProxyProvider : public ProxyProvider { - public: - NullProxyProvider(); + class NullProxyProvider : public ProxyProvider { + public: + NullProxyProvider(); - virtual HostAddressPort getHTTPConnectProxy() const; - virtual HostAddressPort getSOCKS5Proxy() const; - }; + virtual HostAddressPort getHTTPConnectProxy() const; + virtual HostAddressPort getSOCKS5Proxy() const; + }; } diff --git a/Swiften/Network/PlatformDomainNameAddressQuery.cpp b/Swiften/Network/PlatformDomainNameAddressQuery.cpp index 8b72c3b..2d72146 100644 --- a/Swiften/Network/PlatformDomainNameAddressQuery.cpp +++ b/Swiften/Network/PlatformDomainNameAddressQuery.cpp @@ -14,57 +14,57 @@ namespace Swift { PlatformDomainNameAddressQuery::PlatformDomainNameAddressQuery(const boost::optional<std::string>& host, EventLoop* eventLoop, PlatformDomainNameResolver* resolver) : PlatformDomainNameQuery(resolver), hostnameValid(false), eventLoop(eventLoop) { - if (!!host) { - hostname = *host; - hostnameValid = true; - } + if (!!host) { + hostname = *host; + hostnameValid = true; + } } PlatformDomainNameAddressQuery::~PlatformDomainNameAddressQuery() { - + } void PlatformDomainNameAddressQuery::run() { - getResolver()->addQueryToQueue(shared_from_this()); + getResolver()->addQueryToQueue(shared_from_this()); } void PlatformDomainNameAddressQuery::runBlocking() { - if (!hostnameValid) { - emitError(); - return; - } - //std::cout << "PlatformDomainNameResolver::doRun()" << std::endl; - boost::asio::ip::tcp::resolver resolver(ioService); - boost::asio::ip::tcp::resolver::query query(hostname, "5222", boost::asio::ip::resolver_query_base::passive); - try { - //std::cout << "PlatformDomainNameResolver::doRun(): Resolving" << std::endl; - boost::asio::ip::tcp::resolver::iterator endpointIterator = resolver.resolve(query); - //std::cout << "PlatformDomainNameResolver::doRun(): Resolved" << std::endl; - if (endpointIterator == boost::asio::ip::tcp::resolver::iterator()) { - //std::cout << "PlatformDomainNameResolver::doRun(): Error 1" << std::endl; - emitError(); - } - else { - std::vector<HostAddress> results; - for ( ; endpointIterator != boost::asio::ip::tcp::resolver::iterator(); ++endpointIterator) { - boost::asio::ip::address address = (*endpointIterator).endpoint().address(); - results.push_back(address.is_v4() ? HostAddress(&address.to_v4().to_bytes()[0], 4) : HostAddress(&address.to_v6().to_bytes()[0], 16)); - } + if (!hostnameValid) { + emitError(); + return; + } + //std::cout << "PlatformDomainNameResolver::doRun()" << std::endl; + boost::asio::ip::tcp::resolver resolver(ioService); + boost::asio::ip::tcp::resolver::query query(hostname, "5222", boost::asio::ip::resolver_query_base::passive); + try { + //std::cout << "PlatformDomainNameResolver::doRun(): Resolving" << std::endl; + boost::asio::ip::tcp::resolver::iterator endpointIterator = resolver.resolve(query); + //std::cout << "PlatformDomainNameResolver::doRun(): Resolved" << std::endl; + if (endpointIterator == boost::asio::ip::tcp::resolver::iterator()) { + //std::cout << "PlatformDomainNameResolver::doRun(): Error 1" << std::endl; + emitError(); + } + else { + std::vector<HostAddress> results; + for ( ; endpointIterator != boost::asio::ip::tcp::resolver::iterator(); ++endpointIterator) { + boost::asio::ip::address address = (*endpointIterator).endpoint().address(); + results.push_back(address.is_v4() ? HostAddress(&address.to_v4().to_bytes()[0], 4) : HostAddress(&address.to_v6().to_bytes()[0], 16)); + } - //std::cout << "PlatformDomainNameResolver::doRun(): Success" << std::endl; - eventLoop->postEvent( - boost::bind(boost::ref(onResult), results, boost::optional<DomainNameResolveError>()), - shared_from_this()); - } - } - catch (...) { - //std::cout << "PlatformDomainNameResolver::doRun(): Error 2" << std::endl; - emitError(); - } + //std::cout << "PlatformDomainNameResolver::doRun(): Success" << std::endl; + eventLoop->postEvent( + boost::bind(boost::ref(onResult), results, boost::optional<DomainNameResolveError>()), + shared_from_this()); + } + } + catch (...) { + //std::cout << "PlatformDomainNameResolver::doRun(): Error 2" << std::endl; + emitError(); + } } void PlatformDomainNameAddressQuery::emitError() { - eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), shared_from_this()); + eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), shared_from_this()); } } diff --git a/Swiften/Network/PlatformDomainNameAddressQuery.h b/Swiften/Network/PlatformDomainNameAddressQuery.h index c241f2a..a5cfda7 100644 --- a/Swiften/Network/PlatformDomainNameAddressQuery.h +++ b/Swiften/Network/PlatformDomainNameAddressQuery.h @@ -16,26 +16,26 @@ #include <Swiften/Network/PlatformDomainNameQuery.h> namespace Swift { - class PlatformDomainNameResolver; - class EventLoop; - - class PlatformDomainNameAddressQuery : public DomainNameAddressQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameAddressQuery>, public EventOwner { - public: - PlatformDomainNameAddressQuery(const boost::optional<std::string>& host, EventLoop* eventLoop, PlatformDomainNameResolver*); - virtual ~PlatformDomainNameAddressQuery(); - - void run(); - - private: - void runBlocking(); - void emitError(); - - private: - boost::asio::io_service ioService; - std::string hostname; - bool hostnameValid; - EventLoop* eventLoop; - }; + class PlatformDomainNameResolver; + class EventLoop; + + class PlatformDomainNameAddressQuery : public DomainNameAddressQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameAddressQuery>, public EventOwner { + public: + PlatformDomainNameAddressQuery(const boost::optional<std::string>& host, EventLoop* eventLoop, PlatformDomainNameResolver*); + virtual ~PlatformDomainNameAddressQuery(); + + void run(); + + private: + void runBlocking(); + void emitError(); + + private: + boost::asio::io_service ioService; + std::string hostname; + bool hostnameValid; + EventLoop* eventLoop; + }; } diff --git a/Swiften/Network/PlatformDomainNameQuery.h b/Swiften/Network/PlatformDomainNameQuery.h index e8161de..3c5e152 100644 --- a/Swiften/Network/PlatformDomainNameQuery.h +++ b/Swiften/Network/PlatformDomainNameQuery.h @@ -9,23 +9,23 @@ #include <boost/shared_ptr.hpp> namespace Swift { - class PlatformDomainNameResolver; + class PlatformDomainNameResolver; - class PlatformDomainNameQuery { - public: - typedef boost::shared_ptr<PlatformDomainNameQuery> ref; + class PlatformDomainNameQuery { + public: + typedef boost::shared_ptr<PlatformDomainNameQuery> ref; - PlatformDomainNameQuery(PlatformDomainNameResolver* resolver) : resolver(resolver) {} - virtual ~PlatformDomainNameQuery() {} + PlatformDomainNameQuery(PlatformDomainNameResolver* resolver) : resolver(resolver) {} + virtual ~PlatformDomainNameQuery() {} - virtual void runBlocking() = 0; + virtual void runBlocking() = 0; - protected: - PlatformDomainNameResolver* getResolver() { - return resolver; - } + protected: + PlatformDomainNameResolver* getResolver() { + return resolver; + } - private: - PlatformDomainNameResolver* resolver; - }; + private: + PlatformDomainNameResolver* resolver; + }; } diff --git a/Swiften/Network/PlatformDomainNameResolver.cpp b/Swiften/Network/PlatformDomainNameResolver.cpp index 507bd37..ed08057 100644 --- a/Swiften/Network/PlatformDomainNameResolver.cpp +++ b/Swiften/Network/PlatformDomainNameResolver.cpp @@ -28,54 +28,54 @@ using namespace Swift; namespace Swift { PlatformDomainNameResolver::PlatformDomainNameResolver(IDNConverter* idnConverter, EventLoop* eventLoop) : idnConverter(idnConverter), eventLoop(eventLoop), stopRequested(false) { - thread = new boost::thread(boost::bind(&PlatformDomainNameResolver::run, this)); + thread = new boost::thread(boost::bind(&PlatformDomainNameResolver::run, this)); } PlatformDomainNameResolver::~PlatformDomainNameResolver() { - stopRequested = true; - addQueryToQueue(boost::shared_ptr<PlatformDomainNameQuery>()); - thread->join(); - delete thread; + stopRequested = true; + addQueryToQueue(boost::shared_ptr<PlatformDomainNameQuery>()); + thread->join(); + delete thread; } boost::shared_ptr<DomainNameServiceQuery> PlatformDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) { - boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain); - std::string result; - if (encodedDomain) { - result = serviceLookupPrefix + *encodedDomain; - } - return boost::shared_ptr<DomainNameServiceQuery>(new PlatformDomainNameServiceQuery(result, eventLoop, this)); + boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain); + std::string result; + if (encodedDomain) { + result = serviceLookupPrefix + *encodedDomain; + } + return boost::shared_ptr<DomainNameServiceQuery>(new PlatformDomainNameServiceQuery(result, eventLoop, this)); } boost::shared_ptr<DomainNameAddressQuery> PlatformDomainNameResolver::createAddressQuery(const std::string& name) { - return boost::shared_ptr<DomainNameAddressQuery>(new PlatformDomainNameAddressQuery(idnConverter->getIDNAEncoded(name), eventLoop, this)); + return boost::shared_ptr<DomainNameAddressQuery>(new PlatformDomainNameAddressQuery(idnConverter->getIDNAEncoded(name), eventLoop, this)); } void PlatformDomainNameResolver::run() { - while (!stopRequested) { - PlatformDomainNameQuery::ref query; - { - boost::unique_lock<boost::mutex> lock(queueMutex); - while (queue.empty()) { - queueNonEmpty.wait(lock); - } - query = queue.front(); - queue.pop_front(); - } - // Check whether we don't have a non-null query (used to stop the - // resolver) - if (query) { - query->runBlocking(); - } - } + while (!stopRequested) { + PlatformDomainNameQuery::ref query; + { + boost::unique_lock<boost::mutex> lock(queueMutex); + while (queue.empty()) { + queueNonEmpty.wait(lock); + } + query = queue.front(); + queue.pop_front(); + } + // Check whether we don't have a non-null query (used to stop the + // resolver) + if (query) { + query->runBlocking(); + } + } } void PlatformDomainNameResolver::addQueryToQueue(PlatformDomainNameQuery::ref query) { - { - boost::lock_guard<boost::mutex> lock(queueMutex); - queue.push_back(query); - } - queueNonEmpty.notify_one(); + { + boost::lock_guard<boost::mutex> lock(queueMutex); + queue.push_back(query); + } + queueNonEmpty.notify_one(); } } diff --git a/Swiften/Network/PlatformDomainNameResolver.h b/Swiften/Network/PlatformDomainNameResolver.h index ae94179..95fa502 100644 --- a/Swiften/Network/PlatformDomainNameResolver.h +++ b/Swiften/Network/PlatformDomainNameResolver.h @@ -20,30 +20,30 @@ #include <Swiften/Network/PlatformDomainNameQuery.h> namespace Swift { - class IDNConverter; - class EventLoop; - - class SWIFTEN_API PlatformDomainNameResolver : public DomainNameResolver { - public: - PlatformDomainNameResolver(IDNConverter* idnConverter, EventLoop* eventLoop); - virtual ~PlatformDomainNameResolver(); - - virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); - virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name); - - private: - void run(); - void addQueryToQueue(PlatformDomainNameQuery::ref); - - private: - friend class PlatformDomainNameServiceQuery; - friend class PlatformDomainNameAddressQuery; - IDNConverter* idnConverter; - EventLoop* eventLoop; - Atomic<bool> stopRequested; - boost::thread* thread; - std::deque<PlatformDomainNameQuery::ref> queue; - boost::mutex queueMutex; - boost::condition_variable queueNonEmpty; - }; + class IDNConverter; + class EventLoop; + + class SWIFTEN_API PlatformDomainNameResolver : public DomainNameResolver { + public: + PlatformDomainNameResolver(IDNConverter* idnConverter, EventLoop* eventLoop); + virtual ~PlatformDomainNameResolver(); + + virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); + virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name); + + private: + void run(); + void addQueryToQueue(PlatformDomainNameQuery::ref); + + private: + friend class PlatformDomainNameServiceQuery; + friend class PlatformDomainNameAddressQuery; + IDNConverter* idnConverter; + EventLoop* eventLoop; + Atomic<bool> stopRequested; + boost::thread* thread; + std::deque<PlatformDomainNameQuery::ref> queue; + boost::mutex queueMutex; + boost::condition_variable queueNonEmpty; + }; } diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.cpp b/Swiften/Network/PlatformDomainNameServiceQuery.cpp index 673aaff..71611f5 100644 --- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp +++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp @@ -39,148 +39,148 @@ using namespace Swift; namespace Swift { PlatformDomainNameServiceQuery::PlatformDomainNameServiceQuery(const boost::optional<std::string>& serviceName, EventLoop* eventLoop, PlatformDomainNameResolver* resolver) : PlatformDomainNameQuery(resolver), eventLoop(eventLoop), serviceValid(false) { - if (!!serviceName) { - service = *serviceName; - serviceValid = true; - } + if (!!serviceName) { + service = *serviceName; + serviceValid = true; + } } PlatformDomainNameServiceQuery::~PlatformDomainNameServiceQuery() { - + } void PlatformDomainNameServiceQuery::run() { - getResolver()->addQueryToQueue(shared_from_this()); + getResolver()->addQueryToQueue(shared_from_this()); } void PlatformDomainNameServiceQuery::runBlocking() { - if (!serviceValid) { - emitError(); - return; - } + if (!serviceValid) { + emitError(); + return; + } - SWIFT_LOG(debug) << "Querying " << service << std::endl; + SWIFT_LOG(debug) << "Querying " << service << std::endl; - std::vector<DomainNameServiceQuery::Result> records; + std::vector<DomainNameServiceQuery::Result> records; #if defined(SWIFTEN_PLATFORM_WINDOWS) - DNS_RECORD* responses; - // FIXME: This conversion doesn't work if unicode is deffed above - if (DnsQuery(service.c_str(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &responses, NULL) != ERROR_SUCCESS) { - emitError(); - return; - } - - DNS_RECORD* currentEntry = responses; - while (currentEntry) { - if (currentEntry->wType == DNS_TYPE_SRV) { - DomainNameServiceQuery::Result record; - record.priority = currentEntry->Data.SRV.wPriority; - record.weight = currentEntry->Data.SRV.wWeight; - record.port = currentEntry->Data.SRV.wPort; - - // The pNameTarget is actually a PCWSTR, so I would have expected this - // conversion to not work at all, but it does. - // Actually, it doesn't. Fix this and remove explicit cast - // Remove unicode undef above as well - record.hostname = std::string((const char*) currentEntry->Data.SRV.pNameTarget); - records.push_back(record); - } - currentEntry = currentEntry->pNext; - } - DnsRecordListFree(responses, DnsFreeRecordList); + DNS_RECORD* responses; + // FIXME: This conversion doesn't work if unicode is deffed above + if (DnsQuery(service.c_str(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &responses, NULL) != ERROR_SUCCESS) { + emitError(); + return; + } + + DNS_RECORD* currentEntry = responses; + while (currentEntry) { + if (currentEntry->wType == DNS_TYPE_SRV) { + DomainNameServiceQuery::Result record; + record.priority = currentEntry->Data.SRV.wPriority; + record.weight = currentEntry->Data.SRV.wWeight; + record.port = currentEntry->Data.SRV.wPort; + + // The pNameTarget is actually a PCWSTR, so I would have expected this + // conversion to not work at all, but it does. + // Actually, it doesn't. Fix this and remove explicit cast + // Remove unicode undef above as well + record.hostname = std::string((const char*) currentEntry->Data.SRV.pNameTarget); + records.push_back(record); + } + currentEntry = currentEntry->pNext; + } + DnsRecordListFree(responses, DnsFreeRecordList); #else - // Make sure we reinitialize the domain list every time - res_init(); - - ByteArray response; - response.resize(NS_PACKETSZ); - int responseLength = res_query(const_cast<char*>(service.c_str()), ns_c_in, ns_t_srv, reinterpret_cast<u_char*>(vecptr(response)), response.size()); - if (responseLength == -1) { - SWIFT_LOG(debug) << "Error" << std::endl; - emitError(); - return; - } - - // Parse header - HEADER* header = reinterpret_cast<HEADER*>(vecptr(response)); - unsigned char* messageStart = vecptr(response); - unsigned char* messageEnd = messageStart + responseLength; - unsigned char* currentEntry = messageStart + NS_HFIXEDSZ; - - // Skip over the queries - int queriesCount = ntohs(header->qdcount); - while (queriesCount > 0) { - int entryLength = dn_skipname(currentEntry, messageEnd); - if (entryLength < 0) { - emitError(); - return; - } - currentEntry += entryLength + NS_QFIXEDSZ; - queriesCount--; - } - - // Process the SRV answers - int answersCount = ntohs(header->ancount); - while (answersCount > 0) { - DomainNameServiceQuery::Result record; - - int entryLength = dn_skipname(currentEntry, messageEnd); - currentEntry += entryLength; - currentEntry += NS_RRFIXEDSZ; - - // Priority - if (currentEntry + 2 >= messageEnd) { - emitError(); - return; - } - record.priority = boost::numeric_cast<int>(ns_get16(currentEntry)); - currentEntry += 2; - - // Weight - if (currentEntry + 2 >= messageEnd) { - emitError(); - return; - } - record.weight = boost::numeric_cast<int>(ns_get16(currentEntry)); - currentEntry += 2; - - // Port - if (currentEntry + 2 >= messageEnd) { - emitError(); - return; - } - record.port = boost::numeric_cast<int>(ns_get16(currentEntry)); - currentEntry += 2; - - // Hostname - if (currentEntry >= messageEnd) { - emitError(); - return; - } - ByteArray entry; - entry.resize(NS_MAXDNAME); - entryLength = dn_expand(messageStart, messageEnd, currentEntry, reinterpret_cast<char*>(vecptr(entry)), entry.size()); - if (entryLength < 0) { - emitError(); - return; - } - record.hostname = std::string(reinterpret_cast<const char*>(vecptr(entry))); - records.push_back(record); - currentEntry += entryLength; - answersCount--; - } + // Make sure we reinitialize the domain list every time + res_init(); + + ByteArray response; + response.resize(NS_PACKETSZ); + int responseLength = res_query(const_cast<char*>(service.c_str()), ns_c_in, ns_t_srv, reinterpret_cast<u_char*>(vecptr(response)), response.size()); + if (responseLength == -1) { + SWIFT_LOG(debug) << "Error" << std::endl; + emitError(); + return; + } + + // Parse header + HEADER* header = reinterpret_cast<HEADER*>(vecptr(response)); + unsigned char* messageStart = vecptr(response); + unsigned char* messageEnd = messageStart + responseLength; + unsigned char* currentEntry = messageStart + NS_HFIXEDSZ; + + // Skip over the queries + int queriesCount = ntohs(header->qdcount); + while (queriesCount > 0) { + int entryLength = dn_skipname(currentEntry, messageEnd); + if (entryLength < 0) { + emitError(); + return; + } + currentEntry += entryLength + NS_QFIXEDSZ; + queriesCount--; + } + + // Process the SRV answers + int answersCount = ntohs(header->ancount); + while (answersCount > 0) { + DomainNameServiceQuery::Result record; + + int entryLength = dn_skipname(currentEntry, messageEnd); + currentEntry += entryLength; + currentEntry += NS_RRFIXEDSZ; + + // Priority + if (currentEntry + 2 >= messageEnd) { + emitError(); + return; + } + record.priority = boost::numeric_cast<int>(ns_get16(currentEntry)); + currentEntry += 2; + + // Weight + if (currentEntry + 2 >= messageEnd) { + emitError(); + return; + } + record.weight = boost::numeric_cast<int>(ns_get16(currentEntry)); + currentEntry += 2; + + // Port + if (currentEntry + 2 >= messageEnd) { + emitError(); + return; + } + record.port = boost::numeric_cast<int>(ns_get16(currentEntry)); + currentEntry += 2; + + // Hostname + if (currentEntry >= messageEnd) { + emitError(); + return; + } + ByteArray entry; + entry.resize(NS_MAXDNAME); + entryLength = dn_expand(messageStart, messageEnd, currentEntry, reinterpret_cast<char*>(vecptr(entry)), entry.size()); + if (entryLength < 0) { + emitError(); + return; + } + record.hostname = std::string(reinterpret_cast<const char*>(vecptr(entry))); + records.push_back(record); + currentEntry += entryLength; + answersCount--; + } #endif - BoostRandomGenerator generator; - DomainNameServiceQuery::sortResults(records, generator); - //std::cout << "Sending out " << records.size() << " SRV results " << std::endl; - eventLoop->postEvent(boost::bind(boost::ref(onResult), records), shared_from_this()); + BoostRandomGenerator generator; + DomainNameServiceQuery::sortResults(records, generator); + //std::cout << "Sending out " << records.size() << " SRV results " << std::endl; + eventLoop->postEvent(boost::bind(boost::ref(onResult), records), shared_from_this()); } void PlatformDomainNameServiceQuery::emitError() { - eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<DomainNameServiceQuery::Result>()), shared_from_this()); + eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<DomainNameServiceQuery::Result>()), shared_from_this()); } } diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.h b/Swiften/Network/PlatformDomainNameServiceQuery.h index afc4a90..e415005 100644 --- a/Swiften/Network/PlatformDomainNameServiceQuery.h +++ b/Swiften/Network/PlatformDomainNameServiceQuery.h @@ -15,22 +15,22 @@ #include <Swiften/Network/PlatformDomainNameQuery.h> namespace Swift { - class EventLoop; + class EventLoop; - class PlatformDomainNameServiceQuery : public DomainNameServiceQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameServiceQuery>, public EventOwner { - public: - PlatformDomainNameServiceQuery(const boost::optional<std::string>& serviceName, EventLoop* eventLoop, PlatformDomainNameResolver* resolver); - virtual ~PlatformDomainNameServiceQuery(); + class PlatformDomainNameServiceQuery : public DomainNameServiceQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameServiceQuery>, public EventOwner { + public: + PlatformDomainNameServiceQuery(const boost::optional<std::string>& serviceName, EventLoop* eventLoop, PlatformDomainNameResolver* resolver); + virtual ~PlatformDomainNameServiceQuery(); - virtual void run(); + virtual void run(); - private: - void runBlocking(); - void emitError(); + private: + void runBlocking(); + void emitError(); - private: - EventLoop* eventLoop; - std::string service; - bool serviceValid; - }; + private: + EventLoop* eventLoop; + std::string service; + bool serviceValid; + }; } diff --git a/Swiften/Network/PlatformNATTraversalWorker.cpp b/Swiften/Network/PlatformNATTraversalWorker.cpp index ef1876c..e6fb05f 100644 --- a/Swiften/Network/PlatformNATTraversalWorker.cpp +++ b/Swiften/Network/PlatformNATTraversalWorker.cpp @@ -26,193 +26,193 @@ namespace Swift { class PlatformNATTraversalRequest : public boost::enable_shared_from_this<PlatformNATTraversalRequest>, public EventOwner { - public: - typedef boost::shared_ptr<PlatformNATTraversalRequest> ref; + public: + typedef boost::shared_ptr<PlatformNATTraversalRequest> ref; - public: - PlatformNATTraversalRequest(PlatformNATTraversalWorker* worker) : worker(worker) { - } + public: + PlatformNATTraversalRequest(PlatformNATTraversalWorker* worker) : worker(worker) { + } - virtual ~PlatformNATTraversalRequest() { - } + virtual ~PlatformNATTraversalRequest() { + } - virtual void doRun() { - worker->addRequestToQueue(shared_from_this()); - } + virtual void doRun() { + worker->addRequestToQueue(shared_from_this()); + } - NATTraversalInterface* getNATTraversalInterface() const { - return worker->getNATTraversalInterface(); - } + NATTraversalInterface* getNATTraversalInterface() const { + return worker->getNATTraversalInterface(); + } - EventLoop* getEventLoop() const { - return worker->getEventLoop(); - } + EventLoop* getEventLoop() const { + return worker->getEventLoop(); + } - virtual void runBlocking() = 0; + virtual void runBlocking() = 0; - private: - PlatformNATTraversalWorker* worker; + private: + PlatformNATTraversalWorker* worker; }; class PlatformNATTraversalGetPublicIPRequest : public NATTraversalGetPublicIPRequest, public PlatformNATTraversalRequest { - public: - PlatformNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalRequest(worker) { - } + public: + PlatformNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalRequest(worker) { + } - virtual ~PlatformNATTraversalGetPublicIPRequest() { - } + virtual ~PlatformNATTraversalGetPublicIPRequest() { + } - virtual void start() { - doRun(); - } + virtual void start() { + doRun(); + } - virtual void stop() { - onResult.disconnect_all_slots(); - } + virtual void stop() { + onResult.disconnect_all_slots(); + } - virtual void runBlocking() { - getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->getPublicIP()), shared_from_this()); - } + virtual void runBlocking() { + getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->getPublicIP()), shared_from_this()); + } }; class PlatformNATTraversalForwardPortRequest : public NATTraversalForwardPortRequest, public PlatformNATTraversalRequest { - public: - PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker, unsigned int localIP, unsigned int publicIP) : PlatformNATTraversalRequest(worker), localIP(localIP), publicIP(publicIP) { - } + public: + PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker, unsigned int localIP, unsigned int publicIP) : PlatformNATTraversalRequest(worker), localIP(localIP), publicIP(publicIP) { + } - virtual ~PlatformNATTraversalForwardPortRequest() { - } + virtual ~PlatformNATTraversalForwardPortRequest() { + } - virtual void start() { - doRun(); - } + virtual void start() { + doRun(); + } - virtual void stop() { - onResult.disconnect_all_slots(); - } + virtual void stop() { + onResult.disconnect_all_slots(); + } - virtual void runBlocking() { - getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->addPortForward(boost::numeric_cast<int>(localIP), boost::numeric_cast<int>(publicIP))), shared_from_this()); - } + virtual void runBlocking() { + getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->addPortForward(boost::numeric_cast<int>(localIP), boost::numeric_cast<int>(publicIP))), shared_from_this()); + } - private: - unsigned int localIP; - unsigned int publicIP; + private: + unsigned int localIP; + unsigned int publicIP; }; class PlatformNATTraversalRemovePortForwardingRequest : public NATTraversalRemovePortForwardingRequest, public PlatformNATTraversalRequest { - public: - PlatformNATTraversalRemovePortForwardingRequest(PlatformNATTraversalWorker* worker, const NATPortMapping& mapping) : PlatformNATTraversalRequest(worker), mapping(mapping) { - } + public: + PlatformNATTraversalRemovePortForwardingRequest(PlatformNATTraversalWorker* worker, const NATPortMapping& mapping) : PlatformNATTraversalRequest(worker), mapping(mapping) { + } - virtual ~PlatformNATTraversalRemovePortForwardingRequest() { - } + virtual ~PlatformNATTraversalRemovePortForwardingRequest() { + } - virtual void start() { - doRun(); - } + virtual void start() { + doRun(); + } - virtual void stop() { - onResult.disconnect_all_slots(); - } + virtual void stop() { + onResult.disconnect_all_slots(); + } - virtual void runBlocking() { - getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->removePortForward(mapping)), shared_from_this()); - } + virtual void runBlocking() { + getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->removePortForward(mapping)), shared_from_this()); + } - private: - NATPortMapping mapping; + private: + NATPortMapping mapping; }; PlatformNATTraversalWorker::PlatformNATTraversalWorker(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), natPMPSupported(boost::logic::indeterminate), natPMPInterface(NULL), miniUPnPSupported(boost::logic::indeterminate), miniUPnPInterface(NULL) { - nullNATTraversalInterface = new NullNATTraversalInterface(); - // FIXME: This should be done from start(), and the current start() should be an internal method - thread = new boost::thread(boost::bind(&PlatformNATTraversalWorker::start, this)); + nullNATTraversalInterface = new NullNATTraversalInterface(); + // FIXME: This should be done from start(), and the current start() should be an internal method + thread = new boost::thread(boost::bind(&PlatformNATTraversalWorker::start, this)); } PlatformNATTraversalWorker::~PlatformNATTraversalWorker() { - stopRequested = true; - addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>()); - thread->join(); - delete thread; + stopRequested = true; + addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>()); + thread->join(); + delete thread; #ifdef HAVE_LIBNATPMP - delete natPMPInterface; + delete natPMPInterface; #endif #ifdef HAVE_LIBMINIUPNPC - delete miniUPnPInterface; + delete miniUPnPInterface; #endif - delete nullNATTraversalInterface; + delete nullNATTraversalInterface; } NATTraversalInterface* PlatformNATTraversalWorker::getNATTraversalInterface() const { #ifdef HAVE_LIBMINIUPNPC - if (boost::logic::indeterminate(miniUPnPSupported)) { - miniUPnPInterface = new MiniUPnPInterface(); - miniUPnPSupported = miniUPnPInterface->isAvailable(); - } - SWIFT_LOG(debug) << "UPnP NAT traversal supported: " << miniUPnPSupported << std::endl; - if (miniUPnPSupported) { - return miniUPnPInterface; - } + if (boost::logic::indeterminate(miniUPnPSupported)) { + miniUPnPInterface = new MiniUPnPInterface(); + miniUPnPSupported = miniUPnPInterface->isAvailable(); + } + SWIFT_LOG(debug) << "UPnP NAT traversal supported: " << miniUPnPSupported << std::endl; + if (miniUPnPSupported) { + return miniUPnPInterface; + } #endif #ifdef HAVE_LIBNATPMP - if (boost::logic::indeterminate(natPMPSupported)) { - natPMPInterface = new NATPMPInterface(); - natPMPSupported = natPMPInterface->isAvailable(); - } - SWIFT_LOG(debug) << "NAT-PMP NAT traversal supported: " << natPMPSupported << std::endl; - if (natPMPSupported) { - return natPMPInterface; - } + if (boost::logic::indeterminate(natPMPSupported)) { + natPMPInterface = new NATPMPInterface(); + natPMPSupported = natPMPInterface->isAvailable(); + } + SWIFT_LOG(debug) << "NAT-PMP NAT traversal supported: " << natPMPSupported << std::endl; + if (natPMPSupported) { + return natPMPInterface; + } #endif - return nullNATTraversalInterface; + return nullNATTraversalInterface; } boost::shared_ptr<NATTraversalGetPublicIPRequest> PlatformNATTraversalWorker::createGetPublicIPRequest() { - return boost::make_shared<PlatformNATTraversalGetPublicIPRequest>(this); + return boost::make_shared<PlatformNATTraversalGetPublicIPRequest>(this); } boost::shared_ptr<NATTraversalForwardPortRequest> PlatformNATTraversalWorker::createForwardPortRequest(int localPort, int publicPort) { - return boost::make_shared<PlatformNATTraversalForwardPortRequest>(this, localPort, publicPort); + return boost::make_shared<PlatformNATTraversalForwardPortRequest>(this, localPort, publicPort); } boost::shared_ptr<NATTraversalRemovePortForwardingRequest> PlatformNATTraversalWorker::createRemovePortForwardingRequest(int localPort, int publicPort) { - NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); // FIXME - return boost::make_shared<PlatformNATTraversalRemovePortForwardingRequest>(this, mapping); + NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); // FIXME + return boost::make_shared<PlatformNATTraversalRemovePortForwardingRequest>(this, mapping); } void PlatformNATTraversalWorker::start() { - while (!stopRequested) { - PlatformNATTraversalRequest::ref request; - { - boost::unique_lock<boost::mutex> lock(queueMutex); - while (queue.empty()) { - queueNonEmpty.wait(lock); - } - request = queue.front(); - queue.pop_front(); - } - // Check whether we don't have a non-null request (used to stop the - // worker) - if (request) { - request->runBlocking(); - } - } + while (!stopRequested) { + PlatformNATTraversalRequest::ref request; + { + boost::unique_lock<boost::mutex> lock(queueMutex); + while (queue.empty()) { + queueNonEmpty.wait(lock); + } + request = queue.front(); + queue.pop_front(); + } + // Check whether we don't have a non-null request (used to stop the + // worker) + if (request) { + request->runBlocking(); + } + } } void PlatformNATTraversalWorker::stop() { - // TODO + // TODO } void PlatformNATTraversalWorker::addRequestToQueue(PlatformNATTraversalRequest::ref request) { - { - boost::lock_guard<boost::mutex> lock(queueMutex); - queue.push_back(request); - } - queueNonEmpty.notify_one(); + { + boost::lock_guard<boost::mutex> lock(queueMutex); + queue.push_back(request); + } + queueNonEmpty.notify_one(); } } diff --git a/Swiften/Network/PlatformNATTraversalWorker.h b/Swiften/Network/PlatformNATTraversalWorker.h index 2c03dca..280a537 100644 --- a/Swiften/Network/PlatformNATTraversalWorker.h +++ b/Swiften/Network/PlatformNATTraversalWorker.h @@ -27,49 +27,49 @@ #include <Swiften/Network/NullNATTraversalInterface.h> namespace Swift { - class EventLoop; - class NATTraversalGetPublicIPRequest; - class NATTraversalForwardPortRequest; - class NATTraversalRemovePortForwardingRequest; - class PlatformNATTraversalRequest; - class NATPMPInterface; - class MiniUPnPInterface; - class NATTraversalInterface; - class NATPortMapping; + class EventLoop; + class NATTraversalGetPublicIPRequest; + class NATTraversalForwardPortRequest; + class NATTraversalRemovePortForwardingRequest; + class PlatformNATTraversalRequest; + class NATPMPInterface; + class MiniUPnPInterface; + class NATTraversalInterface; + class NATPortMapping; - class SWIFTEN_API PlatformNATTraversalWorker : public NATTraverser { - friend class PlatformNATTraversalRequest; + class SWIFTEN_API PlatformNATTraversalWorker : public NATTraverser { + friend class PlatformNATTraversalRequest; - public: - PlatformNATTraversalWorker(EventLoop* eventLoop); - virtual ~PlatformNATTraversalWorker(); + public: + PlatformNATTraversalWorker(EventLoop* eventLoop); + virtual ~PlatformNATTraversalWorker(); - boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest(); - boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort); - boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort); + boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest(); + boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort); + boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort); - private: - NATTraversalInterface* getNATTraversalInterface() const; - void addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>); - void start(); - void stop(); + private: + NATTraversalInterface* getNATTraversalInterface() const; + void addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>); + void start(); + void stop(); - EventLoop* getEventLoop() const { - return eventLoop; - } + EventLoop* getEventLoop() const { + return eventLoop; + } - private: - EventLoop* eventLoop; - Atomic<bool> stopRequested; - boost::thread* thread; - std::deque<boost::shared_ptr<PlatformNATTraversalRequest> > queue; - boost::mutex queueMutex; - boost::condition_variable queueNonEmpty; + private: + EventLoop* eventLoop; + Atomic<bool> stopRequested; + boost::thread* thread; + std::deque<boost::shared_ptr<PlatformNATTraversalRequest> > queue; + boost::mutex queueMutex; + boost::condition_variable queueNonEmpty; - NullNATTraversalInterface* nullNATTraversalInterface; - mutable boost::logic::tribool natPMPSupported; - mutable NATPMPInterface* natPMPInterface; - mutable boost::logic::tribool miniUPnPSupported; - mutable MiniUPnPInterface* miniUPnPInterface; - }; + NullNATTraversalInterface* nullNATTraversalInterface; + mutable boost::logic::tribool natPMPSupported; + mutable NATPMPInterface* natPMPInterface; + mutable boost::logic::tribool miniUPnPSupported; + mutable MiniUPnPInterface* miniUPnPInterface; + }; } diff --git a/Swiften/Network/PlatformNetworkEnvironment.h b/Swiften/Network/PlatformNetworkEnvironment.h index 2092bfd..ff29491 100644 --- a/Swiften/Network/PlatformNetworkEnvironment.h +++ b/Swiften/Network/PlatformNetworkEnvironment.h @@ -11,22 +11,22 @@ #if defined(SWIFTEN_PLATFORM_MACOSX) #include <Swiften/Network/UnixNetworkEnvironment.h> namespace Swift { - typedef UnixNetworkEnvironment PlatformNetworkEnvironment; + typedef UnixNetworkEnvironment PlatformNetworkEnvironment; } #elif defined(SWIFTEN_PLATFORM_WIN32) #include <Swiften/Network/WindowsNetworkEnvironment.h> namespace Swift { - typedef WindowsNetworkEnvironment PlatformNetworkEnvironment; + typedef WindowsNetworkEnvironment PlatformNetworkEnvironment; } #elif defined(SWIFTEN_PLATFORM_SOLARIS) #include <Swiften/Network/SolarisNetworkEnvironment.h> namespace Swift { - typedef SolarisNetworkEnvironment PlatformNetworkEnvironment; + typedef SolarisNetworkEnvironment PlatformNetworkEnvironment; } #else #include <Swiften/Network/UnixNetworkEnvironment.h> namespace Swift { - typedef UnixNetworkEnvironment PlatformNetworkEnvironment; + typedef UnixNetworkEnvironment PlatformNetworkEnvironment; } #endif diff --git a/Swiften/Network/PlatformProxyProvider.h b/Swiften/Network/PlatformProxyProvider.h index 1a0a1c6..c63e718 100644 --- a/Swiften/Network/PlatformProxyProvider.h +++ b/Swiften/Network/PlatformProxyProvider.h @@ -11,16 +11,16 @@ #if defined(SWIFTEN_PLATFORM_MACOSX) #include <Swiften/Network/MacOSXProxyProvider.h> namespace Swift { - typedef MacOSXProxyProvider PlatformProxyProvider; + typedef MacOSXProxyProvider PlatformProxyProvider; } #elif defined(SWIFTEN_PLATFORM_WIN32) #include <Swiften/Network/WindowsProxyProvider.h> namespace Swift { - typedef WindowsProxyProvider PlatformProxyProvider; + typedef WindowsProxyProvider PlatformProxyProvider; } #else #include <Swiften/Network/UnixProxyProvider.h> namespace Swift { - typedef UnixProxyProvider PlatformProxyProvider; + typedef UnixProxyProvider PlatformProxyProvider; } #endif diff --git a/Swiften/Network/ProxiedConnection.cpp b/Swiften/Network/ProxiedConnection.cpp index 69f719d..27f5cd9 100644 --- a/Swiften/Network/ProxiedConnection.cpp +++ b/Swiften/Network/ProxiedConnection.cpp @@ -16,112 +16,112 @@ using namespace Swift; ProxiedConnection::ProxiedConnection( - DomainNameResolver* resolver, - ConnectionFactory* connectionFactory, - TimerFactory* timerFactory, - const std::string& proxyHost, - int proxyPort) : - resolver_(resolver), - connectionFactory_(connectionFactory), - timerFactory_(timerFactory), - proxyHost_(proxyHost), - proxyPort_(proxyPort), - server_(HostAddressPort(HostAddress("0.0.0.0"), 0)) { - connected_ = false; + DomainNameResolver* resolver, + ConnectionFactory* connectionFactory, + TimerFactory* timerFactory, + const std::string& proxyHost, + int proxyPort) : + resolver_(resolver), + connectionFactory_(connectionFactory), + timerFactory_(timerFactory), + proxyHost_(proxyHost), + proxyPort_(proxyPort), + server_(HostAddressPort(HostAddress("0.0.0.0"), 0)) { + connected_ = false; } ProxiedConnection::~ProxiedConnection() { - cancelConnector(); - if (connection_) { - connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1)); - connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1)); - } - if (connected_) { - SWIFT_LOG(warning) << "Connection was still established." << std::endl; - } + cancelConnector(); + if (connection_) { + connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1)); + connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1)); + } + if (connected_) { + SWIFT_LOG(warning) << "Connection was still established." << std::endl; + } } void ProxiedConnection::cancelConnector() { - if (connector_) { - connector_->onConnectFinished.disconnect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1)); - connector_->stop(); - connector_.reset(); - } + if (connector_) { + connector_->onConnectFinished.disconnect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1)); + connector_->stop(); + connector_.reset(); + } } void ProxiedConnection::connect(const HostAddressPort& server) { - server_ = server; + server_ = server; - connector_ = Connector::create(proxyHost_, proxyPort_, boost::optional<std::string>(), resolver_, connectionFactory_, timerFactory_); - connector_->onConnectFinished.connect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1)); - connector_->start(); + connector_ = Connector::create(proxyHost_, proxyPort_, boost::optional<std::string>(), resolver_, connectionFactory_, timerFactory_); + connector_->onConnectFinished.connect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1)); + connector_->start(); } void ProxiedConnection::listen() { - assert(false); - connection_->listen(); + assert(false); + connection_->listen(); } void ProxiedConnection::disconnect() { - cancelConnector(); - connected_ = false; - if (connection_) { - connection_->disconnect(); - } + cancelConnector(); + connected_ = false; + if (connection_) { + connection_->disconnect(); + } } void ProxiedConnection::handleDisconnected(const boost::optional<Error>& error) { - onDisconnected(error); + onDisconnected(error); } void ProxiedConnection::write(const SafeByteArray& data) { - connection_->write(data); + connection_->write(data); } void ProxiedConnection::handleConnectFinished(Connection::ref connection) { - cancelConnector(); - if (connection) { - connection_ = connection; - connection_->onDataRead.connect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1)); - connection_->onDisconnected.connect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1)); - - initializeProxy(); - } - else { - onConnectFinished(true); - } + cancelConnector(); + if (connection) { + connection_ = connection; + connection_->onDataRead.connect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1)); + connection_->onDisconnected.connect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1)); + + initializeProxy(); + } + else { + onConnectFinished(true); + } } void ProxiedConnection::handleDataRead(boost::shared_ptr<SafeByteArray> data) { - if (!connected_) { - handleProxyInitializeData(data); - } - else { - onDataRead(data); - } + if (!connected_) { + handleProxyInitializeData(data); + } + else { + onDataRead(data); + } } HostAddressPort ProxiedConnection::getLocalAddress() const { - return connection_->getLocalAddress(); + return connection_->getLocalAddress(); } HostAddressPort ProxiedConnection::getRemoteAddress() const { - return connection_->getRemoteAddress(); + return connection_->getRemoteAddress(); } void ProxiedConnection::setProxyInitializeFinished(bool success) { - connected_ = success; - if (!success) { - disconnect(); - } - onConnectFinished(!success); + connected_ = success; + if (!success) { + disconnect(); + } + onConnectFinished(!success); } void ProxiedConnection::reconnect() { - if (connected_) { - connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1)); - connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1)); - connection_->disconnect(); - } - connect(server_); + if (connected_) { + connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1)); + connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1)); + connection_->disconnect(); + } + connect(server_); } diff --git a/Swiften/Network/ProxiedConnection.h b/Swiften/Network/ProxiedConnection.h index f03c7ae..80f748c 100644 --- a/Swiften/Network/ProxiedConnection.h +++ b/Swiften/Network/ProxiedConnection.h @@ -16,56 +16,56 @@ #include <Swiften/Network/HostAddressPort.h> namespace boost { - class thread; - namespace system { - class error_code; - } + class thread; + namespace system { + class error_code; + } } namespace Swift { - class ConnectionFactory; - - class SWIFTEN_API ProxiedConnection : public Connection, public boost::enable_shared_from_this<ProxiedConnection> { - public: - ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); - virtual ~ProxiedConnection(); - - virtual void listen(); - virtual void connect(const HostAddressPort& address); - virtual void disconnect(); - virtual void write(const SafeByteArray& data); - - virtual HostAddressPort getLocalAddress() const; - virtual HostAddressPort getRemoteAddress() const; - - private: - void handleConnectFinished(Connection::ref connection); - void handleDataRead(boost::shared_ptr<SafeByteArray> data); - void handleDisconnected(const boost::optional<Error>& error); - void cancelConnector(); - - protected: - void setProxyInitializeFinished(bool success); - - virtual void initializeProxy() = 0; - virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data) = 0; - - const HostAddressPort& getServer() const { - return server_; - } - - void reconnect(); - - private: - bool connected_; - DomainNameResolver* resolver_; - ConnectionFactory* connectionFactory_; - TimerFactory* timerFactory_; - std::string proxyHost_; - int proxyPort_; - HostAddressPort server_; - Connector::ref connector_; - boost::shared_ptr<Connection> connection_; - }; + class ConnectionFactory; + + class SWIFTEN_API ProxiedConnection : public Connection, public boost::enable_shared_from_this<ProxiedConnection> { + public: + ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); + virtual ~ProxiedConnection(); + + virtual void listen(); + virtual void connect(const HostAddressPort& address); + virtual void disconnect(); + virtual void write(const SafeByteArray& data); + + virtual HostAddressPort getLocalAddress() const; + virtual HostAddressPort getRemoteAddress() const; + + private: + void handleConnectFinished(Connection::ref connection); + void handleDataRead(boost::shared_ptr<SafeByteArray> data); + void handleDisconnected(const boost::optional<Error>& error); + void cancelConnector(); + + protected: + void setProxyInitializeFinished(bool success); + + virtual void initializeProxy() = 0; + virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data) = 0; + + const HostAddressPort& getServer() const { + return server_; + } + + void reconnect(); + + private: + bool connected_; + DomainNameResolver* resolver_; + ConnectionFactory* connectionFactory_; + TimerFactory* timerFactory_; + std::string proxyHost_; + int proxyPort_; + HostAddressPort server_; + Connector::ref connector_; + boost::shared_ptr<Connection> connection_; + }; } diff --git a/Swiften/Network/ProxyProvider.h b/Swiften/Network/ProxyProvider.h index 96f3b21..bf737c0 100644 --- a/Swiften/Network/ProxyProvider.h +++ b/Swiften/Network/ProxyProvider.h @@ -19,12 +19,12 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class SWIFTEN_API ProxyProvider { - public: - ProxyProvider(); - virtual ~ProxyProvider(); - virtual HostAddressPort getHTTPConnectProxy() const = 0; - virtual HostAddressPort getSOCKS5Proxy() const = 0; - }; + class SWIFTEN_API ProxyProvider { + public: + ProxyProvider(); + virtual ~ProxyProvider(); + virtual HostAddressPort getHTTPConnectProxy() const = 0; + virtual HostAddressPort getSOCKS5Proxy() const = 0; + }; } diff --git a/Swiften/Network/SOCKS5ProxiedConnection.cpp b/Swiften/Network/SOCKS5ProxiedConnection.cpp index 1385fa2..2b7a3f3 100644 --- a/Swiften/Network/SOCKS5ProxiedConnection.cpp +++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp @@ -26,98 +26,98 @@ using namespace Swift; SOCKS5ProxiedConnection::SOCKS5ProxiedConnection( - DomainNameResolver* resolver, - ConnectionFactory* connectionFactory, - TimerFactory* timerFactory, - const std::string& proxyHost, - int proxyPort) : - ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort), - proxyState_(Initial) { - } + DomainNameResolver* resolver, + ConnectionFactory* connectionFactory, + TimerFactory* timerFactory, + const std::string& proxyHost, + int proxyPort) : + ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort), + proxyState_(Initial) { + } void SOCKS5ProxiedConnection::initializeProxy() { - proxyState_ = ProxyAuthenticating; - SafeByteArray socksConnect; - socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05 - socksConnect.push_back(0x01); // Number of authentication methods after this byte. - socksConnect.push_back(0x00); // 0x00 == no authentication - // buffer.push_back(0x01); // 0x01 == GSSAPI - // buffer.push_back(0x02); // 0x02 == Username/Password - // rest see RFC 1928 (http://tools.ietf.org/html/rfc1928) - write(socksConnect); + proxyState_ = ProxyAuthenticating; + SafeByteArray socksConnect; + socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05 + socksConnect.push_back(0x01); // Number of authentication methods after this byte. + socksConnect.push_back(0x00); // 0x00 == no authentication + // buffer.push_back(0x01); // 0x01 == GSSAPI + // buffer.push_back(0x02); // 0x02 == Username/Password + // rest see RFC 1928 (http://tools.ietf.org/html/rfc1928) + write(socksConnect); } void SOCKS5ProxiedConnection::handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data) { - SafeByteArray socksConnect; - boost::asio::ip::address rawAddress = getServer().getAddress().getRawAddress(); - assert(rawAddress.is_v4() || rawAddress.is_v6()); + SafeByteArray socksConnect; + boost::asio::ip::address rawAddress = getServer().getAddress().getRawAddress(); + assert(rawAddress.is_v4() || rawAddress.is_v6()); - if (proxyState_ == ProxyAuthenticating) { - SWIFT_LOG(debug) << "ProxyAuthenticating response received, reply with the connect BYTEs" << std::endl; - unsigned char choosenMethod = static_cast<unsigned char> ((*data)[1]); - if ((*data)[0] == 0x05 && choosenMethod != 0xFF) { - switch(choosenMethod) { // use the correct Method - case 0x00: - try { - proxyState_ = ProxyConnecting; - socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05 - socksConnect.push_back(0x01); // Construct a TCP connection. (CMD) - socksConnect.push_back(0x00); // reserved. - socksConnect.push_back(rawAddress.is_v4() ? 0x01 : 0x04); // IPv4 == 0x01, Hostname == 0x02, IPv6 == 0x04. (ATYP) - size_t size = rawAddress.is_v4() ? rawAddress.to_v4().to_bytes().size() : rawAddress.to_v6().to_bytes().size(); - for (size_t s = 0; s < size; s++) { - unsigned char uc; - if(rawAddress.is_v4()) { - uc = rawAddress.to_v4().to_bytes()[s]; // the address. - } - else { - uc = rawAddress.to_v6().to_bytes()[s]; // the address. - } - socksConnect.push_back(uc); - - } - socksConnect.push_back(static_cast<unsigned char> ((getServer().getPort() >> 8) & 0xFF)); // highbyte of the port. - socksConnect.push_back(static_cast<unsigned char> (getServer().getPort() & 0xFF)); // lowbyte of the port. - write(socksConnect); - return; - } - catch(...) { - std::cerr << "exception caught" << std::endl; - } - write(socksConnect); - break; - default: - setProxyInitializeFinished(true); - break; - } - return; - } - setProxyInitializeFinished(false); - } - else if (proxyState_ == ProxyConnecting) { - SWIFT_LOG(debug) << "Connect response received, check if successfully." << std::endl; - SWIFT_LOG(debug) << "Errorbyte: 0x" << std::hex << static_cast<int> ((*data)[1]) << std::dec << std::endl; - /* + if (proxyState_ == ProxyAuthenticating) { + SWIFT_LOG(debug) << "ProxyAuthenticating response received, reply with the connect BYTEs" << std::endl; + unsigned char choosenMethod = static_cast<unsigned char> ((*data)[1]); + if ((*data)[0] == 0x05 && choosenMethod != 0xFF) { + switch(choosenMethod) { // use the correct Method + case 0x00: + try { + proxyState_ = ProxyConnecting; + socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05 + socksConnect.push_back(0x01); // Construct a TCP connection. (CMD) + socksConnect.push_back(0x00); // reserved. + socksConnect.push_back(rawAddress.is_v4() ? 0x01 : 0x04); // IPv4 == 0x01, Hostname == 0x02, IPv6 == 0x04. (ATYP) + size_t size = rawAddress.is_v4() ? rawAddress.to_v4().to_bytes().size() : rawAddress.to_v6().to_bytes().size(); + for (size_t s = 0; s < size; s++) { + unsigned char uc; + if(rawAddress.is_v4()) { + uc = rawAddress.to_v4().to_bytes()[s]; // the address. + } + else { + uc = rawAddress.to_v6().to_bytes()[s]; // the address. + } + socksConnect.push_back(uc); - data.at(1) can be one of the following: - 0x00 succeeded - 0x01 general SOCKS server failure - 0x02 connection not allowed by ruleset - 0x03 Network unreachable - 0x04 Host unreachable - 0x05 Connection refused - 0x06 TTL expired - 0x07 Command not supported (CMD) - 0x08 Address type not supported (ATYP) - 0x09 bis 0xFF unassigned - */ - if ((*data)[0] == 0x05 && (*data)[1] == 0x0) { - SWIFT_LOG(debug) << "Successfully connected the server via the proxy." << std::endl; - setProxyInitializeFinished(true); - } - else { - std::cerr << "SOCKS Proxy returned an error: " << std::hex << (*data)[1] << std::endl; - setProxyInitializeFinished(false); - } - } + } + socksConnect.push_back(static_cast<unsigned char> ((getServer().getPort() >> 8) & 0xFF)); // highbyte of the port. + socksConnect.push_back(static_cast<unsigned char> (getServer().getPort() & 0xFF)); // lowbyte of the port. + write(socksConnect); + return; + } + catch(...) { + std::cerr << "exception caught" << std::endl; + } + write(socksConnect); + break; + default: + setProxyInitializeFinished(true); + break; + } + return; + } + setProxyInitializeFinished(false); + } + else if (proxyState_ == ProxyConnecting) { + SWIFT_LOG(debug) << "Connect response received, check if successfully." << std::endl; + SWIFT_LOG(debug) << "Errorbyte: 0x" << std::hex << static_cast<int> ((*data)[1]) << std::dec << std::endl; + /* + + data.at(1) can be one of the following: + 0x00 succeeded + 0x01 general SOCKS server failure + 0x02 connection not allowed by ruleset + 0x03 Network unreachable + 0x04 Host unreachable + 0x05 Connection refused + 0x06 TTL expired + 0x07 Command not supported (CMD) + 0x08 Address type not supported (ATYP) + 0x09 bis 0xFF unassigned + */ + if ((*data)[0] == 0x05 && (*data)[1] == 0x0) { + SWIFT_LOG(debug) << "Successfully connected the server via the proxy." << std::endl; + setProxyInitializeFinished(true); + } + else { + std::cerr << "SOCKS Proxy returned an error: " << std::hex << (*data)[1] << std::endl; + setProxyInitializeFinished(false); + } + } } diff --git a/Swiften/Network/SOCKS5ProxiedConnection.h b/Swiften/Network/SOCKS5ProxiedConnection.h index ee58d96..edbc56c 100644 --- a/Swiften/Network/SOCKS5ProxiedConnection.h +++ b/Swiften/Network/SOCKS5ProxiedConnection.h @@ -16,29 +16,29 @@ #include <Swiften/Network/ProxiedConnection.h> namespace Swift { - class ConnectionFactory; - class DomainNameResolver; - class TimerFactory; - - class SWIFTEN_API SOCKS5ProxiedConnection : public ProxiedConnection { - public: - typedef boost::shared_ptr<SOCKS5ProxiedConnection> ref; - - static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort) { - return ref(new SOCKS5ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort)); - } - - private: - SOCKS5ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); - - virtual void initializeProxy(); - virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data); - - private: - enum { - Initial = 0, - ProxyAuthenticating, - ProxyConnecting - } proxyState_; - }; + class ConnectionFactory; + class DomainNameResolver; + class TimerFactory; + + class SWIFTEN_API SOCKS5ProxiedConnection : public ProxiedConnection { + public: + typedef boost::shared_ptr<SOCKS5ProxiedConnection> ref; + + static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort) { + return ref(new SOCKS5ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort)); + } + + private: + SOCKS5ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); + + virtual void initializeProxy(); + virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data); + + private: + enum { + Initial = 0, + ProxyAuthenticating, + ProxyConnecting + } proxyState_; + }; } diff --git a/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp b/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp index af99034..3e24f00 100644 --- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp +++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp @@ -14,7 +14,7 @@ SOCKS5ProxiedConnectionFactory::SOCKS5ProxiedConnectionFactory(DomainNameResolve } boost::shared_ptr<Connection> SOCKS5ProxiedConnectionFactory::createConnection() { - return SOCKS5ProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_); + return SOCKS5ProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_); } } diff --git a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h index 0915a9b..1092381 100644 --- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h +++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h @@ -18,20 +18,20 @@ #include <Swiften/Network/HostNameOrAddress.h> namespace Swift { - class DomainNameResolver; - class TimerFactory; + class DomainNameResolver; + class TimerFactory; - class SWIFTEN_API SOCKS5ProxiedConnectionFactory : public ConnectionFactory { - public: - SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); + class SWIFTEN_API SOCKS5ProxiedConnectionFactory : public ConnectionFactory { + public: + SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); - virtual boost::shared_ptr<Connection> createConnection(); + virtual boost::shared_ptr<Connection> createConnection(); - private: - DomainNameResolver* resolver_; - ConnectionFactory* connectionFactory_; - TimerFactory* timerFactory_; - std::string proxyHost_; - int proxyPort_; - }; + private: + DomainNameResolver* resolver_; + ConnectionFactory* connectionFactory_; + TimerFactory* timerFactory_; + std::string proxyHost_; + int proxyPort_; + }; } diff --git a/Swiften/Network/SolarisNetworkEnvironment.cpp b/Swiften/Network/SolarisNetworkEnvironment.cpp index 0404364..4a1012b 100644 --- a/Swiften/Network/SolarisNetworkEnvironment.cpp +++ b/Swiften/Network/SolarisNetworkEnvironment.cpp @@ -39,13 +39,13 @@ * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. + * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * may be used to endorse or promote products derived from this software + * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE @@ -63,193 +63,193 @@ #undef ifa_broadaddr #undef ifa_dstaddr struct ifaddrs { - struct ifaddrs *ifa_next; /* Pointer to next struct */ - char *ifa_name; /* Interface name */ - uint64_t ifa_flags; /* Interface flags */ - struct sockaddr *ifa_addr; /* Interface address */ - struct sockaddr *ifa_netmask; /* Interface netmask */ - struct sockaddr *ifa_dstaddr; /* P2P interface destination */ + struct ifaddrs *ifa_next; /* Pointer to next struct */ + char *ifa_name; /* Interface name */ + uint64_t ifa_flags; /* Interface flags */ + struct sockaddr *ifa_addr; /* Interface address */ + struct sockaddr *ifa_netmask; /* Interface netmask */ + struct sockaddr *ifa_dstaddr; /* P2P interface destination */ }; -#define ifa_broadaddr ifa_dstaddr +#define ifa_broadaddr ifa_dstaddr static int get_lifreq(int fd, struct lifreq **ifr_ret) { - struct lifnum lifn; - struct lifconf lifc; - struct lifreq *lifrp; - - lifn.lifn_family = AF_UNSPEC; - lifn.lifn_flags = 0; - if (ioctl(fd, SIOCGLIFNUM, &lifn) == -1) - lifn.lifn_count = 16; - else - lifn.lifn_count += 16; - - for (;;) { - lifc.lifc_len = lifn.lifn_count * sizeof (*lifrp); - lifrp = (struct lifreq *) malloc(lifc.lifc_len); - if (lifrp == NULL) - return (-1); - - lifc.lifc_family = AF_UNSPEC; - lifc.lifc_flags = 0; - lifc.lifc_buf = (char *)lifrp; - if (ioctl(fd, SIOCGLIFCONF, &lifc) == -1) { - free(lifrp); - if (errno == EINVAL) { - lifn.lifn_count <<= 1; - continue; - } - (void) close(fd); - return (-1); - } - if (lifc.lifc_len < (lifn.lifn_count - 1) * sizeof (*lifrp)) - break; - free(lifrp); - lifn.lifn_count <<= 1; - } - (void) close(fd); - - *ifr_ret = lifrp; - - return (lifc.lifc_len / sizeof (*lifrp)); + struct lifnum lifn; + struct lifconf lifc; + struct lifreq *lifrp; + + lifn.lifn_family = AF_UNSPEC; + lifn.lifn_flags = 0; + if (ioctl(fd, SIOCGLIFNUM, &lifn) == -1) + lifn.lifn_count = 16; + else + lifn.lifn_count += 16; + + for (;;) { + lifc.lifc_len = lifn.lifn_count * sizeof (*lifrp); + lifrp = (struct lifreq *) malloc(lifc.lifc_len); + if (lifrp == NULL) + return (-1); + + lifc.lifc_family = AF_UNSPEC; + lifc.lifc_flags = 0; + lifc.lifc_buf = (char *)lifrp; + if (ioctl(fd, SIOCGLIFCONF, &lifc) == -1) { + free(lifrp); + if (errno == EINVAL) { + lifn.lifn_count <<= 1; + continue; + } + (void) close(fd); + return (-1); + } + if (lifc.lifc_len < (lifn.lifn_count - 1) * sizeof (*lifrp)) + break; + free(lifrp); + lifn.lifn_count <<= 1; + } + (void) close(fd); + + *ifr_ret = lifrp; + + return (lifc.lifc_len / sizeof (*lifrp)); } static size_t nbytes(const struct lifreq *lifrp, int nlif, size_t socklen) { - size_t len = 0; - size_t slen; - - while (nlif > 0) { - slen = strlen(lifrp->lifr_name) + 1; - len += sizeof (struct ifaddrs) + ((slen + 3) & ~3); - len += 3 * socklen; - lifrp++; - nlif--; - } - return (len); + size_t len = 0; + size_t slen; + + while (nlif > 0) { + slen = strlen(lifrp->lifr_name) + 1; + len += sizeof (struct ifaddrs) + ((slen + 3) & ~3); + len += 3 * socklen; + lifrp++; + nlif--; + } + return (len); } static struct sockaddr * addrcpy(struct sockaddr_storage *addr, char **bufp) { - char *buf = *bufp; - size_t len; - - len = addr->ss_family == AF_INET ? sizeof (struct sockaddr_in) : - sizeof (struct sockaddr_in6); - (void) memcpy(buf, addr, len); - *bufp = buf + len; - return ((struct sockaddr *)buf); + char *buf = *bufp; + size_t len; + + len = addr->ss_family == AF_INET ? sizeof (struct sockaddr_in) : + sizeof (struct sockaddr_in6); + (void) memcpy(buf, addr, len); + *bufp = buf + len; + return ((struct sockaddr *)buf); } static int populate(struct ifaddrs *ifa, int fd, struct lifreq *lifrp, int nlif, int af, - char **bufp) + char **bufp) { - char *buf = *bufp; - size_t slen; - - while (nlif > 0) { - ifa->ifa_next = (nlif > 1) ? ifa + 1 : NULL; - (void) strcpy(ifa->ifa_name = buf, lifrp->lifr_name); - slen = strlen(lifrp->lifr_name) + 1; - buf += (slen + 3) & ~3; - if (ioctl(fd, SIOCGLIFFLAGS, lifrp) == -1) - ifa->ifa_flags = 0; - else - ifa->ifa_flags = lifrp->lifr_flags; - if (ioctl(fd, SIOCGLIFADDR, lifrp) == -1) - ifa->ifa_addr = NULL; - else - ifa->ifa_addr = addrcpy(&lifrp->lifr_addr, &buf); - if (ioctl(fd, SIOCGLIFNETMASK, lifrp) == -1) - ifa->ifa_netmask = NULL; - else - ifa->ifa_netmask = addrcpy(&lifrp->lifr_addr, &buf); - if (ifa->ifa_flags & IFF_POINTOPOINT) { - if (ioctl(fd, SIOCGLIFDSTADDR, lifrp) == -1) - ifa->ifa_dstaddr = NULL; - else - ifa->ifa_dstaddr = - addrcpy(&lifrp->lifr_dstaddr, &buf); - } else if (ifa->ifa_flags & IFF_BROADCAST) { - if (ioctl(fd, SIOCGLIFBRDADDR, lifrp) == -1) - ifa->ifa_broadaddr = NULL; - else - ifa->ifa_broadaddr = - addrcpy(&lifrp->lifr_broadaddr, &buf); - } else { - ifa->ifa_dstaddr = NULL; - } - - ifa++; - nlif--; - lifrp++; - } - *bufp = buf; - return (0); + char *buf = *bufp; + size_t slen; + + while (nlif > 0) { + ifa->ifa_next = (nlif > 1) ? ifa + 1 : NULL; + (void) strcpy(ifa->ifa_name = buf, lifrp->lifr_name); + slen = strlen(lifrp->lifr_name) + 1; + buf += (slen + 3) & ~3; + if (ioctl(fd, SIOCGLIFFLAGS, lifrp) == -1) + ifa->ifa_flags = 0; + else + ifa->ifa_flags = lifrp->lifr_flags; + if (ioctl(fd, SIOCGLIFADDR, lifrp) == -1) + ifa->ifa_addr = NULL; + else + ifa->ifa_addr = addrcpy(&lifrp->lifr_addr, &buf); + if (ioctl(fd, SIOCGLIFNETMASK, lifrp) == -1) + ifa->ifa_netmask = NULL; + else + ifa->ifa_netmask = addrcpy(&lifrp->lifr_addr, &buf); + if (ifa->ifa_flags & IFF_POINTOPOINT) { + if (ioctl(fd, SIOCGLIFDSTADDR, lifrp) == -1) + ifa->ifa_dstaddr = NULL; + else + ifa->ifa_dstaddr = + addrcpy(&lifrp->lifr_dstaddr, &buf); + } else if (ifa->ifa_flags & IFF_BROADCAST) { + if (ioctl(fd, SIOCGLIFBRDADDR, lifrp) == -1) + ifa->ifa_broadaddr = NULL; + else + ifa->ifa_broadaddr = + addrcpy(&lifrp->lifr_broadaddr, &buf); + } else { + ifa->ifa_dstaddr = NULL; + } + + ifa++; + nlif--; + lifrp++; + } + *bufp = buf; + return (0); } static int getifaddrs(struct ifaddrs **ifap) { - int fd4, fd6; - int nif4, nif6 = 0; - struct lifreq *ifr4 = NULL; - struct lifreq *ifr6 = NULL; - struct ifaddrs *ifa = NULL; - char *buf; - - if ((fd4 = socket(AF_INET, SOCK_DGRAM, 0)) == -1) - return (-1); - if ((fd6 = socket(AF_INET6, SOCK_DGRAM, 0)) == -1 && - errno != EAFNOSUPPORT) { - (void) close(fd4); - return (-1); - } - - if ((nif4 = get_lifreq(fd4, &ifr4)) == -1 || - (fd6 != -1 && (nif6 = get_lifreq(fd6, &ifr6)) == -1)) - goto failure; - - if (nif4 == 0 && nif6 == 0) { - *ifap = NULL; - return (0); - } - - ifa = (struct ifaddrs *) malloc(nbytes(ifr4, nif4, sizeof (struct sockaddr_in)) + - nbytes(ifr6, nif6, sizeof (struct sockaddr_in6))); - if (ifa == NULL) - goto failure; - - buf = (char *)(ifa + nif4 + nif6); - - if (populate(ifa, fd4, ifr4, nif4, AF_INET, &buf) == -1) - goto failure; - if (nif4 > 0 && nif6 > 0) - ifa[nif4 - 1].ifa_next = ifa + nif4; - if (populate(ifa + nif4, fd6, ifr6, nif6, AF_INET6, &buf) == -1) - goto failure; - - return (0); + int fd4, fd6; + int nif4, nif6 = 0; + struct lifreq *ifr4 = NULL; + struct lifreq *ifr6 = NULL; + struct ifaddrs *ifa = NULL; + char *buf; + + if ((fd4 = socket(AF_INET, SOCK_DGRAM, 0)) == -1) + return (-1); + if ((fd6 = socket(AF_INET6, SOCK_DGRAM, 0)) == -1 && + errno != EAFNOSUPPORT) { + (void) close(fd4); + return (-1); + } + + if ((nif4 = get_lifreq(fd4, &ifr4)) == -1 || + (fd6 != -1 && (nif6 = get_lifreq(fd6, &ifr6)) == -1)) + goto failure; + + if (nif4 == 0 && nif6 == 0) { + *ifap = NULL; + return (0); + } + + ifa = (struct ifaddrs *) malloc(nbytes(ifr4, nif4, sizeof (struct sockaddr_in)) + + nbytes(ifr6, nif6, sizeof (struct sockaddr_in6))); + if (ifa == NULL) + goto failure; + + buf = (char *)(ifa + nif4 + nif6); + + if (populate(ifa, fd4, ifr4, nif4, AF_INET, &buf) == -1) + goto failure; + if (nif4 > 0 && nif6 > 0) + ifa[nif4 - 1].ifa_next = ifa + nif4; + if (populate(ifa + nif4, fd6, ifr6, nif6, AF_INET6, &buf) == -1) + goto failure; + + return (0); failure: - free(ifa); - (void) close(fd4); - if (fd6 != -1) - (void) close(fd6); - free(ifr4); - free(ifr6); - return (-1); + free(ifa); + (void) close(fd4); + if (fd6 != -1) + (void) close(fd6); + free(ifr4); + free(ifr6); + return (-1); } static void freeifaddrs(struct ifaddrs *ifa) { - free(ifa); + free(ifa); } /* End WIDE Project code */ @@ -257,38 +257,38 @@ freeifaddrs(struct ifaddrs *ifa) namespace Swift { std::vector<NetworkInterface> SolarisNetworkEnvironment::getNetworkInterfaces() const { - std::map<std::string, NetworkInterface> interfaces; - - ifaddrs* addrs = 0; - int ret = getifaddrs(&addrs); - if (ret != 0) { - return std::vector<NetworkInterface>(); - } - - for (ifaddrs* a = addrs; a != 0; a = a->ifa_next) { - std::string name(a->ifa_name); - boost::optional<HostAddress> address; - if (a->ifa_addr->sa_family == PF_INET) { - sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(a->ifa_addr); - address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4); - } - else if (a->ifa_addr->sa_family == PF_INET6) { - sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(a->ifa_addr); - address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16); - } - if (address) { - std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, a->ifa_flags & IFF_LOOPBACK))).first; - i->second.addAddress(*address); - } - } - - freeifaddrs(addrs); - - std::vector<NetworkInterface> result; - for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) { - result.push_back(i->second); - } - return result; + std::map<std::string, NetworkInterface> interfaces; + + ifaddrs* addrs = 0; + int ret = getifaddrs(&addrs); + if (ret != 0) { + return std::vector<NetworkInterface>(); + } + + for (ifaddrs* a = addrs; a != 0; a = a->ifa_next) { + std::string name(a->ifa_name); + boost::optional<HostAddress> address; + if (a->ifa_addr->sa_family == PF_INET) { + sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(a->ifa_addr); + address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4); + } + else if (a->ifa_addr->sa_family == PF_INET6) { + sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(a->ifa_addr); + address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16); + } + if (address) { + std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, a->ifa_flags & IFF_LOOPBACK))).first; + i->second.addAddress(*address); + } + } + + freeifaddrs(addrs); + + std::vector<NetworkInterface> result; + for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) { + result.push_back(i->second); + } + return result; } } diff --git a/Swiften/Network/SolarisNetworkEnvironment.h b/Swiften/Network/SolarisNetworkEnvironment.h index ed5adb7..6dc9673 100644 --- a/Swiften/Network/SolarisNetworkEnvironment.h +++ b/Swiften/Network/SolarisNetworkEnvironment.h @@ -20,9 +20,9 @@ namespace Swift { - class SolarisNetworkEnvironment : public NetworkEnvironment { - public: - std::vector<NetworkInterface> getNetworkInterfaces() const; - }; + class SolarisNetworkEnvironment : public NetworkEnvironment { + public: + std::vector<NetworkInterface> getNetworkInterfaces() const; + }; } diff --git a/Swiften/Network/StaticDomainNameResolver.cpp b/Swiften/Network/StaticDomainNameResolver.cpp index ab24be5..45e6c5f 100644 --- a/Swiften/Network/StaticDomainNameResolver.cpp +++ b/Swiften/Network/StaticDomainNameResolver.cpp @@ -17,65 +17,65 @@ using namespace Swift; namespace { - struct ServiceQuery : public DomainNameServiceQuery, public boost::enable_shared_from_this<ServiceQuery> { - ServiceQuery(const std::string& service, Swift::StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), service(service), resolver(resolver), owner(owner) {} - - virtual void run() { - if (!resolver->getIsResponsive()) { - return; - } - std::vector<DomainNameServiceQuery::Result> results; - for(StaticDomainNameResolver::ServicesCollection::const_iterator i = resolver->getServices().begin(); i != resolver->getServices().end(); ++i) { - if (i->first == service) { - results.push_back(i->second); - } - } - eventLoop->postEvent(boost::bind(&ServiceQuery::emitOnResult, shared_from_this(), results), owner); - } - - void emitOnResult(std::vector<DomainNameServiceQuery::Result> results) { - onResult(results); - } - - EventLoop* eventLoop; - std::string service; - StaticDomainNameResolver* resolver; - boost::shared_ptr<EventOwner> owner; - }; - - struct AddressQuery : public DomainNameAddressQuery, public boost::enable_shared_from_this<AddressQuery> { - AddressQuery(const std::string& host, StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), host(host), resolver(resolver), owner(owner) {} - - virtual void run() { - if (!resolver->getIsResponsive()) { - return; - } - StaticDomainNameResolver::AddressesMap::const_iterator i = resolver->getAddresses().find(host); - if (i != resolver->getAddresses().end()) { - eventLoop->postEvent( - boost::bind(&AddressQuery::emitOnResult, shared_from_this(), i->second, boost::optional<DomainNameResolveError>())); - } - else { - eventLoop->postEvent(boost::bind(&AddressQuery::emitOnResult, shared_from_this(), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), owner); - } - } - - void emitOnResult(std::vector<HostAddress> results, boost::optional<DomainNameResolveError> error) { - onResult(results, error); - } - - EventLoop* eventLoop; - std::string host; - StaticDomainNameResolver* resolver; - boost::shared_ptr<EventOwner> owner; - }; + struct ServiceQuery : public DomainNameServiceQuery, public boost::enable_shared_from_this<ServiceQuery> { + ServiceQuery(const std::string& service, Swift::StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), service(service), resolver(resolver), owner(owner) {} + + virtual void run() { + if (!resolver->getIsResponsive()) { + return; + } + std::vector<DomainNameServiceQuery::Result> results; + for(StaticDomainNameResolver::ServicesCollection::const_iterator i = resolver->getServices().begin(); i != resolver->getServices().end(); ++i) { + if (i->first == service) { + results.push_back(i->second); + } + } + eventLoop->postEvent(boost::bind(&ServiceQuery::emitOnResult, shared_from_this(), results), owner); + } + + void emitOnResult(std::vector<DomainNameServiceQuery::Result> results) { + onResult(results); + } + + EventLoop* eventLoop; + std::string service; + StaticDomainNameResolver* resolver; + boost::shared_ptr<EventOwner> owner; + }; + + struct AddressQuery : public DomainNameAddressQuery, public boost::enable_shared_from_this<AddressQuery> { + AddressQuery(const std::string& host, StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), host(host), resolver(resolver), owner(owner) {} + + virtual void run() { + if (!resolver->getIsResponsive()) { + return; + } + StaticDomainNameResolver::AddressesMap::const_iterator i = resolver->getAddresses().find(host); + if (i != resolver->getAddresses().end()) { + eventLoop->postEvent( + boost::bind(&AddressQuery::emitOnResult, shared_from_this(), i->second, boost::optional<DomainNameResolveError>())); + } + else { + eventLoop->postEvent(boost::bind(&AddressQuery::emitOnResult, shared_from_this(), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), owner); + } + } + + void emitOnResult(std::vector<HostAddress> results, boost::optional<DomainNameResolveError> error) { + onResult(results, error); + } + + EventLoop* eventLoop; + std::string host; + StaticDomainNameResolver* resolver; + boost::shared_ptr<EventOwner> owner; + }; } class StaticDomainNameResolverEventOwner : public EventOwner { - public: - ~StaticDomainNameResolverEventOwner() { + public: + ~StaticDomainNameResolverEventOwner() { - } + } }; @@ -85,36 +85,36 @@ StaticDomainNameResolver::StaticDomainNameResolver(EventLoop* eventLoop) : event } StaticDomainNameResolver::~StaticDomainNameResolver() { - eventLoop->removeEventsFromOwner(owner); + eventLoop->removeEventsFromOwner(owner); } void StaticDomainNameResolver::addAddress(const std::string& domain, const HostAddress& address) { - addresses[domain].push_back(address); + addresses[domain].push_back(address); } void StaticDomainNameResolver::addService(const std::string& service, const DomainNameServiceQuery::Result& result) { - services.push_back(std::make_pair(service, result)); + services.push_back(std::make_pair(service, result)); } void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const HostAddressPort& address) { - static int hostid = 0; - std::string hostname(std::string("host-") + boost::lexical_cast<std::string>(hostid)); - hostid++; + static int hostid = 0; + std::string hostname(std::string("host-") + boost::lexical_cast<std::string>(hostid)); + hostid++; - addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, address.getPort(), 0, 0)); - addAddress(hostname, address.getAddress()); + addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, address.getPort(), 0, 0)); + addAddress(hostname, address.getAddress()); } void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const std::string& hostname, int port) { - addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, port, 0, 0)); + addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, port, 0, 0)); } boost::shared_ptr<DomainNameServiceQuery> StaticDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) { - return boost::shared_ptr<DomainNameServiceQuery>(new ServiceQuery(serviceLookupPrefix + domain, this, eventLoop, owner)); + return boost::shared_ptr<DomainNameServiceQuery>(new ServiceQuery(serviceLookupPrefix + domain, this, eventLoop, owner)); } boost::shared_ptr<DomainNameAddressQuery> StaticDomainNameResolver::createAddressQuery(const std::string& name) { - return boost::shared_ptr<DomainNameAddressQuery>(new AddressQuery(name, this, eventLoop, owner)); + return boost::shared_ptr<DomainNameAddressQuery>(new AddressQuery(name, this, eventLoop, owner)); } } diff --git a/Swiften/Network/StaticDomainNameResolver.h b/Swiften/Network/StaticDomainNameResolver.h index ebbc29f..6d38a26 100644 --- a/Swiften/Network/StaticDomainNameResolver.h +++ b/Swiften/Network/StaticDomainNameResolver.h @@ -18,43 +18,43 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { - class SWIFTEN_API StaticDomainNameResolver : public DomainNameResolver { - public: - typedef std::map<std::string, std::vector<HostAddress> > AddressesMap; - typedef std::vector< std::pair<std::string, DomainNameServiceQuery::Result> > ServicesCollection; - - public: - StaticDomainNameResolver(EventLoop* eventLoop); - virtual ~StaticDomainNameResolver(); - - void addAddress(const std::string& domain, const HostAddress& address); - void addService(const std::string& service, const DomainNameServiceQuery::Result& result); - void addXMPPClientService(const std::string& domain, const HostAddressPort&); - void addXMPPClientService(const std::string& domain, const std::string& host, int port); - - const AddressesMap& getAddresses() const { - return addresses; - } - - const ServicesCollection& getServices() const { - return services; - } - - bool getIsResponsive() const { - return isResponsive; - } - - void setIsResponsive(bool b) { - isResponsive = b; - } - - virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); - virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name); - private: - EventLoop* eventLoop; - bool isResponsive; - AddressesMap addresses; - ServicesCollection services; - boost::shared_ptr<EventOwner> owner; - }; + class SWIFTEN_API StaticDomainNameResolver : public DomainNameResolver { + public: + typedef std::map<std::string, std::vector<HostAddress> > AddressesMap; + typedef std::vector< std::pair<std::string, DomainNameServiceQuery::Result> > ServicesCollection; + + public: + StaticDomainNameResolver(EventLoop* eventLoop); + virtual ~StaticDomainNameResolver(); + + void addAddress(const std::string& domain, const HostAddress& address); + void addService(const std::string& service, const DomainNameServiceQuery::Result& result); + void addXMPPClientService(const std::string& domain, const HostAddressPort&); + void addXMPPClientService(const std::string& domain, const std::string& host, int port); + + const AddressesMap& getAddresses() const { + return addresses; + } + + const ServicesCollection& getServices() const { + return services; + } + + bool getIsResponsive() const { + return isResponsive; + } + + void setIsResponsive(bool b) { + isResponsive = b; + } + + virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); + virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name); + private: + EventLoop* eventLoop; + bool isResponsive; + AddressesMap addresses; + ServicesCollection services; + boost::shared_ptr<EventOwner> owner; + }; } diff --git a/Swiften/Network/TLSConnection.cpp b/Swiften/Network/TLSConnection.cpp index c7087ae..4099de7 100644 --- a/Swiften/Network/TLSConnection.cpp +++ b/Swiften/Network/TLSConnection.cpp @@ -15,85 +15,85 @@ namespace Swift { TLSConnection::TLSConnection(Connection::ref connection, TLSContextFactory* tlsFactory, const TLSOptions& tlsOptions) : connection(connection) { - context = tlsFactory->createTLSContext(tlsOptions); - context->onDataForNetwork.connect(boost::bind(&TLSConnection::handleTLSDataForNetwork, this, _1)); - context->onDataForApplication.connect(boost::bind(&TLSConnection::handleTLSDataForApplication, this, _1)); - context->onConnected.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, false)); - context->onError.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, true)); + context = tlsFactory->createTLSContext(tlsOptions); + context->onDataForNetwork.connect(boost::bind(&TLSConnection::handleTLSDataForNetwork, this, _1)); + context->onDataForApplication.connect(boost::bind(&TLSConnection::handleTLSDataForApplication, this, _1)); + context->onConnected.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, false)); + context->onError.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, true)); - connection->onConnectFinished.connect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); - connection->onDataRead.connect(boost::bind(&TLSConnection::handleRawDataRead, this, _1)); - connection->onDataWritten.connect(boost::bind(&TLSConnection::handleRawDataWritten, this)); - connection->onDisconnected.connect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1)); + connection->onConnectFinished.connect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); + connection->onDataRead.connect(boost::bind(&TLSConnection::handleRawDataRead, this, _1)); + connection->onDataWritten.connect(boost::bind(&TLSConnection::handleRawDataWritten, this)); + connection->onDisconnected.connect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1)); } TLSConnection::~TLSConnection() { - connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); - connection->onDataRead.disconnect(boost::bind(&TLSConnection::handleRawDataRead, this, _1)); - connection->onDataWritten.disconnect(boost::bind(&TLSConnection::handleRawDataWritten, this)); - connection->onDisconnected.disconnect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1)); - delete context; + connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); + connection->onDataRead.disconnect(boost::bind(&TLSConnection::handleRawDataRead, this, _1)); + connection->onDataWritten.disconnect(boost::bind(&TLSConnection::handleRawDataWritten, this)); + connection->onDisconnected.disconnect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1)); + delete context; } void TLSConnection::handleTLSConnectFinished(bool error) { - onConnectFinished(error); - if (error) { - disconnect(); - } + onConnectFinished(error); + if (error) { + disconnect(); + } } void TLSConnection::handleTLSDataForNetwork(const SafeByteArray& data) { - connection->write(data); + connection->write(data); } void TLSConnection::handleTLSDataForApplication(const SafeByteArray& data) { - onDataRead(boost::make_shared<SafeByteArray>(data)); + onDataRead(boost::make_shared<SafeByteArray>(data)); } void TLSConnection::connect(const HostAddressPort& address) { - connection->connect(address); + connection->connect(address); } void TLSConnection::disconnect() { - connection->disconnect(); + connection->disconnect(); } void TLSConnection::write(const SafeByteArray& data) { - context->handleDataFromApplication(data); + context->handleDataFromApplication(data); } HostAddressPort TLSConnection::getLocalAddress() const { - return connection->getLocalAddress(); + return connection->getLocalAddress(); } HostAddressPort TLSConnection::getRemoteAddress() const { - return connection->getRemoteAddress(); + return connection->getRemoteAddress(); } TLSContext* TLSConnection::getTLSContext() const { - return context; + return context; } void TLSConnection::handleRawConnectFinished(bool error) { - connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); - if (error) { - onConnectFinished(true); - } - else { - context->connect(); - } + connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); + if (error) { + onConnectFinished(true); + } + else { + context->connect(); + } } void TLSConnection::handleRawDisconnected(const boost::optional<Error>& error) { - onDisconnected(error); + onDisconnected(error); } void TLSConnection::handleRawDataRead(boost::shared_ptr<SafeByteArray> data) { - context->handleDataFromNetwork(*data); + context->handleDataFromNetwork(*data); } void TLSConnection::handleRawDataWritten() { - onDataWritten(); + onDataWritten(); } } diff --git a/Swiften/Network/TLSConnection.h b/Swiften/Network/TLSConnection.h index b3acffc..41543a2 100644 --- a/Swiften/Network/TLSConnection.h +++ b/Swiften/Network/TLSConnection.h @@ -16,37 +16,37 @@ #include <Swiften/TLS/TLSOptions.h> namespace Swift { - class HostAddressPort; - class TLSContextFactory; - class TLSContext; - - class SWIFTEN_API TLSConnection : public Connection { - public: - - TLSConnection(Connection::ref connection, TLSContextFactory* tlsFactory, const TLSOptions&); - virtual ~TLSConnection(); - - virtual void listen() {assert(false);} - virtual void connect(const HostAddressPort& address); - virtual void disconnect(); - virtual void write(const SafeByteArray& data); - - virtual HostAddressPort getLocalAddress() const; - virtual HostAddressPort getRemoteAddress() const; - - TLSContext* getTLSContext() const; - - private: - void handleRawConnectFinished(bool error); - void handleRawDisconnected(const boost::optional<Error>& error); - void handleRawDataRead(boost::shared_ptr<SafeByteArray> data); - void handleRawDataWritten(); - void handleTLSConnectFinished(bool error); - void handleTLSDataForNetwork(const SafeByteArray& data); - void handleTLSDataForApplication(const SafeByteArray& data); - - private: - TLSContext* context; - Connection::ref connection; - }; + class HostAddressPort; + class TLSContextFactory; + class TLSContext; + + class SWIFTEN_API TLSConnection : public Connection { + public: + + TLSConnection(Connection::ref connection, TLSContextFactory* tlsFactory, const TLSOptions&); + virtual ~TLSConnection(); + + virtual void listen() {assert(false);} + virtual void connect(const HostAddressPort& address); + virtual void disconnect(); + virtual void write(const SafeByteArray& data); + + virtual HostAddressPort getLocalAddress() const; + virtual HostAddressPort getRemoteAddress() const; + + TLSContext* getTLSContext() const; + + private: + void handleRawConnectFinished(bool error); + void handleRawDisconnected(const boost::optional<Error>& error); + void handleRawDataRead(boost::shared_ptr<SafeByteArray> data); + void handleRawDataWritten(); + void handleTLSConnectFinished(bool error); + void handleTLSDataForNetwork(const SafeByteArray& data); + void handleTLSDataForApplication(const SafeByteArray& data); + + private: + TLSContext* context; + Connection::ref connection; + }; } diff --git a/Swiften/Network/TLSConnectionFactory.cpp b/Swiften/Network/TLSConnectionFactory.cpp index cc20b2d..e0396e2 100644 --- a/Swiften/Network/TLSConnectionFactory.cpp +++ b/Swiften/Network/TLSConnectionFactory.cpp @@ -22,7 +22,7 @@ TLSConnectionFactory::~TLSConnectionFactory() { boost::shared_ptr<Connection> TLSConnectionFactory::createConnection() { - return boost::make_shared<TLSConnection>(connectionFactory->createConnection(), contextFactory, options_); + return boost::make_shared<TLSConnection>(connectionFactory->createConnection(), contextFactory, options_); } } diff --git a/Swiften/Network/TLSConnectionFactory.h b/Swiften/Network/TLSConnectionFactory.h index 0c67014..8e39c35 100644 --- a/Swiften/Network/TLSConnectionFactory.h +++ b/Swiften/Network/TLSConnectionFactory.h @@ -14,17 +14,17 @@ #include <Swiften/TLS/TLSOptions.h> namespace Swift { - class Connection; + class Connection; - class SWIFTEN_API TLSConnectionFactory : public ConnectionFactory { - public: - TLSConnectionFactory(TLSContextFactory* contextFactory, ConnectionFactory* connectionFactory, const TLSOptions&); - virtual ~TLSConnectionFactory(); + class SWIFTEN_API TLSConnectionFactory : public ConnectionFactory { + public: + TLSConnectionFactory(TLSContextFactory* contextFactory, ConnectionFactory* connectionFactory, const TLSOptions&); + virtual ~TLSConnectionFactory(); - virtual boost::shared_ptr<Connection> createConnection(); - private: - TLSContextFactory* contextFactory; - ConnectionFactory* connectionFactory; - TLSOptions options_; - }; + virtual boost::shared_ptr<Connection> createConnection(); + private: + TLSContextFactory* contextFactory; + ConnectionFactory* connectionFactory; + TLSOptions options_; + }; } diff --git a/Swiften/Network/Timer.h b/Swiften/Network/Timer.h index 2697200..1abf5bc 100644 --- a/Swiften/Network/Timer.h +++ b/Swiften/Network/Timer.h @@ -10,32 +10,32 @@ #include <Swiften/Base/boost_bsignals.h> namespace Swift { - /** - * A class for triggering an event after a given period. - */ - class SWIFTEN_API Timer { - public: - typedef boost::shared_ptr<Timer> ref; + /** + * A class for triggering an event after a given period. + */ + class SWIFTEN_API Timer { + public: + typedef boost::shared_ptr<Timer> ref; - virtual ~Timer(); + virtual ~Timer(); - /** - * Starts the timer. - * - * After the given period, onTick() will be called. - */ - virtual void start() = 0; + /** + * Starts the timer. + * + * After the given period, onTick() will be called. + */ + virtual void start() = 0; - /** - * Cancels the timer. - * - * If the timer was started, onTick() will no longer be called. - */ - virtual void stop() = 0; + /** + * Cancels the timer. + * + * If the timer was started, onTick() will no longer be called. + */ + virtual void stop() = 0; - /** - * Emitted when the timer expires. - */ - boost::signal<void ()> onTick; - }; + /** + * Emitted when the timer expires. + */ + boost::signal<void ()> onTick; + }; } diff --git a/Swiften/Network/TimerFactory.h b/Swiften/Network/TimerFactory.h index a27e76e..47e89f8 100644 --- a/Swiften/Network/TimerFactory.h +++ b/Swiften/Network/TimerFactory.h @@ -12,10 +12,10 @@ #include <Swiften/Network/Timer.h> namespace Swift { - class SWIFTEN_API TimerFactory { - public: - virtual ~TimerFactory(); + class SWIFTEN_API TimerFactory { + public: + virtual ~TimerFactory(); - virtual Timer::ref createTimer(int milliseconds) = 0; - }; + virtual Timer::ref createTimer(int milliseconds) = 0; + }; } diff --git a/Swiften/Network/UnboundDomainNameResolver.cpp b/Swiften/Network/UnboundDomainNameResolver.cpp index 68d40e1..a9fed24 100755 --- a/Swiften/Network/UnboundDomainNameResolver.cpp +++ b/Swiften/Network/UnboundDomainNameResolver.cpp @@ -34,219 +34,219 @@ namespace Swift { class UnboundQuery { - public: - UnboundQuery(UnboundDomainNameResolver* resolver, ub_ctx* context) : resolver(resolver), ubContext(context) {} - virtual ~UnboundQuery() {} - virtual void handleResult(int err, ub_result* result) = 0; - protected: - UnboundDomainNameResolver* resolver; - ub_ctx* ubContext; + public: + UnboundQuery(UnboundDomainNameResolver* resolver, ub_ctx* context) : resolver(resolver), ubContext(context) {} + virtual ~UnboundQuery() {} + virtual void handleResult(int err, ub_result* result) = 0; + protected: + UnboundDomainNameResolver* resolver; + ub_ctx* ubContext; }; struct UnboundWrapperHelper { - UnboundWrapperHelper(UnboundDomainNameResolver* resolver, boost::shared_ptr<UnboundQuery> query) : resolver(resolver), query(query) {} - UnboundDomainNameResolver* resolver; - boost::shared_ptr<UnboundQuery> query; + UnboundWrapperHelper(UnboundDomainNameResolver* resolver, boost::shared_ptr<UnboundQuery> query) : resolver(resolver), query(query) {} + UnboundDomainNameResolver* resolver; + boost::shared_ptr<UnboundQuery> query; }; class UnboundDomainNameServiceQuery : public DomainNameServiceQuery, public UnboundQuery, public boost::enable_shared_from_this<UnboundDomainNameServiceQuery> { - public: - UnboundDomainNameServiceQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) { - } - - virtual ~UnboundDomainNameServiceQuery() { } - - virtual void run() { - int retval; - UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this()); - - retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_SRV, - 1 /* CLASS IN (internet) */, - helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL); - if(retval != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl; - delete helper; - } - } - - void handleResult(int err, struct ub_result* result) { - std::vector<DomainNameServiceQuery::Result> serviceRecords; - - if(err != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl; - } else { - if(result->havedata) { - ldns_pkt* replyPacket = 0; - ldns_buffer* buffer = ldns_buffer_new(1024); - if (buffer && ldns_wire2pkt(&replyPacket, static_cast<const uint8_t*>(result->answer_packet), result->answer_len) == LDNS_STATUS_OK) { - ldns_rr_list* rrList = ldns_pkt_answer(replyPacket); - for (size_t n = 0; n < ldns_rr_list_rr_count(rrList); n++) { - ldns_rr* rr = ldns_rr_list_rr(rrList, n); - if ((ldns_rr_get_type(rr) != LDNS_RR_TYPE_SRV) || - (ldns_rr_get_class(rr) != LDNS_RR_CLASS_IN) || - (ldns_rr_rd_count(rr) != 4)) { - continue; - } - - DomainNameServiceQuery::Result serviceRecord; - serviceRecord.priority = ldns_rdf2native_int16(ldns_rr_rdf(rr, 0)); - serviceRecord.weight = ldns_rdf2native_int16(ldns_rr_rdf(rr, 1)); - serviceRecord.port = ldns_rdf2native_int16(ldns_rr_rdf(rr, 2)); - - ldns_buffer_rewind(buffer); - if ((ldns_rdf2buffer_str_dname(buffer, ldns_rr_rdf(rr, 3)) != LDNS_STATUS_OK) || - (ldns_buffer_position(buffer) < 2) || - !ldns_buffer_reserve(buffer, 1)) { - // either name invalid, empty or buffer to small - continue; - } - char terminator = 0; - ldns_buffer_write(buffer, &terminator, sizeof(terminator)); - - serviceRecord.hostname = std::string(reinterpret_cast<char*>(ldns_buffer_at(buffer, 0))); - serviceRecords.push_back(serviceRecord); - SWIFT_LOG(debug) << "hostname " << serviceRecord.hostname << " added" << std::endl; - } - } - if (replyPacket) ldns_pkt_free(replyPacket); - if (buffer) ldns_buffer_free(buffer); - } - } - - ub_resolve_free(result); - onResult(serviceRecords); - } - - private: - std::string name; + public: + UnboundDomainNameServiceQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) { + } + + virtual ~UnboundDomainNameServiceQuery() { } + + virtual void run() { + int retval; + UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this()); + + retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_SRV, + 1 /* CLASS IN (internet) */, + helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL); + if(retval != 0) { + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl; + delete helper; + } + } + + void handleResult(int err, struct ub_result* result) { + std::vector<DomainNameServiceQuery::Result> serviceRecords; + + if(err != 0) { + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl; + } else { + if(result->havedata) { + ldns_pkt* replyPacket = 0; + ldns_buffer* buffer = ldns_buffer_new(1024); + if (buffer && ldns_wire2pkt(&replyPacket, static_cast<const uint8_t*>(result->answer_packet), result->answer_len) == LDNS_STATUS_OK) { + ldns_rr_list* rrList = ldns_pkt_answer(replyPacket); + for (size_t n = 0; n < ldns_rr_list_rr_count(rrList); n++) { + ldns_rr* rr = ldns_rr_list_rr(rrList, n); + if ((ldns_rr_get_type(rr) != LDNS_RR_TYPE_SRV) || + (ldns_rr_get_class(rr) != LDNS_RR_CLASS_IN) || + (ldns_rr_rd_count(rr) != 4)) { + continue; + } + + DomainNameServiceQuery::Result serviceRecord; + serviceRecord.priority = ldns_rdf2native_int16(ldns_rr_rdf(rr, 0)); + serviceRecord.weight = ldns_rdf2native_int16(ldns_rr_rdf(rr, 1)); + serviceRecord.port = ldns_rdf2native_int16(ldns_rr_rdf(rr, 2)); + + ldns_buffer_rewind(buffer); + if ((ldns_rdf2buffer_str_dname(buffer, ldns_rr_rdf(rr, 3)) != LDNS_STATUS_OK) || + (ldns_buffer_position(buffer) < 2) || + !ldns_buffer_reserve(buffer, 1)) { + // either name invalid, empty or buffer to small + continue; + } + char terminator = 0; + ldns_buffer_write(buffer, &terminator, sizeof(terminator)); + + serviceRecord.hostname = std::string(reinterpret_cast<char*>(ldns_buffer_at(buffer, 0))); + serviceRecords.push_back(serviceRecord); + SWIFT_LOG(debug) << "hostname " << serviceRecord.hostname << " added" << std::endl; + } + } + if (replyPacket) ldns_pkt_free(replyPacket); + if (buffer) ldns_buffer_free(buffer); + } + } + + ub_resolve_free(result); + onResult(serviceRecords); + } + + private: + std::string name; }; class UnboundDomainNameAddressQuery : public DomainNameAddressQuery, public UnboundQuery, public boost::enable_shared_from_this<UnboundDomainNameAddressQuery> { - public: - UnboundDomainNameAddressQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) { - } - - virtual ~UnboundDomainNameAddressQuery() { } - - virtual void run() { - int retval; - UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this()); - - //FIXME: support AAAA queries in some way - retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_A, - 1 /* CLASS IN (internet) */, - helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL); - if(retval != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl; - delete helper; - } - } - - void handleResult(int err, struct ub_result* result) { - std::vector<HostAddress> addresses; - boost::optional<DomainNameResolveError> error; - SWIFT_LOG(debug) << "Result for: " << name << std::endl; - - if(err != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl; - error = DomainNameResolveError(); - } else { - if(result->havedata) { - for(int i=0; result->data[i]; i++) { - char address[100]; - const char* addressStr = 0; - if ((addressStr = inet_ntop(AF_INET, result->data[i], address, 100))) { - SWIFT_LOG(debug) << "IPv4 address: " << addressStr << std::endl; - addresses.push_back(HostAddress(std::string(addressStr))); - } else if ((addressStr = inet_ntop(AF_INET6, result->data[i], address, 100))) { - SWIFT_LOG(debug) << "IPv6 address: " << addressStr << std::endl; - addresses.push_back(HostAddress(std::string(addressStr))); - } else { - SWIFT_LOG(debug) << "inet_ntop() failed" << std::endl; - error = DomainNameResolveError(); - } - } - } else { - error = DomainNameResolveError(); - } - } - - ub_resolve_free(result); - onResult(addresses, error); - } - - private: - std::string name; + public: + UnboundDomainNameAddressQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) { + } + + virtual ~UnboundDomainNameAddressQuery() { } + + virtual void run() { + int retval; + UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this()); + + //FIXME: support AAAA queries in some way + retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_A, + 1 /* CLASS IN (internet) */, + helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL); + if(retval != 0) { + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl; + delete helper; + } + } + + void handleResult(int err, struct ub_result* result) { + std::vector<HostAddress> addresses; + boost::optional<DomainNameResolveError> error; + SWIFT_LOG(debug) << "Result for: " << name << std::endl; + + if(err != 0) { + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl; + error = DomainNameResolveError(); + } else { + if(result->havedata) { + for(int i=0; result->data[i]; i++) { + char address[100]; + const char* addressStr = 0; + if ((addressStr = inet_ntop(AF_INET, result->data[i], address, 100))) { + SWIFT_LOG(debug) << "IPv4 address: " << addressStr << std::endl; + addresses.push_back(HostAddress(std::string(addressStr))); + } else if ((addressStr = inet_ntop(AF_INET6, result->data[i], address, 100))) { + SWIFT_LOG(debug) << "IPv6 address: " << addressStr << std::endl; + addresses.push_back(HostAddress(std::string(addressStr))); + } else { + SWIFT_LOG(debug) << "inet_ntop() failed" << std::endl; + error = DomainNameResolveError(); + } + } + } else { + error = DomainNameResolveError(); + } + } + + ub_resolve_free(result); + onResult(addresses, error); + } + + private: + std::string name; }; UnboundDomainNameResolver::UnboundDomainNameResolver(IDNConverter* idnConverter, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : idnConverter(idnConverter), ioService(ioService), ubDescriptior(*ioService), eventLoop(eventLoop) { - ubContext = ub_ctx_create(); - if(!ubContext) { - SWIFT_LOG(debug) << "could not create unbound context" << std::endl; - } - eventOwner = boost::make_shared<EventOwner>(); + ubContext = ub_ctx_create(); + if(!ubContext) { + SWIFT_LOG(debug) << "could not create unbound context" << std::endl; + } + eventOwner = boost::make_shared<EventOwner>(); - ub_ctx_async(ubContext, true); + ub_ctx_async(ubContext, true); - int ret; + int ret; - /* read /etc/resolv.conf for DNS proxy settings (from DHCP) */ - if( (ret=ub_ctx_resolvconf(ubContext, const_cast<char*>("/etc/resolv.conf"))) != 0) { - SWIFT_LOG(error) << "error reading resolv.conf: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl; - } - /* read /etc/hosts for locally supplied host addresses */ - if( (ret=ub_ctx_hosts(ubContext, const_cast<char*>("/etc/hosts"))) != 0) { - SWIFT_LOG(error) << "error reading hosts: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl; - } + /* read /etc/resolv.conf for DNS proxy settings (from DHCP) */ + if( (ret=ub_ctx_resolvconf(ubContext, const_cast<char*>("/etc/resolv.conf"))) != 0) { + SWIFT_LOG(error) << "error reading resolv.conf: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl; + } + /* read /etc/hosts for locally supplied host addresses */ + if( (ret=ub_ctx_hosts(ubContext, const_cast<char*>("/etc/hosts"))) != 0) { + SWIFT_LOG(error) << "error reading hosts: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl; + } - ubDescriptior.assign(ub_fd(ubContext)); + ubDescriptior.assign(ub_fd(ubContext)); - ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error)); + ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error)); } UnboundDomainNameResolver::~UnboundDomainNameResolver() { - eventLoop->removeEventsFromOwner(eventOwner); - if (ubContext) { - ub_ctx_delete(ubContext); - } + eventLoop->removeEventsFromOwner(eventOwner); + if (ubContext) { + ub_ctx_delete(ubContext); + } } void UnboundDomainNameResolver::unbound_callback(boost::shared_ptr<UnboundQuery> query, int err, ub_result* result) { - query->handleResult(err, result); + query->handleResult(err, result); } void UnboundDomainNameResolver::unbound_callback_wrapper(void* data, int err, ub_result* result) { - UnboundWrapperHelper* helper = static_cast<UnboundWrapperHelper*>(data); - UnboundDomainNameResolver* resolver = helper->resolver; - resolver->unbound_callback(helper->query, err, result); - delete helper; + UnboundWrapperHelper* helper = static_cast<UnboundWrapperHelper*>(data); + UnboundDomainNameResolver* resolver = helper->resolver; + resolver->unbound_callback(helper->query, err, result); + delete helper; } void UnboundDomainNameResolver::handleUBSocketReadable(boost::system::error_code) { - eventLoop->postEvent(boost::bind(&UnboundDomainNameResolver::processData, this), eventOwner); - ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error)); + eventLoop->postEvent(boost::bind(&UnboundDomainNameResolver::processData, this), eventOwner); + ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error)); } void UnboundDomainNameResolver::processData() { - if (ub_poll(ubContext)) { - int ret = ub_process(ubContext); - if(ret != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(ret) << std::endl; - } - } + if (ub_poll(ubContext)) { + int ret = ub_process(ubContext); + if(ret != 0) { + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(ret) << std::endl; + } + } } boost::shared_ptr<DomainNameServiceQuery> UnboundDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) { - boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain); - std::string result; - if (encodedDomain) { - result = serviceLookupPrefix + *encodedDomain; - } - return boost::make_shared<UnboundDomainNameServiceQuery>(this, ubContext, result); + boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain); + std::string result; + if (encodedDomain) { + result = serviceLookupPrefix + *encodedDomain; + } + return boost::make_shared<UnboundDomainNameServiceQuery>(this, ubContext, result); } boost::shared_ptr<DomainNameAddressQuery> UnboundDomainNameResolver::createAddressQuery(const std::string& name) { - return boost::make_shared<UnboundDomainNameAddressQuery>(this, ubContext, idnConverter->getIDNAEncoded(name).get_value_or("")); + return boost::make_shared<UnboundDomainNameAddressQuery>(this, ubContext, idnConverter->getIDNAEncoded(name).get_value_or("")); } } diff --git a/Swiften/Network/UnboundDomainNameResolver.h b/Swiften/Network/UnboundDomainNameResolver.h index f7092eb..afb21c8 100755 --- a/Swiften/Network/UnboundDomainNameResolver.h +++ b/Swiften/Network/UnboundDomainNameResolver.h @@ -24,36 +24,36 @@ struct ub_ctx; struct ub_result; namespace Swift { - class EventLoop; - class IDNConverter; - class TimerFactory; + class EventLoop; + class IDNConverter; + class TimerFactory; - class UnboundDomainNameResolver; - class UnboundQuery; + class UnboundDomainNameResolver; + class UnboundQuery; - class UnboundDomainNameResolver : public DomainNameResolver, public EventOwner, public boost::enable_shared_from_this<UnboundDomainNameResolver> { - public: - UnboundDomainNameResolver(IDNConverter* idnConverter, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); - virtual ~UnboundDomainNameResolver(); + class UnboundDomainNameResolver : public DomainNameResolver, public EventOwner, public boost::enable_shared_from_this<UnboundDomainNameResolver> { + public: + UnboundDomainNameResolver(IDNConverter* idnConverter, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); + virtual ~UnboundDomainNameResolver(); - virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); - virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name); + virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain); + virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name); - static void unbound_callback_wrapper(void* data, int err, ub_result* result); + static void unbound_callback_wrapper(void* data, int err, ub_result* result); - private: - void unbound_callback(boost::shared_ptr<UnboundQuery> query, int err, ub_result* result); + private: + void unbound_callback(boost::shared_ptr<UnboundQuery> query, int err, ub_result* result); - void handleUBSocketReadable(boost::system::error_code); - void processData(); + void handleUBSocketReadable(boost::system::error_code); + void processData(); - private: - IDNConverter* idnConverter; - boost::shared_ptr<EventOwner> eventOwner; - boost::shared_ptr<boost::asio::io_service> ioService; - boost::asio::posix::stream_descriptor ubDescriptior; - EventLoop* eventLoop; - ub_ctx* ubContext; - }; + private: + IDNConverter* idnConverter; + boost::shared_ptr<EventOwner> eventOwner; + boost::shared_ptr<boost::asio::io_service> ioService; + boost::asio::posix::stream_descriptor ubDescriptior; + EventLoop* eventLoop; + ub_ctx* ubContext; + }; } diff --git a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp index e8d8c4a..e781742 100644 --- a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp +++ b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp @@ -33,436 +33,436 @@ typedef boost::shared_ptr<BOSHConnectionPool> PoolRef; class BOSHConnectionPoolTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(BOSHConnectionPoolTest); - CPPUNIT_TEST(testConnectionCount_OneWrite); - CPPUNIT_TEST(testConnectionCount_TwoWrites); - CPPUNIT_TEST(testConnectionCount_ThreeWrites); - CPPUNIT_TEST(testConnectionCount_ThreeWrites_ManualConnect); - CPPUNIT_TEST(testConnectionCount_ThreeWritesTwoReads); - CPPUNIT_TEST(testSession); - CPPUNIT_TEST(testWrite_Empty); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - to = "wonderland.lit"; - path = "/http-bind"; - port = "5280"; - sid = "MyShinySID"; - initial = "<body wait='60' " - "inactivity='30' " - "polling='5' " - "requests='2' " - "hold='1' " - "maxpause='120' " - "sid='" + sid + "' " - "ver='1.6' " - "from='wonderland.lit' " - "xmlns='http://jabber.org/protocol/httpbind'/>"; - eventLoop = new DummyEventLoop(); - connectionFactory = new MockConnectionFactory(eventLoop); - boshURL = URL("http", to, 5280, path); - sessionTerminated = 0; - sessionStarted = 0; - initialRID = 2349876; - xmppDataRead.clear(); - boshDataRead.clear(); - boshDataWritten.clear(); - resolver = new StaticDomainNameResolver(eventLoop); - resolver->addAddress(to, HostAddress("127.0.0.1")); - timerFactory = new DummyTimerFactory(); - } - - void tearDown() { - eventLoop->processEvents(); - delete connectionFactory; - delete resolver; - delete timerFactory; - delete eventLoop; - } - - void testConnectionCount_OneWrite() { - PoolRef testling = createTestling(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(0, sessionStarted); - readResponse(initial, connectionFactory->connections[0]); - CPPUNIT_ASSERT_EQUAL(1, sessionStarted); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - testling->write(createSafeByteArray("<blah/>")); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - CPPUNIT_ASSERT_EQUAL(1, sessionStarted); - } - - void testConnectionCount_TwoWrites() { - PoolRef testling = createTestling(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - eventLoop->processEvents(); - readResponse(initial, connectionFactory->connections[0]); - eventLoop->processEvents(); - testling->write(createSafeByteArray("<blah/>")); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - testling->write(createSafeByteArray("<bleh/>")); - eventLoop->processEvents(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); - } - - void testConnectionCount_ThreeWrites() { - PoolRef testling = createTestling(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - eventLoop->processEvents(); - readResponse(initial, connectionFactory->connections[0]); - testling->restartStream(); - readResponse("<body/>", connectionFactory->connections[0]); - testling->restartStream(); - readResponse("<body/>", connectionFactory->connections[0]); - testling->write(createSafeByteArray("<blah/>")); - testling->write(createSafeByteArray("<bleh/>")); - testling->write(createSafeByteArray("<bluh/>")); - eventLoop->processEvents(); - CPPUNIT_ASSERT(st(2) >= connectionFactory->connections.size()); - } - - void testConnectionCount_ThreeWrites_ManualConnect() { - connectionFactory->autoFinishConnect = false; - PoolRef testling = createTestling(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - CPPUNIT_ASSERT_EQUAL(st(0), boshDataWritten.size()); /* Connection not connected yet, can't send data */ - - connectionFactory->connections[0]->onConnectFinished(false); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Connection finished, stream header sent */ - - readResponse(initial, connectionFactory->connections[0]); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Don't respond to initial data with a holding call */ - - testling->restartStream(); - eventLoop->processEvents(); - readResponse("<body/>", connectionFactory->connections[0]); - eventLoop->processEvents(); - testling->restartStream(); - eventLoop->processEvents(); - - - testling->write(createSafeByteArray("<blah/>")); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); - CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); /* New connection isn't up yet. */ - - connectionFactory->connections[1]->onConnectFinished(false); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* New connection ready. */ - - testling->write(createSafeByteArray("<bleh/>")); - eventLoop->processEvents(); - testling->write(createSafeByteArray("<bluh/>")); - CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* New data can't be sent, no free connections. */ - eventLoop->processEvents(); - CPPUNIT_ASSERT(st(2) >= connectionFactory->connections.size()); - } - - void testConnectionCount_ThreeWritesTwoReads() { - boost::shared_ptr<MockConnection> c0; - boost::shared_ptr<MockConnection> c1; - unsigned long long rid = initialRID; - - PoolRef testling = createTestling(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - c0 = connectionFactory->connections[0]; - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* header*/ - - rid++; - readResponse(initial, c0); - CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - CPPUNIT_ASSERT(!c0->pending); - - rid++; - testling->restartStream(); - eventLoop->processEvents(); - readResponse("<body/>", connectionFactory->connections[0]); - - rid++; - testling->write(createSafeByteArray("<blah/>")); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* 0 was waiting for response, open and send on 1 */ - CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* data */ - c1 = connectionFactory->connections[1]; - std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(rid) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'><blah/></body>"; /* check empty write */ - CPPUNIT_ASSERT_EQUAL(fullBody, lastBody()); - CPPUNIT_ASSERT(c0->pending); - CPPUNIT_ASSERT(c1->pending); - - - rid++; - readResponse("<body xmlns='http://jabber.org/protocol/httpbind'><message><splatploing/></message></body>", c0); /* Doesn't include necessary attributes - as the support is improved this'll start to fail */ - eventLoop->processEvents(); - CPPUNIT_ASSERT(!c0->pending); - CPPUNIT_ASSERT(c1->pending); - CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* don't send empty in [0], still have [1] waiting */ - CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); - - rid++; - readResponse("<body xmlns='http://jabber.org/protocol/httpbind'><message><splatploing><blittlebarg/></splatploing></message></body>", c1); - eventLoop->processEvents(); - CPPUNIT_ASSERT(!c1->pending); - CPPUNIT_ASSERT(c0->pending); - CPPUNIT_ASSERT_EQUAL(st(5), boshDataWritten.size()); /* empty to make room */ - CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); - - rid++; - testling->write(createSafeByteArray("<bleh/>")); - eventLoop->processEvents(); - CPPUNIT_ASSERT(c0->pending); - CPPUNIT_ASSERT(c1->pending); - CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size()); /* data */ - - rid++; - testling->write(createSafeByteArray("<bluh/>")); - CPPUNIT_ASSERT(c0->pending); - CPPUNIT_ASSERT(c1->pending); - CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size()); /* Don't send data, no room */ - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); - } - - void testSession() { - to = "prosody.doomsong.co.uk"; - resolver->addAddress("prosody.doomsong.co.uk", HostAddress("127.0.0.1")); - path = "/http-bind/"; - boshURL = URL("http", to, 5280, path); - - PoolRef testling = createTestling(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* header*/ - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - std::string response = "<body authid='743da605-4c2e-4de1-afac-ac040dd4a940' xmpp:version='1.0' xmlns:stream='http://etherx.jabber.org/streams' xmlns:xmpp='urn:xmpp:xbosh' inactivity='60' wait='60' polling='5' secure='true' hold='1' from='prosody.doomsong.co.uk' ver='1.6' sid='743da605-4c2e-4de1-afac-ac040dd4a940' requests='2' xmlns='http://jabber.org/protocol/httpbind'><stream:features><auth xmlns='http://jabber.org/features/iq-auth'/><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>SCRAM-SHA-1</mechanism><mechanism>DIGEST-MD5</mechanism></mechanisms></stream:features></body>"; - readResponse(response, connectionFactory->connections[0]); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - std::string send = "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"SCRAM-SHA-1\">biwsbj1hZG1pbixyPWZhOWE5ZDhiLWZmMDctNGE4Yy04N2E3LTg4YWRiNDQxZGUwYg==</auth>"; - testling->write(createSafeByteArray(send)); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - response = "<body xmlns='http://jabber.org/protocol/httpbind' sid='743da605-4c2e-4de1-afac-ac040dd4a940' xmlns:stream = 'http://etherx.jabber.org/streams'><challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>cj1mYTlhOWQ4Yi1mZjA3LTRhOGMtODdhNy04OGFkYjQ0MWRlMGJhZmZlMWNhMy1mMDJkLTQ5NzEtYjkyNS0yM2NlNWQ2MDQyMjYscz1OVGd5WkdWaFptTXRaVE15WXkwMFpXUmhMV0ZqTURRdFpqYzRNbUppWmpGa1pqWXgsaT00MDk2</challenge></body>"; - readResponse(response, connectionFactory->connections[0]); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - send = "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">Yz1iaXdzLHI9ZmE5YTlkOGItZmYwNy00YThjLTg3YTctODhhZGI0NDFkZTBiYWZmZTFjYTMtZjAyZC00OTcxLWI5MjUtMjNjZTVkNjA0MjI2LHA9aU11NWt3dDN2VWplU2RqL01Jb3VIRldkZjBnPQ==</response>"; - testling->write(createSafeByteArray(send)); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - response = "<body xmlns='http://jabber.org/protocol/httpbind' sid='743da605-4c2e-4de1-afac-ac040dd4a940' xmlns:stream = 'http://etherx.jabber.org/streams'><success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>dj1YNmNBY3BBOWxHNjNOOXF2bVQ5S0FacERrVm89</success></body>"; - readResponse(response, connectionFactory->connections[0]); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - testling->restartStream(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - response = "<body xmpp:version='1.0' xmlns:stream='http://etherx.jabber.org/streams' xmlns:xmpp='urn:xmpp:xbosh' inactivity='60' wait='60' polling='5' secure='true' hold='1' from='prosody.doomsong.co.uk' ver='1.6' sid='743da605-4c2e-4de1-afac-ac040dd4a940' requests='2' xmlns='http://jabber.org/protocol/httpbind'><stream:features><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><required/></bind><session xmlns='urn:ietf:params:xml:ns:xmpp-session'><optional/></session><sm xmlns='urn:xmpp:sm:2'><optional/></sm></stream:features></body>"; - readResponse(response, connectionFactory->connections[0]); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(5), boshDataWritten.size()); /* Now we've authed (restarted) we should be keeping one query in flight so the server can reply to us at any time it wants. */ - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - - send = "<body rid='2821988967416214' sid='cf663f6b94279d4f' xmlns='http://jabber.org/protocol/httpbind'><iq id='session-bind' type='set'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>d5a9744036cd20a0</resource></bind></iq></body>"; - testling->write(createSafeByteArray(send)); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size()); - CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* and as it keeps one in flight, it's needed to open a second to send these data */ - - } - - void testWrite_Empty() { - boost::shared_ptr<MockConnection> c0; - - PoolRef testling = createTestling(); - CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); - c0 = connectionFactory->connections[0]; - - readResponse(initial, c0); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Shouldn't have sent anything extra */ - eventLoop->processEvents(); - testling->restartStream(); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size()); - readResponse("<body></body>", c0); - eventLoop->processEvents(); - CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); - std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(initialRID + 2) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'></body>"; - std::string response = boshDataWritten[2]; - size_t bodyPosition = response.find("\r\n\r\n"); - CPPUNIT_ASSERT_EQUAL(fullBody, response.substr(bodyPosition+4)); - - - } - - private: - - PoolRef createTestling() { - // make_shared is limited to 9 arguments; instead new is used here. - PoolRef pool = PoolRef(new BOSHConnectionPool(boshURL, resolver, connectionFactory, &parserFactory, static_cast<TLSContextFactory*>(NULL), timerFactory, eventLoop, to, initialRID, URL(), SafeString(""), SafeString(""), TLSOptions())); - pool->open(); - pool->onXMPPDataRead.connect(boost::bind(&BOSHConnectionPoolTest::handleXMPPDataRead, this, _1)); - pool->onBOSHDataRead.connect(boost::bind(&BOSHConnectionPoolTest::handleBOSHDataRead, this, _1)); - pool->onBOSHDataWritten.connect(boost::bind(&BOSHConnectionPoolTest::handleBOSHDataWritten, this, _1)); - pool->onSessionStarted.connect(boost::bind(&BOSHConnectionPoolTest::handleSessionStarted, this)); - pool->onSessionTerminated.connect(boost::bind(&BOSHConnectionPoolTest::handleSessionTerminated, this)); - eventLoop->processEvents(); - eventLoop->processEvents(); - return pool; - } - - std::string lastBody() { - std::string response = boshDataWritten[boshDataWritten.size() - 1]; - size_t bodyPosition = response.find("\r\n\r\n"); - return response.substr(bodyPosition+4); - } - - size_t st(int val) { - return static_cast<size_t>(val); - } - - void handleXMPPDataRead(const SafeByteArray& d) { - xmppDataRead.push_back(safeByteArrayToString(d)); - } - - void handleBOSHDataRead(const SafeByteArray& d) { - boshDataRead.push_back(safeByteArrayToString(d)); - } - - void handleBOSHDataWritten(const SafeByteArray& d) { - boshDataWritten.push_back(safeByteArrayToString(d)); - } - - - void handleSessionStarted() { - sessionStarted++; - } - - void handleSessionTerminated() { - sessionTerminated++; - } - - struct MockConnection : public Connection { - public: - MockConnection(const std::vector<HostAddressPort>& failingPorts, EventLoop* eventLoop, bool autoFinishConnect) : eventLoop(eventLoop), failingPorts(failingPorts), disconnected(false), pending(false), autoFinishConnect(autoFinishConnect) { - } - - void listen() { assert(false); } - - void connect(const HostAddressPort& address) { - hostAddressPort = address; - bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end(); - if (autoFinishConnect) { - eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail)); - } - } - - HostAddressPort getLocalAddress() const { return HostAddressPort(); } - HostAddressPort getRemoteAddress() const { return HostAddressPort(); } - - void disconnect() { - disconnected = true; - onDisconnected(boost::optional<Connection::Error>()); - } - - void write(const SafeByteArray& d) { - append(dataWritten, d); - pending = true; - } - - EventLoop* eventLoop; - boost::optional<HostAddressPort> hostAddressPort; - std::vector<HostAddressPort> failingPorts; - ByteArray dataWritten; - bool disconnected; - bool pending; - bool autoFinishConnect; - }; - - struct MockConnectionFactory : public ConnectionFactory { - MockConnectionFactory(EventLoop* eventLoop, bool autoFinishConnect = true) : eventLoop(eventLoop), autoFinishConnect(autoFinishConnect) { - } - - boost::shared_ptr<Connection> createConnection() { - boost::shared_ptr<MockConnection> connection = boost::make_shared<MockConnection>(failingPorts, eventLoop, autoFinishConnect); - connections.push_back(connection); - return connection; - } - - EventLoop* eventLoop; - std::vector< boost::shared_ptr<MockConnection> > connections; - std::vector<HostAddressPort> failingPorts; - bool autoFinishConnect; - }; - - void readResponse(const std::string& response, boost::shared_ptr<MockConnection> connection) { - connection->pending = false; - boost::shared_ptr<SafeByteArray> data1 = boost::make_shared<SafeByteArray>(createSafeByteArray( - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/xml; charset=utf-8\r\n" - "Access-Control-Allow-Origin: *\r\n" - "Access-Control-Allow-Headers: Content-Type\r\n" - "Content-Length: ")); - connection->onDataRead(data1); - boost::shared_ptr<SafeByteArray> data2 = boost::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size()))); - connection->onDataRead(data2); - boost::shared_ptr<SafeByteArray> data3 = boost::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n")); - connection->onDataRead(data3); - boost::shared_ptr<SafeByteArray> data4 = boost::make_shared<SafeByteArray>(createSafeByteArray(response)); - connection->onDataRead(data4); - } - - std::string fullRequestFor(const std::string& data) { - std::string body = data; - std::string result = "POST /" + path + " HTTP/1.1\r\n" - + "Host: " + to + ":" + port + "\r\n" - + "Content-Type: text/xml; charset=utf-8\r\n" - + "Content-Length: " + boost::lexical_cast<std::string>(body.size()) + "\r\n\r\n" - + body; - return result; - } - - private: - URL boshURL; - DummyEventLoop* eventLoop; - MockConnectionFactory* connectionFactory; - std::vector<std::string> xmppDataRead; - std::vector<std::string> boshDataRead; - std::vector<std::string> boshDataWritten; - PlatformXMLParserFactory parserFactory; - StaticDomainNameResolver* resolver; - TimerFactory* timerFactory; - std::string to; - std::string path; - std::string port; - std::string sid; - std::string initial; - unsigned long long initialRID; - int sessionStarted; - int sessionTerminated; + CPPUNIT_TEST_SUITE(BOSHConnectionPoolTest); + CPPUNIT_TEST(testConnectionCount_OneWrite); + CPPUNIT_TEST(testConnectionCount_TwoWrites); + CPPUNIT_TEST(testConnectionCount_ThreeWrites); + CPPUNIT_TEST(testConnectionCount_ThreeWrites_ManualConnect); + CPPUNIT_TEST(testConnectionCount_ThreeWritesTwoReads); + CPPUNIT_TEST(testSession); + CPPUNIT_TEST(testWrite_Empty); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + to = "wonderland.lit"; + path = "/http-bind"; + port = "5280"; + sid = "MyShinySID"; + initial = "<body wait='60' " + "inactivity='30' " + "polling='5' " + "requests='2' " + "hold='1' " + "maxpause='120' " + "sid='" + sid + "' " + "ver='1.6' " + "from='wonderland.lit' " + "xmlns='http://jabber.org/protocol/httpbind'/>"; + eventLoop = new DummyEventLoop(); + connectionFactory = new MockConnectionFactory(eventLoop); + boshURL = URL("http", to, 5280, path); + sessionTerminated = 0; + sessionStarted = 0; + initialRID = 2349876; + xmppDataRead.clear(); + boshDataRead.clear(); + boshDataWritten.clear(); + resolver = new StaticDomainNameResolver(eventLoop); + resolver->addAddress(to, HostAddress("127.0.0.1")); + timerFactory = new DummyTimerFactory(); + } + + void tearDown() { + eventLoop->processEvents(); + delete connectionFactory; + delete resolver; + delete timerFactory; + delete eventLoop; + } + + void testConnectionCount_OneWrite() { + PoolRef testling = createTestling(); + CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(0, sessionStarted); + readResponse(initial, connectionFactory->connections[0]); + CPPUNIT_ASSERT_EQUAL(1, sessionStarted); + CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); + testling->write(createSafeByteArray("<blah/>")); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); + CPPUNIT_ASSERT_EQUAL(1, sessionStarted); + } + + void testConnectionCount_TwoWrites() { + PoolRef testling = createTestling(); + CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); + eventLoop->processEvents(); + readResponse(initial, connectionFactory->connections[0]); + eventLoop->processEvents(); + testling->write(createSafeByteArray("<blah/>")); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); + testling->write(createSafeByteArray("<bleh/>")); + eventLoop->processEvents(); + eventLoop->processEvents(); + CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); + } + + void testConnectionCount_ThreeWrites() { + PoolRef testling = createTestling(); |