diff options
| author | Kevin Smith <git@kismith.co.uk> | 2014-08-21 08:38:11 (GMT) |
|---|---|---|
| committer | Kevin Smith <git@kismith.co.uk> | 2014-08-21 08:40:10 (GMT) |
| commit | 381b22fc365c27b9cd585f4b78f53ebc698d9f54 (patch) | |
| tree | 0ffd89a8be13293c75c7ddfea524c74e0bf87b72 | |
| parent | 8ec22a9c5591584fd1725ed028d714c51b7509d3 (diff) | |
| download | swift-contrib-381b22fc365c27b9cd585f4b78f53ebc698d9f54.zip swift-contrib-381b22fc365c27b9cd585f4b78f53ebc698d9f54.tar.bz2 | |
Clean up compilation errors in Swiften due to boost 1.56
Can no longer implicitly convert boost::optional to bool temporaries. Also fixed assorted uses of cerr where logging was appropriate.
Test-Information:
Swiften compiles against boost 1.56 (link fails for me so far)
Change-Id: Iec058af933a82a987da64291435a475f8b40ef96
| -rw-r--r-- | Swiften/Client/ClientSession.cpp | 5 | ||||
| -rw-r--r-- | Swiften/FileTransfer/IBBReceiveSession.cpp | 16 | ||||
| -rw-r--r-- | Swiften/FileTransfer/IncomingFileTransferManager.cpp | 5 | ||||
| -rw-r--r-- | Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp | 2 | ||||
| -rw-r--r-- | Swiften/Jingle/JingleResponder.cpp | 4 | ||||
| -rw-r--r-- | Swiften/Network/BOSHConnection.cpp | 2 | ||||
| -rw-r--r-- | Swiften/Network/FakeConnection.cpp | 4 | ||||
| -rw-r--r-- | Swiften/Network/NATPMPInterface.cpp | 8 | ||||
| -rw-r--r-- | Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp | 10 | ||||
| -rw-r--r-- | Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp | 9 |
10 files changed, 42 insertions, 23 deletions
diff --git a/Swiften/Client/ClientSession.cpp b/Swiften/Client/ClientSession.cpp index 441189e..500299a 100644 --- a/Swiften/Client/ClientSession.cpp +++ b/Swiften/Client/ClientSession.cpp @@ -1,478 +1,477 @@ /* * Copyright (c) 2010-2014 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <Swiften/Client/ClientSession.h> #include <boost/bind.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/smart_ptr/make_shared.hpp> #include <Swiften/Base/Platform.h> #include <Swiften/Base/Log.h> #include <Swiften/Elements/ProtocolHeader.h> #include <Swiften/Elements/StreamFeatures.h> #include <Swiften/Elements/StreamError.h> #include <Swiften/Elements/StartTLSRequest.h> #include <Swiften/Elements/StartTLSFailure.h> #include <Swiften/Elements/TLSProceed.h> #include <Swiften/Elements/AuthRequest.h> #include <Swiften/Elements/AuthSuccess.h> #include <Swiften/Elements/AuthFailure.h> #include <Swiften/Elements/AuthChallenge.h> #include <Swiften/Elements/AuthResponse.h> #include <Swiften/Elements/Compressed.h> #include <Swiften/Elements/CompressFailure.h> #include <Swiften/Elements/CompressRequest.h> #include <Swiften/Elements/EnableStreamManagement.h> #include <Swiften/Elements/StreamManagementEnabled.h> #include <Swiften/Elements/StreamManagementFailed.h> #include <Swiften/Elements/StartSession.h> #include <Swiften/Elements/StanzaAck.h> #include <Swiften/Elements/StanzaAckRequest.h> #include <Swiften/Elements/IQ.h> #include <Swiften/Elements/ResourceBind.h> #include <Swiften/SASL/PLAINClientAuthenticator.h> #include <Swiften/SASL/EXTERNALClientAuthenticator.h> #include <Swiften/SASL/SCRAMSHA1ClientAuthenticator.h> #include <Swiften/SASL/DIGESTMD5ClientAuthenticator.h> #include <Swiften/Crypto/CryptoProvider.h> #include <Swiften/Session/SessionStream.h> #include <Swiften/TLS/CertificateTrustChecker.h> #include <Swiften/TLS/ServerIdentityVerifier.h> -#include <Swiften/Base/Log.h> #ifdef SWIFTEN_PLATFORM_WIN32 #include <Swiften/Base/WindowsRegistry.h> #endif #define CHECK_STATE_OR_RETURN(a) \ if (!checkState(a)) { return; } namespace Swift { ClientSession::ClientSession( const JID& jid, boost::shared_ptr<SessionStream> stream, IDNConverter* idnConverter, CryptoProvider* crypto) : localJID(jid), state(Initial), stream(stream), idnConverter(idnConverter), crypto(crypto), allowPLAINOverNonTLS(false), useStreamCompression(true), useTLS(UseTLSWhenAvailable), useAcks(true), needSessionStart(false), needResourceBind(false), needAcking(false), rosterVersioningSupported(false), authenticator(NULL), certificateTrustChecker(NULL) { #ifdef SWIFTEN_PLATFORM_WIN32 if (WindowsRegistry::isFIPSEnabled()) { SWIFT_LOG(info) << "Windows is running in FIPS-140 mode. Some authentication methods will be unavailable." << std::endl; } #endif } ClientSession::~ClientSession() { } void ClientSession::start() { stream->onStreamStartReceived.connect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1)); stream->onElementReceived.connect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1)); stream->onClosed.connect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1)); stream->onTLSEncrypted.connect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this())); assert(state == Initial); state = WaitingForStreamStart; sendStreamHeader(); } void ClientSession::sendStreamHeader() { ProtocolHeader header; header.setTo(getRemoteJID()); stream->writeHeader(header); } void ClientSession::sendStanza(boost::shared_ptr<Stanza> stanza) { stream->writeElement(stanza); if (stanzaAckRequester_) { stanzaAckRequester_->handleStanzaSent(stanza); } } void ClientSession::handleStreamStart(const ProtocolHeader&) { CHECK_STATE_OR_RETURN(WaitingForStreamStart); state = Negotiating; } void ClientSession::handleElement(boost::shared_ptr<ToplevelElement> element) { if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) { if (stanzaAckResponder_) { stanzaAckResponder_->handleStanzaReceived(); } if (getState() == Initialized) { onStanzaReceived(stanza); } else if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(element)) { if (state == BindingResource) { boost::shared_ptr<ResourceBind> resourceBind(iq->getPayload<ResourceBind>()); if (iq->getType() == IQ::Error && iq->getID() == "session-bind") { finishSession(Error::ResourceBindError); } else if (!resourceBind) { finishSession(Error::UnexpectedElementError); } else if (iq->getType() == IQ::Result) { localJID = resourceBind->getJID(); if (!localJID.isValid()) { finishSession(Error::ResourceBindError); } needResourceBind = false; continueSessionInitialization(); } else { finishSession(Error::UnexpectedElementError); } } else if (state == StartingSession) { if (iq->getType() == IQ::Result) { needSessionStart = false; continueSessionInitialization(); } else if (iq->getType() == IQ::Error) { finishSession(Error::SessionStartError); } else { finishSession(Error::UnexpectedElementError); } } else { finishSession(Error::UnexpectedElementError); } } } else if (boost::dynamic_pointer_cast<StanzaAckRequest>(element)) { if (stanzaAckResponder_) { stanzaAckResponder_->handleAckRequestReceived(); } } else if (boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(element)) { if (stanzaAckRequester_) { if (ack->isValid()) { stanzaAckRequester_->handleAckReceived(ack->getHandledStanzasCount()); } else { - std::cerr << "Warning: Got invalid ack from server" << std::endl; + SWIFT_LOG(warning) << "Got invalid ack from server"; } } else { - std::cerr << "Warning: Ignoring ack" << std::endl; + SWIFT_LOG(warning) << "Ignoring ack"; } } else if (StreamError::ref streamError = boost::dynamic_pointer_cast<StreamError>(element)) { finishSession(Error::StreamError); } else if (getState() == Initialized) { boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element); if (stanza) { if (stanzaAckResponder_) { stanzaAckResponder_->handleStanzaReceived(); } onStanzaReceived(stanza); } } else if (StreamFeatures* streamFeatures = dynamic_cast<StreamFeatures*>(element.get())) { CHECK_STATE_OR_RETURN(Negotiating); if (streamFeatures->hasStartTLS() && stream->supportsTLSEncryption() && useTLS != NeverUseTLS) { state = WaitingForEncrypt; stream->writeElement(boost::make_shared<StartTLSRequest>()); } else if (useTLS == RequireTLS && !stream->isTLSEncrypted()) { finishSession(Error::NoSupportedAuthMechanismsError); } else if (useStreamCompression && stream->supportsZLibCompression() && streamFeatures->hasCompressionMethod("zlib")) { state = Compressing; stream->writeElement(boost::make_shared<CompressRequest>("zlib")); } else if (streamFeatures->hasAuthenticationMechanisms()) { if (stream->hasTLSCertificate()) { if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) { authenticator = new EXTERNALClientAuthenticator(); state = Authenticating; stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray(""))); } else { finishSession(Error::TLSClientCertificateError); } } else if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) { authenticator = new EXTERNALClientAuthenticator(); state = Authenticating; stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray(""))); } else if (streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1") || streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS")) { std::ostringstream s; ByteArray finishMessage; bool plus = streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS"); if (stream->isTLSEncrypted()) { finishMessage = stream->getTLSFinishMessage(); plus &= !finishMessage.empty(); } s << boost::uuids::random_generator()(); SCRAMSHA1ClientAuthenticator* scramAuthenticator = new SCRAMSHA1ClientAuthenticator(s.str(), plus, idnConverter, crypto); if (!finishMessage.empty()) { scramAuthenticator->setTLSChannelBindingData(finishMessage); } authenticator = scramAuthenticator; state = WaitingForCredentials; onNeedCredentials(); } else if ((stream->isTLSEncrypted() || allowPLAINOverNonTLS) && streamFeatures->hasAuthenticationMechanism("PLAIN")) { authenticator = new PLAINClientAuthenticator(); state = WaitingForCredentials; onNeedCredentials(); } else if (streamFeatures->hasAuthenticationMechanism("DIGEST-MD5") && crypto->isMD5AllowedForCrypto()) { std::ostringstream s; s << boost::uuids::random_generator()(); // FIXME: Host should probably be the actual host authenticator = new DIGESTMD5ClientAuthenticator(localJID.getDomain(), s.str(), crypto); state = WaitingForCredentials; onNeedCredentials(); } else { finishSession(Error::NoSupportedAuthMechanismsError); } } else { // Start the session rosterVersioningSupported = streamFeatures->hasRosterVersioning(); stream->setWhitespacePingEnabled(true); needSessionStart = streamFeatures->hasSession(); needResourceBind = streamFeatures->hasResourceBind(); needAcking = streamFeatures->hasStreamManagement() && useAcks; if (!needResourceBind) { // Resource binding is a MUST finishSession(Error::ResourceBindError); } else { continueSessionInitialization(); } } } else if (boost::dynamic_pointer_cast<Compressed>(element)) { CHECK_STATE_OR_RETURN(Compressing); state = WaitingForStreamStart; stream->addZLibCompression(); stream->resetXMPPParser(); sendStreamHeader(); } else if (boost::dynamic_pointer_cast<CompressFailure>(element)) { finishSession(Error::CompressionFailedError); } else if (boost::dynamic_pointer_cast<StreamManagementEnabled>(element)) { stanzaAckRequester_ = boost::make_shared<StanzaAckRequester>(); stanzaAckRequester_->onRequestAck.connect(boost::bind(&ClientSession::requestAck, shared_from_this())); stanzaAckRequester_->onStanzaAcked.connect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1)); stanzaAckResponder_ = boost::make_shared<StanzaAckResponder>(); stanzaAckResponder_->onAck.connect(boost::bind(&ClientSession::ack, shared_from_this(), _1)); needAcking = false; continueSessionInitialization(); } else if (boost::dynamic_pointer_cast<StreamManagementFailed>(element)) { needAcking = false; continueSessionInitialization(); } else if (AuthChallenge* challenge = dynamic_cast<AuthChallenge*>(element.get())) { CHECK_STATE_OR_RETURN(Authenticating); assert(authenticator); if (authenticator->setChallenge(challenge->getValue())) { stream->writeElement(boost::make_shared<AuthResponse>(authenticator->getResponse())); } else { finishSession(Error::AuthenticationFailedError); } } else if (AuthSuccess* authSuccess = dynamic_cast<AuthSuccess*>(element.get())) { CHECK_STATE_OR_RETURN(Authenticating); assert(authenticator); if (!authenticator->setChallenge(authSuccess->getValue())) { finishSession(Error::ServerVerificationFailedError); } else { state = WaitingForStreamStart; delete authenticator; authenticator = NULL; stream->resetXMPPParser(); sendStreamHeader(); } } else if (dynamic_cast<AuthFailure*>(element.get())) { finishSession(Error::AuthenticationFailedError); } else if (dynamic_cast<TLSProceed*>(element.get())) { CHECK_STATE_OR_RETURN(WaitingForEncrypt); state = Encrypting; stream->addTLSEncryption(); } else if (dynamic_cast<StartTLSFailure*>(element.get())) { finishSession(Error::TLSError); } else { // FIXME Not correct? state = Initialized; onInitialized(); } } void ClientSession::continueSessionInitialization() { if (needResourceBind) { state = BindingResource; boost::shared_ptr<ResourceBind> resourceBind(boost::make_shared<ResourceBind>()); if (!localJID.getResource().empty()) { resourceBind->setResource(localJID.getResource()); } sendStanza(IQ::createRequest(IQ::Set, JID(), "session-bind", resourceBind)); } else if (needAcking) { state = EnablingSessionManagement; stream->writeElement(boost::make_shared<EnableStreamManagement>()); } else if (needSessionStart) { state = StartingSession; sendStanza(IQ::createRequest(IQ::Set, JID(), "session-start", boost::make_shared<StartSession>())); } else { state = Initialized; onInitialized(); } } bool ClientSession::checkState(State state) { if (this->state != state) { finishSession(Error::UnexpectedElementError); return false; } return true; } void ClientSession::sendCredentials(const SafeByteArray& password) { assert(WaitingForCredentials); assert(authenticator); state = Authenticating; authenticator->setCredentials(localJID.getNode(), password); stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse())); } void ClientSession::handleTLSEncrypted() { CHECK_STATE_OR_RETURN(Encrypting); std::vector<Certificate::ref> certificateChain = stream->getPeerCertificateChain(); boost::shared_ptr<CertificateVerificationError> verificationError = stream->getPeerCertificateVerificationError(); if (verificationError) { checkTrustOrFinish(certificateChain, verificationError); } else { ServerIdentityVerifier identityVerifier(localJID, idnConverter); if (!certificateChain.empty() && identityVerifier.certificateVerifies(certificateChain[0])) { continueAfterTLSEncrypted(); } else { checkTrustOrFinish(certificateChain, boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidServerIdentity)); } } } void ClientSession::checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error) { if (certificateTrustChecker && certificateTrustChecker->isCertificateTrusted(certificateChain)) { continueAfterTLSEncrypted(); } else { finishSession(error); } } void ClientSession::continueAfterTLSEncrypted() { state = WaitingForStreamStart; stream->resetXMPPParser(); sendStreamHeader(); } void ClientSession::handleStreamClosed(boost::shared_ptr<Swift::Error> streamError) { State previousState = state; state = Finished; if (stanzaAckRequester_) { stanzaAckRequester_->onRequestAck.disconnect(boost::bind(&ClientSession::requestAck, shared_from_this())); stanzaAckRequester_->onStanzaAcked.disconnect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1)); stanzaAckRequester_.reset(); } if (stanzaAckResponder_) { stanzaAckResponder_->onAck.disconnect(boost::bind(&ClientSession::ack, shared_from_this(), _1)); stanzaAckResponder_.reset(); } stream->setWhitespacePingEnabled(false); stream->onStreamStartReceived.disconnect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1)); stream->onElementReceived.disconnect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1)); stream->onClosed.disconnect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1)); stream->onTLSEncrypted.disconnect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this())); if (previousState == Finishing) { onFinished(error_); } else { onFinished(streamError); } } void ClientSession::finish() { finishSession(boost::shared_ptr<Error>()); } void ClientSession::finishSession(Error::Type error) { finishSession(boost::make_shared<Swift::ClientSession::Error>(error)); } void ClientSession::finishSession(boost::shared_ptr<Swift::Error> error) { state = Finishing; if (!error_) { error_ = error; } else { SWIFT_LOG(warning) << "Session finished twice"; } assert(stream->isOpen()); if (stanzaAckResponder_) { stanzaAckResponder_->handleAckRequestReceived(); } if (authenticator) { delete authenticator; authenticator = NULL; } stream->writeFooter(); stream->close(); } void ClientSession::requestAck() { stream->writeElement(boost::make_shared<StanzaAckRequest>()); } void ClientSession::handleStanzaAcked(boost::shared_ptr<Stanza> stanza) { onStanzaAcked(stanza); } void ClientSession::ack(unsigned int handledStanzasCount) { stream->writeElement(boost::make_shared<StanzaAck>(handledStanzasCount)); } } diff --git a/Swiften/FileTransfer/IBBReceiveSession.cpp b/Swiften/FileTransfer/IBBReceiveSession.cpp index 3aa6fdc..8cfd95d 100644 --- a/Swiften/FileTransfer/IBBReceiveSession.cpp +++ b/Swiften/FileTransfer/IBBReceiveSession.cpp @@ -1,117 +1,117 @@ /* * Copyright (c) 2010 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <Swiften/FileTransfer/IBBReceiveSession.h> #include <boost/bind.hpp> #include <Swiften/Base/Log.h> #include <Swiften/Queries/IQRouter.h> #include <Swiften/FileTransfer/IBBRequest.h> #include <Swiften/FileTransfer/BytestreamException.h> #include <Swiften/Queries/SetResponder.h> #include <cassert> namespace Swift { class IBBReceiveSession::IBBResponder : public SetResponder<IBB> { public: IBBResponder(IBBReceiveSession* session, IQRouter* router) : SetResponder<IBB>(router), session(session), sequenceNumber(0), receivedSize(0) { } virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, IBB::ref ibb) { if (from == session->from && ibb->getStreamID() == session->id) { if (ibb->getAction() == IBB::Data) { if (sequenceNumber == ibb->getSequenceNumber()) { session->bytestream->write(ibb->getData()); receivedSize += ibb->getData().size(); sequenceNumber++; sendResponse(from, id, IBB::ref()); if (receivedSize >= session->size) { if (receivedSize > session->size) { - std::cerr << "Warning: Received more data than expected" << std::endl; + SWIFT_LOG(warning) << "Received more data than expected"; } session->finish(boost::optional<FileTransferError>()); } } else { - SWIFT_LOG(warning) << "Received data out of order" << std::endl; + SWIFT_LOG(warning) << "Received data out of order"; sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel); session->finish(FileTransferError(FileTransferError::ClosedError)); } } else if (ibb->getAction() == IBB::Open) { - SWIFT_LOG(debug) << "IBB open received" << std::endl; + SWIFT_LOG(debug) << "IBB open received"; sendResponse(from, id, IBB::ref()); } else if (ibb->getAction() == IBB::Close) { - SWIFT_LOG(debug) << "IBB close received" << std::endl; + SWIFT_LOG(debug) << "IBB close received"; sendResponse(from, id, IBB::ref()); session->finish(FileTransferError(FileTransferError::ClosedError)); } return true; } - SWIFT_LOG(debug) << "wrong from/sessionID: " << from << " == " << session->from << " / " <<ibb->getStreamID() << " == " << session->id << std::endl; + SWIFT_LOG(debug) << "wrong from/sessionID: " << from << " == " << session->from << " / " <<ibb->getStreamID() << " == " << session->id; return false; } private: IBBReceiveSession* session; int sequenceNumber; unsigned long long receivedSize; }; IBBReceiveSession::IBBReceiveSession( const std::string& id, const JID& from, const JID& to, unsigned long long size, boost::shared_ptr<WriteBytestream> bytestream, IQRouter* router) : id(id), from(from), to(to), size(size), bytestream(bytestream), router(router), active(false) { assert(!id.empty()); assert(from.isValid()); responder = new IBBResponder(this, router); } IBBReceiveSession::~IBBReceiveSession() { if (active) { - SWIFT_LOG(warning) << "Session still active" << std::endl; + SWIFT_LOG(warning) << "Session still active"; } delete responder; } void IBBReceiveSession::start() { - SWIFT_LOG(debug) << "receive session started" << std::endl; + SWIFT_LOG(debug) << "receive session started"; active = true; responder->start(); } void IBBReceiveSession::stop() { - SWIFT_LOG(debug) << "receive session stopped" << std::endl; + SWIFT_LOG(debug) << "receive session stopped"; responder->stop(); if (active) { if (router->isAvailable()) { IBBRequest::create(to, from, IBB::createIBBClose(id), router)->send(); } finish(boost::optional<FileTransferError>()); } } void IBBReceiveSession::finish(boost::optional<FileTransferError> error) { active = false; onFinished(error); } } diff --git a/Swiften/FileTransfer/IncomingFileTransferManager.cpp b/Swiften/FileTransfer/IncomingFileTransferManager.cpp index d40c5de..d8c4f89 100644 --- a/Swiften/FileTransfer/IncomingFileTransferManager.cpp +++ b/Swiften/FileTransfer/IncomingFileTransferManager.cpp @@ -1,67 +1,68 @@ /* - * Copyright (c) 2010-2013 Remko Tronçon + * Copyright (c) 2010-2014 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <Swiften/FileTransfer/IncomingFileTransferManager.h> #include <boost/smart_ptr/make_shared.hpp> +#include <Swiften/Base/Log.h> #include <Swiften/Elements/JingleDescription.h> #include <Swiften/Elements/JingleFileTransferDescription.h> #include <Swiften/Elements/JingleIBBTransportPayload.h> #include <Swiften/Elements/JingleS5BTransportPayload.h> #include <Swiften/Jingle/JingleSessionManager.h> #include <Swiften/Jingle/Jingle.h> #include <Swiften/FileTransfer/IncomingJingleFileTransfer.h> namespace Swift { IncomingFileTransferManager::IncomingFileTransferManager( JingleSessionManager* jingleSessionManager, IQRouter* router, FileTransferTransporterFactory* transporterFactory, TimerFactory* timerFactory, CryptoProvider* crypto) : jingleSessionManager(jingleSessionManager), router(router), transporterFactory(transporterFactory), timerFactory(timerFactory), crypto(crypto) { jingleSessionManager->addIncomingSessionHandler(this); } IncomingFileTransferManager::~IncomingFileTransferManager() { jingleSessionManager->removeIncomingSessionHandler(this); } bool IncomingFileTransferManager::handleIncomingJingleSession( JingleSession::ref session, const std::vector<JingleContentPayload::ref>& contents, const JID& recipient) { if (JingleContentPayload::ref content = Jingle::getContentWithDescription<JingleFileTransferDescription>(contents)) { if (content->getTransport<JingleS5BTransportPayload>()) { JingleFileTransferDescription::ref description = content->getDescription<JingleFileTransferDescription>(); if (description && description->getOffers().size() == 1) { IncomingJingleFileTransfer::ref transfer = boost::make_shared<IncomingJingleFileTransfer>( recipient, session, content, transporterFactory, timerFactory, crypto); onIncomingFileTransfer(transfer); } else { - std::cerr << "Received a file-transfer request with no description or more than one file!" << std::endl; + SWIFT_LOG(warning) << "Received a file-transfer request with no description or more than one file."; session->sendTerminate(JinglePayload::Reason::FailedApplication); } } else { session->sendTerminate(JinglePayload::Reason::UnsupportedTransports); } return true; } else { return false; } } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp index f393c8d..cb34c58 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp @@ -1,199 +1,199 @@ /* * 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/SOCKS5BytestreamServerSession.h> #include <boost/bind.hpp> #include <boost/numeric/conversion/cast.hpp> #include <iostream> #include <Swiften/Base/ByteArray.h> #include <Swiften/Base/SafeByteArray.h> #include <Swiften/Base/Algorithm.h> #include <Swiften/Base/Concat.h> #include <Swiften/Base/Log.h> #include <Swiften/Network/HostAddressPort.h> #include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h> #include <Swiften/FileTransfer/BytestreamException.h> namespace Swift { SOCKS5BytestreamServerSession::SOCKS5BytestreamServerSession( boost::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* bytestreams) : connection(connection), bytestreams(bytestreams), state(Initial), chunkSize(131072), waitingForData(false) { disconnectedConnection = connection->onDisconnected.connect(boost::bind(&SOCKS5BytestreamServerSession::handleDisconnected, this, _1)); } SOCKS5BytestreamServerSession::~SOCKS5BytestreamServerSession() { if (state != Finished && state != Initial) { std::cerr << "Warning: SOCKS5BytestreamServerSession unfinished" << std::endl; finish(false); } } void SOCKS5BytestreamServerSession::start() { SWIFT_LOG(debug) << std::endl; dataReadConnection = connection->onDataRead.connect( boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1)); state = WaitingForAuthentication; } void SOCKS5BytestreamServerSession::stop() { finish(false); } void SOCKS5BytestreamServerSession::startSending(boost::shared_ptr<ReadBytestream> stream) { if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; } readBytestream = stream; state = WritingData; dataAvailableConnection = readBytestream->onDataAvailable.connect( boost::bind(&SOCKS5BytestreamServerSession::handleDataAvailable, this)); dataWrittenConnection = connection->onDataWritten.connect( boost::bind(&SOCKS5BytestreamServerSession::sendData, this)); sendData(); } void SOCKS5BytestreamServerSession::startReceiving(boost::shared_ptr<WriteBytestream> stream) { if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; } writeBytestream = stream; state = ReadingData; writeBytestream->write(unprocessedData); // onBytesReceived(unprocessedData.size()); unprocessedData.clear(); } HostAddressPort SOCKS5BytestreamServerSession::getAddressPort() const { return connection->getLocalAddress(); } void SOCKS5BytestreamServerSession::handleDataRead(boost::shared_ptr<SafeByteArray> data) { if (state != ReadingData) { append(unprocessedData, *data); process(); } else { writeBytestream->write(createByteArray(vecptr(*data), data->size())); // onBytesReceived(data->size()); } } void SOCKS5BytestreamServerSession::handleDataAvailable() { if (waitingForData) { sendData(); } } void SOCKS5BytestreamServerSession::handleDisconnected(const boost::optional<Connection::Error>& error) { SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl; - finish(error); + finish(error ? true : false); } void SOCKS5BytestreamServerSession::process() { if (state == WaitingForAuthentication) { if (unprocessedData.size() >= 2) { size_t authCount = unprocessedData[1]; size_t i = 2; while (i < 2 + authCount && i < unprocessedData.size()) { // Skip authentication mechanism ++i; } if (i == 2 + authCount) { // Authentication message is complete if (i != unprocessedData.size()) { SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl; } unprocessedData.clear(); connection->write(createSafeByteArray("\x05\x00", 2)); state = WaitingForRequest; } } } else if (state == WaitingForRequest) { if (unprocessedData.size() >= 5) { ByteArray requestID; size_t i = 5; size_t hostnameSize = unprocessedData[4]; while (i < 5 + hostnameSize && i < unprocessedData.size()) { requestID.push_back(unprocessedData[i]); ++i; } // Skip the port: 2 byte large, one already skipped. Add one for comparison with size i += 2; if (i <= unprocessedData.size()) { if (i != unprocessedData.size()) { SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl; } unprocessedData.clear(); streamID = byteArrayToString(requestID); bool hasBytestream = bytestreams->hasBytestream(streamID); SafeByteArray result = createSafeByteArray("\x05", 1); result.push_back(hasBytestream ? 0x0 : 0x4); append(result, createByteArray("\x00\x03", 2)); result.push_back(boost::numeric_cast<unsigned char>(requestID.size())); append(result, concat(requestID, createByteArray("\x00\x00", 2))); if (!hasBytestream) { SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl; connection->write(result); finish(true); } else { SWIFT_LOG(debug) << "Found stream. Sent OK." << std::endl; connection->write(result); state = ReadyForTransfer; } } } } } void SOCKS5BytestreamServerSession::sendData() { if (!readBytestream->isFinished()) { try { SafeByteArray dataToSend = createSafeByteArray(*readBytestream->read(boost::numeric_cast<size_t>(chunkSize))); if (!dataToSend.empty()) { connection->write(dataToSend); onBytesSent(dataToSend.size()); waitingForData = false; } else { waitingForData = true; } } catch (const BytestreamException&) { finish(true); } } else { finish(false); } } void SOCKS5BytestreamServerSession::finish(bool error) { SWIFT_LOG(debug) << error << " " << state << std::endl; if (state == Finished) { return; } disconnectedConnection.disconnect(); dataReadConnection.disconnect(); dataWrittenConnection.disconnect(); dataAvailableConnection.disconnect(); readBytestream.reset(); state = Finished; if (error) { onFinished(boost::optional<FileTransferError>(FileTransferError::PeerError)); } else { onFinished(boost::optional<FileTransferError>()); } } } diff --git a/Swiften/Jingle/JingleResponder.cpp b/Swiften/Jingle/JingleResponder.cpp index 4c82f51..e963ef6 100644 --- a/Swiften/Jingle/JingleResponder.cpp +++ b/Swiften/Jingle/JingleResponder.cpp @@ -1,62 +1,62 @@ /* - * Copyright (c) 2011 Remko Tronçon + * Copyright (c) 2011-2014 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <Swiften/Jingle/JingleResponder.h> #include <boost/smart_ptr/make_shared.hpp> #include <Swiften/Jingle/JingleSessionManager.h> #include <Swiften/Jingle/JingleSessionImpl.h> #include <Swiften/Base/Log.h> namespace Swift { JingleResponder::JingleResponder(JingleSessionManager* sessionManager, IQRouter* router) : SetResponder<JinglePayload>(router), sessionManager(sessionManager), router(router) { } JingleResponder::~JingleResponder() { } bool JingleResponder::handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload) { if (payload->getAction() == JinglePayload::SessionInitiate) { if (sessionManager->getSession(from, payload->getSessionID())) { // TODO: Add tie-break error sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel); } else { sendResponse(from, id, boost::shared_ptr<JinglePayload>()); if (!payload->getInitiator().isBare()) { JingleSessionImpl::ref session = boost::make_shared<JingleSessionImpl>(payload->getInitiator(), from, payload->getSessionID(), router); sessionManager->handleIncomingSession(from, to, session, payload->getContents()); } else { SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID." << std::endl; } } } else { JingleSessionImpl::ref session; if (payload->getInitiator().isValid()) { SWIFT_LOG(debug) << "Lookup session by initiator." << std::endl; session = sessionManager->getSession(payload->getInitiator(), payload->getSessionID()); } else { SWIFT_LOG(debug) << "Lookup session by from attribute." << std::endl; session = sessionManager->getSession(from, payload->getSessionID()); } if (session) { session->handleIncomingAction(payload); sendResponse(from, id, boost::shared_ptr<JinglePayload>()); } else { - std::cerr << "WARN: Didn't find jingle session!" << std::endl; + SWIFT_LOG(warning) << "Didn't find jingle session!"; // TODO: Add jingle-specific error sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel); } } return true; } } diff --git a/Swiften/Network/BOSHConnection.cpp b/Swiften/Network/BOSHConnection.cpp index bde689e..28e27d5 100644 --- a/Swiften/Network/BOSHConnection.cpp +++ b/Swiften/Network/BOSHConnection.cpp @@ -1,300 +1,300 @@ /* * Copyright (c) 2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* * Copyright (c) 2011-2014 Kevin Smith * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <Swiften/Network/BOSHConnection.h> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <Swiften/Base/Log.h> #include <Swiften/Base/String.h> #include <Swiften/Base/Concat.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/Network/HostAddressPort.h> #include <Swiften/Parser/BOSHBodyExtractor.h> namespace Swift { BOSHConnection::BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory) : boshURL_(boshURL), connector_(connector), parserFactory_(parserFactory), sid_(), waitingForStartResponse_(false), rid_(~0ULL), pending_(false), connectionReady_(false) { } BOSHConnection::~BOSHConnection() { cancelConnector(); if (connection_) { connection_->onDataRead.disconnect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1)); connection_->onDisconnected.disconnect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); } disconnect(); } void BOSHConnection::connect() { connector_->onConnectFinished.connect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1)); connector_->start(); } void BOSHConnection::cancelConnector() { if (connector_) { connector_->onConnectFinished.disconnect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1)); connector_->stop(); connector_.reset(); } } void BOSHConnection::disconnect() { if (connection_) { connection_->disconnect(); sid_ = ""; } else { /* handleDisconnected takes care of the connector_ as well */ handleDisconnected(boost::optional<Connection::Error>()); } } void BOSHConnection::restartStream() { write(createSafeByteArray(""), true, false); } void BOSHConnection::terminateStream() { write(createSafeByteArray(""), false, true); } void BOSHConnection::write(const SafeByteArray& data) { write(data, false, false); } std::pair<SafeByteArray, size_t> BOSHConnection::createHTTPRequest(const SafeByteArray& data, bool streamRestart, bool terminate, unsigned long long rid, const std::string& sid, const URL& boshURL) { size_t size; std::stringstream content; SafeByteArray contentTail = createSafeByteArray("</body>"); std::stringstream header; content << "<body rid='" << rid << "' sid='" << sid << "'"; if (streamRestart) { content << " xmpp:restart='true' xmlns:xmpp='urn:xmpp:xbosh'"; } if (terminate) { content << " type='terminate'"; } content << " xmlns='http://jabber.org/protocol/httpbind'>"; SafeByteArray safeContent = createSafeByteArray(content.str()); safeContent.insert(safeContent.end(), data.begin(), data.end()); safeContent.insert(safeContent.end(), contentTail.begin(), contentTail.end()); size = safeContent.size(); header << "POST " << boshURL.getPath() << " HTTP/1.1\r\n" << "Host: " << boshURL.getHost(); if (boshURL.getPort()) { header << ":" << *boshURL.getPort(); } header << "\r\n" // << "Accept-Encoding: deflate\r\n" << "Content-Type: text/xml; charset=utf-8\r\n" << "Content-Length: " << size << "\r\n\r\n"; SafeByteArray safeHeader = createSafeByteArray(header.str()); safeHeader.insert(safeHeader.end(), safeContent.begin(), safeContent.end()); return std::pair<SafeByteArray, size_t>(safeHeader, size); } void BOSHConnection::write(const SafeByteArray& data, bool streamRestart, bool terminate) { assert(connectionReady_); assert(!sid_.empty()); SafeByteArray safeHeader = createHTTPRequest(data, streamRestart, terminate, rid_, sid_, boshURL_).first; onBOSHDataWritten(safeHeader); connection_->write(safeHeader); pending_ = true; SWIFT_LOG(debug) << "write data: " << safeByteArrayToString(safeHeader) << std::endl; } void BOSHConnection::handleConnectFinished(Connection::ref connection) { cancelConnector(); connectionReady_ = !!connection; if (connectionReady_) { connection_ = connection; connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1)); connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1)); } onConnectFinished(!connectionReady_); } void BOSHConnection::startStream(const std::string& to, unsigned long long rid) { assert(connectionReady_); // Session Creation Request std::stringstream content; std::stringstream header; content << "<body content='text/xml; charset=utf-8'" << " hold='1'" << " to='" << to << "'" << " rid='" << rid << "'" << " ver='1.6'" << " wait='60'" /* FIXME: we probably want this configurable*/ // << " ack='0'" FIXME: support acks << " xml:lang='en'" << " xmlns:xmpp='urn:xmpp:bosh'" << " xmpp:version='1.0'" << " xmlns='http://jabber.org/protocol/httpbind' />"; std::string contentString = content.str(); header << "POST " << boshURL_.getPath() << " HTTP/1.1\r\n" << "Host: " << boshURL_.getHost(); if (boshURL_.getPort()) { header << ":" << *boshURL_.getPort(); } header << "\r\n" // << "Accept-Encoding: deflate\r\n" << "Content-Type: text/xml; charset=utf-8\r\n" << "Content-Length: " << contentString.size() << "\r\n\r\n" << contentString; waitingForStartResponse_ = true; SafeByteArray safeHeader = createSafeByteArray(header.str()); onBOSHDataWritten(safeHeader); connection_->write(safeHeader); SWIFT_LOG(debug) << "write stream header: " << safeByteArrayToString(safeHeader) << std::endl; } void BOSHConnection::handleDataRead(boost::shared_ptr<SafeByteArray> data) { onBOSHDataRead(*data); buffer_ = concat(buffer_, *data); std::string response = safeByteArrayToString(buffer_); if (response.find("\r\n\r\n") == std::string::npos) { onBOSHDataRead(createSafeByteArray("[[Previous read incomplete, pending]]")); return; } std::string httpCode = response.substr(response.find(" ") + 1, 3); if (httpCode != "200") { onHTTPError(httpCode); return; } BOSHBodyExtractor parser(parserFactory_, createByteArray(response.substr(response.find("\r\n\r\n") + 4))); if (parser.getBody()) { if (parser.getBody()->attributes.getAttribute("type") == "terminate") { BOSHError::Type errorType = parseTerminationCondition(parser.getBody()->attributes.getAttribute("condition")); onSessionTerminated(errorType == BOSHError::NoError ? boost::shared_ptr<BOSHError>() : boost::make_shared<BOSHError>(errorType)); } buffer_.clear(); if (waitingForStartResponse_) { waitingForStartResponse_ = false; sid_ = parser.getBody()->attributes.getAttribute("sid"); std::string requestsString = parser.getBody()->attributes.getAttribute("requests"); size_t requests = 2; if (!requestsString.empty()) { try { requests = boost::lexical_cast<size_t>(requestsString); } catch (const boost::bad_lexical_cast&) { } } onSessionStarted(sid_, requests); } SafeByteArray payload = createSafeByteArray(parser.getBody()->content); /* Say we're good to go again, so don't add anything after here in the method */ pending_ = false; onXMPPDataRead(payload); } } BOSHError::Type BOSHConnection::parseTerminationCondition(const std::string& text) { BOSHError::Type condition = BOSHError::UndefinedCondition; if (text == "bad-request") { condition = BOSHError::BadRequest; } else if (text == "host-gone") { condition = BOSHError::HostGone; } else if (text == "host-unknown") { condition = BOSHError::HostUnknown; } else if (text == "improper-addressing") { condition = BOSHError::ImproperAddressing; } else if (text == "internal-server-error") { condition = BOSHError::InternalServerError; } else if (text == "item-not-found") { condition = BOSHError::ItemNotFound; } else if (text == "other-request") { condition = BOSHError::OtherRequest; } else if (text == "policy-violation") { condition = BOSHError::PolicyViolation; } else if (text == "remote-connection-failed") { condition = BOSHError::RemoteConnectionFailed; } else if (text == "remote-stream-error") { condition = BOSHError::RemoteStreamError; } else if (text == "see-other-uri") { condition = BOSHError::SeeOtherURI; } else if (text == "system-shutdown") { condition = BOSHError::SystemShutdown; } else if (text == "") { condition = BOSHError::NoError; } return condition; } const std::string& BOSHConnection::getSID() { return sid_; } void BOSHConnection::setRID(unsigned long long rid) { rid_ = rid; } void BOSHConnection::setSID(const std::string& sid) { sid_ = sid; } void BOSHConnection::handleDisconnected(const boost::optional<Connection::Error>& error) { cancelConnector(); - onDisconnected(error); + onDisconnected(error ? true : false); sid_ = ""; connectionReady_ = false; } bool BOSHConnection::isReadyToSend() { /* Without pipelining you need to not send more without first receiving the response */ /* With pipelining you can. Assuming we can't, here */ return connectionReady_ && !pending_ && !waitingForStartResponse_ && !sid_.empty(); } } diff --git a/Swiften/Network/FakeConnection.cpp b/Swiften/Network/FakeConnection.cpp index be5555c..a84c92e 100644 --- a/Swiften/Network/FakeConnection.cpp +++ b/Swiften/Network/FakeConnection.cpp @@ -1,64 +1,64 @@ /* - * Copyright (c) 2010 Remko Tronçon + * Copyright (c) 2010-2014 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #include <Swiften/Network/FakeConnection.h> #include <boost/bind.hpp> namespace Swift { FakeConnection::FakeConnection(EventLoop* eventLoop) : eventLoop(eventLoop), state(Initial), delayConnect(false) { } FakeConnection::~FakeConnection() { } void FakeConnection::listen() { assert(false); } void FakeConnection::setError(const Error& e) { error = boost::optional<Error>(e); state = DisconnectedWithError; if (connectedTo) { eventLoop->postEvent( boost::bind(boost::ref(onDisconnected), error), shared_from_this()); } } void FakeConnection::connect(const HostAddressPort& address) { if (delayConnect) { state = Connecting; } else { if (!error) { connectedTo = address; state = Connected; } else { state = DisconnectedWithError; } eventLoop->postEvent( - boost::bind(boost::ref(onConnectFinished), error), + boost::bind(boost::ref(onConnectFinished), error ? true : false), shared_from_this()); } } void FakeConnection::disconnect() { if (!error) { state = Disconnected; } else { state = DisconnectedWithError; } connectedTo.reset(); eventLoop->postEvent( boost::bind(boost::ref(onDisconnected), error), shared_from_this()); } } diff --git a/Swiften/Network/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp index c7a41ff..dcae641 100644 --- a/Swiften/Network/NATPMPInterface.cpp +++ b/Swiften/Network/NATPMPInterface.cpp @@ -1,127 +1,133 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* +* Copyright (c) 2014 Kevin Smith +* Licensed under the GNU General Public License v3. +* See Documentation/Licenses/GPLv3.txt for more information. +*/ + #include <Swiften/Network/NATPMPInterface.h> #include <boost/smart_ptr/make_shared.hpp> #include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Log.h> // This has to be included after the previous headers, because of WIN32 macro // being defined somewhere. #include <natpmp.h> #pragma GCC diagnostic ignored "-Wold-style-cast" namespace Swift { struct NATPMPInterface::Private { natpmp_t natpmp; }; NATPMPInterface::NATPMPInterface() : p(boost::make_shared<Private>()) { initnatpmp(&p->natpmp, 0, 0); } NATPMPInterface::~NATPMPInterface() { closenatpmp(&p->natpmp); } bool NATPMPInterface::isAvailable() { - return getPublicIP(); + return getPublicIP() ? true : false; } boost::optional<HostAddress> NATPMPInterface::getPublicIP() { if (sendpublicaddressrequest(&p->natpmp) < 0) { SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl; return boost::optional<HostAddress>(); } int r = 0; natpmpresp_t response; do { fd_set fds; struct timeval timeout; FD_ZERO(&fds); FD_SET(p->natpmp.s, &fds); getnatpmprequesttimeout(&p->natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&p->natpmp, &response); } while (r == NATPMP_TRYAGAIN); if (r == 0) { return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4)); } else { SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl; return boost::optional<HostAddress>(); } } boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, int publicPort) { NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); if (sendnewportmappingrequest( &p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, boost::numeric_cast<uint16_t>(mapping.getLocalPort()), boost::numeric_cast<uint16_t>(mapping.getPublicPort()), boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) { SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl; return boost::optional<NATPortMapping>(); } int r = 0; natpmpresp_t response; do { fd_set fds; struct timeval timeout; FD_ZERO(&fds); FD_SET(p->natpmp.s, &fds); getnatpmprequesttimeout(&p->natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&p->natpmp, &response); } while(r == NATPMP_TRYAGAIN); if (r == 0) { NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime)); return result; } else { SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; return boost::optional<NATPortMapping>(); } } bool NATPMPInterface::removePortForward(const NATPortMapping& mapping) { if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, boost::numeric_cast<uint32_t>(mapping.getLocalPort())) < 0) { SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl; return false; } int r = 0; natpmpresp_t response; do { fd_set fds; struct timeval timeout; FD_ZERO(&fds); FD_SET(p->natpmp.s, &fds); getnatpmprequesttimeout(&p->natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&p->natpmp, &response); } while(r == NATPMP_TRYAGAIN); if (r == 0) { return true; } else { SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; return false; } } } diff --git a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp index 14a80e6..7be4c26 100644 --- a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp +++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp @@ -1,88 +1,94 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* +* Copyright (c) 2014 Kevin Smith +* Licensed under the GNU General Public License v3. +* See Documentation/Licenses/GPLv3.txt for more information. +*/ + #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include "JingleS5BTransportMethodPayloadParser.h" #include <Swiften/Base/Log.h> namespace Swift { JingleS5BTransportMethodPayloadParser::JingleS5BTransportMethodPayloadParser() : level(0) { } void JingleS5BTransportMethodPayloadParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) { if (level == 0) { getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or("")); std::string mode = attributes.getAttributeValue("mode").get_value_or("tcp"); if (mode == "tcp") { getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode); } else if(mode == "udp") { getPayloadInternal()->setMode(JingleS5BTransportPayload::UDPMode); } else { - std::cerr << "Unknown S5B mode; falling back to defaul!" << std::endl; + SWIFT_LOG(warning) << "Unknown S5B mode; falling back to defaul!"; getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode); } } else if (level == 1) { if (element == "candidate") { JingleS5BTransportPayload::Candidate candidate; candidate.cid = attributes.getAttributeValue("cid").get_value_or(""); int port = -1; try { port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("-1")); } catch(boost::bad_lexical_cast &) { } candidate.hostPort = HostAddressPort(HostAddress(attributes.getAttributeValue("host").get_value_or("")), port); candidate.jid = JID(attributes.getAttributeValue("jid").get_value_or("")); int priority = -1; try { priority = boost::lexical_cast<int>(attributes.getAttributeValue("priority").get_value_or("-1")); } catch(boost::bad_lexical_cast &) { } candidate.priority = priority; candidate.type = stringToType(attributes.getAttributeValue("type").get_value_or("direct")); getPayloadInternal()->addCandidate(candidate); } else if (element == "candidate-used") { getPayloadInternal()->setCandidateUsed(attributes.getAttributeValue("cid").get_value_or("")); } else if (element == "candidate-error") { getPayloadInternal()->setCandidateError(true); } else if (element == "activated") { getPayloadInternal()->setActivated(attributes.getAttributeValue("cid").get_value_or("")); } else if (element == "proxy-error") { getPayloadInternal()->setProxyError(true); } } ++level; } void JingleS5BTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) { --level; } void JingleS5BTransportMethodPayloadParser::handleCharacterData(const std::string&) { } JingleS5BTransportPayload::Candidate::Type JingleS5BTransportMethodPayloadParser::stringToType(const std::string &str) const { if (str == "direct") { return JingleS5BTransportPayload::Candidate::DirectType; } else if (str == "assisted") { return JingleS5BTransportPayload::Candidate::AssistedType; } else if (str == "tunnel") { return JingleS5BTransportPayload::Candidate::TunnelType; } else if (str == "proxy") { return JingleS5BTransportPayload::Candidate::ProxyType; } else { - std::cerr << "Unknown candidate type; falling back to default!" << std::endl; + SWIFT_LOG(warning) << "Unknown candidate type; falling back to default!"; return JingleS5BTransportPayload::Candidate::DirectType; } } } diff --git a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp index 0e21812..6ba264a 100644 --- a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp @@ -1,78 +1,85 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* +* Copyright (c) 2014 Kevin Smith +* Licensed under the GNU General Public License v3. +* See Documentation/Licenses/GPLv3.txt for more information. +*/ + #include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h> #include <boost/shared_ptr.hpp> #include <boost/smart_ptr/make_shared.hpp> #include <boost/smart_ptr/intrusive_ptr.hpp> +#include <Swiften/Base/Log.h> #include <Swiften/Base/foreach.h> #include <Swiften/Serializer/XML/XMLNode.h> #include <Swiften/Serializer/XML/XMLElement.h> #include <Swiften/Serializer/XML/XMLRawTextNode.h> #include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h> #include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h> namespace Swift { JingleContentPayloadSerializer::JingleContentPayloadSerializer() { } std::string JingleContentPayloadSerializer::serializePayload(boost::shared_ptr<JingleContentPayload> payload) const { XMLElement payloadXML("content"); payloadXML.setAttribute("creator", creatorToString(payload->getCreator())); payloadXML.setAttribute("name", payload->getName()); if (!payload->getDescriptions().empty()) { // JingleFileTransferDescription JingleFileTransferDescriptionSerializer ftSerializer; JingleFileTransferDescription::ref filetransfer; foreach(JingleDescription::ref desc, payload->getDescriptions()) { if ((filetransfer = boost::dynamic_pointer_cast<JingleFileTransferDescription>(desc))) { payloadXML.addNode(boost::make_shared<XMLRawTextNode>(ftSerializer.serializePayload(filetransfer))); } } } if (!payload->getTransports().empty()) { // JingleIBBTransportPayload JingleIBBTransportPayloadSerializer ibbSerializer; JingleIBBTransportPayload::ref ibb; // JingleS5BTransportPayload JingleS5BTransportPayloadSerializer s5bSerializer; JingleS5BTransportPayload::ref s5b; foreach(JingleTransportPayload::ref transport, payload->getTransports()) { if ((ibb = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) { payloadXML.addNode(boost::make_shared<XMLRawTextNode>(ibbSerializer.serializePayload(ibb))); } else if ((s5b = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport))) { payloadXML.addNode(boost::make_shared<XMLRawTextNode>(s5bSerializer.serializePayload(s5b))); } } } return payloadXML.serialize(); } std::string JingleContentPayloadSerializer::creatorToString(JingleContentPayload::Creator creator) const { switch(creator) { case JingleContentPayload::InitiatorCreator: return "initiator"; case JingleContentPayload::ResponderCreator: return "responder"; case JingleContentPayload::UnknownCreator: - std::cerr << "Serializing unknown creator value." << std::endl; + SWIFT_LOG(error) << "Serializing unknown creator value."; return "ERROR ERROR ERROR"; } assert(false); return ""; } } |
Swift