<commit_before>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "test_roudi_portmanager_fixture.hpp"

namespace iox_test_roudi_portmanager
{
using namespace iox::popo;

constexpr uint64_t RESPONSE_QUEUE_CAPACITY{2U};
constexpr uint64_t REQUEST_QUEUE_CAPACITY{2U};

ClientOptions createTestClientOptions()
{
    return ClientOptions{RESPONSE_QUEUE_CAPACITY, iox::NodeName_t("node")};
}

ServerOptions createTestServerOptions()
{
    return ServerOptions{REQUEST_QUEUE_CAPACITY, iox::NodeName_t("node")};
}

// BEGIN aquireClientPortData tests

TEST_F(PortManager_test, AcquireClientPortDataReturnsPort)
{
    ::testing::Test::RecordProperty("TEST_ID", "92225f2c-619a-425b-bba0-6a014822c4c3");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = false;
    clientOptions.responseQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER;
    clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
    m_portManager->acquireClientPortData(sd, clientOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .and_then([&](const auto& clientPortData) {
            EXPECT_THAT(clientPortData->m_serviceDescription, Eq(sd));
            EXPECT_THAT(clientPortData->m_runtimeName, Eq(runtimeName));
            EXPECT_THAT(clientPortData->m_nodeName, Eq(clientOptions.nodeName));
            EXPECT_THAT(clientPortData->m_toBeDestroyed, Eq(false));
            EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queue.capacity(),
                        Eq(clientOptions.responseQueueCapacity));
            EXPECT_THAT(clientPortData->m_connectRequested, Eq(clientOptions.connectOnCreate));
            EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queueFullPolicy,
                        Eq(clientOptions.responseQueueFullPolicy));
            EXPECT_THAT(clientPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
                        Eq(clientOptions.serverTooSlowPolicy));
        })
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });
}

// END aquireClientPortData tests

// BEGIN aquireServerPortData tests

TEST_F(PortManager_test, AcquireServerPortDataReturnsPort)
{
    ::testing::Test::RecordProperty("TEST_ID", "776c51c4-074a-4404-b6a7-ed08f59f05a0");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = false;
    serverOptions.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER;
    serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .and_then([&](const auto& serverPortData) {
            EXPECT_THAT(serverPortData->m_serviceDescription, Eq(sd));
            EXPECT_THAT(serverPortData->m_runtimeName, Eq(runtimeName));
            EXPECT_THAT(serverPortData->m_nodeName, Eq(serverOptions.nodeName));
            EXPECT_THAT(serverPortData->m_toBeDestroyed, Eq(false));
            EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queue.capacity(), Eq(serverOptions.requestQueueCapacity));
            EXPECT_THAT(serverPortData->m_offeringRequested, Eq(serverOptions.offerOnCreate));
            EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queueFullPolicy,
                        Eq(serverOptions.requestQueueFullPolicy));
            EXPECT_THAT(serverPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
                        Eq(serverOptions.clientTooSlowPolicy));
        })
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });
}

TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceCallsErrorHandlerAndReturnsError)
{
    ::testing::Test::RecordProperty("TEST_ID", "9f2c24ba-192d-4ce8-a61a-fe40b42c655b");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto serverOptions = createTestServerOptions();

    // first call must be successful
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });

    iox::cxx::optional<iox::Error> detectedError;
    auto errorHandlerGuard =
        iox::ErrorHandler::setTemporaryErrorHandler([&](const auto error, const auto, const auto errorLevel) {
            EXPECT_THAT(error, Eq(iox::Error::kPOSH__PORT_MANAGER_SERVERPORT_NOT_UNIQUE));
            EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE));
            detectedError.emplace(error);
        });

    // second call must fail
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .and_then([&](const auto&) {
            GTEST_FAIL() << "Expected PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS but got ServerPortData";
        })
        .or_else([&](const auto& error) { EXPECT_THAT(error, Eq(PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS)); });

    EXPECT_TRUE(detectedError.has_value());
}

TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceAndFirstPortMarkedToBeDestroyedReturnsPort)
{
    ::testing::Test::RecordProperty("TEST_ID", "d7f2815d-f1ea-403d-9355-69470d92a10f");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto serverOptions = createTestServerOptions();

    // first call must be successful
    auto serverPortDataResult =
        m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {});

    ASSERT_FALSE(serverPortDataResult.has_error());

    serverPortDataResult.value()->m_toBeDestroyed = true;

    iox::cxx::optional<iox::Error> detectedError;
    auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
        [&](const auto error, const auto, const auto) { detectedError.emplace(error); });

    // second call must now also succeed
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });

    detectedError.and_then(
        [&](const auto& error) { GTEST_FAIL() << "Expected error handler to not be called but got: " << error; });
}

// END aquireServerPortData tests

} // namespace iox_test_roudi_portmanager
<commit_msg>iox-#27 Add PortManager tests for client and server discovery<commit_after>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "test_roudi_portmanager_fixture.hpp"

namespace iox_test_roudi_portmanager
{
using namespace iox::popo;

constexpr uint64_t RESPONSE_QUEUE_CAPACITY{2U};
constexpr uint64_t REQUEST_QUEUE_CAPACITY{2U};

ClientOptions createTestClientOptions()
{
    return ClientOptions{RESPONSE_QUEUE_CAPACITY, iox::NodeName_t("node")};
}

ServerOptions createTestServerOptions()
{
    return ServerOptions{REQUEST_QUEUE_CAPACITY, iox::NodeName_t("node")};
}

// BEGIN aquireClientPortData tests

TEST_F(PortManager_test, AcquireClientPortDataReturnsPort)
{
    ::testing::Test::RecordProperty("TEST_ID", "92225f2c-619a-425b-bba0-6a014822c4c3");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = false;
    clientOptions.responseQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER;
    clientOptions.serverTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
    m_portManager->acquireClientPortData(sd, clientOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .and_then([&](const auto& clientPortData) {
            EXPECT_THAT(clientPortData->m_serviceDescription, Eq(sd));
            EXPECT_THAT(clientPortData->m_runtimeName, Eq(runtimeName));
            EXPECT_THAT(clientPortData->m_nodeName, Eq(clientOptions.nodeName));
            EXPECT_THAT(clientPortData->m_toBeDestroyed, Eq(false));
            EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queue.capacity(),
                        Eq(clientOptions.responseQueueCapacity));
            EXPECT_THAT(clientPortData->m_connectRequested, Eq(clientOptions.connectOnCreate));
            EXPECT_THAT(clientPortData->m_chunkReceiverData.m_queueFullPolicy,
                        Eq(clientOptions.responseQueueFullPolicy));
            EXPECT_THAT(clientPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
                        Eq(clientOptions.serverTooSlowPolicy));
        })
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });
}

// END aquireClientPortData tests

// BEGIN aquireServerPortData tests

TEST_F(PortManager_test, AcquireServerPortDataReturnsPort)
{
    ::testing::Test::RecordProperty("TEST_ID", "776c51c4-074a-4404-b6a7-ed08f59f05a0");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = false;
    serverOptions.requestQueueFullPolicy = QueueFullPolicy::BLOCK_PRODUCER;
    serverOptions.clientTooSlowPolicy = ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER;
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .and_then([&](const auto& serverPortData) {
            EXPECT_THAT(serverPortData->m_serviceDescription, Eq(sd));
            EXPECT_THAT(serverPortData->m_runtimeName, Eq(runtimeName));
            EXPECT_THAT(serverPortData->m_nodeName, Eq(serverOptions.nodeName));
            EXPECT_THAT(serverPortData->m_toBeDestroyed, Eq(false));
            EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queue.capacity(), Eq(serverOptions.requestQueueCapacity));
            EXPECT_THAT(serverPortData->m_offeringRequested, Eq(serverOptions.offerOnCreate));
            EXPECT_THAT(serverPortData->m_chunkReceiverData.m_queueFullPolicy,
                        Eq(serverOptions.requestQueueFullPolicy));
            EXPECT_THAT(serverPortData->m_chunkSenderData.m_consumerTooSlowPolicy,
                        Eq(serverOptions.clientTooSlowPolicy));
        })
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });
}

TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceCallsErrorHandlerAndReturnsError)
{
    ::testing::Test::RecordProperty("TEST_ID", "9f2c24ba-192d-4ce8-a61a-fe40b42c655b");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto serverOptions = createTestServerOptions();

    // first call must be successful
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });

    iox::cxx::optional<iox::Error> detectedError;
    auto errorHandlerGuard =
        iox::ErrorHandler::setTemporaryErrorHandler([&](const auto error, const auto, const auto errorLevel) {
            EXPECT_THAT(error, Eq(iox::Error::kPOSH__PORT_MANAGER_SERVERPORT_NOT_UNIQUE));
            EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE));
            detectedError.emplace(error);
        });

    // second call must fail
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .and_then([&](const auto&) {
            GTEST_FAIL() << "Expected PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS but got ServerPortData";
        })
        .or_else([&](const auto& error) { EXPECT_THAT(error, Eq(PortPoolError::UNIQUE_SERVER_PORT_ALREADY_EXISTS)); });

    EXPECT_TRUE(detectedError.has_value());
}

