<commit_before>/**
 * @file persistentConnection.cc
 * @author Konrad Zemek
 * @copyright (C) 2015 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "persistentConnection.h"

#include "exception.h"
#include "logging.h"

#include <asio.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/steady_timer.hpp>
#include <openssl/ssl.h>

#include <future>

using namespace std::placeholders;
using namespace std::literals;

namespace one {
namespace communication {

PersistentConnection::PersistentConnection(std::string host,
    const unsigned short port, asio::ssl::context &context,
    std::function<void(std::string)> onMessage,
    std::function<void(PersistentConnection &)> onReady,
    std::function<std::string()> getHandshake,
    std::function<std::error_code(std::string)> onHandshakeResponse,
    std::function<void(std::error_code)> onHandshakeDone)
    : m_host{std::move(host)}
    , m_port{port}
    , m_context{context}
    , m_onMessage{std::move(onMessage)}
    , m_onReady{std::move(onReady)}
    , m_getHandshake{std::move(getHandshake)}
    , m_onHandshakeResponse{std::move(onHandshakeResponse)}
    , m_callback{std::move(onHandshakeDone)}
{
}

PersistentConnection::~PersistentConnection() { close(); }

void PersistentConnection::connect()
{
    m_socket = std::make_shared<etls::TLSSocket>(m_app, m_context);
    m_socket->connectAsync(m_socket, m_host, m_port,
        createCallback<etls::TLSSocket::Ptr>([=](auto) { this->onConnect(); }));
}

void PersistentConnection::onConnect()
{
    if (!m_getHandshake) {
        start();
        return;
    }

    auto buffer = prepareOutBuffer(m_getHandshake());
    m_socket->sendAsync(
        m_socket, buffer, createCallback([=] { onHandshakeSent(); }));
}

void PersistentConnection::onHandshakeSent()
{
    asyncRead([=](auto) { this->onHandshakeReceived(); });
}

void PersistentConnection::onHandshakeReceived()
{
    std::error_code ec;
    if (m_onHandshakeResponse)
        ec = m_onHandshakeResponse(std::move(m_inData));

    if (ec)
        onError(ec);
    else
        start();
}

void PersistentConnection::onSent()
{
    notify();
    m_onReady(*this);
}

void PersistentConnection::onError(const std::error_code &ec1)
{
    m_recreateTimer.expires_at(
        std::chrono::steady_clock::now() + RECREATE_DELAY);

    m_recreateTimer.async_wait([this](auto ec2) {
        if (!ec2)
            this->connect();
    });

    notify(ec1);
    close();
}

void PersistentConnection::send(std::string message, Callback callback)
{
    asio::post(m_app.ioService(), [
        =,
        message = std::move(message),
        callback = std::move(callback)
    ]() mutable {
        auto socket = getSocket();
        if (!m_connected || !socket) {
            callback(asio::error::not_connected);
            return;
        }

        m_callback = std::move(callback);
        auto buffer = prepareOutBuffer(std::move(message));
        socket->sendAsync(socket, buffer, createCallback([=] { onSent(); }));
    });
}

std::array<asio::const_buffer, 2> PersistentConnection::prepareOutBuffer(
    std::string message)
{
    m_outHeader = htonl(message.size());
    m_outData = std::move(message);
    return {{headerToBuffer(m_outHeader), asio::buffer(m_outData)}};
}

void PersistentConnection::readLoop()
{
    asyncRead([=](asio::mutable_buffer) {
        m_onMessage(std::move(m_inData));
        readLoop();
    });
}

void PersistentConnection::close()
{
    if (!m_socket)
        return;

    ++m_connectionId;
    m_connected = false;

    auto socket = std::atomic_exchange(&m_socket, {});
    socket->closeAsync(socket, {[=] {}, [=](auto) {}});
}

void PersistentConnection::notify(const std::error_code &ec)
{
    if (m_callback) {
        decltype(m_callback) callback;
        std::swap(callback, m_callback);
        callback(ec);
    }
    if (!m_connected && m_onHandshakeDone) {
        m_onHandshakeDone(ec);
    }
}

void PersistentConnection::start()
{
    notify();
    m_connected = true;
    readLoop();
    m_onReady(*this);
}

etls::TLSSocket::Ptr PersistentConnection::getSocket()
{
    return std::atomic_load(&m_socket);
}

template <typename... Args, typename SF>
etls::Callback<Args...> PersistentConnection::createCallback(SF &&onSuccess)
{
    const int connectionId = m_connectionId;

    auto wrappedSuccess = [ =, onSuccess = std::forward<SF>(onSuccess) ](
        Args && ... args) mutable
    {
        if (m_connectionId == connectionId)
            onSuccess(std::forward<Args>(args)...);
    };

    auto wrappedError = [=](const std::error_code &ec) {
        if (m_connectionId == connectionId)
            onError(ec);
    };

    return {std::move(wrappedSuccess), std::move(wrappedError)};
}

template <typename SF> void PersistentConnection::asyncRead(SF &&onSuccess)
{
    auto onHeaderSuccess = [ =, onSuccess = std::forward<SF>(onSuccess) ](
        asio::mutable_buffer) mutable
    {
        const std::size_t size = ntohl(m_inHeader);
        m_inData.resize(size);

        if (auto socket = getSocket())
            socket->recvAsync(socket, asio::buffer(m_inData),
                createCallback<asio::mutable_buffer>(std::move(onSuccess)));
    };

    if (auto socket = getSocket())
        socket->recvAsync(socket, headerToBuffer(m_inHeader),
            createCallback<asio::mutable_buffer>(std::move(onHeaderSuccess)));
}

asio::mutable_buffers_1 PersistentConnection::headerToBuffer(
    std::uint32_t &header)
{
    return {static_cast<void *>(&header), sizeof(header)};
}

std::unique_ptr<Connection> createConnection(std::string host,
    const unsigned short port, asio::ssl::context &context,
    std::function<void(std::string)> onMessage,
    std::function<void(Connection &)> onReady,
    std::function<std::string()> getHandshake,
    std::function<std::error_code(std::string)> onHandshakeResponse,
    std::function<void(std::error_code)> onHandshakeDone)
{
    return std::make_unique<PersistentConnection>(std::move(host), port,
        context, std::move(onMessage), std::move(onReady),
        std::move(getHandshake), std::move(onHandshakeResponse),
        std::move(onHandshakeDone));
}

} // namespace communication
} // namespace one
<commit_msg>Fix adding message size twice to the tpc message in connection layer during retry.<commit_after>/**
 * @file persistentConnection.cc
 * @author Konrad Zemek
 * @copyright (C) 2015 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "persistentConnection.h"

#include "exception.h"
#include "logging.h"

#include <asio.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/steady_timer.hpp>
#include <openssl/ssl.h>

#include <future>

using namespace std::placeholders;
using namespace std::literals;

namespace one {
namespace communication {

PersistentConnection::PersistentConnection(std::string host,
    const unsigned short port, asio::ssl::context &context,
    std::function<void(std::string)> onMessage,
    std::function<void(PersistentConnection &)> onReady,
    std::function<std::string()> getHandshake,
    std::function<std::error_code(std::string)> onHandshakeResponse,
    std::function<void(std::error_code)> onHandshakeDone)
    : m_host{std::move(host)}
    , m_port{port}
    , m_context{context}
    , m_onMessage{std::move(onMessage)}
    , m_onReady{std::move(onReady)}
    , m_getHandshake{std::move(getHandshake)}
    , m_onHandshakeResponse{std::move(onHandshakeResponse)}
    , m_callback{std::move(onHandshakeDone)}
{
}

PersistentConnection::~PersistentConnection() { close(); }

void PersistentConnection::connect()
{
    m_socket = std::make_shared<etls::TLSSocket>(m_app, m_context);
    m_socket->connectAsync(m_socket, m_host, m_port,
        createCallback<etls::TLSSocket::Ptr>([=](auto) { this->onConnect(); }));
}

void PersistentConnection::onConnect()
{
    if (!m_getHandshake) {
        start();
        return;
    }

    auto buffer = prepareOutBuffer(m_getHandshake());
    m_socket->sendAsync(
        m_socket, buffer, createCallback([=] { onHandshakeSent(); }));
}

void PersistentConnection::onHandshakeSent()
{
    asyncRead([=](auto) { this->onHandshakeReceived(); });
}

void PersistentConnection::onHandshakeReceived()
{
    std::error_code ec;
    if (m_onHandshakeResponse)
        ec = m_onHandshakeResponse(std::move(m_inData));

    if (ec)
        onError(ec);
    else
        start();
}

void PersistentConnection::onSent()
{
    notify();
    m_onReady(*this);
}

void PersistentConnection::onError(const std::error_code &ec1)
{
    m_recreateTimer.expires_at(
        std::chrono::steady_clock::now() + RECREATE_DELAY);

    m_recreateTimer.async_wait([this](auto ec2) {
        if (!ec2)
            this->connect();
    });

    notify(ec1);
    close();
}

void PersistentConnection::send(std::string message, Callback callback)
{
    asio::post(m_app.ioService(), [
        =,
        message = std::move(message),
        callback = std::move(callback)
    ]() mutable {
        auto socket = getSocket();
        if (!m_connected || !socket) {
            callback(asio::error::not_connected);
            return;
        }

        m_callback = std::move(callback);
        auto buffer = prepareOutBuffer(message);
        socket->sendAsync(socket, buffer, createCallback([=] { onSent(); }));
    });
}

std::array<asio::const_buffer, 2> PersistentConnection::prepareOutBuffer(
    std::string message)
{
    m_outHeader = htonl(message.size());
    m_outData = std::move(message);
    return {{headerToBuffer(m_outHeader), asio::buffer(m_outData)}};
}

void PersistentConnection::readLoop()
{
    asyncRead([=](asio::mutable_buffer) {
        m_onMessage(std::move(m_inData));
        readLoop();
    });
}

void PersistentConnection::close()
{
    if (!m_socket)
        return;

    ++m_connectionId;
    m_connected = false;

    auto socket = std::atomic_exchange(&m_socket, {});
    socket->closeAsync(socket, {[=] {}, [=](auto) {}});
}

void PersistentConnection::notify(const std::error_code &ec)
{
    if (m_callback) {
        decltype(m_callback) callback;
        std::swap(callback, m_callback);
        callback(ec);
    }
    if (!m_connected && m_onHandshakeDone) {
        m_onHandshakeDone(ec);
    }
}

void PersistentConnection::start()
{
    notify();
    m_connected = true;
    readLoop();
    m_onReady(*this);
}

etls::TLSSocket::Ptr PersistentConnection::getSocket()
{
    return std::atomic_load(&m_socket);
}

template <typename... Args, typename SF>
etls::Callback<Args...> PersistentConnection::createCallback(SF &&onSuccess)
{
    const int connectionId = m_connectionId;

    auto wrappedSuccess = [ =, onSuccess = std::forward<SF>(onSuccess) ](
        Args && ... args) mutable
    {
        if (m_connectionId == connectionId)
            onSuccess(std::forward<Args>(args)...);
    };

    auto wrappedError = [=](const std::error_code &ec) {
        if (m_connectionId == connectionId)
            onError(ec);
    };

    return {std::move(wrappedSuccess), std::move(wrappedError)};
}

template <typename SF> void PersistentConnection::asyncRead(SF &&onSuccess)
{
    auto onHeaderSuccess = [ =, onSuccess = std::forward<SF>(onSuccess) ](
        asio::mutable_buffer) mutable
    {
        const std::size_t size = ntohl(m_inHeader);
        m_inData.resize(size);

        if (auto socket = getSocket())
            socket->recvAsync(socket, asio::buffer(m_inData),
                createCallback<asio::mutable_buffer>(std::move(onSuccess)));
    };

    if (auto socket = getSocket())
        socket->recvAsync(socket, headerToBuffer(m_inHeader),
            createCallback<asio::mutable_buffer>(std::move(onHeaderSuccess)));
}

asio::mutable_buffers_1 PersistentConnection::headerToBuffer(
    std::uint32_t &header)
{
    return {static_cast<void *>(&header), sizeof(header)};
}

std::unique_ptr<Connection> createConnection(std::string host,
    const unsigned short port, asio::ssl::context &context,
    std::function<void(std::string)> onMessage,
    std::function<void(Connection &)> onReady,
    std::function<std::string()> getHandshake,
    std::function<std::error_code(std::string)> onHandshakeResponse,
    std::function<void(std::error_code)> onHandshakeDone)
{
    return std::make_unique<PersistentConnection>(std::move(host), port,
        context, std::move(onMessage), std::move(onReady),
        std::move(getHandshake), std::move(onHandshakeResponse),
        std::move(onHandshakeDone));
}

} // namespace communication
} // namespace one
<|endoftext|>


<commit_before>/**
 * @file
 * A VirtualEndpoint is a representation of an AllJoyn endpoint that exists behind a remote
 * AllJoyn daemon.
 */

