diff options
Diffstat (limited to 'Swiften')
126 files changed, 1186 insertions, 415 deletions
diff --git a/Swiften/Base/BoostRandomGenerator.h b/Swiften/Base/BoostRandomGenerator.h index b5a6cac..6065ff3 100644 --- a/Swiften/Base/BoostRandomGenerator.h +++ b/Swiften/Base/BoostRandomGenerator.h @@ -7,6 +7,7 @@ #pragma once #include <Swiften/Base/RandomGenerator.h> +#include <Swiften/Base/Override.h> #include <boost/random/mersenne_twister.hpp> @@ -15,7 +16,7 @@ namespace Swift { public: BoostRandomGenerator(); - int generateRandomInteger(int max); + int generateRandomInteger(int max) SWIFTEN_OVERRIDE; private: boost::mt19937 generator; diff --git a/Swiften/Base/ByteArray.cpp b/Swiften/Base/ByteArray.cpp index 6be96aa..d6b5c97 100644 --- a/Swiften/Base/ByteArray.cpp +++ b/Swiften/Base/ByteArray.cpp @@ -1,11 +1,12 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <Swiften/Base/ByteArray.h> +#include <boost/numeric/conversion/cast.hpp> #include <fstream> namespace Swift { @@ -18,7 +19,7 @@ void readByteArrayFromFile(ByteArray& data, const std::string& file) { size_t oldSize = data.size(); data.resize(oldSize + BUFFER_SIZE); input.read(reinterpret_cast<char*>(&data[oldSize]), BUFFER_SIZE); - data.resize(oldSize + input.gcount()); + data.resize(oldSize + boost::numeric_cast<size_t>(input.gcount())); } input.close(); } diff --git a/Swiften/Base/ByteArray.h b/Swiften/Base/ByteArray.h index 34b89d3..8688aab 100644 --- a/Swiften/Base/ByteArray.h +++ b/Swiften/Base/ByteArray.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -26,7 +26,7 @@ namespace Swift { } inline ByteArray createByteArray(char c) { - return std::vector<unsigned char>(1, c); + return std::vector<unsigned char>(1, static_cast<unsigned char>(c)); } template<typename T, typename A> diff --git a/Swiften/Base/Override.h b/Swiften/Base/Override.h new file mode 100644 index 0000000..7f410cf --- /dev/null +++ b/Swiften/Base/Override.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2012 Remko Tronçon + * Licensed under the GNU General Public License v3. + * See Documentation/Licenses/GPLv3.txt for more information. + */ + +#pragma once + +#if defined(__clang__) +# if __has_feature(cxx_override_control) || __has_extension(cxx_override_control) +# define SWIFTEN_OVERRIDE override +# else +# define SWIFTEN_OVERRIDE +# endif + +#elif defined(__GNUC__) +# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) +# define SWIFTEN_OVERRIDE override +# else +# define SWIFTEN_OVERRIDE +# endif + +#elif defined(_MSC_VER) +// Actually, 1700 is the first version that supports the C++11 override, but +// older versions apparently support a similar keyword. +# if _MSC_VER >= 1400 +# define SWIFTEN_OVERRIDE override +# else +# define SWIFTEN_OVERRIDE +# endif + +#else +# define SWIFTEN_OVERRIDE +#endif diff --git a/Swiften/Base/SafeByteArray.h b/Swiften/Base/SafeByteArray.h index dda51fe..b85373c 100644 --- a/Swiften/Base/SafeByteArray.h +++ b/Swiften/Base/SafeByteArray.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011 Remko Tronçon + * Copyright (c) 2011-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -31,7 +31,7 @@ namespace Swift { } inline SafeByteArray createSafeByteArray(char c) { - return SafeByteArray(1, c); + return SafeByteArray(1, static_cast<unsigned char>(c)); } inline SafeByteArray createSafeByteArray(const char* c, size_t n) { diff --git a/Swiften/Client/ClientXMLTracer.cpp b/Swiften/Client/ClientXMLTracer.cpp index 405e3d1..d2b5446 100644 --- a/Swiften/Client/ClientXMLTracer.cpp +++ b/Swiften/Client/ClientXMLTracer.cpp @@ -25,14 +25,14 @@ void ClientXMLTracer::printData(char direction, const SafeByteArray& data) { printLine(direction); if (bosh) { std::string line = byteArrayToString(ByteArray(data.begin(), data.end())); - size_t endOfHTTP = line.find("\r\n\r\n"); - if (false && endOfHTTP != std::string::npos) { - /* Disabled because it swallows bits of XML (namespaces, if I recall) */ - std::cerr << line.substr(0, endOfHTTP) << std::endl << beautifier->beautify(line.substr(endOfHTTP)) << std::endl; - } - else { +// 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; diff --git a/Swiften/Client/CoreClient.h b/Swiften/Client/CoreClient.h index c9da0eb..16f7cb1 100644 --- a/Swiften/Client/CoreClient.h +++ b/Swiften/Client/CoreClient.h @@ -204,7 +204,7 @@ namespace Swift { /** * Called before onConnected signal is emmitted. */ - virtual void handleConnected() {}; + virtual void handleConnected() {} private: void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error> error); diff --git a/Swiften/Compress/ZLibCodecompressor.cpp b/Swiften/Compress/ZLibCodecompressor.cpp index 125492a..85d0174 100644 --- a/Swiften/Compress/ZLibCodecompressor.cpp +++ b/Swiften/Compress/ZLibCodecompressor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -9,13 +9,14 @@ #include <cassert> #include <string.h> #include <zlib.h> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Compress/ZLibException.h> #include <Swiften/Compress/ZLibCodecompressor_Private.h> namespace Swift { -static const int CHUNK_SIZE = 1024; // If you change this, also change the unittest +static const size_t CHUNK_SIZE = 1024; // If you change this, also change the unittest ZLibCodecompressor::ZLibCodecompressor() : p(boost::make_shared<Private>()) { @@ -30,9 +31,9 @@ ZLibCodecompressor::~ZLibCodecompressor() { SafeByteArray ZLibCodecompressor::process(const SafeByteArray& input) { SafeByteArray output; - p->stream.avail_in = input.size(); + p->stream.avail_in = static_cast<unsigned int>(input.size()); p->stream.next_in = reinterpret_cast<Bytef*>(const_cast<unsigned char*>(vecptr(input))); - int outputPosition = 0; + size_t outputPosition = 0; do { output.resize(outputPosition + CHUNK_SIZE); p->stream.avail_out = CHUNK_SIZE; diff --git a/Swiften/Config/SConscript b/Swiften/Config/SConscript index 357a5e6..c7ec32e 100644 --- a/Swiften/Config/SConscript +++ b/Swiften/Config/SConscript @@ -6,7 +6,7 @@ def replaceSwiftenPath(input) : return input.replace(env.Dir("#").abspath, "#") def cStringVariable(env, cVar, sconsVar) : - result = "const char* " + cVar + "[] = {\n" + result = "static const char* " + cVar + "[] = {\n" # FIXME: Probably not very robust for var in sconsVar.split(" ") : result += "\t\"" + env.subst(var).replace("\\", "\\\\") + "\",\n" @@ -17,8 +17,8 @@ def cStringVariable(env, cVar, sconsVar) : config_flags = "" swiften_env = env.Clone() -swiften_env.MergeFlags(swiften_env["SWIFTEN_FLAGS"]) -swiften_env.MergeFlags(swiften_env["SWIFTEN_DEP_FLAGS"]) +swiften_env.UseFlags(swiften_env["SWIFTEN_FLAGS"]) +swiften_env.UseFlags(swiften_env["SWIFTEN_DEP_FLAGS"]) cppflags = replaceSwiftenPath(" ".join([swiften_env.subst("$_CPPDEFFLAGS"), swiften_env.subst("$_CPPINCFLAGS")])) config_flags += cStringVariable(swiften_env, "CPPFLAGS", cppflags) @@ -29,8 +29,8 @@ config_flags += cStringVariable(swiften_env, "LIBFLAGS", libflags) config_env = env.Clone() # Create a local copy of Paths.cpp to avoid a Swiften dependency config_env.Install(".", "#/Swiften/Base/Paths.cpp") -config_env.MergeFlags(config_env["BOOST_FLAGS"]) -config_env.MergeFlags(config_env["PLATFORM_FLAGS"]) +config_env.UseFlags(config_env["BOOST_FLAGS"]) +config_env.UseFlags(config_env["PLATFORM_FLAGS"]) config_env.WriteVal("swiften-config.h", config_env.Value(config_flags)) swiften_config = config_env.Program("swiften-config", [ "Paths.cpp", diff --git a/Swiften/Config/swiften-config.cpp b/Swiften/Config/swiften-config.cpp index 81a8357..de07d74 100644 --- a/Swiften/Config/swiften-config.cpp +++ b/Swiften/Config/swiften-config.cpp @@ -22,7 +22,7 @@ using namespace Swift; -void printFlags(const std::vector<std::string>& flags) { +static void printFlags(const std::vector<std::string>& flags) { for (size_t i = 0; i < flags.size(); ++i) { if (i > 0) { std::cout << " "; diff --git a/Swiften/Elements/Command.h b/Swiften/Elements/Command.h index 91ae5a3..5454d8d 100644 --- a/Swiften/Elements/Command.h +++ b/Swiften/Elements/Command.h @@ -26,7 +26,7 @@ namespace Swift { struct Note { enum Type {Info, Warn, Error}; - Note(std::string note, Type type) : note(note), type(type) {}; + Note(std::string note, Type type) : note(note), type(type) {} std::string note; Type type; diff --git a/Swiften/Elements/Delay.h b/Swiften/Elements/Delay.h index f7c4570..f4376dc 100644 --- a/Swiften/Elements/Delay.h +++ b/Swiften/Elements/Delay.h @@ -15,14 +15,14 @@ namespace Swift { class Delay : public Payload { public: - Delay() {}; - Delay(const boost::posix_time::ptime& time, const JID& from = JID()) : time_(time), from_(from) {}; + 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_; diff --git a/Swiften/Elements/JingleIBBTransportPayload.h b/Swiften/Elements/JingleIBBTransportPayload.h index 8c174f0..7633f6b 100644 --- a/Swiften/Elements/JingleIBBTransportPayload.h +++ b/Swiften/Elements/JingleIBBTransportPayload.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011 Remko Tronçon + * Copyright (c) 2011-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -29,16 +29,16 @@ namespace Swift { return stanzaType; } - int getBlockSize() const { + unsigned int getBlockSize() const { return blockSize; } - void setBlockSize(int blockSize) { + void setBlockSize(unsigned int blockSize) { this->blockSize = blockSize; } private: - int blockSize; + unsigned int blockSize; StanzaType stanzaType; }; } diff --git a/Swiften/Elements/JinglePayload.h b/Swiften/Elements/JinglePayload.h index 31d4448..5f12e90 100644 --- a/Swiften/Elements/JinglePayload.h +++ b/Swiften/Elements/JinglePayload.h @@ -15,8 +15,6 @@ #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/JingleContentPayload.h> -#include <Swiften/Base/Log.h> - namespace Swift { class JinglePayload : public Payload { public: diff --git a/Swiften/Elements/Last.h b/Swiften/Elements/Last.h index fe0323a..cb7e0c6 100644 --- a/Swiften/Elements/Last.h +++ b/Swiften/Elements/Last.h @@ -11,7 +11,7 @@ namespace Swift { class Last : public Payload { public: - Last(int seconds = 0) : seconds_(seconds) {}; + Last(int seconds = 0) : seconds_(seconds) {} int getSeconds() const {return seconds_;} void setSeconds(int seconds) {seconds_ = seconds;} diff --git a/Swiften/Elements/Replace.h b/Swiften/Elements/Replace.h index 230bce7..96935f5 100644 --- a/Swiften/Elements/Replace.h +++ b/Swiften/Elements/Replace.h @@ -15,7 +15,7 @@ namespace Swift { class Replace : public Payload { public: typedef boost::shared_ptr<Replace> ref; - Replace(const std::string& id = std::string()) : replaceID_(id) {}; + Replace(const std::string& id = std::string()) : replaceID_(id) {} const std::string& getID() const { return replaceID_; } diff --git a/Swiften/Elements/StanzaAck.cpp b/Swiften/Elements/StanzaAck.cpp new file mode 100644 index 0000000..5bcab73 --- /dev/null +++ b/Swiften/Elements/StanzaAck.cpp @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2013 Remko Tronçon + * Licensed under the GNU General Public License v3. + * See Documentation/Licenses/GPLv3.txt for more information. + */ + +#include <Swiften/Elements/StanzaAck.h> + +#include <boost/numeric/conversion/cast.hpp> + +using namespace Swift; + +StanzaAck::~StanzaAck() { +} + +void StanzaAck::setHandledStanzasCount(int i) { + handledStanzasCount = boost::numeric_cast<unsigned int>(i); + valid = true; +} diff --git a/Swiften/Elements/StanzaAck.h b/Swiften/Elements/StanzaAck.h index 3aa2dfd..8fe64e0 100644 --- a/Swiften/Elements/StanzaAck.h +++ b/Swiften/Elements/StanzaAck.h @@ -1,13 +1,14 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #pragma once -#include <Swiften/Elements/Element.h> +#include <boost/shared_ptr.hpp> +#include <Swiften/Elements/Element.h> namespace Swift { class StanzaAck : public Element { @@ -16,15 +17,13 @@ namespace Swift { StanzaAck() : valid(false), handledStanzasCount(0) {} StanzaAck(unsigned int handledStanzasCount) : valid(true), handledStanzasCount(handledStanzasCount) {} + virtual ~StanzaAck(); unsigned int getHandledStanzasCount() const { return handledStanzasCount; } - void setHandledStanzasCount(int i) { - handledStanzasCount = i; - valid = true; - } + void setHandledStanzasCount(int i); bool isValid() const { return valid; diff --git a/Swiften/Elements/StatusShow.h b/Swiften/Elements/StatusShow.h index 3eeb44e..afa30de 100644 --- a/Swiften/Elements/StatusShow.h +++ b/Swiften/Elements/StatusShow.h @@ -8,6 +8,7 @@ #include <Swiften/Base/API.h> #include <Swiften/Elements/Payload.h> +#include <cassert> namespace Swift { class SWIFTEN_API StatusShow : public Payload { @@ -37,6 +38,7 @@ namespace Swift { case DND: return 3; case None: return 0; } + assert(false); return 0; } diff --git a/Swiften/Elements/StreamInitiationFileInfo.h b/Swiften/Elements/StreamInitiationFileInfo.h index 6569c3d..d7907b9 100644 --- a/Swiften/Elements/StreamInitiationFileInfo.h +++ b/Swiften/Elements/StreamInitiationFileInfo.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011 Remko Tronçon + * Copyright (c) 2011-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -19,7 +19,7 @@ public: typedef boost::shared_ptr<StreamInitiationFileInfo> ref; public: - StreamInitiationFileInfo(const std::string& name = "", const std::string& description = "", int size = 0, + 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) {} @@ -39,11 +39,11 @@ public: return this->description; } - void setSize(const boost::uintmax_t size) { + void setSize(const unsigned long long size) { this->size = size; } - boost::uintmax_t getSize() const { + unsigned long long getSize() const { return this->size; } @@ -79,24 +79,24 @@ public: return supportsRangeRequests; } - void setRangeOffset(const int offset) { - supportsRangeRequests = offset >= 0 ? true : false; + void setRangeOffset(unsigned long long offset) { + supportsRangeRequests = true; rangeOffset = offset; } - boost::uintmax_t getRangeOffset() const { + unsigned long long getRangeOffset() const { return rangeOffset; } private: std::string name; std::string description; - boost::uintmax_t size; + unsigned long long size; std::string hash; boost::posix_time::ptime date; std::string algo; bool supportsRangeRequests; - boost::uintmax_t rangeOffset; + unsigned long long rangeOffset; }; } diff --git a/Swiften/Elements/VCard.h b/Swiften/Elements/VCard.h index f9822c9..84b6cfe 100644 --- a/Swiften/Elements/VCard.h +++ b/Swiften/Elements/VCard.h @@ -7,8 +7,10 @@ #pragma once #include <boost/shared_ptr.hpp> +#include <boost/date_time/posix_time/ptime.hpp> #include <string> +#include <Swiften/JID/JID.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/Elements/Payload.h> @@ -29,6 +31,71 @@ namespace Swift { 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; } @@ -78,8 +145,124 @@ namespace Swift { emailAddresses_.push_back(email); } + void clearEMailAddresses() { + emailAddresses_.clear(); + } + EMailAddress getPreferredEMailAddress() const; + void setBirthday(const boost::posix_time::ptime& birthday) { + birthday_ = birthday; + } + + const boost::posix_time::ptime& getBirthday() const { + return birthday_; + } + + const std::vector<Telephone>& getTelephones() const { + return telephones_; + } + + void addTelephone(const Telephone& phone) { + telephones_.push_back(phone); + } + + void clearTelephones() { + telephones_.clear(); + } + + const std::vector<Address>& getAddresses() const { + return addresses_; + } + + 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(); + } + private: std::string version_; std::string fullName_; @@ -92,7 +275,17 @@ namespace Swift { 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/Whiteboard/WhiteboardOperation.h b/Swiften/Elements/Whiteboard/WhiteboardOperation.h index 02c6438..75f6e6a 100644 --- a/Swiften/Elements/Whiteboard/WhiteboardOperation.h +++ b/Swiften/Elements/Whiteboard/WhiteboardOperation.h @@ -14,7 +14,7 @@ namespace Swift { public: typedef boost::shared_ptr<WhiteboardOperation> ref; public: - virtual ~WhiteboardOperation(){}; + virtual ~WhiteboardOperation(){} std::string getID() const { return id_; diff --git a/Swiften/EventLoop/EventLoop.cpp b/Swiften/EventLoop/EventLoop.cpp index afb6858..0f78d96 100644 --- a/Swiften/EventLoop/EventLoop.cpp +++ b/Swiften/EventLoop/EventLoop.cpp @@ -12,7 +12,10 @@ #include <cassert> #include <Swiften/Base/Log.h> +#include <boost/lambda/lambda.hpp> +#include <boost/lambda/bind.hpp> +namespace lambda = boost::lambda; namespace Swift { @@ -83,7 +86,7 @@ void EventLoop::postEvent(boost::function<void ()> callback, boost::shared_ptr<E void EventLoop::removeEventsFromOwner(boost::shared_ptr<EventOwner> owner) { boost::lock_guard<boost::mutex> lock(eventsMutex_); - events_.remove_if(HasOwner(owner)); + events_.remove_if(lambda::bind(&Event::owner, lambda::_1) == owner); } } diff --git a/Swiften/EventLoop/EventLoop.h b/Swiften/EventLoop/EventLoop.h index 4a602ae..587ba22 100644 --- a/Swiften/EventLoop/EventLoop.h +++ b/Swiften/EventLoop/EventLoop.h @@ -35,11 +35,6 @@ namespace Swift { void handleEvent(const Event& event); private: - struct HasOwner { - HasOwner(boost::shared_ptr<EventOwner> owner) : owner(owner) {} - bool operator()(const Event& event) const { return event.owner == owner; } - boost::shared_ptr<EventOwner> owner; - }; boost::mutex eventsMutex_; unsigned int nextEventID_; std::list<Event> events_; diff --git a/Swiften/EventLoop/SimpleEventLoop.cpp b/Swiften/EventLoop/SimpleEventLoop.cpp index 63b8ba5..42a5481 100644 --- a/Swiften/EventLoop/SimpleEventLoop.cpp +++ b/Swiften/EventLoop/SimpleEventLoop.cpp @@ -14,8 +14,6 @@ namespace Swift { -void nop() {} - SimpleEventLoop::SimpleEventLoop() : isRunning_(true) { } diff --git a/Swiften/Examples/BenchTool/BenchTool.cpp b/Swiften/Examples/BenchTool/BenchTool.cpp index ba6cf84..9725b7e 100644 --- a/Swiften/Examples/BenchTool/BenchTool.cpp +++ b/Swiften/Examples/BenchTool/BenchTool.cpp @@ -20,13 +20,13 @@ using namespace Swift; -SimpleEventLoop eventLoop; -BoostNetworkFactories networkFactories(&eventLoop); -int numberOfConnectedClients = 0; -int numberOfInstances = 100; +static SimpleEventLoop eventLoop; +static BoostNetworkFactories networkFactories(&eventLoop); +static int numberOfConnectedClients = 0; +static int numberOfInstances = 100; -void handleConnected() { +static void handleConnected() { numberOfConnectedClients++; std::cout << "Connected " << numberOfConnectedClients << std::endl; } diff --git a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp index 636a52a..df2a23d 100644 --- a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp +++ b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp @@ -21,15 +21,15 @@ using namespace Swift; enum ExitCodes {OK = 0, CANNOT_CONNECT, CANNOT_AUTH, NO_RESPONSE, DISCO_ERROR}; -SimpleEventLoop eventLoop; -BoostNetworkFactories networkFactories(&eventLoop); +static SimpleEventLoop eventLoop; +static BoostNetworkFactories networkFactories(&eventLoop); -Client* client = 0; -JID recipient; -int exitCode = CANNOT_CONNECT; -boost::bsignals::connection errorConnection; +static Client* client = 0; +static JID recipient; +static int exitCode = CANNOT_CONNECT; +static boost::bsignals::connection errorConnection; -void handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> /*info*/, ErrorPayload::ref error) { +static void handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> /*info*/, ErrorPayload::ref error) { if (!error) { errorConnection.disconnect(); client->disconnect(); @@ -41,14 +41,14 @@ void handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> /*info*/, ErrorP } } -void handleConnected() { +static void handleConnected() { exitCode = NO_RESPONSE; GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(), client->getIQRouter()); discoInfoRequest->onResponse.connect(&handleServerDiscoInfoResponse); discoInfoRequest->send(); } -void handleDisconnected(const boost::optional<ClientError>&) { +static void handleDisconnected(const boost::optional<ClientError>&) { exitCode = CANNOT_AUTH; eventLoop.stop(); } diff --git a/Swiften/Examples/ConnectivityTest/SConscript b/Swiften/Examples/ConnectivityTest/SConscript index 7bc3892..55a0821 100644 --- a/Swiften/Examples/ConnectivityTest/SConscript +++ b/Swiften/Examples/ConnectivityTest/SConscript @@ -1,7 +1,7 @@ Import("env") myenv = env.Clone() -myenv.MergeFlags(myenv["SWIFTEN_FLAGS"]) -myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"]) tester = myenv.Program("ConnectivityTest", ["ConnectivityTest.cpp"]) diff --git a/Swiften/Examples/LinkLocalTool/SConscript b/Swiften/Examples/LinkLocalTool/SConscript index 788f5c1..18eb91f 100644 --- a/Swiften/Examples/LinkLocalTool/SConscript +++ b/Swiften/Examples/LinkLocalTool/SConscript @@ -1,8 +1,8 @@ Import("env") myenv = env.Clone() -myenv.MergeFlags(myenv["SWIFTEN_FLAGS"]) -myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"]) linkLocalTool = myenv.Program("LinkLocalTool", [ "main.cpp" diff --git a/Swiften/Examples/NetworkTool/main.cpp b/Swiften/Examples/NetworkTool/main.cpp index 00c12d2..4ac7e6a 100644 --- a/Swiften/Examples/NetworkTool/main.cpp +++ b/Swiften/Examples/NetworkTool/main.cpp @@ -16,9 +16,9 @@ using namespace Swift; -SimpleEventLoop eventLoop; +static SimpleEventLoop eventLoop; -void handleGetPublicIPRequestResponse(const boost::optional<HostAddress>& result) { +static void handleGetPublicIPRequestResponse(const boost::optional<HostAddress>& result) { if (result) { std::cerr << "Result: " << result->toString() << std::endl;; } @@ -28,7 +28,7 @@ void handleGetPublicIPRequestResponse(const boost::optional<HostAddress>& result eventLoop.stop(); } -void handleGetForwardPortRequestResponse(const boost::optional<NATPortMapping>& result) { +static void handleGetForwardPortRequestResponse(const boost::optional<NATPortMapping>& result) { if (result) { std::cerr << "Result: " << result->getPublicPort() << " -> " << result->getLocalPort() << std::endl;; } @@ -38,7 +38,7 @@ void handleGetForwardPortRequestResponse(const boost::optional<NATPortMapping>& eventLoop.stop(); } -void handleRemovePortForwardingRequestResponse(bool result) { +static void handleRemovePortForwardingRequestResponse(bool result) { if (result) { std::cerr << "Result: OK" << std::endl; } diff --git a/Swiften/Examples/ParserTester/SConscript b/Swiften/Examples/ParserTester/SConscript index 09cffc9..5c93552 100644 --- a/Swiften/Examples/ParserTester/SConscript +++ b/Swiften/Examples/ParserTester/SConscript @@ -1,7 +1,7 @@ Import("env") myenv = env.Clone() -myenv.MergeFlags(myenv["SWIFTEN_FLAGS"]) -myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"]) myenv.Program("ParserTester", ["ParserTester.cpp"]) diff --git a/Swiften/Examples/SendFile/ReceiveFile.cpp b/Swiften/Examples/SendFile/ReceiveFile.cpp index 39b3cc3..8b0af37 100644 --- a/Swiften/Examples/SendFile/ReceiveFile.cpp +++ b/Swiften/Examples/SendFile/ReceiveFile.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -10,6 +10,7 @@ #include <iostream> #include <Swiften/Elements/Presence.h> +#include <Swiften/Base/Log.h> #include <Swiften/Base/foreach.h> #include <Swiften/Client/Client.h> #include <Swiften/Elements/DiscoInfo.h> @@ -27,10 +28,10 @@ using namespace Swift; -SimpleEventLoop eventLoop; -BoostNetworkFactories networkFactories(&eventLoop); +static SimpleEventLoop eventLoop; +static BoostNetworkFactories networkFactories(&eventLoop); -int exitCode = 2; +static int exitCode = 2; static const std::string CLIENT_NAME = "Swiften FT Test"; static const std::string CLIENT_NODE = "http://swift.im"; diff --git a/Swiften/Examples/SendFile/SConscript b/Swiften/Examples/SendFile/SConscript index d335513..e0f1256 100644 --- a/Swiften/Examples/SendFile/SConscript +++ b/Swiften/Examples/SendFile/SConscript @@ -1,8 +1,8 @@ Import("env") myenv = env.Clone() -myenv.MergeFlags(myenv["SWIFTEN_FLAGS"]) -myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"]) myenv.Program("SendFile", ["SendFile.cpp"]) myenv.Program("ReceiveFile", ["ReceiveFile.cpp"]) diff --git a/Swiften/Examples/SendFile/SendFile.cpp b/Swiften/Examples/SendFile/SendFile.cpp index a926170..657949b 100644 --- a/Swiften/Examples/SendFile/SendFile.cpp +++ b/Swiften/Examples/SendFile/SendFile.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -11,6 +11,7 @@ #include <Swiften/Client/Client.h> #include <Swiften/Elements/Presence.h> +#include <Swiften/Base/Log.h> #include <Swiften/Network/BoostTimer.h> #include <Swiften/Network/TimerFactory.h> #include <Swiften/Network/BoostNetworkFactories.h> @@ -35,10 +36,10 @@ using namespace Swift; -SimpleEventLoop eventLoop; -BoostNetworkFactories networkFactories(&eventLoop); +static SimpleEventLoop eventLoop; +static BoostNetworkFactories networkFactories(&eventLoop); -int exitCode = 2; +static int exitCode = 2; class FileSender { public: diff --git a/Swiften/Examples/SendMessage/SConscript b/Swiften/Examples/SendMessage/SConscript index 8907d25..0466187 100644 --- a/Swiften/Examples/SendMessage/SConscript +++ b/Swiften/Examples/SendMessage/SConscript @@ -1,7 +1,7 @@ Import("env") myenv = env.Clone() -myenv.MergeFlags(myenv["SWIFTEN_FLAGS"]) -myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_FLAGS"]) +myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"]) tester = myenv.Program("SendMessage", ["SendMessage.cpp"]) diff --git a/Swiften/Examples/SendMessage/SendMessage.cpp b/Swiften/Examples/SendMessage/SendMessage.cpp index 07e289e..2a3170f 100644 --- a/Swiften/Examples/SendMessage/SendMessage.cpp +++ b/Swiften/Examples/SendMessage/SendMessage.cpp @@ -18,17 +18,17 @@ using namespace Swift; -SimpleEventLoop eventLoop; -BoostNetworkFactories networkFactories(&eventLoop); +static SimpleEventLoop eventLoop; +static BoostNetworkFactories networkFactories(&eventLoop); -Client* client = 0; -JID recipient; -std::string messageBody; -int exitCode = 2; -boost::bsignals::connection errorConnection; +static Client* client = 0; +static JID recipient; +static std::string messageBody; +static int exitCode = 2; +static boost::bsignals::connection errorConnection; -void handleConnected() { +static void handleConnected() { boost::shared_ptr<Message> message(new Message()); message->setBody(messageBody); message->setTo(recipient); @@ -39,7 +39,7 @@ void handleConnected() { eventLoop.stop(); } -void handleDisconnected(const boost::optional<ClientError>&) { +static void handleDisconnected(const boost::optional<ClientError>&) { std::cerr << "Error!" << std::endl; exitCode = 1; eventLoop.stop(); diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp new file mode 100644 index 0000000..4ba791f --- /dev/null +++ b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2010-2013 Remko Tronçon + * Licensed under the GNU General Public License v3. + * See Documentation/Licenses/GPLv3.txt for more information. + */ + +#include <Swiften/FileTransfer/ByteArrayReadBytestream.h> + +#include <boost/smart_ptr/make_shared.hpp> +#include <boost/numeric/conversion/cast.hpp> + +#include <Swiften/Base/Algorithm.h> + +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)); + + onRead(*result); + position += readSize; + return result; +} + +void ByteArrayReadBytestream::addData(const std::vector<unsigned char>& moreData) { + append(data, moreData); + onDataAvailable(); +} diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.h b/Swiften/FileTransfer/ByteArrayReadBytestream.h index 9311099..664698a 100644 --- a/Swiften/FileTransfer/ByteArrayReadBytestream.h +++ b/Swiften/FileTransfer/ByteArrayReadBytestream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,9 +7,7 @@ #pragma once #include <vector> -#include <boost/smart_ptr/make_shared.hpp> -#include <Swiften/Base/Algorithm.h> #include <Swiften/FileTransfer/ReadBytestream.h> #include <Swiften/Base/ByteArray.h> @@ -19,17 +17,7 @@ namespace Swift { ByteArrayReadBytestream(const std::vector<unsigned char>& data) : data(data), position(0), dataComplete(true) { } - virtual boost::shared_ptr<ByteArray> 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() + position, data.begin() + position + readSize); - - onRead(*result); - position += readSize; - return result; - } + virtual boost::shared_ptr<ByteArray> read(size_t size); virtual bool isFinished() const { return position >= data.size() && dataComplete; @@ -39,10 +27,7 @@ namespace Swift { dataComplete = b; } - void addData(const std::vector<unsigned char>& moreData) { - append(data, moreData); - onDataAvailable(); - } + void addData(const std::vector<unsigned char>& moreData); private: std::vector<unsigned char> data; diff --git a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp index 32b4df8..4a6b61f 100644 --- a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp +++ b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp @@ -4,7 +4,7 @@ * See Documentation/Licenses/BSD-simplified.txt for more information. */ -#include "DefaultRemoteJingleTransportCandidateSelector.h" +#include <Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h> #include <boost/smart_ptr/make_shared.hpp> #include <boost/bind.hpp> @@ -97,7 +97,7 @@ void DefaultRemoteJingleTransportCandidateSelector::setMinimumPriority(int prior SWIFT_LOG(debug) << "priority: " << priority << std::endl; } -void DefaultRemoteJingleTransportCandidateSelector::setRequesterTargtet(const JID& requester, const JID& target) { +void DefaultRemoteJingleTransportCandidateSelector::setRequesterTarget(const JID& requester, const JID& target) { this->requester = requester; this->target = target; } diff --git a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h index 255acd9..073c51f 100644 --- a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h +++ b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h @@ -11,6 +11,7 @@ #include <boost/shared_ptr.hpp> +#include <Swiften/Base/Override.h> #include <Swiften/JID/JID.h> #include <Swiften/Network/Connection.h> #include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h> @@ -28,15 +29,15 @@ public: DefaultRemoteJingleTransportCandidateSelector(ConnectionFactory*, TimerFactory*); virtual ~DefaultRemoteJingleTransportCandidateSelector(); - virtual void addRemoteTransportCandidates(JingleTransportPayload::ref); - virtual void selectCandidate(); - virtual void setMinimumPriority(int); - void setRequesterTargtet(const JID& requester, const JID& target); - virtual SOCKS5BytestreamClientSession::ref getS5BSession(); + virtual void addRemoteTransportCandidates(JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual void selectCandidate() SWIFTEN_OVERRIDE; + virtual void setMinimumPriority(int) SWIFTEN_OVERRIDE; + virtual void setRequesterTarget(const JID& requester, const JID& target) SWIFTEN_OVERRIDE; + virtual SOCKS5BytestreamClientSession::ref getS5BSession() SWIFTEN_OVERRIDE; - virtual bool isActualCandidate(JingleTransportPayload::ref); - virtual int getPriority(JingleTransportPayload::ref); - virtual JingleTransport::ref selectTransport(JingleTransportPayload::ref); + virtual bool isActualCandidate(JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual int getPriority(JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual JingleTransport::ref selectTransport(JingleTransportPayload::ref) SWIFTEN_OVERRIDE; private: void tryNextCandidate(bool error); diff --git a/Swiften/FileTransfer/FileReadBytestream.cpp b/Swiften/FileTransfer/FileReadBytestream.cpp index a8946a0..4257f8b 100644 --- a/Swiften/FileTransfer/FileReadBytestream.cpp +++ b/Swiften/FileTransfer/FileReadBytestream.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,6 +7,7 @@ #include <boost/filesystem/fstream.hpp> #include <cassert> #include <boost/smart_ptr/make_shared.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/FileTransfer/FileReadBytestream.h> #include <Swiften/Base/ByteArray.h> @@ -30,8 +31,8 @@ boost::shared_ptr<ByteArray> FileReadBytestream::read(size_t size) { boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>(); result->resize(size); assert(stream->good()); - stream->read(reinterpret_cast<char*>(vecptr(*result)), size); - result->resize(stream->gcount()); + 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; } diff --git a/Swiften/FileTransfer/FileTransfer.h b/Swiften/FileTransfer/FileTransfer.h index 336c51c..01c9449 100644 --- a/Swiften/FileTransfer/FileTransfer.h +++ b/Swiften/FileTransfer/FileTransfer.h @@ -48,7 +48,7 @@ public: virtual void cancel() = 0; public: - boost::signal<void (int /* proccessedBytes */)> onProcessedBytes; + boost::signal<void (size_t /* proccessedBytes */)> onProcessedBytes; boost::signal<void (State)> onStateChange; boost::signal<void (boost::optional<FileTransferError>)> onFinished; diff --git a/Swiften/FileTransfer/FileTransferManager.h b/Swiften/FileTransfer/FileTransferManager.h index 30d9faf..68f3d0d 100644 --- a/Swiften/FileTransfer/FileTransferManager.h +++ b/Swiften/FileTransfer/FileTransferManager.h @@ -7,7 +7,7 @@ #pragma once #include <string> -#include <boost/filesystem.hpp> +#include <boost/filesystem/path.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <Swiften/Base/API.h> diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.cpp b/Swiften/FileTransfer/FileTransferManagerImpl.cpp index 84b2061..d5d4aaf 100644 --- a/Swiften/FileTransfer/FileTransferManagerImpl.cpp +++ b/Swiften/FileTransfer/FileTransferManagerImpl.cpp @@ -7,9 +7,11 @@ #include <Swiften/FileTransfer/FileTransferManagerImpl.h> #include <boost/bind.hpp> +#include <boost/filesystem.hpp> #include <boost/cstdint.hpp> #include <Swiften/Base/foreach.h> +#include <Swiften/Base/Log.h> #include "Swiften/Disco/EntityCapsProvider.h" #include <Swiften/JID/JID.h> #include <Swiften/Elements/StreamInitiationFileInfo.h> diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.h b/Swiften/FileTransfer/FileTransferManagerImpl.h index ecc692d..0bbbf31 100644 --- a/Swiften/FileTransfer/FileTransferManagerImpl.h +++ b/Swiften/FileTransfer/FileTransferManagerImpl.h @@ -9,7 +9,7 @@ #include <vector> #include <string> -#include <boost/filesystem.hpp> +#include <boost/filesystem/path.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/optional.hpp> diff --git a/Swiften/FileTransfer/FileWriteBytestream.cpp b/Swiften/FileTransfer/FileWriteBytestream.cpp index 6a22c6a..5725e18 100644 --- a/Swiften/FileTransfer/FileWriteBytestream.cpp +++ b/Swiften/FileTransfer/FileWriteBytestream.cpp @@ -1,11 +1,12 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <boost/filesystem/fstream.hpp> #include <cassert> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/FileTransfer/FileWriteBytestream.h> @@ -26,7 +27,7 @@ void FileWriteBytestream::write(const std::vector<unsigned char>& data) { stream = new boost::filesystem::ofstream(file, std::ios_base::out|std::ios_base::binary); } assert(stream->good()); - stream->write(reinterpret_cast<const char*>(&data[0]), data.size()); + stream->write(reinterpret_cast<const char*>(&data[0]), boost::numeric_cast<std::streamsize>(data.size())); onWrite(data); } diff --git a/Swiften/FileTransfer/IBBSendSession.cpp b/Swiften/FileTransfer/IBBSendSession.cpp index c24cc0a..4d7477f 100644 --- a/Swiften/FileTransfer/IBBSendSession.cpp +++ b/Swiften/FileTransfer/IBBSendSession.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,6 +7,7 @@ #include <Swiften/FileTransfer/IBBSendSession.h> #include <boost/bind.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/ByteArray.h> #include <Swiften/Queries/IQRouter.h> @@ -24,7 +25,7 @@ IBBSendSession::~IBBSendSession() { } void IBBSendSession::start() { - IBBRequest::ref request = IBBRequest::create(from, to, IBB::createIBBOpen(id, blockSize), router); + 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(); diff --git a/Swiften/FileTransfer/IBBSendSession.h b/Swiften/FileTransfer/IBBSendSession.h index a535382..dcda11f 100644 --- a/Swiften/FileTransfer/IBBSendSession.h +++ b/Swiften/FileTransfer/IBBSendSession.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -36,12 +36,12 @@ namespace Swift { return to; } - void setBlockSize(int blockSize) { + void setBlockSize(unsigned int blockSize) { this->blockSize = blockSize; } boost::signal<void (boost::optional<FileTransferError>)> onFinished; - boost::signal<void (int)> onBytesSent; + boost::signal<void (unsigned long long)> onBytesSent; private: void handleIBBResponse(IBB::ref, ErrorPayload::ref); @@ -55,7 +55,7 @@ namespace Swift { JID to; boost::shared_ptr<ReadBytestream> bytestream; IQRouter* router; - int blockSize; + unsigned int blockSize; int sequenceNumber; bool active; bool waitingForData; diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp index 808ff58..c462381 100644 --- a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp +++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp @@ -110,7 +110,7 @@ void IncomingJingleFileTransfer::accept(WriteBytestream::ref stream) { s5bRegistry->addWriteBytestream(s5bDestination, stream); fillCandidateMap(theirCandidates, s5bTransport); candidateSelector->addRemoteTransportCandidates(s5bTransport); - candidateSelector->setRequesterTargtet(session->getInitiator(), ourJID); + candidateSelector->setRequesterTarget(session->getInitiator(), ourJID); s5bTransport->setSessionID(s5bSessionID); candidateGenerator->generateLocalTransportCandidates(s5bTransport); } @@ -173,8 +173,9 @@ void IncomingJingleFileTransfer::handleRemoteTransportCandidateSelectFinished(Ji } } +// TODO: Why was assert(false) there? Is this method no longer used perhaps? Delete it if not void IncomingJingleFileTransfer::checkCandidateSelected() { - assert(false); + //assert(false); if (localTransportCandidateSelectFinished && remoteTransportCandidateSelectFinished) { if (candidateGenerator->isActualCandidate(selectedLocalTransportCandidate) && candidateSelector->isActualCandidate(selectedRemoteTransportCandidate)) { if (candidateGenerator->getPriority(selectedLocalTransportCandidate) > candidateSelector->getPriority(selectedRemoteTransportCandidate)) { diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp index e22260e..4da70ef 100644 --- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp +++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp @@ -119,7 +119,7 @@ void OutgoingJingleFileTransfer::handleSessionAcceptReceived(const JingleContent } else if ((s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload))) { fillCandidateMap(theirCandidates, s5bPayload); - remoteCandidateSelector->setRequesterTargtet(toJID, session->getInitiator()); + remoteCandidateSelector->setRequesterTarget(toJID, session->getInitiator()); remoteCandidateSelector->addRemoteTransportCandidates(s5bPayload); remoteCandidateSelector->selectCandidate(); } diff --git a/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp b/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp index fc0a551..5e93343 100644 --- a/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp +++ b/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -16,7 +16,7 @@ namespace Swift { -OutgoingSIFileTransfer::OutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, int size, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer) : id(id), from(from), to(to), name(name), size(size), description(description), bytestream(bytestream), iqRouter(iqRouter), socksServer(socksServer) { +OutgoingSIFileTransfer::OutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, unsigned long long size, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer) : id(id), from(from), to(to), name(name), size(size), description(description), bytestream(bytestream), iqRouter(iqRouter), socksServer(socksServer) { } void OutgoingSIFileTransfer::start() { diff --git a/Swiften/FileTransfer/OutgoingSIFileTransfer.h b/Swiften/FileTransfer/OutgoingSIFileTransfer.h index 584eb60..79da339 100644 --- a/Swiften/FileTransfer/OutgoingSIFileTransfer.h +++ b/Swiften/FileTransfer/OutgoingSIFileTransfer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -25,7 +25,7 @@ namespace Swift { class OutgoingSIFileTransfer : public OutgoingFileTransfer { public: - OutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, int size, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer); + OutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, unsigned long long size, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer); virtual void start(); virtual void stop(); @@ -43,7 +43,7 @@ namespace Swift { JID from; JID to; std::string name; - int size; + unsigned long long size; std::string description; boost::shared_ptr<ReadBytestream> bytestream; IQRouter* iqRouter; diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h index 487747c..3d5612a 100644 --- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h +++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h @@ -22,7 +22,7 @@ namespace Swift { virtual void addRemoteTransportCandidates(JingleTransportPayload::ref) = 0; virtual void selectCandidate() = 0; virtual void setMinimumPriority(int) = 0; - virtual void setRequesterTargtet(const JID&, const JID&) {} + virtual void setRequesterTarget(const JID&, const JID&) {} virtual SOCKS5BytestreamClientSession::ref getS5BSession() { return SOCKS5BytestreamClientSession::ref(); } virtual bool isActualCandidate(JingleTransportPayload::ref) = 0; diff --git a/Swiften/FileTransfer/SConscript b/Swiften/FileTransfer/SConscript index 4e79992..8d98477 100644 --- a/Swiften/FileTransfer/SConscript +++ b/Swiften/FileTransfer/SConscript @@ -1,6 +1,7 @@ Import("swiften_env", "env") sources = [ + "ByteArrayReadBytestream.cpp", "OutgoingFileTransfer.cpp", "OutgoingSIFileTransfer.cpp", "OutgoingJingleFileTransfer.cpp", diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp index cd555e5..1b3399f 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp @@ -7,6 +7,7 @@ #include "SOCKS5BytestreamClientSession.h" #include <boost/bind.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Algorithm.h> #include <Swiften/Base/SafeByteArray.h> @@ -127,7 +128,7 @@ void SOCKS5BytestreamClientSession::authenticate() { SWIFT_LOG(debug) << std::endl; SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4); SafeByteArray message = header; - append(message, createSafeByteArray(destination.size())); + 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 @@ -165,7 +166,7 @@ HostAddressPort SOCKS5BytestreamClientSession::getAddressPort() const { void SOCKS5BytestreamClientSession::sendData() { if (!readBytestream->isFinished()) { try { - boost::shared_ptr<ByteArray> dataToSend = readBytestream->read(chunkSize); + boost::shared_ptr<ByteArray> dataToSend = readBytestream->read(boost::numeric_cast<size_t>(chunkSize)); connection->write(createSafeByteArray(*dataToSend)); onBytesSent(dataToSend->size()); } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h index 0b9790d..a832796 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h @@ -58,8 +58,8 @@ public: boost::signal<void (bool /*error*/)> onSessionReady; boost::signal<void (boost::optional<FileTransferError>)> onFinished; - boost::signal<void (int)> onBytesSent; - boost::signal<void (int)> onBytesReceived; + boost::signal<void (size_t)> onBytesSent; + boost::signal<void (size_t)> onBytesReceived; private: void process(); diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp index 4412d0b..7521822 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,6 +7,7 @@ #include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h> #include <boost/bind.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <iostream> #include <Swiften/Base/ByteArray.h> @@ -133,7 +134,7 @@ void SOCKS5BytestreamServerSession::process() { SafeByteArray result = createSafeByteArray("\x05", 1); result.push_back((readBytestream || writeBytestream) ? 0x0 : 0x4); append(result, createByteArray("\x00\x03", 2)); - result.push_back(static_cast<char>(requestID.size())); + result.push_back(boost::numeric_cast<unsigned char>(requestID.size())); append(result, concat(requestID, createByteArray("\x00\x00", 2))); if (!readBytestream && !writeBytestream) { SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl; @@ -159,7 +160,7 @@ void SOCKS5BytestreamServerSession::process() { void SOCKS5BytestreamServerSession::sendData() { if (!readBytestream->isFinished()) { try { - SafeByteArray dataToSend = createSafeByteArray(*readBytestream->read(chunkSize)); + SafeByteArray dataToSend = createSafeByteArray(*readBytestream->read(boost::numeric_cast<size_t>(chunkSize))); if (!dataToSend.empty()) { connection->write(dataToSend); onBytesSent(dataToSend.size()); diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h index 4cbda7c..60a404b 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h @@ -47,8 +47,8 @@ namespace Swift { HostAddressPort getAddressPort() const; boost::signal<void (boost::optional<FileTransferError>)> onFinished; - boost::signal<void (int)> onBytesSent; - boost::signal<void (int)> onBytesReceived; + boost::signal<void (unsigned long long)> onBytesSent; + boost::signal<void (unsigned long long)> onBytesReceived; private: void finish(bool error); diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h index ae06cd3..9975a67 100644 --- a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h +++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h @@ -7,7 +7,7 @@ #pragma once #include <string> -#include <boost/filesystem.hpp> +#include <boost/filesystem/path.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <Swiften/FileTransfer/FileTransferManager.h> diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp index 5fe096a..502cf2d 100644 --- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp @@ -33,7 +33,7 @@ using namespace Swift; -boost::mt19937 randomGen; +static boost::mt19937 randomGen; class SOCKS5BytestreamClientSessionTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SOCKS5BytestreamClientSessionTest); @@ -52,7 +52,7 @@ public: destination(SOCKS5BytestreamRegistry::getHostname("foo", JID("requester@example.com/test"), JID("target@example.com/test"))), eventLoop(NULL), timerFactory(NULL) { } void setUp() { - randomGen.seed(time(NULL)); + randomGen.seed(static_cast<unsigned int>(time(NULL))); eventLoop = new DummyEventLoop(); timerFactory = new DummyTimerFactory(); connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop); @@ -82,7 +82,7 @@ public: serverRespondHelloOK(); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4)); - CPPUNIT_ASSERT_EQUAL(createByteArray(destination.size()), createByteArray(helper.unprocessedInput[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)); @@ -128,7 +128,7 @@ public: serverRespondHelloOK(); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4)); - CPPUNIT_ASSERT_EQUAL(createByteArray(destination.size()), createByteArray(helper.unprocessedInput[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)); @@ -205,7 +205,7 @@ private: boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randomByte(randomGen, dist); ByteArray result(len); for (size_t i=0; i < len; ++i ) { - result[i] = randomByte(); + result[i] = static_cast<unsigned char>(randomByte()); } return result; } @@ -221,7 +221,7 @@ private: void serverRespondRequestOK() { boost::shared_ptr<SafeByteArray> dataToSend = createSafeByteArrayRef("\x05\x00\x00\x03", 4); - append(*dataToSend, createSafeByteArray(destination.size())); + append(*dataToSend, createSafeByteArray(static_cast<char>(destination.size()))); append(*dataToSend, createSafeByteArray(destination)); append(*dataToSend, createSafeByteArray("\x00", 1)); connection->onDataRead(dataToSend); @@ -229,7 +229,7 @@ private: void serverRespondRequestFail() { boost::shared_ptr<SafeByteArray> correctData = createSafeByteArrayRef("\x05\x00\x00\x03", 4); - append(*correctData, createSafeByteArray(destination.size())); + append(*correctData, createSafeByteArray(static_cast<char>(destination.size()))); append(*correctData, createSafeByteArray(destination)); append(*correctData, createSafeByteArray("\x00", 1)); diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp index 6dec37f..4e97399 100644 --- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp @@ -76,7 +76,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture { authenticate(); ByteArray hostname(createByteArray("abcdef")); - receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(hostname.size()), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); + 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)); } @@ -86,7 +86,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture { authenticate(); ByteArray hostname(createByteArray("abcdef")); - receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(hostname.size()), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); + 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); } @@ -173,11 +173,11 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture { } void request(const std::string& hostname) { - receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(hostname.size()), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2))); + 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) { - int headerSize = 7 + hostname.size(); + size_t headerSize = 7 + hostname.size(); receivedData = createByteArray(&receivedData[headerSize], receivedData.size() - headerSize); } diff --git a/Swiften/History/HistoryStorage.h b/Swiften/History/HistoryStorage.h index fcf28b5..6d24d15 100644 --- a/Swiften/History/HistoryStorage.h +++ b/Swiften/History/HistoryStorage.h @@ -21,7 +21,7 @@ namespace Swift { * Messages are stored using localtime timestamps. */ public: - virtual ~HistoryStorage() {}; + 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; diff --git a/Swiften/History/SQLiteHistoryStorage.cpp b/Swiften/History/SQLiteHistoryStorage.cpp index 04bd00f..d7e7477 100644 --- a/Swiften/History/SQLiteHistoryStorage.cpp +++ b/Swiften/History/SQLiteHistoryStorage.cpp @@ -6,6 +6,7 @@ #include <iostream> #include <boost/lexical_cast.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <sqlite3.h> #include <3rdParty/SQLiteAsync/sqlite3async.h> @@ -78,8 +79,8 @@ void SQLiteHistoryStorage::addMessage(const HistoryMessage& message) { 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<int> selfID = getIDFromJID(selfJID.toBare()); - boost::optional<int> contactID = getIDFromJID(contactJID.toBare()); + boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); + boost::optional<long long> contactID = getIDFromJID(contactJID.toBare()); if (!selfID || !contactID) { // JIDs missing from the database @@ -111,7 +112,7 @@ std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromDate(const JID& " AND time<" + boost::lexical_cast<std::string>(upperBound) + ")"; } - int r = sqlite3_prepare(db_, selectQuery.c_str(), selectQuery.size(), &selectStatement, NULL); + 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; } @@ -157,8 +158,8 @@ std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromDate(const JID& return result; } -int SQLiteHistoryStorage::getIDForJID(const JID& jid) { - boost::optional<int> id = getIDFromJID(jid); +long long SQLiteHistoryStorage::getIDForJID(const JID& jid) { + boost::optional<long long> id = getIDFromJID(jid); if (id) { return *id; } @@ -167,7 +168,7 @@ int SQLiteHistoryStorage::getIDForJID(const JID& jid) { } } -int SQLiteHistoryStorage::addJID(const JID& 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); @@ -178,11 +179,11 @@ int SQLiteHistoryStorage::addJID(const JID& jid) { return sqlite3_last_insert_rowid(db_); } -boost::optional<JID> SQLiteHistoryStorage::getJIDFromID(int id) const { +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(), selectQuery.size(), &selectStatement, NULL); + 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; } @@ -194,17 +195,17 @@ boost::optional<JID> SQLiteHistoryStorage::getJIDFromID(int id) const { return result; } -boost::optional<int> SQLiteHistoryStorage::getIDFromJID(const JID& jid) const { - boost::optional<int> 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() + "'"); - int r = sqlite3_prepare(db_, selectQuery.c_str(), selectQuery.size(), &selectStatement, NULL); + 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<int>(sqlite3_column_int(selectStatement, 0)); + result = boost::optional<long long>(sqlite3_column_int(selectStatement, 0)); } sqlite3_finalize(selectStatement); return result; @@ -215,7 +216,7 @@ ContactsMap SQLiteHistoryStorage::getContacts(const JID& selfJID, HistoryMessage sqlite3_stmt* selectStatement; // get id - boost::optional<int> id = getIDFromJID(selfJID); + boost::optional<long long> id = getIDFromJID(selfJID); if (!id) { return result; } @@ -231,7 +232,7 @@ ContactsMap SQLiteHistoryStorage::getContacts(const JID& selfJID, HistoryMessage query += " AND message LIKE '%" + getEscapedString(keyword) + "%'"; } - int r = sqlite3_prepare(db_, query.c_str(), query.size(), &selectStatement, NULL); + 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; } @@ -280,8 +281,8 @@ ContactsMap SQLiteHistoryStorage::getContacts(const JID& selfJID, HistoryMessage 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<int> selfID = getIDFromJID(selfJID.toBare()); - boost::optional<int> contactID = getIDFromJID(contactJID.toBare()); + boost::optional<long long> selfID = getIDFromJID(selfJID.toBare()); + boost::optional<long long> contactID = getIDFromJID(contactJID.toBare()); if (!selfID || !contactID) { // JIDs missing from the database @@ -310,7 +311,7 @@ boost::gregorian::date SQLiteHistoryStorage::getNextDateWithLogs(const JID& self 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(), selectQuery.size(), &selectStatement, NULL); + 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; } @@ -347,8 +348,8 @@ std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromPreviousDate(co } boost::posix_time::ptime SQLiteHistoryStorage::getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const { - boost::optional<int> selfID = getIDFromJID(selfJID.toBare()); - boost::optional<int> 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 @@ -361,7 +362,7 @@ boost::posix_time::ptime SQLiteHistoryStorage::getLastTimeStampFromMUC(const JID 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(), selectQuery.size(), &selectStatement, NULL); + 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; } diff --git a/Swiften/History/SQLiteHistoryStorage.h b/Swiften/History/SQLiteHistoryStorage.h index 782334a..dd526b1 100644 --- a/Swiften/History/SQLiteHistoryStorage.h +++ b/Swiften/History/SQLiteHistoryStorage.h @@ -29,11 +29,11 @@ namespace Swift { private: void run(); boost::gregorian::date getNextDateWithLogs(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date, bool reverseOrder) const; - int getIDForJID(const JID&); - int addJID(const JID&); + long long getIDForJID(const JID&); + long long addJID(const JID&); - boost::optional<JID> getJIDFromID(int id) const; - boost::optional<int> getIDFromJID(const JID& jid) const; + 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/IDN/StringPrep.cpp b/Swiften/IDN/StringPrep.cpp index dfaba06..3ab7088 100644 --- a/Swiften/IDN/StringPrep.cpp +++ b/Swiften/IDN/StringPrep.cpp @@ -29,10 +29,10 @@ using namespace Swift; namespace { static UStringPrepProfileType getICUProfileType(StringPrep::Profile profile) { switch(profile) { - case StringPrep::NamePrep: return USPREP_RFC3491_NAMEPREP; break; - case StringPrep::XMPPNodePrep: return USPREP_RFC3920_NODEPREP; break; - case StringPrep::XMPPResourcePrep: return USPREP_RFC3920_RESOURCEPREP; break; - case StringPrep::SASLPrep: return USPREP_RFC4013_SASLPREP; break; + case StringPrep::NamePrep: return USPREP_RFC3491_NAMEPREP; + case StringPrep::XMPPNodePrep: return USPREP_RFC3920_NODEPREP; + case StringPrep::XMPPResourcePrep: return USPREP_RFC3920_RESOURCEPREP; + case StringPrep::SASLPrep: return USPREP_RFC4013_SASLPREP; } assert(false); return USPREP_RFC3491_NAMEPREP; @@ -100,10 +100,10 @@ namespace { const Stringprep_profile* getLibIDNProfile(StringPrep::Profile profile) { switch(profile) { - case StringPrep::NamePrep: return stringprep_nameprep; break; - case StringPrep::XMPPNodePrep: return stringprep_xmpp_nodeprep; break; - case StringPrep::XMPPResourcePrep: return stringprep_xmpp_resourceprep; break; - case StringPrep::SASLPrep: return stringprep_saslprep; break; + case StringPrep::NamePrep: return stringprep_nameprep; + case StringPrep::XMPPNodePrep: return stringprep_xmpp_nodeprep; + case StringPrep::XMPPResourcePrep: return stringprep_xmpp_resourceprep; + case StringPrep::SASLPrep: return stringprep_saslprep; } assert(false); return 0; diff --git a/Swiften/JID/JID.cpp b/Swiften/JID/JID.cpp index 0822595..1bdf390 100644 --- a/Swiften/JID/JID.cpp +++ b/Swiften/JID/JID.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -18,6 +18,7 @@ #include <boost/assign/list_of.hpp> #include <boost/algorithm/string/find_format.hpp> #include <boost/algorithm/string/finder.hpp> +#include <iostream> #include <sstream> #include <Swiften/Base/String.h> @@ -111,6 +112,8 @@ struct EscapedCharacterFormatter { }; #endif +namespace Swift { + JID::JID(const char* jid) : valid_(true) { initializeFromString(std::string(jid)); } @@ -270,3 +273,10 @@ std::string JID::getUnescapedNode() const { return result; //return boost::find_format_all_copy(node_, EscapedCharacterFinder(), EscapedCharacterFormatter()); } + +std::ostream& operator<<(std::ostream& os, const JID& j) { + os << j.toString(); + return os; +} + +} diff --git a/Swiften/JID/JID.h b/Swiften/JID/JID.h index 08309d3..3ccf7de 100644 --- a/Swiften/JID/JID.h +++ b/Swiften/JID/JID.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,11 +7,11 @@ #pragma once #include <string> -//#include <iosfwd> -#include <iostream> +#include <iosfwd> #include <Swiften/Base/API.h> + namespace Swift { /** * This represents the JID used in XMPP @@ -146,10 +146,7 @@ namespace Swift { return compare(b, Swift::JID::WithResource) < 0; } - friend std::ostream& operator<<(std::ostream& os, const Swift::JID& j) { - os << j.toString(); - return os; - } + 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; @@ -170,4 +167,7 @@ namespace Swift { bool hasResource_; std::string resource_; }; + + std::ostream& operator<<(std::ostream& os, const Swift::JID& j); } + diff --git a/Swiften/Jingle/JingleSessionImpl.cpp b/Swiften/Jingle/JingleSessionImpl.cpp index 98c5196..53092fc 100644 --- a/Swiften/Jingle/JingleSessionImpl.cpp +++ b/Swiften/Jingle/JingleSessionImpl.cpp @@ -76,7 +76,7 @@ void JingleSessionImpl::handleIncomingAction(JinglePayload::ref action) { case JinglePayload::UnknownAction: return; } - std::cerr << "Unhandled Jingle action!!! ACTION: " << action->getAction() << std::endl; + assert(false); } void JingleSessionImpl::sendInitiate(const JingleContentID& id, JingleDescription::ref description, JingleTransportPayload::ref transport) { diff --git a/Swiften/Jingle/JingleSessionManager.cpp b/Swiften/Jingle/JingleSessionManager.cpp index 2e15fcd..f31ddb8 100644 --- a/Swiften/Jingle/JingleSessionManager.cpp +++ b/Swiften/Jingle/JingleSessionManager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011 Remko Tronçon + * Copyright (c) 2011-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,6 +7,7 @@ #include <Swiften/Jingle/JingleSessionManager.h> #include <Swiften/Jingle/JingleResponder.h> #include <Swiften/Jingle/IncomingJingleSessionHandler.h> +#include <Swiften/Base/Log.h> #include <Swiften/Base/foreach.h> #include <Swiften/Base/Algorithm.h> diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h index 6e79290..52d6654 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -9,6 +9,7 @@ #include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h> #include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h> #include <Swiften/EventLoop/EventLoop.h> +#include <boost/numeric/conversion/cast.hpp> namespace Swift { class BonjourQuerier; @@ -48,7 +49,7 @@ namespace Swift { } else { //std::cout << "Discovered service: name:" << name << " domain:" << domain << " type: " << type << std::endl; - DNSSDServiceID service(name, domain, type, interfaceIndex); + DNSSDServiceID service(name, domain, type, boost::numeric_cast<int>(interfaceIndex)); if (flags & kDNSServiceFlagsAdd) { eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this()); } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h index d3c9488..1bec5f7 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h @@ -10,6 +10,7 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/EventLoop/EventLoop.h> +#include <boost/numeric/conversion/cast.hpp> namespace Swift { class BonjourQuerier; @@ -18,8 +19,8 @@ namespace Swift { 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, port, - txtRecord.size(), vecptr(txtRecord), + &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; @@ -41,7 +42,7 @@ namespace Swift { void updateServiceInfo(const ByteArray& txtRecord) { boost::lock_guard<boost::mutex> lock(sdRefMutex); - DNSServiceUpdateRecord(sdRef, NULL, 0, txtRecord.size(), vecptr(txtRecord), 0); + DNSServiceUpdateRecord(sdRef, NULL, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0); } private: diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h index 9fdd3d5..59d1af5 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -13,6 +13,7 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h> #include <Swiften/EventLoop/EventLoop.h> #include <Swiften/Network/HostAddress.h> +#include <boost/numeric/conversion/cast.hpp> #include <netinet/in.h> @@ -23,7 +24,7 @@ namespace Swift { public: BonjourResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { DNSServiceErrorType result = DNSServiceGetAddrInfo( - &sdRef, 0, interfaceIndex, kDNSServiceProtocol_IPv4, + &sdRef, 0, boost::numeric_cast<unsigned int>(interfaceIndex), kDNSServiceProtocol_IPv4, hostname.c_str(), &BonjourResolveHostnameQuery::handleHostnameResolvedStatic, this); if (result != kDNSServiceErr_NoError) { diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h index 1fb050c..2eeac64 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -19,7 +19,7 @@ namespace Swift { public: BonjourResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { DNSServiceErrorType result = DNSServiceResolve( - &sdRef, 0, service.getNetworkInterfaceID(), + &sdRef, 0, boost::numeric_cast<unsigned int>(service.getNetworkInterfaceID()), service.getName().c_str(), service.getType().c_str(), service.getDomain().c_str(), &BonjourResolveServiceQuery::handleServiceResolvedStatic, this); diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp index 516d303..7e18315 100644 --- a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp +++ b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,6 +7,7 @@ #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> #include <boost/lexical_cast.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Algorithm.h> #include <Swiften/Base/Concat.h> @@ -49,7 +50,7 @@ ByteArray LinkLocalServiceInfo::toTXTRecord() const { ByteArray LinkLocalServiceInfo::getEncoded(const std::string& s) { ByteArray sizeByte; sizeByte.resize(1); - sizeByte[0] = s.size(); + sizeByte[0] = boost::numeric_cast<unsigned char>(s.size()); return concat(sizeByte, createByteArray(s)); } @@ -109,11 +110,11 @@ std::pair<std::string,std::string> LinkLocalServiceInfo::readEntry(const ByteArr inKey = false; } else { - key += record[i]; + key += static_cast<char>(record[i]); } } else { - value += record[i]; + value += static_cast<char>(record[i]); } ++i; } diff --git a/Swiften/Network/BOSHConnection.cpp b/Swiften/Network/BOSHConnection.cpp index 377373d..23772eb 100644 --- a/Swiften/Network/BOSHConnection.cpp +++ b/Swiften/Network/BOSHConnection.cpp @@ -110,7 +110,7 @@ std::pair<SafeByteArray, size_t> BOSHConnection::createHTTPRequest(const SafeByt header << ":" << *boshURL.getPort(); } header << "\r\n" - /*<< "Accept-Encoding: deflate\r\n"*/ + // << "Accept-Encoding: deflate\r\n" << "Content-Type: text/xml; charset=utf-8\r\n" << "Content-Length: " << size << "\r\n\r\n"; @@ -156,7 +156,7 @@ void BOSHConnection::startStream(const std::string& to, unsigned long long rid) << " rid='" << rid << "'" << " ver='1.6'" << " wait='60'" /* FIXME: we probably want this configurable*/ - /*<< " ack='0'" FIXME: support acks */ + // << " ack='0'" FIXME: support acks << " xml:lang='en'" << " xmlns:xmpp='urn:xmpp:bosh'" << " xmpp:version='1.0'" @@ -170,7 +170,7 @@ void BOSHConnection::startStream(const std::string& to, unsigned long long rid) header << ":" << *boshURL_.getPort(); } header << "\r\n" - /*<< "Accept-Encoding: deflate\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; @@ -208,7 +208,7 @@ void BOSHConnection::handleDataRead(boost::shared_ptr<SafeByteArray> data) { waitingForStartResponse_ = false; sid_ = parser.getBody()->attributes.getAttribute("sid"); std::string requestsString = parser.getBody()->attributes.getAttribute("requests"); - int requests = 2; + size_t requests = 2; if (!requestsString.empty()) { try { requests = boost::lexical_cast<size_t>(requestsString); diff --git a/Swiften/Network/BOSHConnectionPool.cpp b/Swiften/Network/BOSHConnectionPool.cpp index e535deb..4517ffb 100644 --- a/Swiften/Network/BOSHConnectionPool.cpp +++ b/Swiften/Network/BOSHConnectionPool.cpp @@ -210,14 +210,14 @@ void BOSHConnectionPool::handleHTTPError(const std::string& /*errorCode*/) { handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); } -void BOSHConnectionPool::handleConnectionDisconnected(bool error, BOSHConnection::ref connection) { +void BOSHConnectionPool::handleConnectionDisconnected(bool/* error*/, BOSHConnection::ref connection) { destroyConnection(connection); if (pendingTerminate && sid.empty() && connections.empty()) { handleSessionTerminated(BOSHError::ref()); } - else if (false && error) { - handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); - } + //else if (error) { + // handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition)); + //} else { /* We might have just freed up a connection slot to send with */ tryToSendQueuedData(); diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp index 1d4bd32..5137c3c 100644 --- a/Swiften/Network/BoostConnection.cpp +++ b/Swiften/Network/BoostConnection.cpp @@ -14,6 +14,7 @@ #include <boost/asio/placeholders.hpp> #include <boost/asio/write.hpp> #include <boost/smart_ptr/make_shared.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Log.h> #include <Swiften/Base/Algorithm.h> @@ -63,7 +64,7 @@ void BoostConnection::listen() { void BoostConnection::connect(const HostAddressPort& addressPort) { boost::asio::ip::tcp::endpoint endpoint( - boost::asio::ip::address::from_string(addressPort.getAddress().toString()), addressPort.getPort()); + 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)); diff --git a/Swiften/Network/BoostConnectionServer.cpp b/Swiften/Network/BoostConnectionServer.cpp index eccffc6..e015eaa 100644 --- a/Swiften/Network/BoostConnectionServer.cpp +++ b/Swiften/Network/BoostConnectionServer.cpp @@ -9,6 +9,7 @@ #include <boost/bind.hpp> #include <boost/system/system_error.hpp> #include <boost/asio/placeholders.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/EventLoop/EventLoop.h> @@ -26,12 +27,12 @@ void BoostConnectionServer::start() { if (address_.isValid()) { acceptor_ = new boost::asio::ip::tcp::acceptor( *ioService_, - boost::asio::ip::tcp::endpoint(address_.getRawAddress(), port_)); + boost::asio::ip::tcp::endpoint(address_.getRawAddress(), boost::numeric_cast<unsigned short>(port_))); } else { acceptor_ = new boost::asio::ip::tcp::acceptor( *ioService_, - boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port_)); + boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), boost::numeric_cast<unsigned short>(port_))); } acceptNextConnection(); } diff --git a/Swiften/Network/DomainNameServiceQuery.cpp b/Swiften/Network/DomainNameServiceQuery.cpp index da1e1ab..6ce1d97 100644 --- a/Swiften/Network/DomainNameServiceQuery.cpp +++ b/Swiften/Network/DomainNameServiceQuery.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -13,8 +13,12 @@ #include <Swiften/Base/RandomGenerator.h> #include <boost/numeric/conversion/cast.hpp> +#include <boost/lambda/lambda.hpp> +#include <boost/lambda/bind.hpp> +#include <boost/typeof/typeof.hpp> using namespace Swift; +namespace lambda = boost::lambda; namespace { struct ResultPriorityComparator { @@ -22,14 +26,6 @@ namespace { return a.priority < b.priority; } }; - - struct GetWeight { - GetWeight() {} - - int operator()(const DomainNameServiceQuery::Result& result) { - return result.weight + 1 /* easy hack to account for '0' weights getting at least some weight */; - } - }; } namespace Swift { @@ -46,12 +42,17 @@ void DomainNameServiceQuery::sortResults(std::vector<DomainNameServiceQuery::Res 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), GetWeight()); - for (size_t j = 0; j < weights.size() - 1; ++j) { + 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)); + std::partial_sum( + weights.begin() + j, + weights.end(), + std::back_inserter(cumulativeWeights)); int randomNumber = generator.generateRandomInteger(cumulativeWeights.back()); - int selectedIndex = std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin(); + 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]); } diff --git a/Swiften/Network/HostAddress.cpp b/Swiften/Network/HostAddress.cpp index f00581f..9443b53 100644 --- a/Swiften/Network/HostAddress.cpp +++ b/Swiften/Network/HostAddress.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -28,18 +28,18 @@ HostAddress::HostAddress(const std::string& address) { } } -HostAddress::HostAddress(const unsigned char* address, int length) { +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 (int i = 0; i < length; ++i) { + 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 (int i = 0; i < length; ++i) { + for (size_t i = 0; i < length; ++i) { data[i] = address[i]; } address_ = boost::asio::ip::address(boost::asio::ip::address_v6(data)); diff --git a/Swiften/Network/HostAddress.h b/Swiften/Network/HostAddress.h index 621aa5d..b8e3462 100644 --- a/Swiften/Network/HostAddress.h +++ b/Swiften/Network/HostAddress.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -15,7 +15,7 @@ namespace Swift { public: HostAddress(); HostAddress(const std::string&); - HostAddress(const unsigned char* address, int length); + HostAddress(const unsigned char* address, size_t length); HostAddress(const boost::asio::ip::address& address); std::string toString() const; diff --git a/Swiften/Network/MacOSXProxyProvider.cpp b/Swiften/Network/MacOSXProxyProvider.cpp index 00fb478..3456c73 100644 --- a/Swiften/Network/MacOSXProxyProvider.cpp +++ b/Swiften/Network/MacOSXProxyProvider.cpp @@ -4,18 +4,27 @@ * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2013 Remko Tronçon + * Licensed under the GNU General Public License v3. + * See Documentation/Licenses/GPLv3.txt for more information. + */ + #include <Swiften/Base/Platform.h> #include <Swiften/Network/MacOSXProxyProvider.h> #include <stdio.h> #include <stdlib.h> #include <iostream> +#include <boost/numeric/conversion/cast.hpp> #include <utility> #ifndef SWIFTEN_PLATFORM_IPHONE #include <SystemConfiguration/SystemConfiguration.h> #endif +#pragma clang diagnostic ignored "-Wdisabled-macro-expansion" + using namespace Swift; #ifndef SWIFTEN_PLATFORM_IPHONE @@ -27,6 +36,7 @@ static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabl const int i = 0; CFNumberRef zero = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &i); CFComparisonResult result = CFNumberCompare(numberValue, zero, NULL); + CFRelease(zero); if(result != kCFCompareEqualTo) { int port = 0; @@ -44,7 +54,7 @@ static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabl // 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(length); + 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; @@ -75,6 +85,7 @@ HostAddressPort MacOSXProxyProvider::getHTTPConnectProxy() const { CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); if(proxies != NULL) { result = getFromDictionary(proxies, kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort); + CFRelease(proxies); } #endif return result; @@ -86,6 +97,7 @@ HostAddressPort MacOSXProxyProvider::getSOCKS5Proxy() const { CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); if(proxies != NULL) { result = getFromDictionary(proxies, kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort); + CFRelease(proxies); } #endif return result; diff --git a/Swiften/Network/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp index 220e3e9..c7a41ff 100644 --- a/Swiften/Network/NATPMPInterface.cpp +++ b/Swiften/Network/NATPMPInterface.cpp @@ -7,6 +7,7 @@ #include <Swiften/Network/NATPMPInterface.h> #include <boost/smart_ptr/make_shared.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Log.h> @@ -63,9 +64,14 @@ boost::optional<HostAddress> NATPMPInterface::getPublicIP() { 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, mapping.getLeaseInSeconds(), mapping.getPublicPort(), mapping.getLocalPort()) < 0) { - SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl; - return boost::optional<NATPortMapping>(); + 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; @@ -81,7 +87,7 @@ boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, i } while(r == NATPMP_TRYAGAIN); if (r == 0) { - NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, response.pnu.newportmapping.lifetime); + NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime)); return result; } else { @@ -91,7 +97,7 @@ boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, i } bool NATPMPInterface::removePortForward(const NATPortMapping& mapping) { - if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, mapping.getLocalPort()) < 0) { + 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; } diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.cpp b/Swiften/Network/PlatformDomainNameServiceQuery.cpp index b0579a7..5788d2f 100644 --- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp +++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp @@ -12,6 +12,7 @@ #include <Swiften/Base/Platform.h> #include <stdlib.h> +#include <boost/numeric/conversion/cast.hpp> #ifdef SWIFTEN_PLATFORM_WINDOWS #undef UNICODE #include <windows.h> @@ -121,7 +122,7 @@ void PlatformDomainNameServiceQuery::runBlocking() { emitError(); return; } - record.priority = ns_get16(currentEntry); + record.priority = boost::numeric_cast<int>(ns_get16(currentEntry)); currentEntry += 2; // Weight @@ -129,7 +130,7 @@ void PlatformDomainNameServiceQuery::runBlocking() { emitError(); return; } - record.weight = ns_get16(currentEntry); + record.weight = boost::numeric_cast<int>(ns_get16(currentEntry)); currentEntry += 2; // Port @@ -137,7 +138,7 @@ void PlatformDomainNameServiceQuery::runBlocking() { emitError(); return; } - record.port = ns_get16(currentEntry); + record.port = boost::numeric_cast<int>(ns_get16(currentEntry)); currentEntry += 2; // Hostname diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.h b/Swiften/Network/PlatformDomainNameServiceQuery.h index 3372517..310e639 100644 --- a/Swiften/Network/PlatformDomainNameServiceQuery.h +++ b/Swiften/Network/PlatformDomainNameServiceQuery.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ diff --git a/Swiften/Network/PlatformNATTraversalWorker.cpp b/Swiften/Network/PlatformNATTraversalWorker.cpp index c962b3b..eeecb38 100644 --- a/Swiften/Network/PlatformNATTraversalWorker.cpp +++ b/Swiften/Network/PlatformNATTraversalWorker.cpp @@ -8,6 +8,7 @@ #include <boost/smart_ptr/make_shared.hpp> #include <boost/enable_shared_from_this.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Log.h> #include <Swiften/Network/NATTraversalGetPublicIPRequest.h> @@ -68,7 +69,7 @@ class PlatformNATTraversalForwardPortRequest : public NATTraversalForwardPortReq } virtual void runBlocking() { - onResult(getNATTraversalInterface()->addPortForward(localIP, publicIP)); + onResult(getNATTraversalInterface()->addPortForward(boost::numeric_cast<int>(localIP), boost::numeric_cast<int>(publicIP))); } private: diff --git a/Swiften/Network/ProxyProvider.h b/Swiften/Network/ProxyProvider.h index 0b63d51..9a1ccee 100644 --- a/Swiften/Network/ProxyProvider.h +++ b/Swiften/Network/ProxyProvider.h @@ -7,7 +7,6 @@ #pragma once #include <map> -#include <Swiften/Base/Log.h> #include <Swiften/Network/HostAddressPort.h> #include <Swiften/Base/String.h> diff --git a/Swiften/Network/SOCKS5ProxiedConnection.cpp b/Swiften/Network/SOCKS5ProxiedConnection.cpp index bf7a056..a9243d6 100644 --- a/Swiften/Network/SOCKS5ProxiedConnection.cpp +++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp @@ -65,7 +65,7 @@ void SOCKS5ProxiedConnection::handleProxyInitializeData(boost::shared_ptr<SafeBy else { uc = rawAddress.to_v6().to_bytes()[s]; // the address. } - socksConnect.push_back(static_cast<char>(uc)); + socksConnect.push_back(uc); } socksConnect.push_back(static_cast<unsigned char> ((getServer().getPort() >> 8) & 0xFF)); // highbyte of the port. diff --git a/Swiften/Network/TLSConnection.h b/Swiften/Network/TLSConnection.h index a798393..60f73ea 100644 --- a/Swiften/Network/TLSConnection.h +++ b/Swiften/Network/TLSConnection.h @@ -24,7 +24,7 @@ namespace Swift { TLSConnection(Connection::ref connection, TLSContextFactory* tlsFactory); virtual ~TLSConnection(); - virtual void listen() {assert(false);}; + virtual void listen() {assert(false);} virtual void connect(const HostAddressPort& address); virtual void disconnect(); virtual void write(const SafeByteArray& data); diff --git a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp index 23f1a3c..8a63fcb 100644 --- a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp +++ b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp @@ -170,7 +170,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { void testConnectionCount_ThreeWritesTwoReads() { boost::shared_ptr<MockConnection> c0; boost::shared_ptr<MockConnection> c1; - long rid = initialRID; + unsigned long long rid = initialRID; PoolRef testling = createTestling(); CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size()); @@ -461,7 +461,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { std::string port; std::string sid; std::string initial; - long initialRID; + unsigned long long initialRID; int sessionStarted; int sessionTerminated; diff --git a/Swiften/Parser/AttributeMap.cpp b/Swiften/Parser/AttributeMap.cpp index 1aeaf99..d508157 100644 --- a/Swiften/Parser/AttributeMap.cpp +++ b/Swiften/Parser/AttributeMap.cpp @@ -8,27 +8,18 @@ #include <algorithm> #include <boost/optional.hpp> +#include <boost/lambda/lambda.hpp> +#include <boost/lambda/bind.hpp> using namespace Swift; - -namespace { - struct AttributeIs { - AttributeIs(const Attribute& attribute) : attribute(attribute) { - } - - bool operator()(const AttributeMap::Entry& o) const { - return o.getAttribute() == attribute; - } - - Attribute attribute; - }; -} +namespace lambda = boost::lambda; AttributeMap::AttributeMap() { } std::string AttributeMap::getAttribute(const std::string& attribute, const std::string& ns) const { - AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), AttributeIs(Attribute(attribute, ns))); + AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), + lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ns)); if (i == attributes.end()) { return ""; } @@ -38,7 +29,8 @@ std::string AttributeMap::getAttribute(const std::string& attribute, const std:: } bool AttributeMap::getBoolAttribute(const std::string& attribute, bool defaultValue) const { - AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), AttributeIs(Attribute(attribute, ""))); + AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), + lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, "")); if (i == attributes.end()) { return defaultValue; } @@ -48,7 +40,8 @@ bool AttributeMap::getBoolAttribute(const std::string& attribute, bool defaultVa } boost::optional<std::string> AttributeMap::getAttributeValue(const std::string& attribute) const { - AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), AttributeIs(Attribute(attribute, ""))); + AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), + lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, "")); if (i == attributes.end()) { return boost::optional<std::string>(); } diff --git a/Swiften/Parser/BOSHBodyExtractor.cpp b/Swiften/Parser/BOSHBodyExtractor.cpp index eeebe8a..715a448 100644 --- a/Swiften/Parser/BOSHBodyExtractor.cpp +++ b/Swiften/Parser/BOSHBodyExtractor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011 Remko Tronçon + * Copyright (c) 2011-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,6 +7,7 @@ #include <Swiften/Parser/BOSHBodyExtractor.h> #include <boost/shared_ptr.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Parser/XMLParserClient.h> #include <Swiften/Parser/XMLParser.h> @@ -33,7 +34,7 @@ class BOSHBodyParserClient : public XMLParserClient { BOSHBodyExtractor* bodyExtractor; }; -inline bool isWhitespace(char c) { +inline bool isWhitespace(unsigned char c) { return c == ' ' || c == '\n' || c == '\t' || c == '\r'; } @@ -117,13 +118,17 @@ BOSHBodyExtractor::BOSHBodyExtractor(XMLParserFactory* parserFactory, const Byte body = BOSHBody(); if (!endElementSeen) { - body->content = std::string(reinterpret_cast<const char*>(vecptr(data) + std::distance(data.begin(), i)), std::distance(i, j.base())); + body->content = std::string( + reinterpret_cast<const char*>(vecptr(data) + std::distance(data.begin(), i)), + boost::numeric_cast<size_t>(std::distance(i, j.base()))); } // Parse the body element BOSHBodyParserClient parserClient(this); boost::shared_ptr<XMLParser> parser(parserFactory->createXMLParser(&parserClient)); - if (!parser->parse(std::string(reinterpret_cast<const char*>(vecptr(data)), std::distance(data.begin(), i)))) { + if (!parser->parse(std::string( + reinterpret_cast<const char*>(vecptr(data)), + boost::numeric_cast<size_t>(std::distance(data.begin(), i))))) { /* TODO: This needs to be only validating the BOSH <body> element, so that XMPP parsing errors are caught at the correct higher layer */ body = boost::optional<BOSHBody>(); diff --git a/Swiften/Parser/ExpatParser.cpp b/Swiften/Parser/ExpatParser.cpp index 8222ae0..8b7bf82 100644 --- a/Swiften/Parser/ExpatParser.cpp +++ b/Swiften/Parser/ExpatParser.cpp @@ -9,10 +9,13 @@ #include <iostream> #include <string> #include <expat.h> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/String.h> #include <Swiften/Parser/XMLParserClient.h> +#pragma clang diagnostic ignored "-Wdisabled-macro-expansion" + namespace Swift { static const char NAMESPACE_SEPARATOR = '\x01'; @@ -52,7 +55,8 @@ static void handleEndElement(void* parser, const XML_Char* name) { } static void handleCharacterData(void* parser, const XML_Char* data, int len) { - static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(data, len)); + assert(len >= 0); + static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(data, static_cast<size_t>(len))); } static void handleXMLDeclaration(void*, const XML_Char*, const XML_Char*, int) { @@ -77,7 +81,7 @@ ExpatParser::~ExpatParser() { } bool ExpatParser::parse(const std::string& data) { - bool success = XML_Parse(p->parser_, data.c_str(), data.size(), false) == XML_STATUS_OK; + bool success = XML_Parse(p->parser_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_STATUS_OK; /*if (!success) { std::cout << "ERROR: " << XML_ErrorString(XML_GetErrorCode(p->parser_)) << " while parsing " << data << std::endl; }*/ diff --git a/Swiften/Parser/LibXMLParser.cpp b/Swiften/Parser/LibXMLParser.cpp index caba716..e4938e1 100644 --- a/Swiften/Parser/LibXMLParser.cpp +++ b/Swiften/Parser/LibXMLParser.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -7,6 +7,7 @@ #include <Swiften/Parser/LibXMLParser.h> #include <iostream> +#include <boost/numeric/conversion/cast.hpp> #include <cassert> #include <cstring> #include <libxml/parser.h> @@ -32,7 +33,11 @@ static void handleStartElement(void* parser, const xmlChar* name, const xmlChar* if (attributes[i+2]) { attributeNS = std::string(reinterpret_cast<const char*>(attributes[i+2])); } - attributeValues.addAttribute(std::string(reinterpret_cast<const char*>(attributes[i])), attributeNS, std::string(reinterpret_cast<const char*>(attributes[i+3]), attributes[i+4]-attributes[i+3])); + attributeValues.addAttribute( + std::string(reinterpret_cast<const char*>(attributes[i])), + attributeNS, + std::string(reinterpret_cast<const char*>(attributes[i+3]), + boost::numeric_cast<size_t>(attributes[i+4]-attributes[i+3]))); } static_cast<XMLParser*>(parser)->getClient()->handleStartElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()), attributeValues); } @@ -42,7 +47,7 @@ static void handleEndElement(void *parser, const xmlChar* name, const xmlChar*, } static void handleCharacterData(void* parser, const xmlChar* data, int len) { - static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(reinterpret_cast<const char*>(data), len)); + static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(reinterpret_cast<const char*>(data), boost::numeric_cast<size_t>(len))); } static void handleError(void*, const char* /*m*/, ... ) { @@ -86,7 +91,7 @@ LibXMLParser::~LibXMLParser() { } bool LibXMLParser::parse(const std::string& data) { - if (xmlParseChunk(p->context_, data.c_str(), data.size(), false) == XML_ERR_OK) { + if (xmlParseChunk(p->context_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_ERR_OK) { return true; } xmlError* error = xmlCtxtGetLastError(p->context_); diff --git a/Swiften/Parser/PayloadParsers/FormParser.h b/Swiften/Parser/PayloadParsers/FormParser.h index a3e2524..ec480a5 100644 --- a/Swiften/Parser/PayloadParsers/FormParser.h +++ b/Swiften/Parser/PayloadParsers/FormParser.h @@ -85,7 +85,7 @@ namespace Swift { name##FormFieldParseHelper() : baseParser##FieldParseHelper() { \ field = name##FormField::create(); \ } \ - }; + } SWIFTEN_DECLARE_FORM_FIELD_PARSE_HELPER(Boolean, Bool); SWIFTEN_DECLARE_FORM_FIELD_PARSE_HELPER(Fixed, String); diff --git a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp index a3dfd12..cfdccf9 100644 --- a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp +++ b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp @@ -18,7 +18,7 @@ namespace Swift { void JingleIBBTransportMethodPayloadParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) { try { - getPayloadInternal()->setBlockSize(boost::lexical_cast<int>(attributes.getAttributeValue("block-size").get_value_or("0"))); + getPayloadInternal()->setBlockSize(boost::lexical_cast<unsigned int>(attributes.getAttributeValue("block-size").get_value_or("0"))); } catch (boost::bad_lexical_cast &) { getPayloadInternal()->setBlockSize(0); } diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp index 0a13844..cc69348 100644 --- a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp +++ b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp @@ -35,7 +35,7 @@ void StreamInitiationFileInfoParser::handleStartElement(const std::string& eleme } else { parseDescription = false; if (element == "range") { - int offset = 0; + boost::uintmax_t offset = 0; try { offset = boost::lexical_cast<boost::uintmax_t>(attributes.getAttributeValue("offset").get_value_or("0")); } catch (boost::bad_lexical_cast &) { diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp index fd3d019..20bad8c 100644 --- a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp +++ b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -40,7 +40,7 @@ void StreamInitiationParser::handleStartElement(const std::string& element, cons currentFile = StreamInitiationFileInfo(); currentFile.setName(attributes.getAttribute("name")); try { - currentFile.setSize(boost::lexical_cast<int>(attributes.getAttribute("size"))); + currentFile.setSize(boost::lexical_cast<unsigned long long>(attributes.getAttribute("size"))); } catch (boost::bad_lexical_cast&) { } diff --git a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp index 8719a5d..39ec98a 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp @@ -121,7 +121,7 @@ class JingleParserTest : public CppUnit::TestFixture { JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>(); CPPUNIT_ASSERT(transportPaylod); - CPPUNIT_ASSERT_EQUAL(4096, transportPaylod->getBlockSize()); + CPPUNIT_ASSERT_EQUAL(4096U, transportPaylod->getBlockSize()); CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID()); } @@ -158,7 +158,7 @@ class JingleParserTest : public CppUnit::TestFixture { JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>(); CPPUNIT_ASSERT(transportPaylod); - CPPUNIT_ASSERT_EQUAL(2048, transportPaylod->getBlockSize()); + CPPUNIT_ASSERT_EQUAL(2048U, transportPaylod->getBlockSize()); CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID()); } @@ -191,7 +191,7 @@ class JingleParserTest : public CppUnit::TestFixture { JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>(); CPPUNIT_ASSERT(transportPaylod); - CPPUNIT_ASSERT_EQUAL(2048, transportPaylod->getBlockSize()); + CPPUNIT_ASSERT_EQUAL(2048U, transportPaylod->getBlockSize()); CPPUNIT_ASSERT_EQUAL(std::string("bt8a71h6"), transportPaylod->getSessionID()); } @@ -468,7 +468,7 @@ class JingleParserTest : public CppUnit::TestFixture { StreamInitiationFileInfo file = content->getDescription<JingleFileTransferDescription>()->getRequests()[0]; CPPUNIT_ASSERT_EQUAL(std::string("552da749930852c69ae5d2141d3766b1"), file.getHash()); - CPPUNIT_ASSERT_EQUAL(static_cast<boost::uintmax_t>(270336), file.getRangeOffset()); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned long long>(270336), file.getRangeOffset()); CPPUNIT_ASSERT_EQUAL(true, file.getSupportsRangeRequests()); } diff --git a/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp index f1e6635..eda2547 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp @@ -7,6 +7,8 @@ #include <Swiften/Base/ByteArray.h> #include <QA/Checker/IO.h> +#include <boost/date_time/posix_time/posix_time.hpp> + #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> @@ -48,8 +50,36 @@ class VCardParserTest : public CppUnit::TestFixture { "<WORK/>" "<X400/>" "</EMAIL>" + "<TEL>" + "<NUMBER>555-6273</NUMBER>" + "<HOME/>" + "<VOICE/>" + "</TEL>" + "<ADR>" + "<LOCALITY>Any Town</LOCALITY>" + "<STREET>Fake Street 123</STREET>" + "<PCODE>12345</PCODE>" + "<CTRY>USA</CTRY>" + "<HOME/>" + "</ADR>" + "<LABEL>" + "<LINE>Fake Street 123</LINE>" + "<LINE>12345 Any Town</LINE>" + "<LINE>USA</LINE>" + "<HOME/>" + "</LABEL>" "<NICKNAME>DreamGirl</NICKNAME>" - "<BDAY>1234</BDAY>" + "<BDAY>1865-05-04</BDAY>" + "<JID>alice@teaparty.lit</JID>" + "<JID>alice@wonderland.lit</JID>" + "<DESC>I once fell down a rabbit hole.</DESC>" + "<ORG>" + "<ORGNAME>Alice In Wonderland Inc.</ORGNAME>" + "</ORG>" + "<TITLE>Some Title</TITLE>" + "<ROLE>Main Character</ROLE>" + "<URL>http://wonderland.lit/~alice</URL>" + "<URL>http://teaparty.lit/~alice2</URL>" "<MAILER>mutt</MAILER>" "</vCard>")); @@ -62,7 +92,7 @@ class VCardParserTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(std::string("Mrs"), payload->getPrefix()); CPPUNIT_ASSERT_EQUAL(std::string("PhD"), payload->getSuffix()); CPPUNIT_ASSERT_EQUAL(std::string("DreamGirl"), payload->getNickname()); - CPPUNIT_ASSERT_EQUAL(std::string("<BDAY xmlns=\"vcard-temp\">1234</BDAY><MAILER xmlns=\"vcard-temp\">mutt</MAILER>"), payload->getUnknownContent()); + CPPUNIT_ASSERT_EQUAL(boost::posix_time::ptime(boost::gregorian::date(1865, 5, 4)), payload->getBirthday()); CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getEMailAddresses().size())); CPPUNIT_ASSERT_EQUAL(std::string("alice@wonderland.lit"), payload->getEMailAddresses()[0].address); CPPUNIT_ASSERT(payload->getEMailAddresses()[0].isHome); @@ -76,6 +106,45 @@ class VCardParserTest : public CppUnit::TestFixture { CPPUNIT_ASSERT(!payload->getEMailAddresses()[1].isPreferred); CPPUNIT_ASSERT(payload->getEMailAddresses()[1].isWork); CPPUNIT_ASSERT(payload->getEMailAddresses()[1].isX400); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getTelephones().size())); + CPPUNIT_ASSERT_EQUAL(std::string("555-6273"), payload->getTelephones()[0].number); + CPPUNIT_ASSERT(payload->getTelephones()[0].isHome); + CPPUNIT_ASSERT(payload->getTelephones()[0].isVoice); + CPPUNIT_ASSERT(!payload->getTelephones()[0].isPreferred); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getAddresses().size())); + CPPUNIT_ASSERT_EQUAL(std::string("Any Town"), payload->getAddresses()[0].locality); + CPPUNIT_ASSERT_EQUAL(std::string("Fake Street 123"), payload->getAddresses()[0].street); + CPPUNIT_ASSERT_EQUAL(std::string("12345"), payload->getAddresses()[0].postalCode); + CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getAddresses()[0].country); + CPPUNIT_ASSERT(payload->getAddresses()[0].isHome); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getAddressLabels().size())); + CPPUNIT_ASSERT_EQUAL(std::string("Fake Street 123"), payload->getAddressLabels()[0].lines[0]); + CPPUNIT_ASSERT_EQUAL(std::string("12345 Any Town"), payload->getAddressLabels()[0].lines[1]); + CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getAddressLabels()[0].lines[2]); + CPPUNIT_ASSERT(payload->getAddressLabels()[0].isHome); + + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getJIDs().size())); + CPPUNIT_ASSERT_EQUAL(JID("alice@teaparty.lit"), payload->getJIDs()[0]); + CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit"), payload->getJIDs()[1]); + + CPPUNIT_ASSERT_EQUAL(std::string("I once fell down a rabbit hole."), payload->getDescription()); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getOrganizations().size())); + CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland Inc."), payload->getOrganizations()[0].name); + CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(payload->getOrganizations()[0].units.size())); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getTitles().size())); + CPPUNIT_ASSERT_EQUAL(std::string("Some Title"), payload->getTitles()[0]); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getRoles().size())); + CPPUNIT_ASSERT_EQUAL(std::string("Main Character"), payload->getRoles()[0]); + CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getURLs().size())); + CPPUNIT_ASSERT_EQUAL(std::string("http://wonderland.lit/~alice"), payload->getURLs()[0]); + CPPUNIT_ASSERT_EQUAL(std::string("http://teaparty.lit/~alice2"), payload->getURLs()[1]); + + CPPUNIT_ASSERT_EQUAL(std::string("<MAILER xmlns=\"vcard-temp\">mutt</MAILER>"), payload->getUnknownContent()); } void testParse_Photo() { diff --git a/Swiften/Parser/PayloadParsers/VCardParser.cpp b/Swiften/Parser/PayloadParsers/VCardParser.cpp index 553d26a..620a307 100644 --- a/Swiften/Parser/PayloadParsers/VCardParser.cpp +++ b/Swiften/Parser/PayloadParsers/VCardParser.cpp @@ -6,6 +6,7 @@ #include <Swiften/Parser/PayloadParsers/VCardParser.h> #include <Swiften/Base/foreach.h> +#include <Swiften/Base/DateTime.h> #include <Swiften/StringCodecs/Base64.h> #include <Swiften/Parser/SerializingParser.h> @@ -20,6 +21,18 @@ void VCardParser::handleStartElement(const std::string& element, const std::stri if (elementHierarchy == "/vCard/EMAIL") { currentEMailAddress_ = VCard::EMailAddress(); } + if (elementHierarchy == "/vCard/TEL") { + currentTelephone_ = VCard::Telephone(); + } + if (elementHierarchy == "/vCard/ADR") { + currentAddress_ = VCard::Address(); + } + if (elementHierarchy == "/vCard/LABEL") { + currentAddressLabel_ = VCard::AddressLabel(); + } + if (elementHierarchy == "/vCard/ORG") { + currentOrganization_ = VCard::Organization(); + } if (elementStack_.size() == 2) { assert(!unknownContentParser_); unknownContentParser_ = new SerializingParser(); @@ -90,9 +103,160 @@ void VCardParser::handleEndElement(const std::string& element, const std::string else if (elementHierarchy == "/vCard/EMAIL/PREF") { currentEMailAddress_.isPreferred = true; } - else if (elementHierarchy == "/vCard/EMAIL") { + else if (elementHierarchy == "/vCard/EMAIL" && !currentEMailAddress_.address.empty()) { getPayloadInternal()->addEMailAddress(currentEMailAddress_); } + else if (elementHierarchy == "/vCard/BDAY" && !currentText_.empty()) { + getPayloadInternal()->setBirthday(stringToDateTime(currentText_)); + } + else if (elementHierarchy == "/vCard/TEL/NUMBER") { + currentTelephone_.number = currentText_; + } + else if (elementHierarchy == "/vCard/TEL/HOME") { + currentTelephone_.isHome = true; + } + else if (elementHierarchy == "/vCard/TEL/WORK") { + currentTelephone_.isWork = true; + } + else if (elementHierarchy == "/vCard/TEL/VOICE") { + currentTelephone_.isVoice = true; + } + else if (elementHierarchy == "/vCard/TEL/FAX") { + currentTelephone_.isFax = true; + } + else if (elementHierarchy == "/vCard/TEL/PAGER") { + currentTelephone_.isPager = true; + } + else if (elementHierarchy == "/vCard/TEL/MSG") { + currentTelephone_.isMSG = true; + } + else if (elementHierarchy == "/vCard/TEL/CELL") { + currentTelephone_.isCell = true; + } + else if (elementHierarchy == "/vCard/TEL/VIDEO") { + currentTelephone_.isVideo = true; + } + else if (elementHierarchy == "/vCard/TEL/BBS") { + currentTelephone_.isBBS = true; + } + else if (elementHierarchy == "/vCard/TEL/MODEM") { + currentTelephone_.isModem = true; + } + else if (elementHierarchy == "/vCard/TEL/ISDN") { + currentTelephone_.isISDN = true; + } + else if (elementHierarchy == "/vCard/TEL/PCS") { + currentTelephone_.isPCS = true; + } + else if (elementHierarchy == "/vCard/TEL/PREF") { + currentTelephone_.isPreferred = true; + } + else if (elementHierarchy == "/vCard/TEL" && !currentTelephone_.number.empty()) { + getPayloadInternal()->addTelephone(currentTelephone_); + } + else if (elementHierarchy == "/vCard/ADR/HOME") { + currentAddress_.isHome = true; + } + else if (elementHierarchy == "/vCard/ADR/WORK") { + currentAddress_.isWork = true; + } + else if (elementHierarchy == "/vCard/ADR/POSTAL") { + currentAddress_.isPostal = true; + } + else if (elementHierarchy == "/vCard/ADR/PARCEL") { + currentAddress_.isParcel = true; + } + else if (elementHierarchy == "/vCard/ADR/DOM") { + currentAddress_.deliveryType = VCard::DomesticDelivery; + } + else if (elementHierarchy == "/vCard/ADR/INTL") { + currentAddress_.deliveryType = VCard::InternationalDelivery; + } + else if (elementHierarchy == "/vCard/ADR/PREF") { + currentAddress_.isPreferred = true; + } + else if (elementHierarchy == "/vCard/ADR/POBOX") { + currentAddress_.poBox = currentText_; + } + else if (elementHierarchy == "/vCard/ADR/EXTADD") { + currentAddress_.addressExtension = currentText_; + } + else if (elementHierarchy == "/vCard/ADR/STREET") { + currentAddress_.street = currentText_; + } + else if (elementHierarchy == "/vCard/ADR/LOCALITY") { + currentAddress_.locality = currentText_; + } + else if (elementHierarchy == "/vCard/ADR/REGION") { + currentAddress_.region = currentText_; + } + else if (elementHierarchy == "/vCard/ADR/PCODE") { + currentAddress_.postalCode = currentText_; + } + else if (elementHierarchy == "/vCard/ADR/CTRY") { + currentAddress_.country = currentText_; + } + else if (elementHierarchy == "/vCard/ADR") { + if (!currentAddress_.poBox.empty() || !currentAddress_.addressExtension.empty() || + !currentAddress_.street.empty() || !currentAddress_.locality.empty() || + !currentAddress_.region.empty() || !currentAddress_.region.empty() || + !currentAddress_.postalCode.empty() || !currentAddress_.country.empty()) { + getPayloadInternal()->addAddress(currentAddress_); + } + } + else if (elementHierarchy == "/vCard/LABEL/HOME") { + currentAddressLabel_.isHome = true; + } + else if (elementHierarchy == "/vCard/LABEL/WORK") { + currentAddressLabel_.isWork = true; + } + else if (elementHierarchy == "/vCard/LABEL/POSTAL") { + currentAddressLabel_.isPostal = true; + } + else if (elementHierarchy == "/vCard/LABEL/PARCEL") { + currentAddressLabel_.isParcel = true; + } + else if (elementHierarchy == "/vCard/LABEL/DOM") { + currentAddressLabel_.deliveryType = VCard::DomesticDelivery; + } + else if (elementHierarchy == "/vCard/LABEL/INTL") { + currentAddressLabel_.deliveryType = VCard::InternationalDelivery; + } + else if (elementHierarchy == "/vCard/LABEL/PREF") { + currentAddressLabel_.isPreferred = true; + } + else if (elementHierarchy == "/vCard/LABEL/LINE") { + currentAddressLabel_.lines.push_back(currentText_); + } + else if (elementHierarchy == "/vCard/LABEL") { + getPayloadInternal()->addAddressLabel(currentAddressLabel_); + } + else if (elementHierarchy == "/vCard/JID" && !currentText_.empty()) { + getPayloadInternal()->addJID(JID(currentText_)); + } + else if (elementHierarchy == "/vCard/DESC") { + getPayloadInternal()->setDescription(currentText_); + } + else if (elementHierarchy == "/vCard/ORG/ORGNAME") { + currentOrganization_.name = currentText_; + } + else if (elementHierarchy == "/vCard/ORG/ORGUNIT" && !currentText_.empty()) { + currentOrganization_.units.push_back(currentText_); + } + else if (elementHierarchy == "/vCard/ORG") { + if (!currentOrganization_.name.empty() || !currentOrganization_.units.empty()) { + getPayloadInternal()->addOrganization(currentOrganization_); + } + } + else if (elementHierarchy == "/vCard/TITLE" && !currentText_.empty()) { + getPayloadInternal()->addTitle(currentText_); + } + else if (elementHierarchy == "/vCard/ROLE" && !currentText_.empty()) { + getPayloadInternal()->addRole(currentText_); + } + else if (elementHierarchy == "/vCard/URL" && !currentText_.empty()) { + getPayloadInternal()->addURL(currentText_); + } else if (elementStack_.size() == 2 && unknownContentParser_) { getPayloadInternal()->addUnknownContent(unknownContentParser_->getResult()); } diff --git a/Swiften/Parser/PayloadParsers/VCardParser.h b/Swiften/Parser/PayloadParsers/VCardParser.h index b1c47a3..f10d639 100644 --- a/Swiften/Parser/PayloadParsers/VCardParser.h +++ b/Swiften/Parser/PayloadParsers/VCardParser.h @@ -28,6 +28,10 @@ namespace Swift { private: std::vector<std::string> elementStack_; VCard::EMailAddress currentEMailAddress_; + VCard::Telephone currentTelephone_; + VCard::Address currentAddress_; + VCard::AddressLabel currentAddressLabel_; + VCard::Organization currentOrganization_; SerializingParser* unknownContentParser_; std::string currentText_; }; diff --git a/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp b/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp index 09d8de9..a480813 100644 --- a/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp +++ b/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp @@ -83,8 +83,8 @@ namespace Swift { std::string pathData = attributes.getAttributeValue("d").get_value_or(""); std::vector<std::pair<int, int> > points; if (pathData[0] == 'M') { - unsigned int pos = 1; - unsigned int npos; + size_t pos = 1; + size_t npos; int x, y; if (pathData[pos] == ' ') { pos++; @@ -163,8 +163,8 @@ namespace Swift { std::string pointsData = attributes.getAttributeValue("points").get_value_or(""); std::vector<std::pair<int, int> > points; - unsigned int pos = 0; - unsigned int npos; + size_t pos = 0; + size_t npos; int x, y; try { while (pos < pointsData.size()) { diff --git a/Swiften/Parser/Tree/ParserElement.cpp b/Swiften/Parser/Tree/ParserElement.cpp index 9d9b9b6..e5f8bc8 100644 --- a/Swiften/Parser/Tree/ParserElement.cpp +++ b/Swiften/Parser/Tree/ParserElement.cpp @@ -9,8 +9,12 @@ #include <Swiften/Parser/Tree/NullParserElement.h> #include <iostream> +#include <boost/lambda/lambda.hpp> +#include <boost/lambda/bind.hpp> -namespace Swift{ +namespace lambda = boost::lambda; + +namespace Swift { ParserElement::ParserElement(const std::string& name, const std::string& xmlns, const AttributeMap& attributes) : name_(name), xmlns_(xmlns), attributes_(attributes) { } @@ -28,19 +32,10 @@ void ParserElement::appendCharacterData(const std::string& data) { text_ += data; } -struct DoesntMatch { - public: - DoesntMatch(const std::string& tagName, const std::string& ns) : tagName(tagName), ns(ns) {} - bool operator()(ParserElement::ref element) { return element->getName() != tagName || element->getNamespace() != ns; } - private: - std::string tagName; - std::string ns; -}; - - std::vector<ParserElement::ref> ParserElement::getChildren(const std::string& name, const std::string& xmlns) const { std::vector<ParserElement::ref> result; - std::remove_copy_if(children_.begin(), children_.end(), std::back_inserter(result), DoesntMatch(name, xmlns)); + std::remove_copy_if(children_.begin(), children_.end(), std::back_inserter(result), + lambda::bind(&ParserElement::getName, *lambda::_1) != name || lambda::bind(&ParserElement::getNamespace, *lambda::_1) != xmlns); return result; } diff --git a/Swiften/QA/ClientTest/ClientTest.cpp b/Swiften/QA/ClientTest/ClientTest.cpp index 397921a..e88e5ac 100644 --- a/Swiften/QA/ClientTest/ClientTest.cpp +++ b/Swiften/QA/ClientTest/ClientTest.cpp @@ -18,19 +18,19 @@ using namespace Swift; -SimpleEventLoop eventLoop; -BoostNetworkFactories networkFactories(&eventLoop); +static SimpleEventLoop eventLoop; +static BoostNetworkFactories networkFactories(&eventLoop); -Client* client = 0; -bool rosterReceived = false; +static Client* client = 0; +static bool rosterReceived = false; enum TestStage { FirstConnect, Reconnect }; -TestStage stage; -ClientOptions options; +static TestStage stage; +static ClientOptions options; -void handleDisconnected(boost::optional<ClientError> e) { +static void handleDisconnected(boost::optional<ClientError> e) { std::cout << "Disconnected: " << e << std::endl; if (stage == FirstConnect) { stage = Reconnect; @@ -41,13 +41,13 @@ void handleDisconnected(boost::optional<ClientError> e) { } } -void handleRosterReceived(boost::shared_ptr<Payload>) { +static void handleRosterReceived(boost::shared_ptr<Payload>) { rosterReceived = true; std::cout << "Disconnecting" << std::endl; client->disconnect(); } -void handleConnected() { +static void handleConnected() { std::cout << "Connected" << std::endl; rosterReceived = false; GetRosterRequest::ref rosterRequest = GetRosterRequest::create(client->getIQRouter()); diff --git a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp index 335f2d2..2accd9c 100644 --- a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp +++ b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp @@ -18,7 +18,7 @@ #include <Swiften/Network/BoostIOServiceThread.h> #include <Swiften/EventLoop/DummyEventLoop.h> -const unsigned char* address = reinterpret_cast<const unsigned char*>("\x41\x63\xde\x89"); +static const unsigned char* address = reinterpret_cast<const unsigned char*>("\x41\x63\xde\x89"); using namespace Swift; diff --git a/Swiften/SASL/DIGESTMD5Properties.cpp b/Swiften/SASL/DIGESTMD5Properties.cpp index 6d406e0..23a3476 100644 --- a/Swiften/SASL/DIGESTMD5Properties.cpp +++ b/Swiften/SASL/DIGESTMD5Properties.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -48,13 +48,13 @@ DIGESTMD5Properties DIGESTMD5Properties::parse(const ByteArray& data) { ByteArray currentKey; ByteArray currentValue; for (size_t i = 0; i < data.size(); ++i) { - char c = data[i]; + char c = static_cast<char>(data[i]); if (inKey) { if (c == '=') { inKey = false; } else { - currentKey.push_back(c); + currentKey.push_back(static_cast<unsigned char>(c)); } } else { @@ -71,7 +71,7 @@ DIGESTMD5Properties DIGESTMD5Properties::parse(const ByteArray& data) { currentValue = ByteArray(); } else { - currentValue.push_back(c); + currentValue.push_back(static_cast<unsigned char>(c)); } } } diff --git a/Swiften/SASL/PLAINMessage.cpp b/Swiften/SASL/PLAINMessage.cpp index 20ffea7..c43b446 100644 --- a/Swiften/SASL/PLAINMessage.cpp +++ b/Swiften/SASL/PLAINMessage.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -15,7 +15,7 @@ PLAINMessage::PLAINMessage(const std::string& authcid, const SafeByteArray& pass PLAINMessage::PLAINMessage(const SafeByteArray& value) { size_t i = 0; while (i < value.size() && value[i] != '\0') { - authzid += value[i]; + authzid += static_cast<char>(value[i]); ++i; } if (i == value.size()) { @@ -23,7 +23,7 @@ PLAINMessage::PLAINMessage(const SafeByteArray& value) { } ++i; while (i < value.size() && value[i] != '\0') { - authcid += value[i]; + authcid += static_cast<char>(value[i]); ++i; } if (i == value.size()) { diff --git a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp index 98460b1..09e202e 100644 --- a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp +++ b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp @@ -131,7 +131,7 @@ std::map<char, std::string> SCRAMSHA1ClientAuthenticator::parseMap(const std::st i++; } else if (s[i] == ',') { - result[static_cast<size_t>(key)] = value; + result[key] = value; value = ""; expectKey = true; } diff --git a/Swiften/SConscript b/Swiften/SConscript index 2111d26..b68dfec 100644 --- a/Swiften/SConscript +++ b/Swiften/SConscript @@ -128,6 +128,7 @@ if env["SCONS_STAGE"] == "build" : "Elements/RosterItemExchangePayload.cpp", "Elements/RosterPayload.cpp", "Elements/Stanza.cpp", + "Elements/StanzaAck.cpp", "Elements/StatusShow.cpp", "Elements/StreamManagementEnabled.cpp", "Elements/StreamResume.cpp", diff --git a/Swiften/Serializer/PayloadSerializers/BlockSerializer.h b/Swiften/Serializer/PayloadSerializers/BlockSerializer.h index 345463c..10ae8b0 100644 --- a/Swiften/Serializer/PayloadSerializers/BlockSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/BlockSerializer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -10,7 +10,6 @@ #include <Swiften/Serializer/GenericPayloadSerializer.h> #include <Swiften/Serializer/XML/XMLElement.h> -#include <Swiften/Base/foreach.h> namespace Swift { template<typename BLOCK_ELEMENT> @@ -19,11 +18,12 @@ namespace Swift { BlockSerializer(std::string tag) : GenericPayloadSerializer<BLOCK_ELEMENT>(), tag(tag) { } - virtual std::string serializePayload(boost::shared_ptr<BLOCK_ELEMENT> payload) const { + virtual std::string serializePayload(boost::shared_ptr<BLOCK_ELEMENT> payload) const { XMLElement element(tag, "urn:xmpp:blocking"); - foreach (const JID& jid, payload->getItems()) { + const std::vector<JID>& items = payload->getItems(); + for (std::vector<JID>::const_iterator i = items.begin(); i != items.end(); ++i) { boost::shared_ptr<XMLElement> item = boost::make_shared<XMLElement>("item"); - item->setAttribute("jid", jid); + item->setAttribute("jid", *i); } return element.serialize(); } diff --git a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp index ee468bb..d23cad7 100644 --- a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp @@ -19,7 +19,6 @@ std::string ChatStateSerializer::serializePayload(boost::shared_ptr<ChatState> c case ChatState::Paused: result += "paused"; break; case ChatState::Inactive: result += "inactive"; break; case ChatState::Gone: result += "gone"; break; - default: result += "gone"; break; } result += " xmlns=\"http://jabber.org/protocol/chatstates\"/>"; return result; diff --git a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp index fa6a566..954b885 100644 --- a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp @@ -20,7 +20,7 @@ std::string ErrorSerializer::serializePayload(boost::shared_ptr<ErrorPayload> er case ErrorPayload::Modify: result += "modify"; break; case ErrorPayload::Auth: result += "auth"; break; case ErrorPayload::Wait: result += "wait"; break; - default: result += "cancel"; break; + case ErrorPayload::Cancel: result += "cancel"; break; } result += "\">"; @@ -47,7 +47,7 @@ std::string ErrorSerializer::serializePayload(boost::shared_ptr<ErrorPayload> er case ErrorPayload::ServiceUnavailable: conditionElement = "service-unavailable"; break; case ErrorPayload::SubscriptionRequired: conditionElement = "subscription-required"; break; case ErrorPayload::UnexpectedRequest: conditionElement = "unexpected-request"; break; - default: conditionElement = "undefined-condition"; break; + case ErrorPayload::UndefinedCondition: conditionElement = "undefined-condition"; break; } result += "<" + conditionElement + " xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"; diff --git a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp index e78cdb4..c83b293 100644 --- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp @@ -8,6 +8,7 @@ #include <boost/shared_ptr.hpp> #include <boost/smart_ptr/make_shared.hpp> +#include <cassert> #include <boost/lexical_cast.hpp> #include <Swiften/Base/foreach.h> @@ -48,6 +49,7 @@ std::string IBBSerializer::serializePayload(boost::shared_ptr<IBB> ibb) const { return ibbElement.serialize(); } } + assert(false); return ""; } diff --git a/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h index 2b5ffcc..2f2623f 100644 --- a/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h @@ -23,7 +23,6 @@ namespace Swift { case MUCOccupant::Member: result = "member"; break; case MUCOccupant::Outcast: result = "outcast"; break; case MUCOccupant::NoAffiliation: result = "none"; break; - default: assert(false); } return result; } @@ -35,7 +34,6 @@ namespace Swift { case MUCOccupant::NoRole: result = "none"; break; case MUCOccupant::Participant: result = "participant"; break; case MUCOccupant::Visitor: result = "visitor"; break; - default: assert(false); } return result; diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp index 3ac1d77..01c8e77 100644 --- a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp @@ -31,14 +31,15 @@ class VCardSerializerTest : public CppUnit::TestFixture vcard->setNickname("DreamGirl"); vcard->setPhoto(createByteArray("abcdef")); vcard->setPhotoType("image/png"); - vcard->addUnknownContent("<BDAY>1234</BDAY><MAILER>mutt</MAILER>"); + vcard->setBirthday(boost::posix_time::ptime(boost::gregorian::date(1865, 5, 4))); + vcard->addUnknownContent("<MAILER>mutt</MAILER>"); - VCard::EMailAddress address1; - address1.address = "alice@wonderland.lit"; - address1.isHome = true; - address1.isPreferred = true; - address1.isInternet = true; - vcard->addEMailAddress(address1); + VCard::EMailAddress emailAddress1; + emailAddress1.address = "alice@wonderland.lit"; + emailAddress1.isHome = true; + emailAddress1.isPreferred = true; + emailAddress1.isInternet = true; + vcard->addEMailAddress(emailAddress1); VCard::EMailAddress address2; address2.address = "alice@teaparty.lit"; @@ -46,6 +47,41 @@ class VCardSerializerTest : public CppUnit::TestFixture address2.isX400 = true; vcard->addEMailAddress(address2); + VCard::Telephone telephone1; + telephone1.number = "555-6273"; + telephone1.isHome = true; + telephone1.isVoice = true; + vcard->addTelephone(telephone1); + + VCard::Address address1; + address1.locality = "Any Town"; + address1.street = "Fake Street 123"; + address1.postalCode = "12345"; + address1.country = "USA"; + address1.isHome = true; + vcard->addAddress(address1); + + VCard::AddressLabel label1; + label1.lines.push_back("Fake Street 123"); + label1.lines.push_back("12345 Any Town"); + label1.lines.push_back("USA"); + label1.isHome = true; + vcard->addAddressLabel(label1); + + vcard->addJID(JID("alice@teaparty.lit")); + vcard->addJID(JID("alice@wonderland.lit")); + + vcard->setDescription("I once fell down a rabbit hole."); + + VCard::Organization org1; + org1.name = "Alice In Wonderland Inc."; + vcard->addOrganization(org1); + + vcard->addTitle("Some Title"); + vcard->addRole("Main Character"); + vcard->addURL("http://wonderland.lit/~alice"); + vcard->addURL("http://teaparty.lit/~alice2"); + std::string expectedResult = "<vCard xmlns=\"vcard-temp\">" "<VERSION>2.0</VERSION>" @@ -73,7 +109,35 @@ class VCardSerializerTest : public CppUnit::TestFixture "<TYPE>image/png</TYPE>" "<BINVAL>YWJjZGVm</BINVAL>" "</PHOTO>" - "<BDAY>1234</BDAY>" + "<BDAY>1865-05-04T00:00:00Z</BDAY>" + "<TEL>" + "<NUMBER>555-6273</NUMBER>" + "<HOME/>" + "<VOICE/>" + "</TEL>" + "<ADR>" + "<STREET>Fake Street 123</STREET>" + "<LOCALITY>Any Town</LOCALITY>" + "<PCODE>12345</PCODE>" + "<CTRY>USA</CTRY>" + "<HOME/>" + "</ADR>" + "<LABEL>" + "<LINE>Fake Street 123</LINE>" + "<LINE>12345 Any Town</LINE>" + "<LINE>USA</LINE>" + "<HOME/>" + "</LABEL>" + "<JID>alice@teaparty.lit</JID>" + "<JID>alice@wonderland.lit</JID>" + "<DESC>I once fell down a rabbit hole.</DESC>" + "<ORG>" + "<ORGNAME>Alice In Wonderland Inc.</ORGNAME>" + "</ORG>" + "<TITLE>Some Title</TITLE>" + "<ROLE>Main Character</ROLE>" + "<URL>http://wonderland.lit/~alice</URL>" + "<URL>http://teaparty.lit/~alice2</URL>" "<MAILER>mutt</MAILER>" "</vCard>"; diff --git a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp index 1512c6c..22d59b4 100644 --- a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp @@ -13,6 +13,7 @@ #include <Swiften/Serializer/XML/XMLTextNode.h> #include <Swiften/Serializer/XML/XMLRawTextNode.h> #include <Swiften/StringCodecs/Base64.h> +#include <Swiften/Base/DateTime.h> #include <Swiften/Base/foreach.h> namespace Swift { @@ -23,49 +24,33 @@ VCardSerializer::VCardSerializer() : GenericPayloadSerializer<VCard>() { std::string VCardSerializer::serializePayload(boost::shared_ptr<VCard> vcard) const { XMLElement queryElement("vCard", "vcard-temp"); if (!vcard->getVersion().empty()) { - boost::shared_ptr<XMLElement> versionElement(new XMLElement("VERSION")); - versionElement->addNode(boost::make_shared<XMLTextNode>(vcard->getVersion())); - queryElement.addNode(versionElement); + queryElement.addNode(boost::make_shared<XMLElement>("VERSION", "", vcard->getVersion())); } if (!vcard->getFullName().empty()) { - boost::shared_ptr<XMLElement> fullNameElement(new XMLElement("FN")); - fullNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getFullName())); - queryElement.addNode(fullNameElement); + queryElement.addNode(boost::make_shared<XMLElement>("FN", "", vcard->getFullName())); } if (!vcard->getGivenName().empty() || !vcard->getFamilyName().empty() || !vcard->getMiddleName().empty() || !vcard->getPrefix().empty() || !vcard->getSuffix().empty()) { boost::shared_ptr<XMLElement> nameElement(new XMLElement("N")); if (!vcard->getFamilyName().empty()) { - boost::shared_ptr<XMLElement> familyNameElement(new XMLElement("FAMILY")); - familyNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getFamilyName())); - nameElement->addNode(familyNameElement); + nameElement->addNode(boost::make_shared<XMLElement>("FAMILY", "", vcard->getFamilyName())); } if (!vcard->getGivenName().empty()) { - boost::shared_ptr<XMLElement> givenNameElement(new XMLElement("GIVEN")); - givenNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getGivenName())); - nameElement->addNode(givenNameElement); + nameElement->addNode(boost::make_shared<XMLElement>("GIVEN", "", vcard->getGivenName())); } if (!vcard->getMiddleName().empty()) { - boost::shared_ptr<XMLElement> middleNameElement(new XMLElement("MIDDLE")); - middleNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getMiddleName())); - nameElement->addNode(middleNameElement); + nameElement->addNode(boost::make_shared<XMLElement>("MIDDLE", "", vcard->getMiddleName())); } if (!vcard->getPrefix().empty()) { - boost::shared_ptr<XMLElement> prefixElement(new XMLElement("PREFIX")); - prefixElement->addNode(boost::make_shared<XMLTextNode>(vcard->getPrefix())); - nameElement->addNode(prefixElement); + nameElement->addNode(boost::make_shared<XMLElement>("PREFIX", "", vcard->getPrefix())); } if (!vcard->getSuffix().empty()) { - boost::shared_ptr<XMLElement> suffixElement(new XMLElement("SUFFIX")); - suffixElement->addNode(boost::make_shared<XMLTextNode>(vcard->getSuffix())); - nameElement->addNode(suffixElement); + nameElement->addNode(boost::make_shared<XMLElement>("SUFFIX", "", vcard->getSuffix())); } queryElement.addNode(nameElement); } foreach(const VCard::EMailAddress& emailAddress, vcard->getEMailAddresses()) { boost::shared_ptr<XMLElement> emailElement(new XMLElement("EMAIL")); - boost::shared_ptr<XMLElement> userIDElement(new XMLElement("USERID")); - userIDElement->addNode(boost::make_shared<XMLTextNode>(emailAddress.address)); - emailElement->addNode(userIDElement); + emailElement->addNode(boost::make_shared<XMLElement>("USERID", "", emailAddress.address)); if (emailAddress.isHome) { emailElement->addNode(boost::make_shared<XMLElement>("HOME")); } @@ -84,24 +69,179 @@ std::string VCardSerializer::serializePayload(boost::shared_ptr<VCard> vcard) c queryElement.addNode(emailElement); } if (!vcard->getNickname().empty()) { - boost::shared_ptr<XMLElement> nickElement(new XMLElement("NICKNAME")); - nickElement->addNode(boost::make_shared<XMLTextNode>(vcard->getNickname())); - queryElement.addNode(nickElement); + queryElement.addNode(boost::make_shared<XMLElement>("NICKNAME", "", vcard->getNickname())); } if (!vcard->getPhoto().empty() || !vcard->getPhotoType().empty()) { XMLElement::ref photoElement(new XMLElement("PHOTO")); if (!vcard->getPhotoType().empty()) { - XMLElement::ref typeElement(new XMLElement("TYPE")); - typeElement->addNode(XMLTextNode::ref(new XMLTextNode(vcard->getPhotoType()))); - photoElement->addNode(typeElement); + photoElement->addNode(boost::make_shared<XMLElement>("TYPE", "", vcard->getPhotoType())); } if (!vcard->getPhoto().empty()) { - XMLElement::ref binvalElement(new XMLElement("BINVAL")); - binvalElement->addNode(XMLTextNode::ref(new XMLTextNode(Base64::encode(vcard->getPhoto())))); - photoElement->addNode(binvalElement); + photoElement->addNode(boost::make_shared<XMLElement>("BINVAL", "", Base64::encode(vcard->getPhoto()))); } queryElement.addNode(photoElement); } + if (!vcard->getBirthday().is_not_a_date_time()) { + queryElement.addNode(boost::make_shared<XMLElement>("BDAY", "", dateTimeToString(vcard->getBirthday()))); + } + + foreach(const VCard::Telephone& telephone, vcard->getTelephones()) { + boost::shared_ptr<XMLElement> telElement(new XMLElement("TEL")); + telElement->addNode(boost::make_shared<XMLElement>("NUMBER", "", telephone.number)); + if (telephone.isHome) { + telElement->addNode(boost::make_shared<XMLElement>("HOME")); + } + if (telephone.isWork) { + telElement->addNode(boost::make_shared<XMLElement>("WORK")); + } + if (telephone.isVoice) { + telElement->addNode(boost::make_shared<XMLElement>("VOICE")); + } + if (telephone.isFax) { + telElement->addNode(boost::make_shared<XMLElement>("FAX")); + } + if (telephone.isPager) { + telElement->addNode(boost::make_shared<XMLElement>("PAGER")); + } + if (telephone.isMSG) { + telElement->addNode(boost::make_shared<XMLElement>("MSG")); + } + if (telephone.isCell) { + telElement->addNode(boost::make_shared<XMLElement>("CELL")); + } + if (telephone.isVideo) { + telElement->addNode(boost::make_shared<XMLElement>("VIDEO")); + } + if (telephone.isBBS) { + telElement->addNode(boost::make_shared<XMLElement>("BBS")); + } + if (telephone.isModem) { + telElement->addNode(boost::make_shared<XMLElement>("MODEM")); + } + if (telephone.isISDN) { + telElement->addNode(boost::make_shared<XMLElement>("ISDN")); + } + if (telephone.isPCS) { + telElement->addNode(boost::make_shared<XMLElement>("PCS")); + } + if (telephone.isPreferred) { + telElement->addNode(boost::make_shared<XMLElement>("PREF")); + } + queryElement.addNode(telElement); + } + + foreach(const VCard::Address& address, vcard->getAddresses()) { + boost::shared_ptr<XMLElement> adrElement = boost::make_shared<XMLElement>("ADR"); + if (!address.poBox.empty()) { + adrElement->addNode(boost::make_shared<XMLElement>("POBOX", "", address.poBox)); + } + if (!address.addressExtension.empty()) { + adrElement->addNode(boost::make_shared<XMLElement>("EXTADD", "", address.addressExtension)); + } + if (!address.street.empty()) { + adrElement->addNode(boost::make_shared<XMLElement>("STREET", "", address.street)); + } + if (!address.locality.empty()) { + adrElement->addNode(boost::make_shared<XMLElement>("LOCALITY", "", address.locality)); + } + if (!address.region.empty()) { + adrElement->addNode(boost::make_shared<XMLElement>("REGION", "", address.region)); + } + if (!address.postalCode.empty()) { + adrElement->addNode(boost::make_shared<XMLElement>("PCODE", "", address.postalCode)); + } + if (!address.country.empty()) { + adrElement->addNode(boost::make_shared<XMLElement>("CTRY", "", address.country)); + } + + if (address.isHome) { + adrElement->addNode(boost::make_shared<XMLElement>("HOME")); + } + if (address.isWork) { + adrElement->addNode(boost::make_shared<XMLElement>("WORK")); + } + if (address.isPostal) { + adrElement->addNode(boost::make_shared<XMLElement>("POSTAL")); + } + if (address.isParcel) { + adrElement->addNode(boost::make_shared<XMLElement>("PARCEL")); + } + if (address.deliveryType == VCard::DomesticDelivery) { + adrElement->addNode(boost::make_shared<XMLElement>("DOM")); + } + if (address.deliveryType == VCard::InternationalDelivery) { + adrElement->addNode(boost::make_shared<XMLElement>("INTL")); + } + if (address.isPreferred) { + adrElement->addNode(boost::make_shared<XMLElement>("PREF")); + } + queryElement.addNode(adrElement); + } + + foreach(const VCard::AddressLabel& addressLabel, vcard->getAddressLabels()) { + boost::shared_ptr<XMLElement> labelElement = boost::make_shared<XMLElement>("LABEL"); + + foreach(const std::string& line, addressLabel.lines) { + labelElement->addNode(boost::make_shared<XMLElement>("LINE", "", line)); + } + + if (addressLabel.isHome) { + labelElement->addNode(boost::make_shared<XMLElement>("HOME")); + } + if (addressLabel.isWork) { + labelElement->addNode(boost::make_shared<XMLElement>("WORK")); + } + if (addressLabel.isPostal) { + labelElement->addNode(boost::make_shared<XMLElement>("POSTAL")); + } + if (addressLabel.isParcel) { + labelElement->addNode(boost::make_shared<XMLElement>("PARCEL")); + } + if (addressLabel.deliveryType == VCard::DomesticDelivery) { + labelElement->addNode(boost::make_shared<XMLElement>("DOM")); + } + if (addressLabel.deliveryType == VCard::InternationalDelivery) { + labelElement->addNode(boost::make_shared<XMLElement>("INTL")); + } + if (addressLabel.isPreferred) { + labelElement->addNode(boost::make_shared<XMLElement>("PREF")); + } + queryElement.addNode(labelElement); + } + + foreach(const JID& jid, vcard->getJIDs()) { + queryElement.addNode(boost::make_shared<XMLElement>("JID", "", jid.toString())); + } + + if (!vcard->getDescription().empty()) { + queryElement.addNode(boost::make_shared<XMLElement>("DESC", "", vcard->getDescription())); + } + + foreach(const VCard::Organization& org, vcard->getOrganizations()) { + boost::shared_ptr<XMLElement> orgElement = boost::make_shared<XMLElement>("ORG"); + if (!org.name.empty()) { + orgElement->addNode(boost::make_shared<XMLElement>("ORGNAME", "", org.name)); + } + if (!org.units.empty()) { + foreach(const std::string& unit, org.units) { + orgElement->addNode(boost::make_shared<XMLElement>("ORGUNIT", "", unit)); + } + } + queryElement.addNode(orgElement); + } + + foreach(const std::string& title, vcard->getTitles()) { + queryElement.addNode(boost::make_shared<XMLElement>("TITLE", "", title)); + } + + foreach(const std::string& role, vcard->getRoles()) { + queryElement.addNode(boost::make_shared<XMLElement>("ROLE", "", role)); + } + + foreach(const std::string& url, vcard->getURLs()) { + queryElement.addNode(boost::make_shared<XMLElement>("URL", "", url)); + } + if (!vcard->getUnknownContent().empty()) { queryElement.addNode(boost::make_shared<XMLRawTextNode>(vcard->getUnknownContent())); } diff --git a/Swiften/Session/BOSHSessionStream.cpp b/Swiften/Session/BOSHSessionStream.cpp index 479e415..5dfff3c 100644 --- a/Swiften/Session/BOSHSessionStream.cpp +++ b/Swiften/Session/BOSHSessionStream.cpp @@ -46,7 +46,7 @@ BOSHSessionStream::BOSHSessionStream( boost::mt19937 random; boost::uniform_int<unsigned long long> dist(0, (1LL<<53) - 1); - random.seed(time(NULL)); + random.seed(static_cast<unsigned int>(time(NULL))); unsigned long long initialRID = boost::variate_generator<boost::mt19937&, boost::uniform_int<unsigned long long> >(random, dist)(); connectionPool = new BOSHConnectionPool(boshURL, resolver, connectionFactory, xmlParserFactory, tlsContextFactory, timerFactory, eventLoop, to, initialRID, boshHTTPConnectProxyURL, boshHTTPConnectProxyAuthID, boshHTTPConnectProxyAuthPassword); diff --git a/Swiften/StringCodecs/Base64.cpp b/Swiften/StringCodecs/Base64.cpp index e4eaa4e..195987e 100644 --- a/Swiften/StringCodecs/Base64.cpp +++ b/Swiften/StringCodecs/Base64.cpp @@ -14,6 +14,7 @@ namespace Swift { #pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma clang diagnostic ignored "-Wconversion" namespace { template<typename TargetType, typename SourceType> diff --git a/Swiften/StringCodecs/Hexify.cpp b/Swiften/StringCodecs/Hexify.cpp index 668079b..0e6dc4e 100644 --- a/Swiften/StringCodecs/Hexify.cpp +++ b/Swiften/StringCodecs/Hexify.cpp @@ -13,6 +13,8 @@ #include <string> #include <Swiften/Base/ByteArray.h> +#pragma clang diagnostic ignored "-Wconversion" + namespace Swift { std::string Hexify::hexify(unsigned char byte) { diff --git a/Swiften/StringCodecs/MD5.cpp b/Swiften/StringCodecs/MD5.cpp index bd03314..ffed37b 100644 --- a/Swiften/StringCodecs/MD5.cpp +++ b/Swiften/StringCodecs/MD5.cpp @@ -32,6 +32,9 @@ */ #pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma clang diagnostic ignored "-Wconversion" +#pragma clang diagnostic ignored "-Wcast-align" +#pragma clang diagnostic ignored "-Wmissing-prototypes" #include <Swiften/StringCodecs/MD5.h> diff --git a/Swiften/StringCodecs/SHA1.cpp b/Swiften/StringCodecs/SHA1.cpp index e4081f4..8b03989 100644 --- a/Swiften/StringCodecs/SHA1.cpp +++ b/Swiften/StringCodecs/SHA1.cpp @@ -185,7 +185,7 @@ SHA1::SHA1() { SHA1& SHA1::update(const std::vector<unsigned char>& input) { std::vector<unsigned char> inputCopy(input); - Update(&context, (boost::uint8_t*) vecptr(inputCopy), inputCopy.size()); + Update(&context, (boost::uint8_t*) vecptr(inputCopy), static_cast<unsigned int>(inputCopy.size())); return *this; } @@ -203,7 +203,7 @@ ByteArray SHA1::getHashInternal(const Container& input) { Init(&context); Container inputCopy(input); - Update(&context, (boost::uint8_t*) vecptr(inputCopy), inputCopy.size()); + Update(&context, (boost::uint8_t*) vecptr(inputCopy), static_cast<unsigned int>(inputCopy.size())); ByteArray digest; digest.resize(20); diff --git a/Swiften/StringCodecs/SHA256.cpp b/Swiften/StringCodecs/SHA256.cpp index f92e7af..6e3c4ec 100644 --- a/Swiften/StringCodecs/SHA256.cpp +++ b/Swiften/StringCodecs/SHA256.cpp @@ -11,6 +11,9 @@ #include <string.h> #pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma clang diagnostic ignored "-Wconversion" +#pragma clang diagnostic ignored "-Wunused-macros" +#pragma clang diagnostic ignored "-Wdisabled-macro-expansion" using namespace Swift; diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp index 76b8bb9..d654787 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp +++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -13,6 +13,9 @@ #include <openssl/x509v3.h> #pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#pragma clang diagnostic ignored "-Wcast-align" +#pragma clang diagnostic ignored "-Wsign-conversion" namespace Swift { @@ -55,7 +58,7 @@ void OpenSSLCertificate::parse() { // Subject name ByteArray subjectNameData; subjectNameData.resize(256); - X509_NAME_oneline(X509_get_subject_name(cert.get()), reinterpret_cast<char*>(vecptr(subjectNameData)), subjectNameData.size()); + X509_NAME_oneline(X509_get_subject_name(cert.get()), reinterpret_cast<char*>(vecptr(subjectNameData)), static_cast<unsigned int>(subjectNameData.size())); this->subjectName = byteArrayToString(subjectNameData); // Common name diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp index e8a9019..77f780f 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp +++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2013 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ @@ -25,13 +25,17 @@ #include <Swiften/TLS/PKCS12Certificate.h> #pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#pragma clang diagnostic ignored "-Wshorten-64-to-32" +#pragma clang diagnostic ignored "-Wcast-align" +#pragma clang diagnostic ignored "-Wsign-conversion" namespace Swift { static const int MAX_FINISHED_SIZE = 4096; static const int SSL_READ_BUFFERSIZE = 8192; -void freeX509Stack(STACK_OF(X509)* stack) { +static void freeX509Stack(STACK_OF(X509)* stack) { sk_X509_free(stack); } diff --git a/Swiften/TLS/ServerIdentityVerifier.cpp b/Swiften/TLS/ServerIdentityVerifier.cpp index a908ad0..59c0614 100644 --- a/Swiften/TLS/ServerIdentityVerifier.cpp +++ b/Swiften/TLS/ServerIdentityVerifier.cpp @@ -67,8 +67,8 @@ bool ServerIdentityVerifier::matchesDomain(const std::string& s) const { if (boost::starts_with(s, "*.")) { std::string matchString(s.substr(2, s.npos)); std::string matchDomain = encodedDomain; - int dotIndex = matchDomain.find('.'); - if (dotIndex >= 0) { + size_t dotIndex = matchDomain.find('.'); + if (dotIndex != matchDomain.npos) { matchDomain = matchDomain.substr(dotIndex + 1, matchDomain.npos); } return matchString == matchDomain; |