TEST_F(PortManager_test, AcquireServerPortDataWithSameServiceDescriptionTwiceAndFirstPortMarkedToBeDestroyedReturnsPort)
{
    ::testing::Test::RecordProperty("TEST_ID", "d7f2815d-f1ea-403d-9355-69470d92a10f");
    const ServiceDescription sd{"hyp", "no", "toad"};
    const RuntimeName_t runtimeName{"hypnotoad"};
    auto serverOptions = createTestServerOptions();

    // first call must be successful
    auto serverPortDataResult =
        m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {});

    ASSERT_FALSE(serverPortDataResult.has_error());

    serverPortDataResult.value()->m_toBeDestroyed = true;

    iox::cxx::optional<iox::Error> detectedError;
    auto errorHandlerGuard = iox::ErrorHandler::setTemporaryErrorHandler(
        [&](const auto error, const auto, const auto) { detectedError.emplace(error); });

    // second call must now also succeed
    m_portManager->acquireServerPortData(sd, serverOptions, runtimeName, m_payloadDataSegmentMemoryManager, {})
        .or_else([&](const auto& error) {
            GTEST_FAIL() << "Expected ClientPortData but got PortPoolError: " << static_cast<uint8_t>(error);
        });

    detectedError.and_then(
        [&](const auto& error) { GTEST_FAIL() << "Expected error handler to not be called but got: " << error; });
}

// END aquireServerPortData tests

// BEGIN discovery tests

TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndNoServerResultsInWaitForOffer)
{
    ::testing::Test::RecordProperty("TEST_ID", "14070d7b-d8e1-4df5-84fc-119e5e126cde");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;

    auto clientPortUser = createClient(clientOptions);

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER));
}

TEST_F(PortManager_test, DoDiscoveryWithClientConnectOnCreateAndNoServerResultsInClientNotConnected)
{
    ::testing::Test::RecordProperty("TEST_ID", "6829e506-9f58-4253-bc42-469f2970a2c7");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;

    auto clientPortUser = createClient(clientOptions);
    m_portManager->doDiscovery();

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER));
}

TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndNotOfferingServerResultsInWaitForOffer)
{
    ::testing::Test::RecordProperty("TEST_ID", "0f7098d0-2646-4c10-b347-9b57b0f593ce");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = false;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER));
}

TEST_F(PortManager_test, CreateClientWithConnectOnCreateAndOfferingServerResultsInClientConnected)
{
    ::testing::Test::RecordProperty("TEST_ID", "108170d4-786b-4266-ad2a-ef922188f70b");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED));
}

TEST_F(PortManager_test, CreateServerWithOfferOnCreateAndClientWaitingToConnectResultsInClientConnected)
{
    ::testing::Test::RecordProperty("TEST_ID", "b5bb10b2-bf9b-400e-ab5c-aa3a1e0e826f");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto clientPortUser = createClient(clientOptions);
    auto serverPortUser = createServer(serverOptions);

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED));
}

TEST_F(PortManager_test, CreateClientWithNotConnectOnCreateAndNoServerResultsInClientNotConnected)
{
    ::testing::Test::RecordProperty("TEST_ID", "fde662f1-f9e1-4302-be41-59a7a0bfa4e7");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = false;

    auto clientPortUser = createClient(clientOptions);

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED));
}

TEST_F(PortManager_test, DoDiscoveryWithClientNotConnectOnCreateAndNoServerResultsInClientNotConnected)
{
    ::testing::Test::RecordProperty("TEST_ID", "c59b7343-6277-4a4b-8204-506048726be4");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = false;

    auto clientPortUser = createClient(clientOptions);
    m_portManager->doDiscovery();

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED));
}

TEST_F(PortManager_test, CreateClientWithNotConnectOnCreateAndOfferingServerResultsInClientNotConnected)
{
    ::testing::Test::RecordProperty("TEST_ID", "17cf22ba-066a-418a-8366-1c6b75177b9a");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = false;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED));
}

TEST_F(PortManager_test, DoDiscoveryWithClientNotConnectOnCreateAndServerResultsInConnectedWhenCallingConnect)
{
    ::testing::Test::RecordProperty("TEST_ID", "87bbb991-4aaf-49c1-b238-d9b0bb18d699");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = false;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    clientPortUser.connect();

    m_portManager->doDiscovery();

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::CONNECTED));
}

TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInClientNotConnectedWhenCallingDisconnect)
{
    ::testing::Test::RecordProperty("TEST_ID", "b6826f93-096d-473d-b846-ab824efff1ee");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    clientPortUser.disconnect();

    m_portManager->doDiscovery();

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED));
}

TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInWaitForOfferWhenCallingStopOffer)
{
    ::testing::Test::RecordProperty("TEST_ID", "45c9cc27-4198-4539-943f-2111ae2d1368");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    serverPortUser.stopOffer();

    m_portManager->doDiscovery();

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER));
}

TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInWaitForOfferWhenServerIsDestroyed)
{
    ::testing::Test::RecordProperty("TEST_ID", "585ad47d-1a03-4599-a4dc-57ea1fb6eac7");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    serverPortUser.destroy();

    m_portManager->doDiscovery();

    EXPECT_THAT(clientPortUser.getConnectionState(), Eq(ConnectionState::WAIT_FOR_OFFER));
}

TEST_F(PortManager_test, DoDiscoveryWithClientConnectResultsInNoClientsWhenClientIsDestroyed)
{
    ::testing::Test::RecordProperty("TEST_ID", "3be2f7b5-7e22-4676-a25b-c8a93a4aaa7d");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser = createClient(clientOptions);

    EXPECT_TRUE(serverPortUser.hasClients());

    clientPortUser.destroy();

    m_portManager->doDiscovery();

    EXPECT_FALSE(serverPortUser.hasClients());
}

TEST_F(PortManager_test, CreateMultipleClientsWithConnectOnCreateAndOfferingServerResultsInAllClientsConnected)
{
    ::testing::Test::RecordProperty("TEST_ID", "08f9981f-2585-4574-b0fc-c16cf0eef7d4");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = true;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser1 = createClient(clientOptions);
    auto clientPortUser2 = createClient(clientOptions);

    EXPECT_THAT(clientPortUser1.getConnectionState(), Eq(ConnectionState::CONNECTED));
    EXPECT_THAT(clientPortUser2.getConnectionState(), Eq(ConnectionState::CONNECTED));
}

TEST_F(PortManager_test,
       DoDiscoveryWithMultipleClientsNotConnectedAndOfferingServerResultsSomeClientsConnectedWhenSomeClientsCallConnect)
{
    ::testing::Test::RecordProperty("TEST_ID", "7d210259-7c50-479e-b108-bf9747ceb0ef");
    auto clientOptions = createTestClientOptions();
    clientOptions.connectOnCreate = false;
    auto serverOptions = createTestServerOptions();
    serverOptions.offerOnCreate = true;

    auto serverPortUser = createServer(serverOptions);
    auto clientPortUser1 = createClient(clientOptions);
    auto clientPortUser2 = createClient(clientOptions);

    clientPortUser2.connect();
    m_portManager->doDiscovery();

    EXPECT_THAT(clientPortUser1.getConnectionState(), Eq(ConnectionState::NOT_CONNECTED));
    EXPECT_THAT(clientPortUser2.getConnectionState(), Eq(ConnectionState::CONNECTED));
}

// END discovery tests

} // namespace iox_test_roudi_portmanager
<|endoftext|>


<commit_before>#include "include/settingsmas.h"
#include <QApplication>
#include <QSettings>
#include <QVariant>
#include <QDir>

SettingsMAS::SettingsMAS(QObject *parent) : QObject(parent)
{
    global = new QSettings( QApplication::organizationName(),
                            QApplication::applicationName(),
                            this );
}

SettingsMAS::~SettingsMAS()
{
    if( global )
        delete global;
    if( kitFile )
        delete kitFile;
}

SettingsMAS &SettingsMAS::Instance()
{
    static SettingsMAS singleInstance;
    return singleInstance;
}

void SettingsMAS::load(Settings *settings)
{
    global->beginGroup( "Global" );
    readArray( "Saved_Kits", "Kit", global, settings->savedKits );
    readArray( "Last_Session", "Session", global, settings->session );
    settings->savedKits.removeAll("");
    settings->session.removeAll("");
    global->endGroup();
    global->beginGroup( "Window" );
    settings->maxOpenTabs = global->value( "Max_Tabs" ).toInt();
    settings->winPosX = global->value( "Pos_X" ).toInt();
    settings->winPosY = global->value( "Pos_Y" ).toInt();
    settings->winSizeX = global->value( "Size_X" ).toInt();
    settings->winSizeY = global->value( "Size_Y" ).toInt();
    global->endGroup();
    QString mDir = qApp->applicationDirPath();
    mDir += "/Market Kits";
    if( !QDir().exists(mDir) )
        QDir().mkdir(mDir);
}

void SettingsMAS::save(const Settings *settings)
{
    clear();
    global->beginGroup( "Global" );
    writeArray( "Saved_Kits", "Kit", global, settings->savedKits );
    writeArray( "Last_Session", "Session", global, settings->session );
    global->endGroup();
    global->beginGroup( "Window" );
    global->setValue( "Max_Tabs", settings->maxOpenTabs );
    global->setValue( "Pos_X", settings->winPosX );
    global->setValue( "Pos_Y", settings->winPosY );
    global->setValue( "Size_X", settings->winSizeX );
    global->setValue( "Size_Y", settings->winSizeY );
    global->endGroup();
}