/******************************************************************************
 * Copyright (c) 2009-2012, AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <qcc/platform.h>
#include <qcc/String.h>
#include <qcc/StringUtil.h>

#include <vector>

#include <alljoyn/Message.h>

#include "VirtualEndpoint.h"
#include "EndpointHelper.h"

#include <alljoyn/Status.h>

#define QCC_MODULE "ALLJOYN_OBJ"

using namespace std;
using namespace qcc;

namespace ajn {

_VirtualEndpoint::_VirtualEndpoint(const String& uniqueName, RemoteEndpoint& b2bEp) :
    _BusEndpoint(ENDPOINT_TYPE_VIRTUAL),
    m_uniqueName(uniqueName),
    m_hasRefs(false),
    m_epState(EP_STARTED)
{
    m_b2bEndpoints.insert(pair<SessionId, RemoteEndpoint>(0, b2bEp));
}

QStatus _VirtualEndpoint::PushMessage(Message& msg)
{
    return PushMessage(msg, msg->GetSessionId());
}

QStatus _VirtualEndpoint::PushMessage(Message& msg, SessionId id)
{
    QCC_DbgTrace(("_VirtualEndpoint::PushMessage(this=%s [%x], SessionId=%u)", GetUniqueName().c_str(), this, id));

    QStatus status = ER_BUS_NO_ROUTE;
    vector<RemoteEndpoint> tryEndpoints;
    /*
     * There may be multiple routes from this virtual endpoint so we are going to try all of
     * them until we either succeed or run out of options.
     */
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    multimap<SessionId, RemoteEndpoint>::iterator it = (id == 0) ? m_b2bEndpoints.begin() : m_b2bEndpoints.lower_bound(id);
    while ((it != m_b2bEndpoints.end()) && (id == it->first)) {
        RemoteEndpoint ep = it->second;
        tryEndpoints.push_back(ep);
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    /*
     * We got the candidates so now try them all.
     */
    for (vector<RemoteEndpoint>::iterator iter = tryEndpoints.begin(); iter != tryEndpoints.end(); ++iter) {
        if (status != ER_OK) {
            status = (*iter)->PushMessage(msg);
        }
    }
    return status;
}