bool SettingsMAS::load(ConfigMT4 *configKit)
{
    if( configKit->nameKit.contains( "New Market Kit" ) ) {
        loadDefault( configKit );
        return true;
    }
    QString configFile = QString("%1/%2").arg( configKit->kitPath )
                                         .arg( "config.ini" );
    if( !QDir().exists(configFile) ) {
        return false;
    }
    kitFile = new QSettings( configFile, QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    configKit->nameKit =            kitFile->value( "Kit_Name" ).toString();
    configKit->kitPath =            kitFile->value( "Kit_Path" ).toString();
    configKit->mt4Path =            kitFile->value( "Mt4_Path" ).toString();
    configKit->mt4Account =         kitFile->value( "Mt4_Account" ).toInt();
    configKit->server =             kitFile->value( "Mt4_Server" ).toString();
    configKit->historyPath =        kitFile->value( "History_Path" ).toString();
    readArray( "Servers", "Srv", kitFile, configKit->servers );
    readArray( "Symbols", "Smb", kitFile, configKit->symbols );
    kitFile->endGroup();
    kitFile->beginGroup( "Model_Parameters" );
    readArray( "Periods", "Tf", kitFile, configKit->periods );
    readArray( "Input", "In", kitFile, configKit->input );
    readArray( "Output", "Out", kitFile, configKit->output );
    configKit->recurrentModel =     kitFile->value( "Recurrent_Model" ).toBool();
    configKit->readVolume =         kitFile->value( "Read_Volume" ).toBool();
    configKit->depthHistory =       kitFile->value( "Depth_History" ).toInt();
    configKit->depthPrediction =    kitFile->value( "Depth_Prediction" ).toInt();
    configKit->layersCount =        kitFile->value( "LayersNN_Count" ).toInt();
    readArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize );
    configKit->trainingMethod =     kitFile->value( "Training_Method" ).toString();
    readArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances );
    configKit->lastTraining.fromTime_t( kitFile->value( "Last_Training" ).toInt() );
    configKit->isReady =            kitFile->value( "Is_Ready" ).toBool();
    configKit->isTrained =          kitFile->value( "Is_Trained" ).toBool();
    if( configKit->isTrained )
        configKit->isLoaded = true;
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
    loadMt4Conf( configKit );
    return true;
}

void SettingsMAS::save(const ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1/%2").arg( configKit->kitPath )
                             .arg( "config.ini" ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    kitFile->setValue( "Kit_Name",         configKit->nameKit );
    kitFile->setValue( "Kit_Path",         configKit->kitPath );
    kitFile->setValue( "Mt4_Path",         configKit->mt4Path );
    kitFile->setValue( "Mt4_Account",      configKit->mt4Account );
    kitFile->setValue( "Mt4_Server",       configKit->server );
    kitFile->setValue( "History_Path",     configKit->historyPath );
    writeArray( "Servers", "Srv", kitFile, configKit->servers );
    writeArray( "Symbols", "Smb", kitFile, configKit->symbols );
    kitFile->endGroup();
    kitFile->beginGroup( "Model_Parameters" );
    writeArray( "Periods", "Tf", kitFile,  configKit->periods );
    writeArray( "Input", "In", kitFile,    configKit->input );
    writeArray( "Output", "Out", kitFile,  configKit->output );
    kitFile->setValue( "Recurrent_Model",  configKit->recurrentModel );
    kitFile->setValue( "Read_Volume",      configKit->readVolume );
    kitFile->setValue( "Depth_History",    configKit->depthHistory );
    kitFile->setValue( "Depth_Prediction", configKit->depthPrediction );
    kitFile->setValue( "LayersNN_Count",   configKit->layersCount );
    writeArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize );
    kitFile->setValue( "Training_Method",  configKit->trainingMethod );
    writeArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances );
    kitFile->setValue( "Last_Training",    configKit->lastTraining.toTime_t() );
    kitFile->setValue( "Is_Ready",         configKit->isReady );
    kitFile->setValue( "Is_Trained",       configKit->isTrained );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
    saveMt4Conf( configKit );
}

void SettingsMAS::loadMt4Conf(ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path )
                             .arg( configKit->configFile ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    configKit->mt4Account = kitFile->value( "Mt4_Account" ).toInt();
//    readArray( "Servers", "Srv", kitFile, configKit->servers );
    readArray( "Symbols", "Smb", kitFile, configKit->symbols );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
}

void SettingsMAS::saveMt4Conf(const ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path )
                             .arg( configKit->configFile ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    QStringList temp;
    readArray( "Kit_Names", "Kit", kitFile, temp );
    if( !temp.contains( configKit->nameKit ) )
        temp.append( configKit->nameKit );
    writeArray( "Kit_Names", "Kit", kitFile, temp );
    kitFile->endGroup();
    kitFile->beginGroup( configKit->nameKit );
    kitFile->setValue( "Depth_Prediction", configKit->depthPrediction );
    writeArray( "Input", "In", kitFile,    configKit->input );
    writeArray( "Output", "Out", kitFile,  configKit->output );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
}

void SettingsMAS::deleteMAKit(ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1%2")
                             .arg( configKit->mt4Path )
                             .arg( configKit->configFile ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    QStringList temp;
    readArray( "Kit_Names", "Kit", kitFile, temp );
    temp.removeOne( configKit->nameKit );
    writeArray( "Kit_Names", "Kit", kitFile, temp );
    kitFile->endGroup();
    kitFile->beginGroup( configKit->nameKit );
    kitFile->remove( "Depth_Prediction" );
    kitFile->remove( "Input" );
    kitFile->remove( "Output" );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
    configKit->removePath( configKit->kitPath );
}

void SettingsMAS::readArray(const QString &arrayName, const QString &valueName,
                            QSettings *setups, QStringList &list)
{
    list.clear();
    qint32 size = setups->beginReadArray( arrayName );
    for( qint32 i = 0; i < size; i++ ) {
        setups->setArrayIndex( i );
        list.append( setups->value( valueName ).toString() );
    }
    setups->endArray();
}

void SettingsMAS::readArray(const QString &arrayName, const QString &valueName,
                            QSettings *setups, QList<qint32> &list)
{
    list.clear();
    qint32 size = setups->beginReadArray( arrayName );
    for( qint32 i = 0; i < size; i++ ) {
        setups->setArrayIndex( i );
        list.append( setups->value( valueName ).toInt() );
    }
    setups->endArray();
}

void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName,
                             QSettings *setups, const QStringList &list)
{
    setups->beginWriteArray( arrayName );
    for( qint32 i = 0; i < list.size(); i++) {
        setups->setArrayIndex( i );
        setups->setValue( valueName, list[i] );
    }
    setups->endArray();
}

void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName,
                             QSettings *setups, const QList<qint32> &list)
{
    setups->beginWriteArray( arrayName );
    for( qint32 i = 0; i < list.size(); i++) {
        setups->setArrayIndex( i );
        setups->setValue( valueName, list[i] );
    }
    setups->endArray();
}

void SettingsMAS::loadDefault(ConfigMT4 *configKit)
{
    configKit->input.append( "YEAR" );
    configKit->input.append( "MONTH" );
    configKit->input.append( "DAY" );
    configKit->input.append( "WEEKDAY" );
    configKit->input.append("EURUSD.pro1440");
    configKit->output.append("EURUSD.pro1440");
    configKit->periods.append( 1440 );
}

void SettingsMAS::clear()
{
    global->beginGroup( "Global" );
    qint32 i = 0;
    while( global->contains( QString("Saved_Kits_%1").arg( i ) ) ) {
        global->remove( QString("Saved_Kits_%1").arg( i ) );
        i++;
    }
    i = 0;
    while( global->contains( QString("Last_Session_%1").arg( i ) ) ) {
        global->remove( QString("Last_Session_%1").arg( i ) );
        i++;
    }
    global->endGroup();
}
<commit_msg>- change IO methods for StringList;<commit_after>#include "include/settingsmas.h"
#include <QApplication>
#include <QSettings>
#include <QVariant>
#include <QDir>

SettingsMAS::SettingsMAS(QObject *parent) : QObject(parent)
{
    global = new QSettings( QApplication::organizationName(),
                            QApplication::applicationName(),
                            this );
}

SettingsMAS::~SettingsMAS()
{
    if( global )
        delete global;
    if( kitFile )
        delete kitFile;
}

SettingsMAS &SettingsMAS::Instance()
{
    static SettingsMAS singleInstance;
    return singleInstance;
}

void SettingsMAS::load(Settings *settings)
{
    global->beginGroup( "Global" );
    readArray( "Saved_Kits", "Kit", global, settings->savedKits );
    readArray( "Last_Session", "Session", global, settings->session );
    settings->savedKits.removeAll("");
    settings->session.removeAll("");
    global->endGroup();
    global->beginGroup( "Window" );
    settings->maxOpenTabs = global->value( "Max_Tabs" ).toInt();
    settings->winPosX = global->value( "Pos_X" ).toInt();
    settings->winPosY = global->value( "Pos_Y" ).toInt();
    settings->winSizeX = global->value( "Size_X" ).toInt();
    settings->winSizeY = global->value( "Size_Y" ).toInt();
    global->endGroup();
    QString mDir = qApp->applicationDirPath();
    mDir += "/Market Kits";
    if( !QDir().exists(mDir) )
        QDir().mkdir(mDir);
}

void SettingsMAS::save(const Settings *settings)
{
    clear();
    global->beginGroup( "Global" );
    writeArray( "Saved_Kits", "Kit", global, settings->savedKits );
    writeArray( "Last_Session", "Session", global, settings->session );
    global->endGroup();
    global->beginGroup( "Window" );
    global->setValue( "Max_Tabs", settings->maxOpenTabs );
    global->setValue( "Pos_X", settings->winPosX );
    global->setValue( "Pos_Y", settings->winPosY );
    global->setValue( "Size_X", settings->winSizeX );
    global->setValue( "Size_Y", settings->winSizeY );
    global->endGroup();
}

bool SettingsMAS::load(ConfigMT4 *configKit)
{
    if( configKit->nameKit.contains( "New Market Kit" ) ) {
        loadDefault( configKit );
        return true;
    }
    QString configFile = QString("%1/%2").arg( configKit->kitPath )
                                         .arg( "config.ini" );
    if( !QDir().exists(configFile) ) {
        return false;
    }
    kitFile = new QSettings( configFile, QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    configKit->nameKit =            kitFile->value( "Kit_Name" ).toString();
    configKit->kitPath =            kitFile->value( "Kit_Path" ).toString();
    configKit->mt4Path =            kitFile->value( "Mt4_Path" ).toString();
    configKit->mt4Account =         kitFile->value( "Mt4_Account" ).toInt();
    configKit->server =             kitFile->value( "Mt4_Server" ).toString();
    configKit->historyPath =        kitFile->value( "History_Path" ).toString();
    readArray( "Servers", "Srv", kitFile, configKit->servers );
    readArray( "Symbols", "Smb", kitFile, configKit->symbols );
    kitFile->endGroup();
    kitFile->beginGroup( "Model_Parameters" );
    readArray( "Periods", "Tf", kitFile, configKit->periods );
    readArray( "Input", "In", kitFile, configKit->input );
    readArray( "Output", "Out", kitFile, configKit->output );
    configKit->recurrentModel =     kitFile->value( "Recurrent_Model" ).toBool();
    configKit->readVolume =         kitFile->value( "Read_Volume" ).toBool();
    configKit->depthHistory =       kitFile->value( "Depth_History" ).toInt();
    configKit->depthPrediction =    kitFile->value( "Depth_Prediction" ).toInt();
    configKit->layersCount =        kitFile->value( "LayersNN_Count" ).toInt();
    readArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize );
    configKit->trainingMethod =     kitFile->value( "Training_Method" ).toString();
    readArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances );
    configKit->lastTraining.fromTime_t( kitFile->value( "Last_Training" ).toInt() );
    configKit->isReady =            kitFile->value( "Is_Ready" ).toBool();
    configKit->isTrained =          kitFile->value( "Is_Trained" ).toBool();
    if( configKit->isTrained )
        configKit->isLoaded = true;
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
    loadMt4Conf( configKit );
    return true;
}