RemoteEndpoint _VirtualEndpoint::GetBusToBusEndpoint(SessionId sessionId, int* b2bCount) const
{
    RemoteEndpoint ret;
    if (b2bCount) {
        *b2bCount = 0;
    }
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.lower_bound(sessionId);
    while ((it != m_b2bEndpoints.end()) && (it->first == sessionId)) {
        if (!ret->IsValid()) {
            ret = it->second;
        }
        if (b2bCount) {
            (*b2bCount)++;
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return ret;
}

bool _VirtualEndpoint::AddBusToBusEndpoint(RemoteEndpoint& endpoint)
{
    QCC_DbgTrace(("_VirtualEndpoint::AddBusToBusEndpoint(this=%s, b2b=%s)", GetUniqueName().c_str(), endpoint->GetUniqueName().c_str()));

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    /* Sanity check */
    assert(m_epState == EP_STARTED);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.begin();
    bool found = false;
    while ((it != m_b2bEndpoints.end()) && (it->first == 0)) {
        if (it->second == endpoint) {
            found = true;
            break;
        }
        ++it;
    }
    if (!found) {
        m_b2bEndpoints.insert(pair<SessionId, RemoteEndpoint>(0, endpoint));
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return !found;
}

void _VirtualEndpoint::GetSessionIdsForB2B(RemoteEndpoint& endpoint, set<SessionId>& sessionIds)
{
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.begin();
    while (it != m_b2bEndpoints.end()) {
        if (it->first && (it->second == endpoint)) {
            sessionIds.insert(it->first);
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
}

bool _VirtualEndpoint::RemoveBusToBusEndpoint(RemoteEndpoint& endpoint)
{
    QCC_DbgTrace(("_VirtualEndpoint::RemoveBusToBusEndpoint(this=%s, b2b=%s)", GetUniqueName().c_str(), endpoint->GetUniqueName().c_str()));

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.begin();
    while (it != m_b2bEndpoints.end()) {
        if (it->second == endpoint) {
            /* A non-zero session means that the b2b has one less ref */
            if (it->first != 0) {
                it->second->DecrementRef();
            }
            m_b2bEndpoints.erase(it++);
        } else {
            ++it;
        }
    }

    /*
     * This Virtual endpoint reports itself as empty (of b2b endpoints) when any of the following are true:
     * 1) The last b2b ep is being removed.
     * 2) A last session route through this vep is being removed and the b2bEp being removed doesnt connect to the same
     *    remote daemon as a different b2bEp in the vep.
     *
     * This algorithm allows for cleanup of the following triangular routing problem:
     * - Device A connects to device B
     * - Device A connects to device C
     * - Device B connects to device C
     * - At this point, each device has a vep for A with 2 b2bEps.
     * - Now device A leaves the bus.
     * - B knows to remove the direct B2BEp to A but it (would otherwise) think it can still reach A through C
     * - C knows to remove the direct B2bEp to A but it (would otherwise) think it can still reach A through B
     * This algorithm solves this problem by removing the veps when they no longer route for any session AND
     * when they are suseptible to the triangular route problem.
     */
    bool isEmpty;
    if (m_hasRefs) {
        isEmpty = (m_b2bEndpoints.lower_bound(1) == m_b2bEndpoints.end());
        if (isEmpty) {
            const qcc::GUID128& guid = endpoint->GetRemoteGUID();
            it = m_b2bEndpoints.begin();
            while (it != m_b2bEndpoints.end()) {
                if (it->second->GetRemoteGUID() == guid) {
                    isEmpty = false;
                    break;
                }
                ++it;
            }
        }
    } else {
        isEmpty = m_b2bEndpoints.empty();
    }
    if (isEmpty) {
        /* The last b2b endpoint has been removed from this virtual endpoint. Set the state to STOPPING. */
        m_epState = EP_STOPPING;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return isEmpty;
}

QStatus _VirtualEndpoint::AddSessionRef(SessionId id, RemoteEndpoint& b2bEp)
{
    QCC_DbgTrace(("_VirtualEndpoint::AddSessionRef(this=%s [%x], id=%u, b2b=%s)", GetUniqueName().c_str(), this, id, b2bEp->GetUniqueName().c_str()));

    assert(id != 0);

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    /* Sanity check. Make sure b2bEp is connected to this virtual ep (with sessionId == 0) */
    bool canUse = CanUseRoute(b2bEp);
    if (canUse) {
        /* Increment b2bEp ref */
        b2bEp->IncrementRef();
        /* Map sessionId to b2bEp */
        m_b2bEndpoints.insert(pair<SessionId, RemoteEndpoint>(id, b2bEp));
        m_hasRefs = true;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return canUse ? ER_OK : ER_BUS_NO_ENDPOINT;
}

QStatus _VirtualEndpoint::AddSessionRef(SessionId id, SessionOpts* opts, RemoteEndpoint& b2bEp)
{
    QCC_DbgTrace(("_VirtualEndpoint::AddSessionRef(this=%s [%x], %u, <opts>, %s)", GetUniqueName().c_str(), this, id, b2bEp->GetUniqueName().c_str()));

    RemoteEndpoint bestEp;
    //uint32_t hops = 1000;

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    /* TODO: Placeholder until we exchange session opts and hop count via ExchangeNames */
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.find(id);
    if (it == m_b2bEndpoints.end()) {
        it = m_b2bEndpoints.begin();
    }
    if ((it != m_b2bEndpoints.end()) && ((it->first == 0) || it->first == id)) {
        bestEp = it->second;
    }

    /* Map session id to bestEp */
    if (bestEp->IsValid()) {
        AddSessionRef(id, bestEp);
    }
    b2bEp = bestEp;
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return bestEp->IsValid() ? ER_OK : ER_BUS_NO_ENDPOINT;
}

void _VirtualEndpoint::RemoveSessionRef(SessionId id)
{
    QCC_DbgTrace(("_VirtualEndpoint::RemoveSessionRef(this=%s [%x], id=%u)", GetUniqueName().c_str(), this, id));
    assert(id != 0);
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.find(id);
    if (it != m_b2bEndpoints.end()) {
        it->second->DecrementRef();
        m_b2bEndpoints.erase(it);
    } else {
        QCC_DbgPrintf(("_VirtualEndpoint::RemoveSessionRef: vep=%s failed to find session = %u", m_uniqueName.c_str(), id));
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
}

bool _VirtualEndpoint::CanUseRoute(const RemoteEndpoint& b2bEndpoint) const
{
    bool isFound = false;
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.begin();
    while ((it != m_b2bEndpoints.end()) && (it->first == 0)) {
        if (it->second == b2bEndpoint) {
            isFound = true;
            break;
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return isFound;
}

bool _VirtualEndpoint::CanUseRoutes(const multiset<String>& b2bNameSet) const
{
    bool isFound = false;
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multiset<String>::const_iterator nit = b2bNameSet.begin();
    while (nit != b2bNameSet.end()) {
        multimap<SessionId, RemoteEndpoint>::const_iterator eit = m_b2bEndpoints.begin();
        while (eit != m_b2bEndpoints.end()) {
            String n = eit->second->GetUniqueName();
            if (*nit == n) {
                isFound = true;
                break;
            }
            ++eit;
        }
        if (isFound) {
            break;
        }
        ++nit;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return isFound;
}

bool _VirtualEndpoint::CanRouteWithout(const qcc::GUID128& guid) const
{
    bool canRoute = false;
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.begin();
    while (it != m_b2bEndpoints.end()) {
        if (guid != it->second->GetRemoteGUID()) {
            canRoute = true;
            break;
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return canRoute;
}

}
<commit_msg>AJCORE-820 Virtual endpoint containing a b2b ep with a matching remote GUID is not empty.<commit_after>/**
 * @file
 * A VirtualEndpoint is a representation of an AllJoyn endpoint that exists behind a remote
 * AllJoyn daemon.
 */

/******************************************************************************
 * Copyright (c) 2009-2014, AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <qcc/platform.h>
#include <qcc/String.h>
#include <qcc/StringUtil.h>

#include <vector>

#include <alljoyn/Message.h>

#include "VirtualEndpoint.h"
#include "EndpointHelper.h"

#include <alljoyn/Status.h>

#define QCC_MODULE "ALLJOYN_OBJ"

using namespace std;
using namespace qcc;

namespace ajn {

_VirtualEndpoint::_VirtualEndpoint(const String& uniqueName, RemoteEndpoint& b2bEp) :
    _BusEndpoint(ENDPOINT_TYPE_VIRTUAL),
    m_uniqueName(uniqueName),
    m_hasRefs(false),
    m_epState(EP_STARTED)
{
    m_b2bEndpoints.insert(pair<SessionId, RemoteEndpoint>(0, b2bEp));
}

QStatus _VirtualEndpoint::PushMessage(Message& msg)
{
    return PushMessage(msg, msg->GetSessionId());
}

QStatus _VirtualEndpoint::PushMessage(Message& msg, SessionId id)
{
    QCC_DbgTrace(("_VirtualEndpoint::PushMessage(this=%s [%x], SessionId=%u)", GetUniqueName().c_str(), this, id));

    QStatus status = ER_BUS_NO_ROUTE;
    vector<RemoteEndpoint> tryEndpoints;
    /*
     * There may be multiple routes from this virtual endpoint so we are going to try all of
     * them until we either succeed or run out of options.
     */
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    multimap<SessionId, RemoteEndpoint>::iterator it = (id == 0) ? m_b2bEndpoints.begin() : m_b2bEndpoints.lower_bound(id);
    while ((it != m_b2bEndpoints.end()) && (id == it->first)) {
        RemoteEndpoint ep = it->second;
        tryEndpoints.push_back(ep);
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    /*
     * We got the candidates so now try them all.
     */
    for (vector<RemoteEndpoint>::iterator iter = tryEndpoints.begin(); iter != tryEndpoints.end(); ++iter) {
        if (status != ER_OK) {
            status = (*iter)->PushMessage(msg);
        }
    }
    return status;
}

RemoteEndpoint _VirtualEndpoint::GetBusToBusEndpoint(SessionId sessionId, int* b2bCount) const
{
    RemoteEndpoint ret;
    if (b2bCount) {
        *b2bCount = 0;
    }
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.lower_bound(sessionId);
    while ((it != m_b2bEndpoints.end()) && (it->first == sessionId)) {
        if (!ret->IsValid()) {
            ret = it->second;
        }
        if (b2bCount) {
            (*b2bCount)++;
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return ret;
}

bool _VirtualEndpoint::AddBusToBusEndpoint(RemoteEndpoint& endpoint)
{
    QCC_DbgTrace(("_VirtualEndpoint::AddBusToBusEndpoint(this=%s, b2b=%s)", GetUniqueName().c_str(), endpoint->GetUniqueName().c_str()));

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    /* Sanity check */
    assert(m_epState == EP_STARTED);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.begin();
    bool found = false;
    while ((it != m_b2bEndpoints.end()) && (it->first == 0)) {
        if (it->second == endpoint) {
            found = true;
            break;
        }
        ++it;
    }
    if (!found) {
        m_b2bEndpoints.insert(pair<SessionId, RemoteEndpoint>(0, endpoint));
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return !found;
}

void _VirtualEndpoint::GetSessionIdsForB2B(RemoteEndpoint& endpoint, set<SessionId>& sessionIds)
{
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.begin();
    while (it != m_b2bEndpoints.end()) {
        if (it->first && (it->second == endpoint)) {
            sessionIds.insert(it->first);
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
}

bool _VirtualEndpoint::RemoveBusToBusEndpoint(RemoteEndpoint& endpoint)
{
    QCC_DbgTrace(("_VirtualEndpoint::RemoveBusToBusEndpoint(this=%s, b2b=%s)", GetUniqueName().c_str(), endpoint->GetUniqueName().c_str()));

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.begin();
    while (it != m_b2bEndpoints.end()) {
        if (it->second == endpoint) {
            /* A non-zero session means that the b2b has one less ref */
            if (it->first != 0) {
                it->second->DecrementRef();
            }
            m_b2bEndpoints.erase(it++);
        } else {
            ++it;
        }
    }

    /*
     * This Virtual endpoint reports itself as empty (of b2b endpoints) when any of the following are true:
     * 1) The last b2b ep is being removed.
     * 2) A last session route through this vep is being removed and the b2bEp being removed doesnt connect to the same
     *    remote daemon as a different b2bEp in the vep.
     *
     * This algorithm allows for cleanup of the following triangular routing problem:
     * - Device A connects to device B
     * - Device A connects to device C
     * - Device B connects to device C
     * - At this point, each device has a vep for A with 2 b2bEps.
     * - Now device A leaves the bus.
     * - B knows to remove the direct B2BEp to A but it (would otherwise) think it can still reach A through C
     * - C knows to remove the direct B2bEp to A but it (would otherwise) think it can still reach A through B
     * This algorithm solves this problem by removing the veps when they no longer route for any session AND
     * when they are suseptible to the triangular route problem.
     */
    bool isEmpty;
    if (m_hasRefs) {
        isEmpty = (m_b2bEndpoints.lower_bound(1) == m_b2bEndpoints.end());
        size_t pos = GetUniqueName().find_first_of(".");
        String vepGUID = GetUniqueName().substr(1, pos - 1);
        if (isEmpty) {
            const qcc::GUID128& guid = endpoint->GetRemoteGUID();
            it = m_b2bEndpoints.begin();
            while (it != m_b2bEndpoints.end()) {
                /* If the endpoint going away has the same remote GUID as another one in the m_b2bEndpoints map OR
                 * If the Remote guid of a endpoint in the m_b2bEndpoints map is the same as the VirtualEndpoint GUID:
                 * then this Virtual endpoint is still valid.
                 */
                if ((it->second->GetRemoteGUID() == guid) || (it->second->GetRemoteGUID().ToShortString() == vepGUID)) {
                    isEmpty = false;
                    break;
                }
                ++it;
            }
        }
    } else {
        isEmpty = m_b2bEndpoints.empty();
    }
    if (isEmpty) {
        /* The last b2b endpoint has been removed from this virtual endpoint. Set the state to STOPPING. */
        m_epState = EP_STOPPING;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return isEmpty;
}

QStatus _VirtualEndpoint::AddSessionRef(SessionId id, RemoteEndpoint& b2bEp)
{
    QCC_DbgTrace(("_VirtualEndpoint::AddSessionRef(this=%s [%x], id=%u, b2b=%s)", GetUniqueName().c_str(), this, id, b2bEp->GetUniqueName().c_str()));

    assert(id != 0);

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    /* Sanity check. Make sure b2bEp is connected to this virtual ep (with sessionId == 0) */
    bool canUse = CanUseRoute(b2bEp);
    if (canUse) {
        /* Increment b2bEp ref */
        b2bEp->IncrementRef();
        /* Map sessionId to b2bEp */
        m_b2bEndpoints.insert(pair<SessionId, RemoteEndpoint>(id, b2bEp));
        m_hasRefs = true;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return canUse ? ER_OK : ER_BUS_NO_ENDPOINT;
}

QStatus _VirtualEndpoint::AddSessionRef(SessionId id, SessionOpts* opts, RemoteEndpoint& b2bEp)
{
    QCC_DbgTrace(("_VirtualEndpoint::AddSessionRef(this=%s [%x], %u, <opts>, %s)", GetUniqueName().c_str(), this, id, b2bEp->GetUniqueName().c_str()));

    RemoteEndpoint bestEp;
    //uint32_t hops = 1000;

    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);

    /* TODO: Placeholder until we exchange session opts and hop count via ExchangeNames */
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.find(id);
    if (it == m_b2bEndpoints.end()) {
        it = m_b2bEndpoints.begin();
    }
    if ((it != m_b2bEndpoints.end()) && ((it->first == 0) || it->first == id)) {
        bestEp = it->second;
    }

    /* Map session id to bestEp */
    if (bestEp->IsValid()) {
        AddSessionRef(id, bestEp);
    }
    b2bEp = bestEp;
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return bestEp->IsValid() ? ER_OK : ER_BUS_NO_ENDPOINT;
}

void _VirtualEndpoint::RemoveSessionRef(SessionId id)
{
    QCC_DbgTrace(("_VirtualEndpoint::RemoveSessionRef(this=%s [%x], id=%u)", GetUniqueName().c_str(), this, id));
    assert(id != 0);
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::iterator it = m_b2bEndpoints.find(id);
    if (it != m_b2bEndpoints.end()) {
        it->second->DecrementRef();
        m_b2bEndpoints.erase(it);
    } else {
        QCC_DbgPrintf(("_VirtualEndpoint::RemoveSessionRef: vep=%s failed to find session = %u", m_uniqueName.c_str(), id));
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
}

bool _VirtualEndpoint::CanUseRoute(const RemoteEndpoint& b2bEndpoint) const
{
    bool isFound = false;
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.begin();
    while ((it != m_b2bEndpoints.end()) && (it->first == 0)) {
        if (it->second == b2bEndpoint) {
            isFound = true;
            break;
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return isFound;
}

bool _VirtualEndpoint::CanUseRoutes(const multiset<String>& b2bNameSet) const
{
    bool isFound = false;
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multiset<String>::const_iterator nit = b2bNameSet.begin();
    while (nit != b2bNameSet.end()) {
        multimap<SessionId, RemoteEndpoint>::const_iterator eit = m_b2bEndpoints.begin();
        while (eit != m_b2bEndpoints.end()) {
            String n = eit->second->GetUniqueName();
            if (*nit == n) {
                isFound = true;
                break;
            }
            ++eit;
        }
        if (isFound) {
            break;
        }
        ++nit;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return isFound;
}

bool _VirtualEndpoint::CanRouteWithout(const qcc::GUID128& guid) const
{
    bool canRoute = false;
    m_b2bEndpointsLock.Lock(MUTEX_CONTEXT);
    multimap<SessionId, RemoteEndpoint>::const_iterator it = m_b2bEndpoints.begin();
    while (it != m_b2bEndpoints.end()) {
        if (guid != it->second->GetRemoteGUID()) {
            canRoute = true;
            break;
        }
        ++it;
    }
    m_b2bEndpointsLock.Unlock(MUTEX_CONTEXT);
    return canRoute;
}

}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: extract_indices.hpp 1897 2011-07-26 20:35:49Z rusu $
 *
 */

#ifndef PCL_FILTERS_IMPL_CROP_BOX_H_
#define PCL_FILTERS_IMPL_CROP_BOX_H_

#include "pcl/filters/crop_box.h"

///////////////////////////////////////////////////////////////////////////////
template<typename PointT>
void
pcl::CropBox<PointT>::applyFilter (PointCloud &output)
{

}

///////////////////////////////////////////////////////////////////////////////
template<typename PointT> void
pcl::CropBox<PointT>::applyFilter (std::vector<int> &indices)
{

  indices.resize (input_->points.size ());
  int indice_count = 0;

  Eigen::Affine3f transform = Eigen::Affine3f::Identity();
  Eigen::Affine3f inverse_transform = Eigen::Affine3f::Identity();

  if (rotation_ != Eigen::Vector3f::Zero ())
  {
    pcl::getTransformation (0, 0, 0,
                            rotation_ (0), rotation_ (1), rotation_ (2), transform);
    inverse_transform = transform.inverse();
  }

  for (size_t index = 0; index < indices_->size (); ++index)
  {
    // Get local point
    PointT local_pt = input_->points[(*indices_)[index]];

    // Transform point to world space
    if (!(transform_.matrix().isIdentity()))
      local_pt = pcl::transformPoint<PointT> (local_pt, transform_);

    if (translation_ != Eigen::Vector3f::Zero ())
    {
      local_pt.x -= translation_ (0);
      local_pt.y -= translation_ (1);
      local_pt.z -= translation_ (2);
    }

    // Transform point to local space of crop box
    if (!(inverse_transform.matrix().isIdentity()))
      local_pt = pcl::transformPoint<PointT> (local_pt, inverse_transform);

    if (local_pt.x < min_pt_[0] || local_pt.y < min_pt_[1] || local_pt.z < min_pt_[2])
      continue;
    if (local_pt.x > max_pt_[0] || local_pt.y > max_pt_[1] || local_pt.z > max_pt_[2])
      continue;

    indices[indice_count++] = (*indices_)[index];
  }
  indices.resize (indice_count);
}

#define PCL_INSTANTIATE_CropBox(T) template class PCL_EXPORTS pcl::CropBox<T>;

#endif    // PCL_FILTERS_IMPL_CROP_BOX_H_
<commit_msg>crop_box filter now supports PointT point clouds<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: extract_indices.hpp 1897 2011-07-26 20:35:49Z rusu $
 *
 */

#ifndef PCL_FILTERS_IMPL_CROP_BOX_H_
#define PCL_FILTERS_IMPL_CROP_BOX_H_

#include "pcl/filters/crop_box.h"

///////////////////////////////////////////////////////////////////////////////
template<typename PointT>
void
pcl::CropBox<PointT>::applyFilter (PointCloud &output)
{
  output.resize (input_->points.size ());
  int indice_count = 0;

  Eigen::Affine3f transform = Eigen::Affine3f::Identity();
  Eigen::Affine3f inverse_transform = Eigen::Affine3f::Identity();

  if (rotation_ != Eigen::Vector3f::Zero ())
  {
    pcl::getTransformation (0, 0, 0,
                            rotation_ (0), rotation_ (1), rotation_ (2),
                            transform);
    inverse_transform = transform.inverse();
  }

  for (size_t index = 0; index < indices_->size (); ++index)
  {
    // Get local point
    PointT local_pt = input_->points[(*indices_)[index]];

    // Transform point to world space
    if (!(transform_.matrix().isIdentity()))
      local_pt = pcl::transformPoint<PointT> (local_pt, transform_);

    if (translation_ != Eigen::Vector3f::Zero ())
    {
      local_pt.x -= translation_ (0);
      local_pt.y -= translation_ (1);
      local_pt.z -= translation_ (2);
    }

    // Transform point to local space of crop box
    if (!(inverse_transform.matrix().isIdentity()))
      local_pt = pcl::transformPoint<PointT> (local_pt, inverse_transform);

    if (local_pt.x < min_pt_[0] || local_pt.y < min_pt_[1] || local_pt.z < min_pt_[2])
      continue;
    if (local_pt.x > max_pt_[0] || local_pt.y > max_pt_[1] || local_pt.z > max_pt_[2])
      continue;

    output.points[indice_count++] = input_->points[(*indices_)[index]];
  }
  output.resize (indice_count);
}

///////////////////////////////////////////////////////////////////////////////
template<typename PointT> void
pcl::CropBox<PointT>::applyFilter (std::vector<int> &indices)
{
  indices.resize (input_->points.size ());
  int indice_count = 0;

  Eigen::Affine3f transform = Eigen::Affine3f::Identity();
  Eigen::Affine3f inverse_transform = Eigen::Affine3f::Identity();

  if (rotation_ != Eigen::Vector3f::Zero ())
  {
    pcl::getTransformation (0, 0, 0,
                            rotation_ (0), rotation_ (1), rotation_ (2),
                            transform);
    inverse_transform = transform.inverse();
  }

  for (size_t index = 0; index < indices_->size (); ++index)
  {
    // Get local point
    PointT local_pt = input_->points[(*indices_)[index]];

    // Transform point to world space
    if (!(transform_.matrix().isIdentity()))
      local_pt = pcl::transformPoint<PointT> (local_pt, transform_);

    if (translation_ != Eigen::Vector3f::Zero ())
    {
      local_pt.x -= translation_ (0);
      local_pt.y -= translation_ (1);
      local_pt.z -= translation_ (2);
    }

    // Transform point to local space of crop box
    if (!(inverse_transform.matrix().isIdentity()))
      local_pt = pcl::transformPoint<PointT> (local_pt, inverse_transform);

    if (local_pt.x < min_pt_[0] || local_pt.y < min_pt_[1] || local_pt.z < min_pt_[2])
      continue;
    if (local_pt.x > max_pt_[0] || local_pt.y > max_pt_[1] || local_pt.z > max_pt_[2])
      continue;

    indices[indice_count++] = (*indices_)[index];
  }
  indices.resize (indice_count);
}

#define PCL_INSTANTIATE_CropBox(T) template class PCL_EXPORTS pcl::CropBox<T>;

#endif    // PCL_FILTERS_IMPL_CROP_BOX_H_
<|endoftext|>


<commit_before>#include <Poco/Buffer.h>
#include <Poco/Clock.h>
#include <Poco/Logger.h>
#include <Poco/SharedPtr.h>
#include <Poco/JSON/Object.h>
#include <Poco/Net/HTTPServerRequestImpl.h>
#include <Poco/Net/WebSocket.h>

#include "di/Injectable.h"
#include "gwmessage/GWGatewayRegister.h"
#include "gwmessage/GWGatewayAccepted.h"
#include "gws/GWRequestHandler.h"
#include "util/Sanitize.h"
#include "util/ThreadNamer.h"

BEEEON_OBJECT_BEGIN(BeeeOn, GWRequestHandlerFactory)
BEEEON_OBJECT_CASTABLE(WebSocketRequestHandlerFactory)
BEEEON_OBJECT_PROPERTY("gatewayCommunicator", &GWRequestHandlerFactory::setGatewayCommunicator)
BEEEON_OBJECT_PROPERTY("maxMessageSize", &GWRequestHandlerFactory::setMaxMessageSize)
BEEEON_OBJECT_PROPERTY("gatewayService", &GWRequestHandlerFactory::setGatewayService)
BEEEON_OBJECT_PROPERTY("verifierFactory", &GWRequestHandlerFactory::setVerifierFactory)
BEEEON_OBJECT_END(BeeeOn, GWRequestHandlerFactory)

using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;

GWRequestHandler::GWRequestHandler(
		size_t maxMessageSize,
		GatewayCommunicator::Ptr communicator,
		GWSGatewayService::Ptr service,
		GatewayPeerVerifier::Ptr peerVerifier):
	m_maxMessageSize(maxMessageSize),
	m_gatewayCommunicator(communicator),
	m_gatewayService(service),
	m_peerVerifier(peerVerifier)
{
}

void GWRequestHandler::handle(WebSocket &ws)
{
	ThreadNamer namer("ws-" + ws.peerAddress().toString());

	Poco::Buffer<char> buffer(m_maxMessageSize);
	int flags;

	int ret = ws.receiveFrame(buffer.begin(), buffer.size(), flags);
	if (ret <= 0 || (flags & WebSocket::FRAME_OP_CLOSE)) {
		if (logger().warning()) {
			logger().warning(ws.peerAddress().toString()
				+ " connection immediately closed",
				__FILE__, __LINE__);
		}
		return;
	}

	logger().information("connection from "
			+ ws.peerAddress().toString(),
			__FILE__, __LINE__);

	processPayload(ws, {buffer.begin(), static_cast<size_t>(ret)});
}

void GWRequestHandler::processPayload(
		WebSocket &ws,
		const string &data)
{
	if (logger().trace())
		logger().trace(data);

	GWMessage::Ptr msg = GWMessage::fromJSON(data);
	GWGatewayRegister::Ptr registerMsg = msg.cast<GWGatewayRegister>();

	if (registerMsg.isNull()) {
		logger().warning("invalid message from "
			+ ws.peerAddress().toString() + ":\n"
			+ msg->toString(),
			__FILE__, __LINE__);
		return;
	}

	Gateway gateway(registerMsg->gatewayID());
	m_peerVerifier->verifyPeer(gateway);

	ThreadNamer namer("gws-register-" + gateway);

	GatewayStatus status;
	status.setVersion(Sanitize::common(registerMsg->version()));
	status.setIPAddress(registerMsg->ipAddress());

	if (!m_gatewayService->registerGateway(status, gateway)) {
		logger().error("failed to register gateway "
				+ gateway, __FILE__, __LINE__);
		return;
	}

	m_gatewayCommunicator->addGateway(gateway.id(), ws);

	const auto &reply = GWGatewayAccepted().toString();
	ws.sendFrame(reply.c_str(), reply.length());
}

GWRequestHandlerFactory::GWRequestHandlerFactory():
	m_maxMessageSize(256)
{
}

void GWRequestHandlerFactory::setGatewayCommunicator(GatewayCommunicator::Ptr communicator)
{
	m_gatewayCommunicator = communicator;
}

void GWRequestHandlerFactory::setGatewayService(GWSGatewayService::Ptr service)
{
	m_gatewayService = service;
}

void GWRequestHandlerFactory::setVerifierFactory(SocketGatewayPeerVerifierFactory::Ptr factory)
{
	m_verifierFactory = factory;
}

void GWRequestHandlerFactory::setMaxMessageSize(int size)
{
	if (size < 0)
		throw InvalidArgumentException("size must be non-negative");

	m_maxMessageSize = size;
}

WebSocketRequestHandler *GWRequestHandlerFactory::createWSHandler(
	const HTTPServerRequest &request)
{
	GatewayPeerVerifier::Ptr verifier;
	const HTTPServerRequestImpl *impl = nullptr;

	impl = dynamic_cast<const HTTPServerRequestImpl *>(&request);
	if (impl == nullptr) {
		throw IllegalStateException(
			"given request instance is not inherited from HTTPServerRequestImpl");
	}

	verifier = m_verifierFactory->preverifyAndCreate(
			const_cast<HTTPServerRequestImpl *>(impl)->socket());

	return new GWRequestHandler(
		m_maxMessageSize,
		m_gatewayCommunicator,
		m_gatewayService,
		verifier
	);
}
<commit_msg>GWRequestHandler: log initial message in the standard way<commit_after>#include <Poco/Buffer.h>
#include <Poco/Clock.h>
#include <Poco/Logger.h>
#include <Poco/SharedPtr.h>
#include <Poco/JSON/Object.h>
#include <Poco/Net/HTTPServerRequestImpl.h>
#include <Poco/Net/WebSocket.h>

#include "di/Injectable.h"
#include "gwmessage/GWGatewayRegister.h"
#include "gwmessage/GWGatewayAccepted.h"
#include "gws/GWRequestHandler.h"
#include "util/Sanitize.h"
#include "util/ThreadNamer.h"

BEEEON_OBJECT_BEGIN(BeeeOn, GWRequestHandlerFactory)
BEEEON_OBJECT_CASTABLE(WebSocketRequestHandlerFactory)
BEEEON_OBJECT_PROPERTY("gatewayCommunicator", &GWRequestHandlerFactory::setGatewayCommunicator)
BEEEON_OBJECT_PROPERTY("maxMessageSize", &GWRequestHandlerFactory::setMaxMessageSize)
BEEEON_OBJECT_PROPERTY("gatewayService", &GWRequestHandlerFactory::setGatewayService)
BEEEON_OBJECT_PROPERTY("verifierFactory", &GWRequestHandlerFactory::setVerifierFactory)
BEEEON_OBJECT_END(BeeeOn, GWRequestHandlerFactory)

using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;

GWRequestHandler::GWRequestHandler(
		size_t maxMessageSize,
		GatewayCommunicator::Ptr communicator,
		GWSGatewayService::Ptr service,
		GatewayPeerVerifier::Ptr peerVerifier):
	m_maxMessageSize(maxMessageSize),
	m_gatewayCommunicator(communicator),
	m_gatewayService(service),
	m_peerVerifier(peerVerifier)
{
}

void GWRequestHandler::handle(WebSocket &ws)
{
	ThreadNamer namer("ws-" + ws.peerAddress().toString());

	Poco::Buffer<char> buffer(m_maxMessageSize);
	int flags;

	int ret = ws.receiveFrame(buffer.begin(), buffer.size(), flags);
	if (ret <= 0 || (flags & WebSocket::FRAME_OP_CLOSE)) {
		if (logger().warning()) {
			logger().warning(ws.peerAddress().toString()
				+ " connection immediately closed",
				__FILE__, __LINE__);
		}
		return;
	}

	logger().information("connection from "
			+ ws.peerAddress().toString(),
			__FILE__, __LINE__);

	processPayload(ws, {buffer.begin(), static_cast<size_t>(ret)});
}

void GWRequestHandler::processPayload(
		WebSocket &ws,
		const string &data)
{
	if (logger().trace()) {
		logger().dump(
			"initial frame of size " + to_string(data.size()),
			data.data(),
			data.size(),
			Message::PRIO_TRACE);
	}
	else if (logger().debug()) {
		logger().debug(
			"initial frame of size " + to_string(data.size()),
			__FILE__, __LINE__);
	}

	GWMessage::Ptr msg = GWMessage::fromJSON(data);
	GWGatewayRegister::Ptr registerMsg = msg.cast<GWGatewayRegister>();

	if (registerMsg.isNull()) {
		logger().warning("invalid message from "
			+ ws.peerAddress().toString() + ":\n"
			+ msg->toString(),
			__FILE__, __LINE__);
		return;
	}

	Gateway gateway(registerMsg->gatewayID());
	m_peerVerifier->verifyPeer(gateway);

	ThreadNamer namer("gws-register-" + gateway);

	GatewayStatus status;
	status.setVersion(Sanitize::common(registerMsg->version()));
	status.setIPAddress(registerMsg->ipAddress());

	if (!m_gatewayService->registerGateway(status, gateway)) {
		logger().error("failed to register gateway "
				+ gateway, __FILE__, __LINE__);
		return;
	}

	m_gatewayCommunicator->addGateway(gateway.id(), ws);

	const auto &reply = GWGatewayAccepted().toString();
	ws.sendFrame(reply.c_str(), reply.length());
}

GWRequestHandlerFactory::GWRequestHandlerFactory():
	m_maxMessageSize(256)
{
}

void GWRequestHandlerFactory::setGatewayCommunicator(GatewayCommunicator::Ptr communicator)
{
	m_gatewayCommunicator = communicator;
}

void GWRequestHandlerFactory::setGatewayService(GWSGatewayService::Ptr service)
{
	m_gatewayService = service;
}

void GWRequestHandlerFactory::setVerifierFactory(SocketGatewayPeerVerifierFactory::Ptr factory)
{
	m_verifierFactory = factory;
}

void GWRequestHandlerFactory::setMaxMessageSize(int size)
{
	if (size < 0)
		throw InvalidArgumentException("size must be non-negative");

	m_maxMessageSize = size;
}

WebSocketRequestHandler *GWRequestHandlerFactory::createWSHandler(
	const HTTPServerRequest &request)
{
	GatewayPeerVerifier::Ptr verifier;
	const HTTPServerRequestImpl *impl = nullptr;

	impl = dynamic_cast<const HTTPServerRequestImpl *>(&request);
	if (impl == nullptr) {
		throw IllegalStateException(
			"given request instance is not inherited from HTTPServerRequestImpl");
	}

	verifier = m_verifierFactory->preverifyAndCreate(
			const_cast<HTTPServerRequestImpl *>(impl)->socket());

	return new GWRequestHandler(
		m_maxMessageSize,
		m_gatewayCommunicator,
		m_gatewayService,
		verifier
	);
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/targeting/targetservicestart.C $                      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2017                        */
/* [+] Google Inc.                                                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/**
 *  @file targeting/targetservicestart.C
 *
 *  @brief Hostboot entry point for target service
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <stdio.h>
#include <stdlib.h>

// Other components
#include <sys/misc.h>
#include <sys/task.h>
#include <targeting/common/trace.H>
#include <targeting/adapters/assertadapter.H>
#include <initservice/taskargs.H>
#include <util/utilmbox_scratch.H>

// This component
#include <targeting/common/targetservice.H>
#include <targeting/attrrp.H>

// Others
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <devicefw/userif.H>
#include <config.h>
#include <initservice/initserviceif.H>
#include <util/misc.H>

#ifdef CONFIG_DRTM
#include <secureboot/drtm.H>
#endif

using namespace INITSERVICE::SPLESS;
//******************************************************************************
// targetService
//******************************************************************************

namespace TARGETING
{

#define TARG_NAMESPACE "TARGETING::"

#define TARG_LOC TARG_NAMESPACE TARG_CLASS TARG_FN ": "

//******************************************************************************
// _start
//******************************************************************************

#define TARG_CLASS ""

/*
 * @brief Initialize any attributes that need to be set early on
 */
static void initializeAttributes(TargetService& i_targetService,
                                 bool i_isMpipl,
                                 bool i_istepMode,
                                 ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch);

/**
 *  @brief Check that at least one processor of our cpu type is being targeted
 */
static void checkProcessorTargeting(TargetService& i_targetService);

/**
 *  @brief Entry point for initialization service to initialize the targeting
 *      code
 *
 *  @param[in] io_pError
 *      Error log handle; returns NULL on success, !NULL otherwise
 *
 *  @note: Link register is configured to automatically invoke task_end() when
 *      this routine returns
 */
static void initTargeting(errlHndl_t& io_pError)
{
    #define TARG_FN "initTargeting(errlHndl_t& io_pError)"

    TARG_ENTER();

    //Need to stash away the master mbox regs as they will
    //be overwritten
    bool l_isMpipl = false;
    bool l_isIstepMode = false;
    ATTR_MASTER_MBOX_SCRATCH_type l_scratch = {0,0,0,0,0,0,0,0};

    for(size_t i=0; i< sizeof(l_scratch)/sizeof(l_scratch[0]); i++)
    {
        l_scratch[i] =
        Util::readScratchReg(MBOX_SCRATCH_REG1+i);
    }

    // Check mbox scratch reg 3 for IPL boot options
    // Specifically istep mode (bit 0) and MPIPL (bit 2)
    INITSERVICE::SPLESS::MboxScratch3_t l_scratch3;
    l_scratch3.data32 = l_scratch[SCRATCH_3];

    if(l_scratch3.isMpipl)
    {
        TARG_INF("We are running MPIPL mode");
        l_isMpipl = true;
    }
    if(l_scratch3.istepMode)
    {
        l_isIstepMode = true;
    }
    if(l_scratch3.overrideSecurity)
    {
        TARG_INF("WARNING: External tool asked master proc to disable "
            "security.");
    }

    AttrRP::init(io_pError, l_isMpipl);

    if (io_pError == NULL)
    {
        TargetService& l_targetService = targetService();
        (void)l_targetService.init();

        initializeAttributes(l_targetService, l_isMpipl, l_isIstepMode, l_scratch);
        checkProcessorTargeting(l_targetService);

        // Print out top-level model value from loaded targeting values.
        // @TODO RTC:88056 Make the model printed more meaniful
        Target* l_pTopLevel = NULL;
        l_targetService.getTopLevelTarget(l_pTopLevel);
        ATTR_MODEL_type l_model = MODEL_NA;
        if (l_pTopLevel->tryGetAttr<ATTR_MODEL>(l_model)) {
            TARG_INF("Initialized targeting for model: %s",
                     l_pTopLevel->getAttrAsString<ATTR_MODEL>());
        }

#ifdef CONFIG_DRTM
        const INITSERVICE::SPLESS::MboxScratch7_t scratch7 =
            {.data32 = l_scratch[SCRATCH_7] };
        const INITSERVICE::SPLESS::MboxScratch8_t scratch8 =
            {.data32 = l_scratch[SCRATCH_8] };

        errlHndl_t pError = SECUREBOOT::DRTM::discoverDrtmState(
            scratch7,scratch8);
        if(pError)
        {
            auto plid = pError->plid();
            errlCommit(pError,SECURE_COMP_ID);
            // TODO: RTC 167205: Better GA error handling
            INITSERVICE::doShutdown(plid, true);
        }
#endif

// No error module loaded in VPO to save load time
#ifndef CONFIG_VPO_COMPILE
        // call ErrlManager function - tell him that TARG is ready!
        ERRORLOG::ErrlManager::errlResourceReady(ERRORLOG::TARG);
#endif

        // set global that TARG is ready
        Util::setIsTargetingLoaded();
    }

    TARG_EXIT();

#undef TARG_FN
}

/**
 *  @brief Create _start entry point using task entry macro and vector to
 *      initTargeting function
 */
TASK_ENTRY_MACRO(initTargeting);

/**
 *  @brief Check that at least one processor of our cpu type is being targeted
 */
static void checkProcessorTargeting(TargetService& i_targetService)
{
    #define TARG_FN "checkProcessorTargeting()"
    TARG_ENTER();

    PredicateCTM l_procChip(CLASS_CHIP,TYPE_PROC);
    ProcessorCoreType l_coreType = cpu_core_type();
    bool l_haveOneCorrectProcessor = false;
    TargetRangeFilter l_filter(
        i_targetService.begin(),
        i_targetService.end(),
        &l_procChip);

    for(;l_filter && (l_haveOneCorrectProcessor != true);++l_filter)
    {
        switch(l_filter->getAttr<ATTR_MODEL>())
        {
            case MODEL_VENICE:
                if(l_coreType == CORE_POWER8_VENICE)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;

            case MODEL_MURANO:
                if(l_coreType == CORE_POWER8_MURANO)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;

            case MODEL_NAPLES:
                if(l_coreType == CORE_POWER8_NAPLES)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;
            case MODEL_NIMBUS:
                if(l_coreType == CORE_POWER9_NIMBUS)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;
            case MODEL_CUMULUS:
                if(l_coreType == CORE_POWER9_CUMULUS)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;

            default:
                break;
        };
    }

    TARG_ASSERT((l_haveOneCorrectProcessor == true), TARG_ERR_LOC "FATAL: No "
                "targeted processors are of the correct type");

    TARG_EXIT();

    #undef TARG_FN
}

/*
 * @brief Initialize any attributes that need to be set early on
 */
static void initializeAttributes(TargetService& i_targetService,
                                 bool i_isMpipl,
                                 bool i_istepMode,
                                 ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch)
{
    #define TARG_FN "initializeAttributes()...)"
    TARG_ENTER();

    Target* l_pTopLevel = NULL;

    TargetHandleList l_chips;

    i_targetService.getTopLevelTarget(l_pTopLevel);
    if(l_pTopLevel)
    {
        Target* l_pMasterProcChip = NULL;
        i_targetService.masterProcChipTargetHandle(l_pMasterProcChip);

        if(l_pMasterProcChip)
        {
            // Master uses xscom by default, needs to be set before
            // doing any other scom accesses
            ScomSwitches l_switches =
              l_pMasterProcChip->getAttr<ATTR_SCOM_SWITCHES>();
            l_switches.useXscom = 1;
            l_switches.useFsiScom = 0;
            l_switches.useSbeScom = 0;
            l_pMasterProcChip->setAttr<ATTR_SCOM_SWITCHES>(l_switches);

            // Master can only use Host I2C so needs to be set before
            // doing any I2C accesses
            I2cSwitches l_i2c_switches =
              l_pMasterProcChip->getAttr<ATTR_I2C_SWITCHES>();
            l_i2c_switches.useHostI2C = 1;
            l_i2c_switches.useFsiI2C  = 0;
            l_pMasterProcChip->setAttr<ATTR_I2C_SWITCHES>(l_i2c_switches);

            l_pMasterProcChip->setAttr<ATTR_PROC_SBE_MASTER_CHIP>(1);

            // Master has SBE started
            l_pMasterProcChip->setAttr<ATTR_SBE_IS_STARTED>(1);

            l_pTopLevel->setAttr<ATTR_MASTER_MBOX_SCRATCH>(i_masterScratch);

            // Targeting data defaults to non istep, only turn "on" if bit
            // is set so we don't tromp default setting
            if (i_istepMode)
            {
                l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(1);
            }
            else
            {
                l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(0);
            }

            //Set the RISK_LEVEL ATTR based off of master Scratch regs
            INITSERVICE::SPLESS::MboxScratch5_t l_scratch5;
            l_scratch5.data32 = i_masterScratch[INITSERVICE::SPLESS::SCRATCH_5];
            if(l_scratch5.riskLevel)
            {
                l_pTopLevel->setAttr<ATTR_RISK_LEVEL>(1);
            }
        }

        if(i_isMpipl)
        {
            l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(1);

            //Clear out some attributes that could have stale data
            l_pTopLevel->setAttr<ATTR_HB_RSV_MEM_NEXT_SECTION>(0);
            l_pTopLevel->setAttr<ATTR_ATTN_CHK_ALL_PROCS>(1);

            TARGETING::PredicateCTM l_chipFilter(CLASS_CHIP, TYPE_PROC);
            TARGETING::PredicateIsFunctional l_functional;
            TARGETING::PredicatePostfixExpr l_functionalChips;
            l_functionalChips.push(&l_chipFilter).push(&l_functional).And();

            i_targetService.getAssociated( l_chips,
                                        l_pTopLevel,
                                        TargetService::CHILD_BY_AFFINITY,
                                        TARGETING::TargetService::ALL,
                                        &l_functionalChips);

            for (auto & l_chip : l_chips)
            {
                l_chip->setAttr<ATTR_XSCOM_VIRTUAL_ADDR>(0);
                l_chip->setAttr<ATTR_HOMER_VIRT_ADDR>(0);
                //TODO RTC:172534 Need to clear volatile attributes during MPIPL for cumulus
            }
        }
        else
        {
            l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(0);
        }
    }
    else // top level is NULL - never expected
    {
        TARG_INF("Top level target is NULL");
    }

    TARG_EXIT();
    #undef TARG_FN
}

#undef TARG_CLASS

#undef TARG_NAMESPACE

} // End namespace TARGETING

<commit_msg>Fix TPM log manager init in MPIPL mode<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/targeting/targetservicestart.C $                      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2017                        */
/* [+] Google Inc.                                                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/**
 *  @file targeting/targetservicestart.C
 *
 *  @brief Hostboot entry point for target service
 */

//******************************************************************************
// Includes
//******************************************************************************

// STD
#include <stdio.h>
#include <stdlib.h>

// Other components
#include <sys/misc.h>
#include <sys/task.h>
#include <sys/sync.h>
#include <targeting/common/trace.H>
#include <targeting/adapters/assertadapter.H>
#include <initservice/taskargs.H>
#include <util/utilmbox_scratch.H>

// This component
#include <targeting/common/targetservice.H>
#include <targeting/attrrp.H>

// Others
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <devicefw/userif.H>
#include <config.h>
#include <initservice/initserviceif.H>
#include <util/misc.H>

#ifdef CONFIG_DRTM
#include <secureboot/drtm.H>
#endif

using namespace INITSERVICE::SPLESS;
//******************************************************************************
// targetService
//******************************************************************************

namespace TARGETING
{

#define TARG_NAMESPACE "TARGETING::"

#define TARG_LOC TARG_NAMESPACE TARG_CLASS TARG_FN ": "

//******************************************************************************
// _start
//******************************************************************************

#define TARG_CLASS ""

/*
 * @brief Initialize any attributes that need to be set early on
 */
static void initializeAttributes(TargetService& i_targetService,
                                 bool i_isMpipl,
                                 bool i_istepMode,
                                 ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch);

/**
 *  @brief Check that at least one processor of our cpu type is being targeted
 */
static void checkProcessorTargeting(TargetService& i_targetService);

/**
 *  @brief Entry point for initialization service to initialize the targeting
 *      code
 *
 *  @param[in] io_pError
 *      Error log handle; returns NULL on success, !NULL otherwise
 *
 *  @note: Link register is configured to automatically invoke task_end() when
 *      this routine returns
 */
static void initTargeting(errlHndl_t& io_pError)
{
    #define TARG_FN "initTargeting(errlHndl_t& io_pError)"

    TARG_ENTER();

    //Need to stash away the master mbox regs as they will
    //be overwritten
    bool l_isMpipl = false;
    bool l_isIstepMode = false;
    ATTR_MASTER_MBOX_SCRATCH_type l_scratch = {0,0,0,0,0,0,0,0};

    for(size_t i=0; i< sizeof(l_scratch)/sizeof(l_scratch[0]); i++)
    {
        l_scratch[i] =
        Util::readScratchReg(MBOX_SCRATCH_REG1+i);
    }

    // Check mbox scratch reg 3 for IPL boot options
    // Specifically istep mode (bit 0) and MPIPL (bit 2)
    INITSERVICE::SPLESS::MboxScratch3_t l_scratch3;
    l_scratch3.data32 = l_scratch[SCRATCH_3];

    if(l_scratch3.isMpipl)
    {
        TARG_INF("We are running MPIPL mode");
        l_isMpipl = true;
    }
    if(l_scratch3.istepMode)
    {
        l_isIstepMode = true;
    }
    if(l_scratch3.overrideSecurity)
    {
        TARG_INF("WARNING: External tool asked master proc to disable "
            "security.");
    }

    AttrRP::init(io_pError, l_isMpipl);

    if (io_pError == NULL)
    {
        TargetService& l_targetService = targetService();
        (void)l_targetService.init();

        initializeAttributes(l_targetService, l_isMpipl, l_isIstepMode, l_scratch);
        checkProcessorTargeting(l_targetService);

        // Print out top-level model value from loaded targeting values.
        // @TODO RTC:88056 Make the model printed more meaniful
        Target* l_pTopLevel = NULL;
        l_targetService.getTopLevelTarget(l_pTopLevel);
        ATTR_MODEL_type l_model = MODEL_NA;
        if (l_pTopLevel->tryGetAttr<ATTR_MODEL>(l_model)) {
            TARG_INF("Initialized targeting for model: %s",
                     l_pTopLevel->getAttrAsString<ATTR_MODEL>());
        }

#ifdef CONFIG_DRTM
        const INITSERVICE::SPLESS::MboxScratch7_t scratch7 =
            {.data32 = l_scratch[SCRATCH_7] };
        const INITSERVICE::SPLESS::MboxScratch8_t scratch8 =
            {.data32 = l_scratch[SCRATCH_8] };

        errlHndl_t pError = SECUREBOOT::DRTM::discoverDrtmState(
            scratch7,scratch8);
        if(pError)
        {
            auto plid = pError->plid();
            errlCommit(pError,SECURE_COMP_ID);
            // TODO: RTC 167205: Better GA error handling
            INITSERVICE::doShutdown(plid, true);
        }
#endif

// No error module loaded in VPO to save load time
#ifndef CONFIG_VPO_COMPILE
        // call ErrlManager function - tell him that TARG is ready!
        ERRORLOG::ErrlManager::errlResourceReady(ERRORLOG::TARG);
#endif

        // set global that TARG is ready
        Util::setIsTargetingLoaded();
    }

    TARG_EXIT();

#undef TARG_FN
}

/**
 *  @brief Create _start entry point using task entry macro and vector to
 *      initTargeting function
 */
TASK_ENTRY_MACRO(initTargeting);

/**
 *  @brief Check that at least one processor of our cpu type is being targeted
 */
static void checkProcessorTargeting(TargetService& i_targetService)
{
    #define TARG_FN "checkProcessorTargeting()"
    TARG_ENTER();

    PredicateCTM l_procChip(CLASS_CHIP,TYPE_PROC);
    ProcessorCoreType l_coreType = cpu_core_type();
    bool l_haveOneCorrectProcessor = false;
    TargetRangeFilter l_filter(
        i_targetService.begin(),
        i_targetService.end(),
        &l_procChip);

    for(;l_filter && (l_haveOneCorrectProcessor != true);++l_filter)
    {
        switch(l_filter->getAttr<ATTR_MODEL>())
        {
            case MODEL_VENICE:
                if(l_coreType == CORE_POWER8_VENICE)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;

            case MODEL_MURANO:
                if(l_coreType == CORE_POWER8_MURANO)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;

            case MODEL_NAPLES:
                if(l_coreType == CORE_POWER8_NAPLES)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;
            case MODEL_NIMBUS:
                if(l_coreType == CORE_POWER9_NIMBUS)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;
            case MODEL_CUMULUS:
                if(l_coreType == CORE_POWER9_CUMULUS)
                {
                    l_haveOneCorrectProcessor = true;
                }
                break;

            default:
                break;
        };
    }

    TARG_ASSERT((l_haveOneCorrectProcessor == true), TARG_ERR_LOC "FATAL: No "
                "targeted processors are of the correct type");

    TARG_EXIT();

    #undef TARG_FN
}

/*
 * @brief Initialize any attributes that need to be set early on
 */
static void initializeAttributes(TargetService& i_targetService,
                                 bool i_isMpipl,
                                 bool i_istepMode,
                                 ATTR_MASTER_MBOX_SCRATCH_type& i_masterScratch)
{
    #define TARG_FN "initializeAttributes()...)"
    TARG_ENTER();

    Target* l_pTopLevel = NULL;

    TargetHandleList l_chips;

    i_targetService.getTopLevelTarget(l_pTopLevel);
    if(l_pTopLevel)
    {
        Target* l_pMasterProcChip = NULL;
        i_targetService.masterProcChipTargetHandle(l_pMasterProcChip);

        if(l_pMasterProcChip)
        {
            // Master uses xscom by default, needs to be set before
            // doing any other scom accesses
            ScomSwitches l_switches =
              l_pMasterProcChip->getAttr<ATTR_SCOM_SWITCHES>();
            l_switches.useXscom = 1;
            l_switches.useFsiScom = 0;
            l_switches.useSbeScom = 0;
            l_pMasterProcChip->setAttr<ATTR_SCOM_SWITCHES>(l_switches);

            // Master can only use Host I2C so needs to be set before
            // doing any I2C accesses
            I2cSwitches l_i2c_switches =
              l_pMasterProcChip->getAttr<ATTR_I2C_SWITCHES>();
            l_i2c_switches.useHostI2C = 1;
            l_i2c_switches.useFsiI2C  = 0;
            l_pMasterProcChip->setAttr<ATTR_I2C_SWITCHES>(l_i2c_switches);

            l_pMasterProcChip->setAttr<ATTR_PROC_SBE_MASTER_CHIP>(1);

            // Master has SBE started
            l_pMasterProcChip->setAttr<ATTR_SBE_IS_STARTED>(1);

            l_pTopLevel->setAttr<ATTR_MASTER_MBOX_SCRATCH>(i_masterScratch);

            // Targeting data defaults to non istep, only turn "on" if bit
            // is set so we don't tromp default setting
            if (i_istepMode)
            {
                l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(1);
            }
            else
            {
                l_pTopLevel->setAttr<ATTR_ISTEP_MODE>(0);
            }

            //Set the RISK_LEVEL ATTR based off of master Scratch regs
            INITSERVICE::SPLESS::MboxScratch5_t l_scratch5;
            l_scratch5.data32 = i_masterScratch[INITSERVICE::SPLESS::SCRATCH_5];
            if(l_scratch5.riskLevel)
            {
                l_pTopLevel->setAttr<ATTR_RISK_LEVEL>(1);
            }
        }

        if(i_isMpipl)
        {
            l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(1);

            //Clear out some attributes that could have stale data
            l_pTopLevel->setAttr<ATTR_HB_RSV_MEM_NEXT_SECTION>(0);
            l_pTopLevel->setAttr<ATTR_ATTN_CHK_ALL_PROCS>(1);

            TARGETING::PredicateCTM l_chipFilter(CLASS_CHIP, TYPE_PROC);
            TARGETING::PredicateIsFunctional l_functional;
            TARGETING::PredicatePostfixExpr l_functionalChips;
            l_functionalChips.push(&l_chipFilter).push(&l_functional).And();

            i_targetService.getAssociated( l_chips,
                                        l_pTopLevel,
                                        TargetService::CHILD_BY_AFFINITY,
                                        TARGETING::TargetService::ALL,
                                        &l_functionalChips);

            for (auto & l_chip : l_chips)
            {
                l_chip->setAttr<ATTR_XSCOM_VIRTUAL_ADDR>(0);
                l_chip->setAttr<ATTR_HOMER_VIRT_ADDR>(0);
                //TODO RTC:172534 Need to clear volatile attributes during MPIPL for cumulus
            }

            TargetHandleList tpms;
            TARGETING::PredicateCTM tpmFilter(CLASS_CHIP, TYPE_TPM);
            i_targetService.getAssociated(
                tpms,
                l_pTopLevel,
                TargetService::CHILD,
                TARGETING::TargetService::ALL,
                &tpmFilter);
            for (auto & tpm : tpms)
            {
                tpm->setAttr<ATTR_HB_TPM_INIT_ATTEMPTED>(0);
                tpm->setAttr<ATTR_HB_TPM_LOG_MGR_PTR>(0);
                auto tpmMutex=tpm->getHbMutexAttr<ATTR_HB_TPM_MUTEX>();
                mutex_init(tpmMutex);
            }
        }
        else
        {
            l_pTopLevel->setAttr<ATTR_IS_MPIPL_HB>(0);
        }
    }
    else // top level is NULL - never expected
    {
        TARG_INF("Top level target is NULL");
    }

    TARG_EXIT();
    #undef TARG_FN
}

#undef TARG_CLASS

#undef TARG_NAMESPACE

} // End namespace TARGETING

<|endoftext|>