void SettingsMAS::save(const ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1/%2").arg( configKit->kitPath )
                             .arg( "config.ini" ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    kitFile->setValue( "Kit_Name",         configKit->nameKit );
    kitFile->setValue( "Kit_Path",         configKit->kitPath );
    kitFile->setValue( "Mt4_Path",         configKit->mt4Path );
    kitFile->setValue( "Mt4_Account",      configKit->mt4Account );
    kitFile->setValue( "Mt4_Server",       configKit->server );
    kitFile->setValue( "History_Path",     configKit->historyPath );
    writeArray( "Servers", "Srv", kitFile, configKit->servers );
    writeArray( "Symbols", "Smb", kitFile, configKit->symbols );
    kitFile->endGroup();
    kitFile->beginGroup( "Model_Parameters" );
    writeArray( "Periods", "Tf", kitFile,  configKit->periods );
    writeArray( "Input", "In", kitFile,    configKit->input );
    writeArray( "Output", "Out", kitFile,  configKit->output );
    kitFile->setValue( "Recurrent_Model",  configKit->recurrentModel );
    kitFile->setValue( "Read_Volume",      configKit->readVolume );
    kitFile->setValue( "Depth_History",    configKit->depthHistory );
    kitFile->setValue( "Depth_Prediction", configKit->depthPrediction );
    kitFile->setValue( "LayersNN_Count",   configKit->layersCount );
    writeArray( "LayersNN_Sizes", "Size", kitFile, configKit->layersSize );
    kitFile->setValue( "Training_Method",  configKit->trainingMethod );
    writeArray( "Training_Allocation", "Part", kitFile, configKit->divideInstances );
    kitFile->setValue( "Last_Training",    configKit->lastTraining.toTime_t() );
    kitFile->setValue( "Is_Ready",         configKit->isReady );
    kitFile->setValue( "Is_Trained",       configKit->isTrained );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
    saveMt4Conf( configKit );
}

void SettingsMAS::loadMt4Conf(ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path )
                             .arg( configKit->configFile ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    configKit->mt4Account = kitFile->value( "Mt4_Account" ).toInt();
    readArray( "Symbols", "Smb", kitFile, configKit->symbols );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
}

void SettingsMAS::saveMt4Conf(const ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1%2").arg( configKit->mt4Path )
                             .arg( configKit->configFile ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    QStringList temp;
    readArray( "Kit_Names", "Kit", kitFile, temp );
    if( !temp.contains( configKit->nameKit ) )
        temp.append( configKit->nameKit );
    writeArray( "Kit_Names", "Kit", kitFile, temp );
    kitFile->endGroup();
    kitFile->beginGroup( configKit->nameKit );
    kitFile->setValue( "Depth_Prediction", configKit->depthPrediction );
    writeArray( "Input", "In", kitFile,    configKit->input );
    writeArray( "Output", "Out", kitFile,  configKit->output );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
}

void SettingsMAS::deleteMAKit(ConfigMT4 *configKit)
{
    kitFile = new QSettings( QString("%1%2")
                             .arg( configKit->mt4Path )
                             .arg( configKit->configFile ), QSettings::IniFormat);
    kitFile->beginGroup( "Main" );
    QStringList temp;
    readArray( "Kit_Names", "Kit", kitFile, temp );
    temp.removeOne( configKit->nameKit );
    writeArray( "Kit_Names", "Kit", kitFile, temp );
    kitFile->endGroup();
    kitFile->beginGroup( configKit->nameKit );
    kitFile->remove( "Depth_Prediction" );
    kitFile->remove( "Input" );
    kitFile->remove( "Output" );
    kitFile->endGroup();
    delete kitFile;
    kitFile = 0;
    configKit->removePath( configKit->kitPath );
}

void SettingsMAS::readArray(const QString &arrayName, const QString &valueName,
                            QSettings *setups, QStringList &list)
{
    Q_UNUSED(valueName);
    list.clear();
    list = setups->value( arrayName ).toString().split( ";", QString::SkipEmptyParts );
}

void SettingsMAS::readArray(const QString &arrayName, const QString &valueName,
                            QSettings *setups, QList<qint32> &list)
{
    list.clear();
    qint32 size = setups->beginReadArray( arrayName );
    for( qint32 i = 0; i < size; i++ ) {
        setups->setArrayIndex( i );
        list.append( setups->value( valueName ).toInt() );
    }
    setups->endArray();
}

void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName,
                             QSettings *setups, const QStringList &list)
{
    Q_UNUSED(valueName);
    QString tmp = "";
    foreach( QString str, list ) {
        tmp += str; tmp += ";";
    }
    tmp.remove( tmp.size() - 1, 1);
    setups->setValue( arrayName, tmp );
}

void SettingsMAS::writeArray(const QString &arrayName, const QString &valueName,
                             QSettings *setups, const QList<qint32> &list)
{
    setups->beginWriteArray( arrayName );
    for( qint32 i = 0; i < list.size(); i++) {
        setups->setArrayIndex( i );
        setups->setValue( valueName, list[i] );
    }
    setups->endArray();
}

void SettingsMAS::loadDefault(ConfigMT4 *configKit)
{
    configKit->input.append( "YEAR" );
    configKit->input.append( "MONTH" );
    configKit->input.append( "DAY" );
    configKit->input.append( "WEEKDAY" );
    configKit->input.append( "EURUSD.pro1440" );
    configKit->output.append( "EURUSD.pro1440" );
    configKit->periods.append( 1440 );
}

void SettingsMAS::clear()
{
    global->beginGroup( "Global" );
    qint32 i = 0;
    while( global->contains( QString("Saved_Kits_%1").arg( i ) ) ) {
        global->remove( QString("Saved_Kits_%1").arg( i ) );
        i++;
    }
    i = 0;
    while( global->contains( QString("Last_Session_%1").arg( i ) ) ) {
        global->remove( QString("Last_Session_%1").arg( i ) );
        i++;
    }
    global->endGroup();
}
<|endoftext|>


<commit_before>// MathPresso - Mathematical Expression Parser and JIT Compiler.

// Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

// [Dependencies]
#include "MathPresso.h"
#include "MathPresso_AST_p.h"
#include "MathPresso_Optimizer_p.h"
#include "MathPresso_Util_p.h"

namespace MathPresso {

Optimizer::Optimizer(WorkContext& ctx) :
  _ctx(ctx)
{
}

Optimizer::~Optimizer()
{
}

ASTElement* Optimizer::doNode(ASTElement* element)
{
  switch (element->getElementType())
  {
    case MELEMENT_BLOCK:
      return doBlock(reinterpret_cast<ASTBlock*>(element));
    case MELEMENT_OPERATOR:
      return doOperator(reinterpret_cast<ASTOperator*>(element));
    default:
      return element;
  }
}

ASTElement* Optimizer::doBlock(ASTBlock* element)
{
  return element;
}

ASTElement* Optimizer::doOperator(ASTOperator* element)
{
  ASTElement* left;
  ASTElement* right;

  left = element->_left = doNode(element->getLeft());
  right = element->_right = doNode(element->getRight());

  bool leftConst = left->isConstant();
  bool rightConst = right->isConstant();

  if (leftConst && rightConst)
  {
    // Both are constants, simplify them.
    mreal_t result = element->evaluate(NULL);

    ASTConstant* replacement = new ASTConstant(_ctx.genId(), result);
    replacement->_parent = element->getParent();
    delete element;
    return replacement;
  }
  else if (leftConst || rightConst)
  {
    // Left or right is constant, we try to find another one in deeper which
    // could be joined.
    ASTElement* c;
    ASTElement* x;

    if (leftConst)
    {
      c = left;
      x = right;
    }
    else
    {
      c = right;
      x = left;
    }

    ASTElement* y = findConstNode(x, element->getOperatorType());
    if (y != NULL)
    {
      ASTOperator* p = reinterpret_cast<ASTOperator*>(y->getParent());
      ASTElement* keep;

      MP_ASSERT(p->getElementType() == MELEMENT_OPERATOR);

      mreal_t result;

      // Hardcoded evaluator (we accept only PLUS or MUL operators).
      switch (element->getOperatorType())
      {
        case MOPERATOR_PLUS:
          result = c->evaluate(NULL) + y->evaluate(NULL);
          break;
        case MOPERATOR_MUL:
          result = c->evaluate(NULL) * y->evaluate(NULL);
          break;
        default:
          MP_ASSERT_NOT_REACHED();
      }

      if (p->getRight() == y)
      {
        keep = p->getLeft();
        p->_left = NULL;
      }
      else
      {
        keep = p->getRight();
        p->_right = NULL;
      }
      p->getParent()->replaceChild(p, keep);
      delete p;

      reinterpret_cast<ASTConstant*>(c)->setValue(result);
    }
  }
  return element;
}

ASTElement* Optimizer::findConstNode(ASTElement* _element, int op)
{
  if (_element->getElementType() != MELEMENT_OPERATOR) return NULL;
  ASTOperator* element = reinterpret_cast<ASTOperator*>(_element);

  int op0 = op;
  int op1 = element->getOperatorType();

  if ((op0 == MOPERATOR_PLUS && op1 == MOPERATOR_PLUS) ||
      (op0 == MOPERATOR_MUL  && op1 == MOPERATOR_MUL ) )
  {
    ASTElement* left = element->getLeft();
    ASTElement* right = element->getRight();

    if (left->isConstant()) return left;
    if (right->isConstant()) return right;

    if ((left = findConstNode(left, op)) != NULL) return left;
    if ((right = findConstNode(right, op)) != NULL) return right;
  }

  return NULL;
}

} // MathPresso namespace
<commit_msg>fixed a bug http://code.google.com/p/mathpresso/issues/detail?id=2 mathpresso crashed on parsing expressions like "1 + x + sin(1)"<commit_after>// MathPresso - Mathematical Expression Parser and JIT Compiler.

// Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

// [Dependencies]
#include "MathPresso.h"
#include "MathPresso_AST_p.h"
#include "MathPresso_Optimizer_p.h"
#include "MathPresso_Util_p.h"

namespace MathPresso {

Optimizer::Optimizer(WorkContext& ctx) :
  _ctx(ctx)
{
}

Optimizer::~Optimizer()
{
}

ASTElement* Optimizer::doNode(ASTElement* element)
{
  switch (element->getElementType())
  {
    case MELEMENT_BLOCK:
      return doBlock(reinterpret_cast<ASTBlock*>(element));
    case MELEMENT_OPERATOR:
      return doOperator(reinterpret_cast<ASTOperator*>(element));
    default:
      return element;
  }
}

ASTElement* Optimizer::doBlock(ASTBlock* element)
{
  return element;
}

ASTElement* Optimizer::doOperator(ASTOperator* element)
{
  ASTElement* left;
  ASTElement* right;

  left = element->_left = doNode(element->getLeft());
  right = element->_right = doNode(element->getRight());

  bool leftConst = left->isConstant();
  bool rightConst = right->isConstant();

  if (leftConst && rightConst)
  {
    // Both are constants, simplify them.
    mreal_t result = element->evaluate(NULL);

    ASTConstant* replacement = new ASTConstant(_ctx.genId(), result);
    replacement->_parent = element->getParent();
    delete element;
    return replacement;
  }
  else if (leftConst || rightConst)
  {
    // Left or right is constant, we try to find another one in deeper which
    // could be joined.
    ASTElement* c;
    ASTElement* x;

    if (leftConst)
    {
      c = left;
      x = right;
    }
    else
    {
      c = right;
      x = left;
    }

    ASTElement* y = findConstNode(x, element->getOperatorType());
    if (y != NULL)
    {
      ASTOperator* p = reinterpret_cast<ASTOperator*>(y->getParent());
      ASTElement* keep;

      MP_ASSERT(p->getElementType() == MELEMENT_OPERATOR);

      mreal_t result;

      // Hardcoded evaluator (we accept only PLUS or MUL operators).
      switch (element->getOperatorType())
      {
        case MOPERATOR_PLUS:
          result = c->evaluate(NULL) + y->evaluate(NULL);
          break;
        case MOPERATOR_MUL:
          result = c->evaluate(NULL) * y->evaluate(NULL);
          break;
        default:
          MP_ASSERT_NOT_REACHED();
      }

      if (p->getRight() == y)
      {
        keep = p->getLeft();
        p->_left = NULL;
      }
      else
      {
        keep = p->getRight();
        p->_right = NULL;
      }
      p->getParent()->replaceChild(p, keep);
      delete p;
      c->getParent()->replaceChild(c, new ASTConstant(c->getElementId(), result));
      delete c;
    }
  }
  return element;
}

ASTElement* Optimizer::findConstNode(ASTElement* _element, int op)
{
  if (_element->getElementType() != MELEMENT_OPERATOR) return NULL;
  ASTOperator* element = reinterpret_cast<ASTOperator*>(_element);

  int op0 = op;
  int op1 = element->getOperatorType();

  if ((op0 == MOPERATOR_PLUS && op1 == MOPERATOR_PLUS) ||
      (op0 == MOPERATOR_MUL  && op1 == MOPERATOR_MUL ) )
  {
    ASTElement* left = element->getLeft();
    ASTElement* right = element->getRight();

    if (left->isConstant()) return left;
    if (right->isConstant()) return right;

    if ((left = findConstNode(left, op)) != NULL) return left;
    if ((right = findConstNode(right, op)) != NULL) return right;
  }

  return NULL;
}

} // MathPresso namespace
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/zygote_host_linux.h"

#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/environment.h"
#include "base/linux_util.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/renderer_host/render_sandbox_host_linux.h"
#include "content/common/content_switches.h"
#include "content/common/process_watcher.h"
#include "content/common/result_codes.h"
#include "content/common/unix_domain_socket_posix.h"
#include "sandbox/linux/suid/suid_unsafe_environment_variables.h"

static void SaveSUIDUnsafeEnvironmentVariables() {
  // The ELF loader will clear many environment variables so we save them to
  // different names here so that the SUID sandbox can resolve them for the
  // renderer.

  for (unsigned i = 0; kSUIDUnsafeEnvironmentVariables[i]; ++i) {
    const char* const envvar = kSUIDUnsafeEnvironmentVariables[i];
    char* const saved_envvar = SandboxSavedEnvironmentVariable(envvar);
    if (!saved_envvar)
      continue;

    scoped_ptr<base::Environment> env(base::Environment::Create());
    std::string value;
    if (env->GetVar(envvar, &value))
      env->SetVar(saved_envvar, value);
    else
      env->UnSetVar(saved_envvar);

    free(saved_envvar);
  }
}

ZygoteHost::ZygoteHost()
    : control_fd_(-1),
      pid_(-1),
      init_(false),
      using_suid_sandbox_(false),
      have_read_sandbox_status_word_(false),
      sandbox_status_(0) {}

ZygoteHost::~ZygoteHost() {
  if (init_)
    close(control_fd_);
}

// static
ZygoteHost* ZygoteHost::GetInstance() {
  return Singleton<ZygoteHost>::get();
}

void ZygoteHost::Init(const std::string& sandbox_cmd) {
  DCHECK(!init_);
  init_ = true;

  FilePath chrome_path;
  CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
  CommandLine cmd_line(chrome_path);

  cmd_line.AppendSwitchASCII(switches::kProcessType, switches::kZygoteProcess);

  int fds[2];
#if defined(OS_FREEBSD) || defined(OS_OPENBSD)
  // The BSDs often don't support SOCK_SEQPACKET yet, so fall back to
  // SOCK_DGRAM if necessary.
  if (socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) != 0)
    CHECK(socketpair(PF_UNIX, SOCK_DGRAM, 0, fds) == 0);
#else
  CHECK(socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) == 0);
#endif
  base::file_handle_mapping_vector fds_to_map;
  fds_to_map.push_back(std::make_pair(fds[1], 3));

  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
  if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) {
    cmd_line.PrependWrapper(
        browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix));
  }
  // Append any switches from the browser process that need to be forwarded on
  // to the zygote/renderers.
  // Should this list be obtained from browser_render_process_host.cc?
  static const char* kForwardSwitches[] = {
    switches::kAllowSandboxDebugging,
    switches::kLoggingLevel,
    switches::kEnableLogging,  // Support, e.g., --enable-logging=stderr.
    switches::kV,
    switches::kVModule,
    switches::kRegisterPepperPlugins,
    switches::kDisableSeccompSandbox,
    switches::kEnableSeccompSandbox,
    switches::kNaClLinuxHelper,
  };
  cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches,
                            arraysize(kForwardSwitches));

  content::GetContentClient()->browser()->AppendExtraCommandLineSwitches(
      &cmd_line, -1);

  sandbox_binary_ = sandbox_cmd.c_str();

  if (!sandbox_cmd.empty()) {
    struct stat st;
    if (stat(sandbox_binary_.c_str(), &st) == 0 &&
        access(sandbox_binary_.c_str(), X_OK) == 0 &&
        (st.st_uid == 0) &&
        (st.st_mode & S_ISUID) &&
        (st.st_mode & S_IXOTH)) {
      using_suid_sandbox_ = true;
      cmd_line.PrependWrapper(sandbox_binary_);

      SaveSUIDUnsafeEnvironmentVariables();
    } else {
      LOG(FATAL) << "The SUID sandbox helper binary was found, but is not "
                    "configured correctly. Rather than run without sandboxing "
                    "I'm aborting now. You need to make sure that "
                 << sandbox_binary_ << " is mode 4755 and owned by root.";
    }
  } else {
    LOG(WARNING) << "Running without the SUID sandbox! See "
        "http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
        "for more information on developing with the sandbox on.";
  }

  // Start up the sandbox host process and get the file descriptor for the
  // renderers to talk to it.
  const int sfd = RenderSandboxHostLinux::GetInstance()->GetRendererSocket();
  fds_to_map.push_back(std::make_pair(sfd, 5));

  int dummy_fd = -1;
  if (using_suid_sandbox_) {
    dummy_fd = socket(PF_UNIX, SOCK_DGRAM, 0);
    CHECK(dummy_fd >= 0);
    fds_to_map.push_back(std::make_pair(dummy_fd, 7));
  }

  base::ProcessHandle process = -1;
  base::LaunchOptions options;
  options.fds_to_remap = &fds_to_map;
  base::LaunchProcess(cmd_line.argv(), options, &process);
  CHECK(process != -1) << "Failed to launch zygote process";

  if (using_suid_sandbox_) {
    // In the SUID sandbox, the real zygote is forked from the sandbox.
    // We need to look for it.
    // But first, wait for the zygote to tell us it's running.
    // The sending code is in chrome/browser/zygote_main_linux.cc.
    std::vector<int> fds_vec;
    const int kExpectedLength = sizeof(kZygoteMagic);
    char buf[kExpectedLength];
    const ssize_t len = UnixDomainSocket::RecvMsg(fds[0], buf, sizeof(buf),
                                                  &fds_vec);
    CHECK(len == kExpectedLength) << "Incorrect zygote magic length";
    CHECK(0 == strcmp(buf, kZygoteMagic)) << "Incorrect zygote magic";

    std::string inode_output;
    ino_t inode = 0;
    // Figure out the inode for |dummy_fd|, close |dummy_fd| on our end,
    // and find the zygote process holding |dummy_fd|.
    if (base::FileDescriptorGetInode(&inode, dummy_fd)) {
      close(dummy_fd);
      std::vector<std::string> get_inode_cmdline;
      get_inode_cmdline.push_back(sandbox_binary_);
      get_inode_cmdline.push_back(base::kFindInodeSwitch);
      get_inode_cmdline.push_back(base::Int64ToString(inode));
      CommandLine get_inode_cmd(get_inode_cmdline);
      if (base::GetAppOutput(get_inode_cmd, &inode_output)) {
        base::StringToInt(inode_output, &pid_);
      }
    }
    CHECK(pid_ > 0) << "Did not find zygote process (using sandbox binary "
        << sandbox_binary_ << ")";

    if (process != pid_) {
      // Reap the sandbox.
      ProcessWatcher::EnsureProcessGetsReaped(process);
    }
  } else {
    // Not using the SUID sandbox.
    pid_ = process;
  }

  close(fds[1]);
  control_fd_ = fds[0];

  Pickle pickle;
  pickle.WriteInt(kCmdGetSandboxStatus);
  std::vector<int> empty_fds;
  if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(),
                                 empty_fds))
    LOG(FATAL) << "Cannot communicate with zygote";
  // We don't wait for the reply. We'll read it in ReadReply.
}

ssize_t ZygoteHost::ReadReply(void* buf, size_t buf_len) {
  // At startup we send a kCmdGetSandboxStatus request to the zygote, but don't
  // wait for the reply. Thus, the first time that we read from the zygote, we
  // get the reply to that request.
  if (!have_read_sandbox_status_word_) {
    if (HANDLE_EINTR(read(control_fd_, &sandbox_status_,
                          sizeof(sandbox_status_))) !=
        sizeof(sandbox_status_)) {
      return -1;
    }
    have_read_sandbox_status_word_ = true;
  }

  return HANDLE_EINTR(read(control_fd_, buf, buf_len));
}

pid_t ZygoteHost::ForkRequest(
    const std::vector<std::string>& argv,
    const base::GlobalDescriptors::Mapping& mapping,
    const std::string& process_type) {
  DCHECK(init_);
  Pickle pickle;

  pickle.WriteInt(kCmdFork);
  pickle.WriteString(process_type);
  pickle.WriteInt(argv.size());
  for (std::vector<std::string>::const_iterator
       i = argv.begin(); i != argv.end(); ++i)
    pickle.WriteString(*i);

  pickle.WriteInt(mapping.size());

  std::vector<int> fds;
  for (base::GlobalDescriptors::Mapping::const_iterator
       i = mapping.begin(); i != mapping.end(); ++i) {
    pickle.WriteUInt32(i->first);
    fds.push_back(i->second);
  }

  pid_t pid;
  {
    base::AutoLock lock(control_lock_);
    if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(),
                                   fds))
      return base::kNullProcessHandle;

    if (ReadReply(&pid, sizeof(pid)) != sizeof(pid))
      return base::kNullProcessHandle;
    if (pid <= 0)
      return base::kNullProcessHandle;
  }

  const int kRendererScore = 5;
  AdjustRendererOOMScore(pid, kRendererScore);

  return pid;
}

void ZygoteHost::AdjustRendererOOMScore(base::ProcessHandle pid, int score) {
  // 1) You can't change the oom_adj of a non-dumpable process (EPERM) unless
  //    you're root. Because of this, we can't set the oom_adj from the browser
  //    process.
  //
  // 2) We can't set the oom_adj before entering the sandbox because the
  //    zygote is in the sandbox and the zygote is as critical as the browser
  //    process. Its oom_adj value shouldn't be changed.
  //
  // 3) A non-dumpable process can't even change its own oom_adj because it's
  //    root owned 0644. The sandboxed processes don't even have /proc, but one
  //    could imagine passing in a descriptor from outside.
  //
  // So, in the normal case, we use the SUID binary to change it for us.
  // However, Fedora (and other SELinux systems) don't like us touching other
  // process's oom_adj values
  // (https://bugzilla.redhat.com/show_bug.cgi?id=581256).
  //
  // The offical way to get the SELinux mode is selinux_getenforcemode, but I
  // don't want to add another library to the build as it's sure to cause
  // problems with other, non-SELinux distros.
  //
  // So we just check for /selinux. This isn't foolproof, but it's not bad
  // and it's easy.

  static bool selinux;
  static bool selinux_valid = false;

  if (!selinux_valid) {
    selinux = access("/selinux", X_OK) == 0;
    selinux_valid = true;
  }

  if (using_suid_sandbox_ && !selinux) {
    std::vector<std::string> adj_oom_score_cmdline;
    adj_oom_score_cmdline.push_back(sandbox_binary_);
    adj_oom_score_cmdline.push_back(base::kAdjustOOMScoreSwitch);
    adj_oom_score_cmdline.push_back(base::Int64ToString(pid));
    adj_oom_score_cmdline.push_back(base::IntToString(score));

    base::ProcessHandle sandbox_helper_process;
    if (base::LaunchProcess(adj_oom_score_cmdline, base::LaunchOptions(),
                            &sandbox_helper_process)) {
      ProcessWatcher::EnsureProcessGetsReaped(sandbox_helper_process);
    }
  } else if (!using_suid_sandbox_) {
    if (!base::AdjustOOMScore(pid, score))
      PLOG(ERROR) << "Failed to adjust OOM score of renderer with pid " << pid;
  }
}

void ZygoteHost::EnsureProcessTerminated(pid_t process) {
  DCHECK(init_);
  Pickle pickle;

  pickle.WriteInt(kCmdReap);
  pickle.WriteInt(process);

  if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0)
    PLOG(ERROR) << "write";
}

base::TerminationStatus ZygoteHost::GetTerminationStatus(
    base::ProcessHandle handle,
    int* exit_code) {
  DCHECK(init_);
  Pickle pickle;
  pickle.WriteInt(kCmdGetTerminationStatus);
  pickle.WriteInt(handle);

  // Set this now to handle the early termination cases.
  if (exit_code)
    *exit_code = content::RESULT_CODE_NORMAL_EXIT;

  static const unsigned kMaxMessageLength = 128;
  char buf[kMaxMessageLength];
  ssize_t len;
  {
    base::AutoLock lock(control_lock_);
    if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0)
      PLOG(ERROR) << "write";

    len = ReadReply(buf, sizeof(buf));
  }

  if (len == -1) {
    LOG(WARNING) << "Error reading message from zygote: " << errno;
    return base::TERMINATION_STATUS_NORMAL_TERMINATION;
  } else if (len == 0) {
    LOG(WARNING) << "Socket closed prematurely.";
    return base::TERMINATION_STATUS_NORMAL_TERMINATION;
  }

  Pickle read_pickle(buf, len);
  int status, tmp_exit_code;
  void* iter = NULL;
  if (!read_pickle.ReadInt(&iter, &status) ||
      !read_pickle.ReadInt(&iter, &tmp_exit_code)) {
    LOG(WARNING) << "Error parsing GetTerminationStatus response from zygote.";
    return base::TERMINATION_STATUS_NORMAL_TERMINATION;
  }

  if (exit_code)
    *exit_code = tmp_exit_code;

  return static_cast<base::TerminationStatus>(status);
}
<commit_msg>Linux: Fix the sandbox error message when the helper binary is missing.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/zygote_host_linux.h"

#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/environment.h"
#include "base/linux_util.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/renderer_host/render_sandbox_host_linux.h"
#include "content/common/content_switches.h"
#include "content/common/process_watcher.h"
#include "content/common/result_codes.h"
#include "content/common/unix_domain_socket_posix.h"
#include "sandbox/linux/suid/suid_unsafe_environment_variables.h"

static void SaveSUIDUnsafeEnvironmentVariables() {
  // The ELF loader will clear many environment variables so we save them to
  // different names here so that the SUID sandbox can resolve them for the
  // renderer.

  for (unsigned i = 0; kSUIDUnsafeEnvironmentVariables[i]; ++i) {
    const char* const envvar = kSUIDUnsafeEnvironmentVariables[i];
    char* const saved_envvar = SandboxSavedEnvironmentVariable(envvar);
    if (!saved_envvar)
      continue;

    scoped_ptr<base::Environment> env(base::Environment::Create());
    std::string value;
    if (env->GetVar(envvar, &value))
      env->SetVar(saved_envvar, value);
    else
      env->UnSetVar(saved_envvar);

    free(saved_envvar);
  }
}

ZygoteHost::ZygoteHost()
    : control_fd_(-1),
      pid_(-1),
      init_(false),
      using_suid_sandbox_(false),
      have_read_sandbox_status_word_(false),
      sandbox_status_(0) {}

ZygoteHost::~ZygoteHost() {
  if (init_)
    close(control_fd_);
}

// static
ZygoteHost* ZygoteHost::GetInstance() {
  return Singleton<ZygoteHost>::get();
}

void ZygoteHost::Init(const std::string& sandbox_cmd) {
  DCHECK(!init_);
  init_ = true;

  FilePath chrome_path;
  CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
  CommandLine cmd_line(chrome_path);

  cmd_line.AppendSwitchASCII(switches::kProcessType, switches::kZygoteProcess);

  int fds[2];
#if defined(OS_FREEBSD) || defined(OS_OPENBSD)
  // The BSDs often don't support SOCK_SEQPACKET yet, so fall back to
  // SOCK_DGRAM if necessary.
  if (socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) != 0)
    CHECK(socketpair(PF_UNIX, SOCK_DGRAM, 0, fds) == 0);
#else
  CHECK(socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) == 0);
#endif
  base::file_handle_mapping_vector fds_to_map;
  fds_to_map.push_back(std::make_pair(fds[1], 3));

  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
  if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) {
    cmd_line.PrependWrapper(
        browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix));
  }
  // Append any switches from the browser process that need to be forwarded on
  // to the zygote/renderers.
  // Should this list be obtained from browser_render_process_host.cc?
  static const char* kForwardSwitches[] = {
    switches::kAllowSandboxDebugging,
    switches::kLoggingLevel,
    switches::kEnableLogging,  // Support, e.g., --enable-logging=stderr.
    switches::kV,
    switches::kVModule,
    switches::kRegisterPepperPlugins,
    switches::kDisableSeccompSandbox,
    switches::kEnableSeccompSandbox,
    switches::kNaClLinuxHelper,
  };
  cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches,
                            arraysize(kForwardSwitches));

  content::GetContentClient()->browser()->AppendExtraCommandLineSwitches(
      &cmd_line, -1);

  sandbox_binary_ = sandbox_cmd.c_str();

  if (!sandbox_cmd.empty()) {
    struct stat st;
    if (stat(sandbox_binary_.c_str(), &st) != 0) {
      LOG(FATAL) << "The SUID sandbox helper binary is missing: "
                 << sandbox_binary_ << " Aborting now.";
    }

    if (access(sandbox_binary_.c_str(), X_OK) == 0 &&
        (st.st_uid == 0) &&
        (st.st_mode & S_ISUID) &&
        (st.st_mode & S_IXOTH)) {
      using_suid_sandbox_ = true;
      cmd_line.PrependWrapper(sandbox_binary_);

      SaveSUIDUnsafeEnvironmentVariables();
    } else {
      LOG(FATAL) << "The SUID sandbox helper binary was found, but is not "
                    "configured correctly. Rather than run without sandboxing "
                    "I'm aborting now. You need to make sure that "
                 << sandbox_binary_ << " is mode 4755 and owned by root.";
    }
  } else {
    LOG(WARNING) << "Running without the SUID sandbox! See "
        "http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
        "for more information on developing with the sandbox on.";
  }

  // Start up the sandbox host process and get the file descriptor for the
  // renderers to talk to it.
  const int sfd = RenderSandboxHostLinux::GetInstance()->GetRendererSocket();
  fds_to_map.push_back(std::make_pair(sfd, 5));

  int dummy_fd = -1;
  if (using_suid_sandbox_) {
    dummy_fd = socket(PF_UNIX, SOCK_DGRAM, 0);
    CHECK(dummy_fd >= 0);
    fds_to_map.push_back(std::make_pair(dummy_fd, 7));
  }

  base::ProcessHandle process = -1;
  base::LaunchOptions options;
  options.fds_to_remap = &fds_to_map;
  base::LaunchProcess(cmd_line.argv(), options, &process);
  CHECK(process != -1) << "Failed to launch zygote process";

  if (using_suid_sandbox_) {
    // In the SUID sandbox, the real zygote is forked from the sandbox.
    // We need to look for it.
    // But first, wait for the zygote to tell us it's running.
    // The sending code is in chrome/browser/zygote_main_linux.cc.
    std::vector<int> fds_vec;
    const int kExpectedLength = sizeof(kZygoteMagic);
    char buf[kExpectedLength];
    const ssize_t len = UnixDomainSocket::RecvMsg(fds[0], buf, sizeof(buf),
                                                  &fds_vec);
    CHECK(len == kExpectedLength) << "Incorrect zygote magic length";
    CHECK(0 == strcmp(buf, kZygoteMagic)) << "Incorrect zygote magic";

    std::string inode_output;
    ino_t inode = 0;
    // Figure out the inode for |dummy_fd|, close |dummy_fd| on our end,
    // and find the zygote process holding |dummy_fd|.
    if (base::FileDescriptorGetInode(&inode, dummy_fd)) {
      close(dummy_fd);
      std::vector<std::string> get_inode_cmdline;
      get_inode_cmdline.push_back(sandbox_binary_);
      get_inode_cmdline.push_back(base::kFindInodeSwitch);
      get_inode_cmdline.push_back(base::Int64ToString(inode));
      CommandLine get_inode_cmd(get_inode_cmdline);
      if (base::GetAppOutput(get_inode_cmd, &inode_output)) {
        base::StringToInt(inode_output, &pid_);
      }
    }
    CHECK(pid_ > 0) << "Did not find zygote process (using sandbox binary "
        << sandbox_binary_ << ")";

    if (process != pid_) {
      // Reap the sandbox.
      ProcessWatcher::EnsureProcessGetsReaped(process);
    }
  } else {
    // Not using the SUID sandbox.
    pid_ = process;
  }

  close(fds[1]);
  control_fd_ = fds[0];

  Pickle pickle;
  pickle.WriteInt(kCmdGetSandboxStatus);
  std::vector<int> empty_fds;
  if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(),
                                 empty_fds))
    LOG(FATAL) << "Cannot communicate with zygote";
  // We don't wait for the reply. We'll read it in ReadReply.
}

ssize_t ZygoteHost::ReadReply(void* buf, size_t buf_len) {
  // At startup we send a kCmdGetSandboxStatus request to the zygote, but don't
  // wait for the reply. Thus, the first time that we read from the zygote, we
  // get the reply to that request.
  if (!have_read_sandbox_status_word_) {
    if (HANDLE_EINTR(read(control_fd_, &sandbox_status_,
                          sizeof(sandbox_status_))) !=
        sizeof(sandbox_status_)) {
      return -1;
    }
    have_read_sandbox_status_word_ = true;
  }

  return HANDLE_EINTR(read(control_fd_, buf, buf_len));
}

pid_t ZygoteHost::ForkRequest(
    const std::vector<std::string>& argv,
    const base::GlobalDescriptors::Mapping& mapping,
    const std::string& process_type) {
  DCHECK(init_);
  Pickle pickle;

  pickle.WriteInt(kCmdFork);
  pickle.WriteString(process_type);
  pickle.WriteInt(argv.size());
  for (std::vector<std::string>::const_iterator
       i = argv.begin(); i != argv.end(); ++i)
    pickle.WriteString(*i);

  pickle.WriteInt(mapping.size());

  std::vector<int> fds;
  for (base::GlobalDescriptors::Mapping::const_iterator
       i = mapping.begin(); i != mapping.end(); ++i) {
    pickle.WriteUInt32(i->first);
    fds.push_back(i->second);
  }

  pid_t pid;
  {
    base::AutoLock lock(control_lock_);
    if (!UnixDomainSocket::SendMsg(control_fd_, pickle.data(), pickle.size(),
                                   fds))
      return base::kNullProcessHandle;

    if (ReadReply(&pid, sizeof(pid)) != sizeof(pid))
      return base::kNullProcessHandle;
    if (pid <= 0)
      return base::kNullProcessHandle;
  }

  const int kRendererScore = 5;
  AdjustRendererOOMScore(pid, kRendererScore);

  return pid;
}

void ZygoteHost::AdjustRendererOOMScore(base::ProcessHandle pid, int score) {
  // 1) You can't change the oom_adj of a non-dumpable process (EPERM) unless
  //    you're root. Because of this, we can't set the oom_adj from the browser
  //    process.
  //
  // 2) We can't set the oom_adj before entering the sandbox because the
  //    zygote is in the sandbox and the zygote is as critical as the browser
  //    process. Its oom_adj value shouldn't be changed.
  //
  // 3) A non-dumpable process can't even change its own oom_adj because it's
  //    root owned 0644. The sandboxed processes don't even have /proc, but one
  //    could imagine passing in a descriptor from outside.
  //
  // So, in the normal case, we use the SUID binary to change it for us.
  // However, Fedora (and other SELinux systems) don't like us touching other
  // process's oom_adj values
  // (https://bugzilla.redhat.com/show_bug.cgi?id=581256).
  //
  // The offical way to get the SELinux mode is selinux_getenforcemode, but I
  // don't want to add another library to the build as it's sure to cause
  // problems with other, non-SELinux distros.
  //
  // So we just check for /selinux. This isn't foolproof, but it's not bad
  // and it's easy.

  static bool selinux;
  static bool selinux_valid = false;

  if (!selinux_valid) {
    selinux = access("/selinux", X_OK) == 0;
    selinux_valid = true;
  }

  if (using_suid_sandbox_ && !selinux) {
    std::vector<std::string> adj_oom_score_cmdline;
    adj_oom_score_cmdline.push_back(sandbox_binary_);
    adj_oom_score_cmdline.push_back(base::kAdjustOOMScoreSwitch);
    adj_oom_score_cmdline.push_back(base::Int64ToString(pid));
    adj_oom_score_cmdline.push_back(base::IntToString(score));

    base::ProcessHandle sandbox_helper_process;
    if (base::LaunchProcess(adj_oom_score_cmdline, base::LaunchOptions(),
                            &sandbox_helper_process)) {
      ProcessWatcher::EnsureProcessGetsReaped(sandbox_helper_process);
    }
  } else if (!using_suid_sandbox_) {
    if (!base::AdjustOOMScore(pid, score))
      PLOG(ERROR) << "Failed to adjust OOM score of renderer with pid " << pid;
  }
}

void ZygoteHost::EnsureProcessTerminated(pid_t process) {
  DCHECK(init_);
  Pickle pickle;

  pickle.WriteInt(kCmdReap);
  pickle.WriteInt(process);

  if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0)
    PLOG(ERROR) << "write";
}

base::TerminationStatus ZygoteHost::GetTerminationStatus(
    base::ProcessHandle handle,
    int* exit_code) {
  DCHECK(init_);
  Pickle pickle;
  pickle.WriteInt(kCmdGetTerminationStatus);
  pickle.WriteInt(handle);

  // Set this now to handle the early termination cases.
  if (exit_code)
    *exit_code = content::RESULT_CODE_NORMAL_EXIT;

  static const unsigned kMaxMessageLength = 128;
  char buf[kMaxMessageLength];
  ssize_t len;
  {
    base::AutoLock lock(control_lock_);
    if (HANDLE_EINTR(write(control_fd_, pickle.data(), pickle.size())) < 0)
      PLOG(ERROR) << "write";

    len = ReadReply(buf, sizeof(buf));
  }

  if (len == -1) {
    LOG(WARNING) << "Error reading message from zygote: " << errno;
    return base::TERMINATION_STATUS_NORMAL_TERMINATION;
  } else if (len == 0) {
    LOG(WARNING) << "Socket closed prematurely.";
    return base::TERMINATION_STATUS_NORMAL_TERMINATION;
  }

  Pickle read_pickle(buf, len);
  int status, tmp_exit_code;
  void* iter = NULL;
  if (!read_pickle.ReadInt(&iter, &status) ||
      !read_pickle.ReadInt(&iter, &tmp_exit_code)) {
    LOG(WARNING) << "Error parsing GetTerminationStatus response from zygote.";
    return base::TERMINATION_STATUS_NORMAL_TERMINATION;
  }

  if (exit_code)
    *exit_code = tmp_exit_code;

  return static_cast<base::TerminationStatus>(status);
}
<|endoftext|>


<commit_before>/* AkonadiRecord.cc			KPilot
**
** Copyright (C) 2007 by Bertjan Broeksema <b.broeksema@kdemail.net>
** Copyright (C) 2007 by Jason "vanRijn" Kasper <vr@movingparts.net>
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "akonadirecord.h"

#include "options.h"
#include "hhrecord.h"

class AkonadiRecordPrivate : public QSharedData
{
public:
	Akonadi::Item fItem;
	QString fTempId;
	QDateTime fLastSyncDateTime;
	bool fDeleted;
};

AkonadiRecord::AkonadiRecord( const Akonadi::Item& item, const QDateTime& lastSync )
	: d( new AkonadiRecordPrivate )
{
	d->fItem = item;
	d->fLastSyncDateTime = lastSync;
	d->fDeleted = false;
}

AkonadiRecord::AkonadiRecord( const QString& id ) : d( new AkonadiRecordPrivate )
{
	d->fTempId = id;
	d->fDeleted = true;
}

AkonadiRecord::~AkonadiRecord()
{
}

const QString AkonadiRecord::id() const
{
	if( d->fTempId.isEmpty() )
	{
		return QString::number( d->fItem.id() );
	}
	else
	{
		return d->fTempId;
	}
}

Akonadi::Item AkonadiRecord::item() const
{
	FUNCTIONSETUP;

	return d->fItem;
}

bool AkonadiRecord::isDeleted() const
{
	FUNCTIONSETUP;
	return d->fDeleted;
}

bool AkonadiRecord::isModified() const
{
	FUNCTIONSETUP;

	if( !d->fLastSyncDateTime.isValid() )
	{
		// Whe the fLastSyncDateTime isn't valid, the record is most probably marked
		// for deletion and thus modified.
		return true;
	}

	return d->fItem.modificationTime() > d->fLastSyncDateTime;
}

void AkonadiRecord::setId( const QString &id )
{
	FUNCTIONSETUP;

	// Id's < 0 are temporary id's
	if( id.toLongLong() < 0 )
	{
		d->fTempId = id;
	}
	else
	{
		d->fTempId = QString();
		d->fItem.setId( id.toULongLong() );
	}
}

void AkonadiRecord::setItem( const Akonadi::Item& item )
{
	FUNCTIONSETUP;

	d->fItem = item;
	// Make sure that we return the right id after updating the itemobject.
	setId( QString::number( item.id() ) );
}

void AkonadiRecord::synced()
{
	FUNCTIONSETUP;
	// Nothing to do here.
}
<commit_msg>Fix the time skew so that Akonadirecords don't show up as modified when they shouldn't.<commit_after>/* AkonadiRecord.cc			KPilot
**
** Copyright (C) 2007 by Bertjan Broeksema <b.broeksema@kdemail.net>
** Copyright (C) 2007 by Jason "vanRijn" Kasper <vr@movingparts.net>
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "akonadirecord.h"

#include "options.h"
#include "hhrecord.h"

class AkonadiRecordPrivate : public QSharedData
{
public:
	Akonadi::Item fItem;
	QString fTempId;
	QDateTime fLastSyncDateTime;
	bool fDeleted;
};

AkonadiRecord::AkonadiRecord( const Akonadi::Item& item, const QDateTime& lastSync )
	: d( new AkonadiRecordPrivate )
{
	d->fItem = item;
	d->fLastSyncDateTime = lastSync;
	// Item times have UTC timeSpec
	d->fLastSyncDateTime.setTimeSpec( Qt::UTC );
	d->fDeleted = false;
}

AkonadiRecord::AkonadiRecord( const QString& id ) : d( new AkonadiRecordPrivate )
{
	d->fTempId = id;
	d->fDeleted = true;
}

AkonadiRecord::~AkonadiRecord()
{
}

const QString AkonadiRecord::id() const
{
	if( d->fTempId.isEmpty() )
	{
		return QString::number( d->fItem.id() );
	}
	else
	{
		return d->fTempId;
	}
}

Akonadi::Item AkonadiRecord::item() const
{
	FUNCTIONSETUP;

	return d->fItem;
}

bool AkonadiRecord::isDeleted() const
{
	FUNCTIONSETUP;
	return d->fDeleted;
}

bool AkonadiRecord::isModified() const
{
	FUNCTIONSETUP;

	if( !d->fLastSyncDateTime.isValid() )
	{
		// Whe the fLastSyncDateTime isn't valid, the record is most probably marked
		// for deletion and thus modified.
		return true;
	}

	return d->fItem.modificationTime() > d->fLastSyncDateTime;
}

void AkonadiRecord::setId( const QString &id )
{
	FUNCTIONSETUP;

	// Id's < 0 are temporary id's
	if( id.toLongLong() < 0 )
	{
		d->fTempId = id;
	}
	else
	{
		d->fTempId = QString();
		d->fItem.setId( id.toULongLong() );
	}
}

void AkonadiRecord::setItem( const Akonadi::Item& item )
{
	FUNCTIONSETUP;

	d->fItem = item;
	// Make sure that we return the right id after updating the itemobject.
	setId( QString::number( item.id() ) );
}

void AkonadiRecord::synced()
{
	FUNCTIONSETUP;
	// Nothing to do here.
}
<|endoftext|>