<commit_before>#include "clientmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "alert.h"
#include "main.h"
#include "ui_interface.h"

#include <QDateTime>
#include <QTimer>

static const int64 nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0)
{
    numBlocksAtStartup = -1;

    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections() const
{
    return vNodes.size();
}

int ClientModel::getNumBlocks() const
{
    return nBestHeight;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

QDateTime ClientModel::getLastBlockDate() const
{
    return QDateTime::fromTime_t(pindexBest->GetBlockTime());
}

void ClientModel::updateTimer()
{
    // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
    // Periodically check and update with a timer.
    int newNumBlocks = getNumBlocks();
    int newNumBlocksOfPeers = getNumBlocksOfPeers();

    if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers)
    {
        cachedNumBlocks = newNumBlocks;
        cachedNumBlocksOfPeers = newNumBlocksOfPeers;

        emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers);
    }
}

void ClientModel::updateNumConnections(int numConnections)
{
    emit numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert(const QString &hash, int status)
{
    // Show error message notification for new alert
    if(status == CT_NEW)
    {
        uint256 hash_256;
        hash_256.SetHex(hash.toStdString());
        CAlert alert = CAlert::getAlertByHash(hash_256);
        if(!alert.IsNull())
        {
            emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false);
        }
    }

    // Emit a numBlocksChanged when the status message changes,
    // so that the view recomputes and updates the status bar.
    emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers());
}

bool ClientModel::isTestNet() const
{
    return fTestNet;
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

int ClientModel::getNumBlocksOfPeers() const
{
    return GetNumBlocksOfPeers();
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

// Handlers for core signals
static void NotifyBlocksChanged(ClientModel *clientmodel)
{
    // This notification is too frequent. Don't trigger a signal.
    // Don't remove it, though, as it might be useful later.
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
    OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status);
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(hash.GetHex())),
                              Q_ARG(int, status));
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
<commit_msg>BUGFIX: prevent Qt client crash at startup with an empty directory<commit_after>#include "clientmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "alert.h"
#include "main.h"
#include "ui_interface.h"

#include <QDateTime>
#include <QTimer>

static const int64 nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0)
{
    numBlocksAtStartup = -1;

    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections() const
{
    return vNodes.size();
}

int ClientModel::getNumBlocks() const
{
    return nBestHeight;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

QDateTime ClientModel::getLastBlockDate() const
{
    if (pindexBest)
        return QDateTime::fromTime_t(pindexBest->GetBlockTime());
    else
        return QDateTime::fromTime_t(1360105017); // Genesis block's time
}

void ClientModel::updateTimer()
{
    // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
    // Periodically check and update with a timer.
    int newNumBlocks = getNumBlocks();
    int newNumBlocksOfPeers = getNumBlocksOfPeers();

    if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers)
    {
        cachedNumBlocks = newNumBlocks;
        cachedNumBlocksOfPeers = newNumBlocksOfPeers;

        emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers);
    }
}

void ClientModel::updateNumConnections(int numConnections)
{
    emit numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert(const QString &hash, int status)
{
    // Show error message notification for new alert
    if(status == CT_NEW)
    {
        uint256 hash_256;
        hash_256.SetHex(hash.toStdString());
        CAlert alert = CAlert::getAlertByHash(hash_256);
        if(!alert.IsNull())
        {
            emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false);
        }
    }

    // Emit a numBlocksChanged when the status message changes,
    // so that the view recomputes and updates the status bar.
    emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers());
}

bool ClientModel::isTestNet() const
{
    return fTestNet;
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

int ClientModel::getNumBlocksOfPeers() const
{
    return GetNumBlocksOfPeers();
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

// Handlers for core signals
static void NotifyBlocksChanged(ClientModel *clientmodel)
{
    // This notification is too frequent. Don't trigger a signal.
    // Don't remove it, though, as it might be useful later.
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
    OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status);
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(hash.GetHex())),
                              Q_ARG(int, status));
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
<|endoftext|>


<commit_before>/*
*   This program is free software; you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation; either version 2 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 General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with this program; if not, write to the Free Software
*   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*   Copyright (C) Wallix 2010-2015
*   Author(s): Jonathan Poelen
*/

#ifndef PPOCR_SRC_LOADER2_DATAS_LOADER_HPP
#define PPOCR_SRC_LOADER2_DATAS_LOADER_HPP

#include <array>
#include <vector>
#include <type_traits>

#include "image/image.hpp"

namespace ppocr {

class Image;

namespace loader2 {

using std::size_t;

enum class PolicyLoader { img, img90 };

template<class Strategy_, PolicyLoader Policy>
struct Strategy
{
    using strategy_type = Strategy_;
    constexpr static PolicyLoader policy = Policy;
};

namespace details_ {
    template<class T, class...>
    struct first_type
    { using type = T; };

    struct Lt { template <class T> bool operator()(T const & a, T const & b) const { return a < b; } };
    struct Eq { template <class T> bool operator()(T const & a, T const & b) const { return a == b; } };
    struct Noop { template <class T> bool operator()(T const & , T const & ) const { return false; } };

    template<class Cmp, class Cmp2, class Data>
    bool cmp_datas(size_t i1, size_t i2, Cmp cmp, Cmp2, Data const & data) {
        return cmp(data[i1], data[i2]);
    }

    template<class Cmp, class Cmp2, class Data, class... Datas>
    bool cmp_datas(size_t i1, size_t i2, Cmp cmp, Cmp2 cmp2, Data const & data, Datas const & ... others) {
        if (cmp(data[i1], data[i2]) || cmp2(data[i1], data[i2])) {
            return cmp_datas(i1, i2, cmp, cmp2, others...);
        }
        return false;
    }
}

template<class Strategy_>
typename Strategy_::value_type
load(Strategy_ const & strategy, PolicyLoader policy, Image const & img, Image const & img90)
{ return policy == PolicyLoader::img ? strategy.load(img, img90) : strategy.load(img90, img); }

template<class Strategy>
struct Data
{
    using strategy_type = typename Strategy::strategy_type;
    using value_type = typename strategy_type::value_type;
    using relationship_type = typename strategy_type::relationship_type;

    using container_type = std::vector<value_type>;
    using iterator = typename container_type::const_iterator;
    using const_iterator = iterator;

    Data() = default;

    explicit Data(container_type && cont) noexcept
    : data_(std::move(cont))
    {}

    explicit Data(container_type const & cont)
    : data_(cont)
    {}

    container_type release() noexcept {
        return std::move(this->data_.values);
    }

    void load(Image const & img, Image const & img90) {
        this->data_.values.push_back(::ppocr::loader2::load(
            static_cast<strategy_type const &>(this->data_),
            Strategy::policy, img, img90)
        );
    }

    value_type const & operator[](size_t i) const {
        return data_.values[i];
    }

    typename relationship_type::result_type
    relationship(value_type const & a, value_type const & b) const {
        return static_cast<relationship_type const &>(data_)(a, b);
    }

    std::size_t count_posibilities() const {
        return static_cast<relationship_type const &>(data_).count();
    }

    std::size_t size() const noexcept {
        return this->data_.values.size();
    }

    container_type const & data() const noexcept {
        return this->data_.values;
    }

    iterator begin() const { return this->data().begin(); }
    iterator end() const { return this->data().end(); }

private:
    struct impl : strategy_type, relationship_type /*empty class optimization*/ {
        container_type values;

        template<class... Args>
        impl(Args && ... args)
        : relationship_type(static_cast<strategy_type const &>(*this).relationship())
        , values(std::forward<Args>(args)...)
        {}
    } data_;
};

template<class... Strategies>
struct Datas : private Data<Strategies>...
{
    Datas() = default;

    explicit Datas(Data<Strategies> && ... datas)
    : Data<Strategies>(std::move(datas))...
    {}

    template<class Strategy>
    Data<Strategy> const & get() const noexcept {
        return static_cast<Data<Strategy> const &>(*this);
    }

    template<class Strategy>
    Data<Strategy> & get() noexcept {
        return static_cast<Data<Strategy> &>(*this);
    }

    std::size_t size() const noexcept {
        return this->get<typename details_::first_type<Strategies...>::type>().size();
    }

    std::size_t release() const noexcept {
        return this->get<typename details_::first_type<Strategies...>::type>().size();
    }

    void load(Image const & img) {
        auto img90 = img.rotate90();
        (void(std::initializer_list<char>{
            (static_cast<Data<Strategies>&>(*this).load(img, img90), char())...
        }));
    }

    bool lt(size_t i1, size_t i2) const {
        return details_::cmp_datas(i1, i2, details_::Lt(), details_::Eq(), get<Strategies>()...);
    }

    bool eq(size_t i1, size_t i2) const {
        return details_::cmp_datas(i1, i2, details_::Eq(), details_::Noop(), get<Strategies>()...);
    }
};

template<class Fn, class... Strategies>
void apply_from_datas(Datas<Strategies...> const & datas, Fn fn) {
    (void(std::initializer_list<char>{(void(fn(datas.template get<Strategies>())), char())...}));
}

template<class Fn, class... Strategies>
void apply_from_datas(Datas<Strategies...> & datas, Fn fn) {
    (void(std::initializer_list<char>{(void(fn(datas.template get<Strategies>())), char())...}));
}

} }

#endif
<commit_msg>loader2::Data<Strategy>::dist()<commit_after>/*
*   This program is free software; you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation; either version 2 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 General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with this program; if not, write to the Free Software
*   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*   Copyright (C) Wallix 2010-2015
*   Author(s): Jonathan Poelen
*/

#ifndef PPOCR_SRC_LOADER2_DATAS_LOADER_HPP
#define PPOCR_SRC_LOADER2_DATAS_LOADER_HPP

#include <array>
#include <vector>
#include <type_traits>

#include "image/image.hpp"
#include "sassert.hpp"

namespace ppocr {

class Image;

namespace loader2 {

using std::size_t;

enum class PolicyLoader { img, img90 };

template<class Strategy_, PolicyLoader Policy>
struct Strategy
{
    using strategy_type = Strategy_;
    constexpr static PolicyLoader policy = Policy;
};

namespace details_ {
    template<class T, class...>
    struct first_type
    { using type = T; };

    struct Lt { template <class T> bool operator()(T const & a, T const & b) const { return a < b; } };
    struct Eq { template <class T> bool operator()(T const & a, T const & b) const { return a == b; } };
    struct Noop { template <class T> bool operator()(T const & , T const & ) const { return false; } };

    template<class Cmp, class Cmp2, class Data>
    bool cmp_datas(size_t i1, size_t i2, Cmp cmp, Cmp2, Data const & data) {
        return cmp(data[i1], data[i2]);
    }

    template<class Cmp, class Cmp2, class Data, class... Datas>
    bool cmp_datas(size_t i1, size_t i2, Cmp cmp, Cmp2 cmp2, Data const & data, Datas const & ... others) {
        if (cmp(data[i1], data[i2]) || cmp2(data[i1], data[i2])) {
            return cmp_datas(i1, i2, cmp, cmp2, others...);
        }
        return false;
    }
}

template<class Strategy_>
typename Strategy_::value_type
load(Strategy_ const & strategy, PolicyLoader policy, Image const & img, Image const & img90)
{ return policy == PolicyLoader::img ? strategy.load(img, img90) : strategy.load(img90, img); }

template<class Strategy>
struct Data
{
    using strategy_type = typename Strategy::strategy_type;
    using value_type = typename strategy_type::value_type;
    using relationship_type = typename strategy_type::relationship_type;

    using container_type = std::vector<value_type>;
    using iterator = typename container_type::const_iterator;
    using const_iterator = iterator;

    Data() = default;

    explicit Data(container_type && cont) noexcept
    : data_(std::move(cont))
    {}

    explicit Data(container_type const & cont)
    : data_(cont)
    {}

    container_type release() noexcept {
        return std::move(this->data_.values);
    }

    void load(Image const & img, Image const & img90) {
        this->data_.values.push_back(::ppocr::loader2::load(
            static_cast<strategy_type const &>(this->data_),
            Strategy::policy, img, img90)
        );
    }

    value_type const & operator[](size_t i) const {
        return data_.values[i];
    }

    typename relationship_type::result_type
    relationship(value_type const & a, value_type const & b) const {
        return static_cast<relationship_type const &>(data_)(a, b);
    }

    double dist(value_type const & a, value_type const & b) const {
        double const ret = static_cast<relationship_type const &>(data_).dist(a, b);
        assert(0. <= ret && ret <= 1.);
        return ret;
    }

    std::size_t count_posibilities() const {
        return static_cast<relationship_type const &>(data_).count();
    }

    std::size_t size() const noexcept {
        return this->data_.values.size();
    }

    container_type const & data() const noexcept {
        return this->data_.values;
    }

    iterator begin() const { return this->data().begin(); }
    iterator end() const { return this->data().end(); }

private:
    struct impl : strategy_type, relationship_type /*empty class optimization*/ {
        container_type values;

        template<class... Args>
        impl(Args && ... args)
        : relationship_type(static_cast<strategy_type const &>(*this).relationship())
        , values(std::forward<Args>(args)...)
        {}
    } data_;
};

template<class... Strategies>
struct Datas : private Data<Strategies>...
{
    Datas() = default;

    explicit Datas(Data<Strategies> && ... datas)
    : Data<Strategies>(std::move(datas))...
    {}

    template<class Strategy>
    Data<Strategy> const & get() const noexcept {
        return static_cast<Data<Strategy> const &>(*this);
    }

    template<class Strategy>
    Data<Strategy> & get() noexcept {
        return static_cast<Data<Strategy> &>(*this);
    }

    std::size_t size() const noexcept {
        return this->get<typename details_::first_type<Strategies...>::type>().size();
    }

    std::size_t release() const noexcept {
        return this->get<typename details_::first_type<Strategies...>::type>().size();
    }

    void load(Image const & img) {
        auto img90 = img.rotate90();
        (void(std::initializer_list<char>{
            (static_cast<Data<Strategies>&>(*this).load(img, img90), char())...
        }));
    }

    bool lt(size_t i1, size_t i2) const {
        return details_::cmp_datas(i1, i2, details_::Lt(), details_::Eq(), get<Strategies>()...);
    }

    bool eq(size_t i1, size_t i2) const {
        return details_::cmp_datas(i1, i2, details_::Eq(), details_::Noop(), get<Strategies>()...);
    }
};

template<class Fn, class... Strategies>
void apply_from_datas(Datas<Strategies...> const & datas, Fn fn) {
    (void(std::initializer_list<char>{(void(fn(datas.template get<Strategies>())), char())...}));
}

template<class Fn, class... Strategies>
void apply_from_datas(Datas<Strategies...> & datas, Fn fn) {
    (void(std::initializer_list<char>{(void(fn(datas.template get<Strategies>())), char())...}));
}

} }

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#include <boost/algorithm/string.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/tokenizer.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "headers.h"

using namespace boost::interprocess;
using namespace boost::posix_time;
using namespace boost;
using namespace std;

void ipcShutdown()
{
    message_queue::remove("BitcoinURL");
}

void ipcThread(void* parg)
{
    message_queue* mq = (message_queue*)parg;
    char strBuf[257];
    size_t nSize;
    unsigned int nPriority;
    loop
    {
        ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100);
        if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d))
        {
            ThreadSafeHandleURL(std::string(strBuf, nSize));
            Sleep(1000);
        }
        if (fShutdown)
        {
            ipcShutdown();
            break;
        }
    }
    ipcShutdown();
}

void ipcInit()
{
    message_queue* mq;
    char strBuf[257];
    size_t nSize;
    unsigned int nPriority;
    try {
        mq = new message_queue(open_or_create, "BitcoinURL", 2, 256);

        // Make sure we don't lose any bitcoin: URIs
        for (int i = 0; i < 2; i++)
        {
            ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1);
            if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d))
            {
                ThreadSafeHandleURL(std::string(strBuf, nSize));
            }
            else
                break;
        }

        // Make sure only one bitcoin instance is listening
        message_queue::remove("BitcoinURL");
        mq = new message_queue(open_or_create, "BitcoinURL", 2, 256);
    }
    catch (interprocess_exception &ex) {
        return;
    }
    if (!CreateThread(ipcThread, mq))
    {
        delete mq;
    }
}
<commit_msg>Do not start bitcoin: thread on OSX. fixes #889<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#include <boost/algorithm/string.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/tokenizer.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "headers.h"

using namespace boost::interprocess;
using namespace boost::posix_time;
using namespace boost;
using namespace std;

void ipcShutdown()
{
    message_queue::remove("BitcoinURL");
}

void ipcThread(void* parg)
{
    message_queue* mq = (message_queue*)parg;
    char strBuf[257];
    size_t nSize;
    unsigned int nPriority;
    loop
    {
        ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100);
        if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d))
        {
            ThreadSafeHandleURL(std::string(strBuf, nSize));
            Sleep(1000);
        }
        if (fShutdown)
        {
            ipcShutdown();
            break;
        }
    }
    ipcShutdown();
}

void ipcInit()
{
#ifdef MAC_OSX
    // TODO: implement bitcoin: URI handling the Mac Way
    return;
#endif

    message_queue* mq;
    char strBuf[257];
    size_t nSize;
    unsigned int nPriority;
    try {
        mq = new message_queue(open_or_create, "BitcoinURL", 2, 256);

        // Make sure we don't lose any bitcoin: URIs
        for (int i = 0; i < 2; i++)
        {
            ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1);
            if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d))
            {
                ThreadSafeHandleURL(std::string(strBuf, nSize));
            }
            else
                break;
        }

        // Make sure only one bitcoin instance is listening
        message_queue::remove("BitcoinURL");
        mq = new message_queue(open_or_create, "BitcoinURL", 2, 256);
    }
    catch (interprocess_exception &ex) {
        return;
    }
    if (!CreateThread(ipcThread, mq))
    {
        delete mq;
    }
}
<|endoftext|>


<commit_before>#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <string>

#include "log/cert.h"
#include "log/cert_checker.h"
#include "log/ct_extensions.h"
#include "util/testing.h"
#include "util/util.h"

namespace ct {
using std::string;

DEFINE_string(test_certs_dir, "../test/testdata", "Path to test certificates");

// Valid certificates.
// Self-signed
static const char kCaCert[] = "ca-cert.pem";
// Issued by ca-cert.pem
static const char kLeafCert[] = "test-cert.pem";
// Issued by ca-cert.pem
static const char kCaPreCert[] = "ca-pre-cert.pem";
// Issued by ca-cert.pem
static const char kPreCert[] = "test-embedded-pre-cert.pem";
// Issued by ca-pre-cert.pem
static const char kPreWithPreCaCert[] = "test-embedded-with-preca-pre-cert.pem";
// Issued by ca-cert.pem
static const char kIntermediateCert[] = "intermediate-cert.pem";
// Issued by intermediate-cert.pem
static const char kChainLeafCert[] = "test-intermediate-cert.pem";
// CA with no basic constraints.
static const char kCaNoBCCert[] = "test-no-bc-ca-cert.pem";
// Chain terminating in that CA.
static const char kNoBCChain[] = "test-no-bc-cert-chain.pem";
// Chain where a leaf cert issues another cert
static const char kBadNoBCChain[] = "test-no-ca-cert-chain.pem";

namespace {

class CertCheckerTest : public ::testing::Test {
 protected:
  string leaf_pem_;
  string ca_precert_pem_;
  string precert_pem_;
  string precert_with_preca_pem_;
  string intermediate_pem_;
  string chain_leaf_pem_;
  string ca_pem_;
  CertChecker checker_;
  string cert_dir_;

  void SetUp() {
    cert_dir_ = FLAGS_test_certs_dir;
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kLeafCert, &leaf_pem_))
        << "Could not read test data from " << cert_dir_
        << ". Wrong --test_certs_dir?";
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kCaPreCert, &ca_precert_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kPreCert, &precert_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kPreWithPreCaCert,
                             &precert_with_preca_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kIntermediateCert,
                             &intermediate_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kChainLeafCert,
                             &chain_leaf_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kCaCert, &ca_pem_));
  }
};

TEST_F(CertCheckerTest, Certificate) {
  CertChain chain(leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());

  // Fail as we have no CA certs.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckCertChain(&chain));

  // Load CA certs and expect success.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(2U, chain.Length());
}

TEST_F(CertCheckerTest, CertificateWithRoot) {
  CertChain chain(leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(ca_pem_)));

  // Fail as even though we give a CA cert, it's not in the local store.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckCertChain(&chain));

  // Load CA certs and expect success.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(2U, chain.Length());
}

TEST_F(CertCheckerTest, TrimsRepeatedRoots) {
  CertChain chain(leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(ca_pem_)));
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(ca_pem_)));

  // Load CA certs and expect success.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(2U, chain.Length());
}

TEST_F(CertCheckerTest, Intermediates) {
  // Load CA certs.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  // A chain with an intermediate.
  CertChain chain(chain_leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());
  // Fail as it doesn't chain to a trusted CA.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckCertChain(&chain));
  // Add the intermediate and expect success.
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(intermediate_pem_)));
  ASSERT_EQ(2U, chain.Length());
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(3U, chain.Length());

  // An invalid chain, with two certs in wrong order.
  CertChain invalid(intermediate_pem_ + chain_leaf_pem_);
  ASSERT_TRUE(invalid.IsLoaded());
  EXPECT_EQ(CertChecker::INVALID_CERTIFICATE_CHAIN,
            checker_.CheckCertChain(&invalid));
}

TEST_F(CertCheckerTest, PreCert) {
  const string chain_pem = precert_pem_ + ca_pem_;
  PreCertChain chain(chain_pem);

  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(Cert::TRUE, chain.IsWellFormed());

  // Fail as we have no CA certs.
  string issuer_key_hash, tbs;
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));

  // Load CA certs and expect success.
  checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert);
  EXPECT_EQ(CertChecker::OK,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));
  string expected_key_hash;
  ASSERT_EQ(Cert::TRUE,
            chain.CertAt(1)->SPKISha256Digest(&expected_key_hash));
  EXPECT_EQ(expected_key_hash, issuer_key_hash);
  // TODO(ekasper): proper KAT tests.
  EXPECT_FALSE(tbs.empty());
}

TEST_F(CertCheckerTest, PreCertWithPreCa) {
  const string chain_pem = precert_with_preca_pem_ + ca_precert_pem_;
  PreCertChain chain(chain_pem);

  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(Cert::TRUE, chain.IsWellFormed());

  string issuer_key_hash, tbs;
  // Fail as we have no CA certs.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));

  // Load CA certs and expect success.
  checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert);
  EXPECT_EQ(CertChecker::OK,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));
  string expected_key_hash;
  ASSERT_EQ(Cert::TRUE,
            chain.CertAt(2)->SPKISha256Digest(&expected_key_hash));
  EXPECT_EQ(expected_key_hash, issuer_key_hash);
  // TODO(ekasper): proper KAT tests.
  EXPECT_FALSE(tbs.empty());

  // A second, invalid chain, with no CA precert.
  PreCertChain chain2(precert_with_preca_pem_);
  ASSERT_TRUE(chain2.IsLoaded());
  EXPECT_EQ(Cert::TRUE, chain2.IsWellFormed());
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckPreCertChain(&chain2, &issuer_key_hash, &tbs));
}

TEST_F(CertCheckerTest, CertAsPreCert) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));

  PreCertChain chain(leaf_pem_);
  string issuer_key_hash, tbs;
  EXPECT_EQ(CertChecker::PRECERT_CHAIN_NOT_WELL_FORMED,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));
}

TEST_F(CertCheckerTest, PreCertAsCert) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));

  const string chain_pem = precert_pem_ + ca_pem_;
  PreCertChain chain(chain_pem);
  EXPECT_EQ(CertChecker::PRECERT_EXTENSION_IN_CERT_CHAIN,
            checker_.CheckCertChain(&chain));
}

// Accept if the root cert has no CA:True constraint and is in the trust store
TEST_F(CertCheckerTest, AcceptNoBasicConstraints) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaNoBCCert));

  string chain_pem;
  ASSERT_TRUE(util::ReadTextFile(cert_dir_ + "/" + kNoBCChain, &chain_pem));

  CertChain chain(chain_pem);
  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
}

// Don't accept if some other cert without CA:True tries to issue.
TEST_F(CertCheckerTest, DontAcceptNoBasicConstraints) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));

  string chain_pem;
  ASSERT_TRUE(util::ReadTextFile(cert_dir_ + "/" + kBadNoBCChain, &chain_pem));

  CertChain chain(chain_pem);
  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(CertChecker::INVALID_CERTIFICATE_CHAIN,
	    checker_.CheckCertChain(&chain));
}

}  // namespace
}  // namespace ct

int main(int argc, char**argv) {
  ct::test::InitTesting(argv[0], &argc, &argv, true);
  OpenSSL_add_all_algorithms();
  ERR_load_crypto_strings();
  ct::LoadCtExtensions();
  return RUN_ALL_TESTS();
}
<commit_msg>Fix tab,<commit_after>/* -*- indent-tabs-mode: nil -*- */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <string>

#include "log/cert.h"
#include "log/cert_checker.h"
#include "log/ct_extensions.h"
#include "util/testing.h"
#include "util/util.h"

namespace ct {
using std::string;

DEFINE_string(test_certs_dir, "../test/testdata", "Path to test certificates");

// Valid certificates.
// Self-signed
static const char kCaCert[] = "ca-cert.pem";
// Issued by ca-cert.pem
static const char kLeafCert[] = "test-cert.pem";
// Issued by ca-cert.pem
static const char kCaPreCert[] = "ca-pre-cert.pem";
// Issued by ca-cert.pem
static const char kPreCert[] = "test-embedded-pre-cert.pem";
// Issued by ca-pre-cert.pem
static const char kPreWithPreCaCert[] = "test-embedded-with-preca-pre-cert.pem";
// Issued by ca-cert.pem
static const char kIntermediateCert[] = "intermediate-cert.pem";
// Issued by intermediate-cert.pem
static const char kChainLeafCert[] = "test-intermediate-cert.pem";
// CA with no basic constraints.
static const char kCaNoBCCert[] = "test-no-bc-ca-cert.pem";
// Chain terminating in that CA.
static const char kNoBCChain[] = "test-no-bc-cert-chain.pem";
// Chain where a leaf cert issues another cert
static const char kBadNoBCChain[] = "test-no-ca-cert-chain.pem";

namespace {

class CertCheckerTest : public ::testing::Test {
 protected:
  string leaf_pem_;
  string ca_precert_pem_;
  string precert_pem_;
  string precert_with_preca_pem_;
  string intermediate_pem_;
  string chain_leaf_pem_;
  string ca_pem_;
  CertChecker checker_;
  string cert_dir_;

  void SetUp() {
    cert_dir_ = FLAGS_test_certs_dir;
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kLeafCert, &leaf_pem_))
        << "Could not read test data from " << cert_dir_
        << ". Wrong --test_certs_dir?";
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kCaPreCert, &ca_precert_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kPreCert, &precert_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kPreWithPreCaCert,
                             &precert_with_preca_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kIntermediateCert,
                             &intermediate_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kChainLeafCert,
                             &chain_leaf_pem_));
    CHECK(util::ReadTextFile(cert_dir_ + "/" + kCaCert, &ca_pem_));
  }
};

TEST_F(CertCheckerTest, Certificate) {
  CertChain chain(leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());

  // Fail as we have no CA certs.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckCertChain(&chain));

  // Load CA certs and expect success.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(2U, chain.Length());
}

TEST_F(CertCheckerTest, CertificateWithRoot) {
  CertChain chain(leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(ca_pem_)));

  // Fail as even though we give a CA cert, it's not in the local store.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckCertChain(&chain));

  // Load CA certs and expect success.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(2U, chain.Length());
}

TEST_F(CertCheckerTest, TrimsRepeatedRoots) {
  CertChain chain(leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(ca_pem_)));
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(ca_pem_)));

  // Load CA certs and expect success.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(2U, chain.Length());
}

TEST_F(CertCheckerTest, Intermediates) {
  // Load CA certs.
  EXPECT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));
  // A chain with an intermediate.
  CertChain chain(chain_leaf_pem_);
  ASSERT_TRUE(chain.IsLoaded());
  // Fail as it doesn't chain to a trusted CA.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckCertChain(&chain));
  // Add the intermediate and expect success.
  ASSERT_EQ(Cert::TRUE, chain.AddCert(new Cert(intermediate_pem_)));
  ASSERT_EQ(2U, chain.Length());
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
  EXPECT_EQ(3U, chain.Length());

  // An invalid chain, with two certs in wrong order.
  CertChain invalid(intermediate_pem_ + chain_leaf_pem_);
  ASSERT_TRUE(invalid.IsLoaded());
  EXPECT_EQ(CertChecker::INVALID_CERTIFICATE_CHAIN,
            checker_.CheckCertChain(&invalid));
}

TEST_F(CertCheckerTest, PreCert) {
  const string chain_pem = precert_pem_ + ca_pem_;
  PreCertChain chain(chain_pem);

  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(Cert::TRUE, chain.IsWellFormed());

  // Fail as we have no CA certs.
  string issuer_key_hash, tbs;
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));

  // Load CA certs and expect success.
  checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert);
  EXPECT_EQ(CertChecker::OK,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));
  string expected_key_hash;
  ASSERT_EQ(Cert::TRUE,
            chain.CertAt(1)->SPKISha256Digest(&expected_key_hash));
  EXPECT_EQ(expected_key_hash, issuer_key_hash);
  // TODO(ekasper): proper KAT tests.
  EXPECT_FALSE(tbs.empty());
}

TEST_F(CertCheckerTest, PreCertWithPreCa) {
  const string chain_pem = precert_with_preca_pem_ + ca_precert_pem_;
  PreCertChain chain(chain_pem);

  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(Cert::TRUE, chain.IsWellFormed());

  string issuer_key_hash, tbs;
  // Fail as we have no CA certs.
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));

  // Load CA certs and expect success.
  checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert);
  EXPECT_EQ(CertChecker::OK,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));
  string expected_key_hash;
  ASSERT_EQ(Cert::TRUE,
            chain.CertAt(2)->SPKISha256Digest(&expected_key_hash));
  EXPECT_EQ(expected_key_hash, issuer_key_hash);
  // TODO(ekasper): proper KAT tests.
  EXPECT_FALSE(tbs.empty());

  // A second, invalid chain, with no CA precert.
  PreCertChain chain2(precert_with_preca_pem_);
  ASSERT_TRUE(chain2.IsLoaded());
  EXPECT_EQ(Cert::TRUE, chain2.IsWellFormed());
  EXPECT_EQ(CertChecker::ROOT_NOT_IN_LOCAL_STORE,
            checker_.CheckPreCertChain(&chain2, &issuer_key_hash, &tbs));
}

TEST_F(CertCheckerTest, CertAsPreCert) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));

  PreCertChain chain(leaf_pem_);
  string issuer_key_hash, tbs;
  EXPECT_EQ(CertChecker::PRECERT_CHAIN_NOT_WELL_FORMED,
            checker_.CheckPreCertChain(&chain, &issuer_key_hash, &tbs));
}

TEST_F(CertCheckerTest, PreCertAsCert) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));

  const string chain_pem = precert_pem_ + ca_pem_;
  PreCertChain chain(chain_pem);
  EXPECT_EQ(CertChecker::PRECERT_EXTENSION_IN_CERT_CHAIN,
            checker_.CheckCertChain(&chain));
}

// Accept if the root cert has no CA:True constraint and is in the trust store
TEST_F(CertCheckerTest, AcceptNoBasicConstraints) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaNoBCCert));

  string chain_pem;
  ASSERT_TRUE(util::ReadTextFile(cert_dir_ + "/" + kNoBCChain, &chain_pem));

  CertChain chain(chain_pem);
  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(CertChecker::OK, checker_.CheckCertChain(&chain));
}

// Don't accept if some other cert without CA:True tries to issue.
TEST_F(CertCheckerTest, DontAcceptNoBasicConstraints) {
  ASSERT_TRUE(checker_.LoadTrustedCertificates(cert_dir_ + "/" + kCaCert));

  string chain_pem;
  ASSERT_TRUE(util::ReadTextFile(cert_dir_ + "/" + kBadNoBCChain, &chain_pem));

  CertChain chain(chain_pem);
  ASSERT_TRUE(chain.IsLoaded());
  EXPECT_EQ(CertChecker::INVALID_CERTIFICATE_CHAIN,
            checker_.CheckCertChain(&chain));
}

}  // namespace
}  // namespace ct

int main(int argc, char**argv) {
  ct::test::InitTesting(argv[0], &argc, &argv, true);
  OpenSSL_add_all_algorithms();
  ERR_load_crypto_strings();
  ct::LoadCtExtensions();
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "walletmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "headers.h"

#include <QTimer>
#include <QSet>

WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
    transactionTableModel(0),
    cachedBalance(0), cachedUnconfirmedBalance(0), cachedNumTransactions(0)
{
    // Until signal notifications is built into the bitcoin core,
    //  simply update everything after polling using a timer.
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(MODEL_UPDATE_DELAY);

    addressTableModel = new AddressTableModel(wallet, this);
    transactionTableModel = new TransactionTableModel(wallet, this);
}

qint64 WalletModel::getBalance() const
{
    return wallet->GetBalance();
}

qint64 WalletModel::getUnconfirmedBalance() const
{
    return wallet->GetUnconfirmedBalance();
}

int WalletModel::getNumTransactions() const
{
    int numTransactions = 0;
    CRITICAL_BLOCK(wallet->cs_mapWallet)
    {
        numTransactions = wallet->mapWallet.size();
    }
    return numTransactions;
}

void WalletModel::update()
{
    qint64 newBalance = getBalance();
    qint64 newUnconfirmedBalance = getUnconfirmedBalance();
    int newNumTransactions = getNumTransactions();

    if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance)
        emit balanceChanged(newBalance, newUnconfirmedBalance);

    if(cachedNumTransactions != newNumTransactions)
        emit numTransactionsChanged(newNumTransactions);

    cachedBalance = newBalance;
    cachedUnconfirmedBalance = newUnconfirmedBalance;
    cachedNumTransactions = newNumTransactions;

    addressTableModel->update();
}

bool WalletModel::validateAddress(const QString &address)
{
    CBitcoinAddress addressParsed(address.toStdString());
    return addressParsed.IsValid();
}

WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        uint160 hash160 = 0;

        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    if(total > getBalance())
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > getBalance())
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    CRITICAL_BLOCK(cs_main)
    CRITICAL_BLOCK(wallet->cs_mapWallet)
    {
        // Sendmany
        std::vector<std::pair<CScript, int64> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetBitcoinAddress(rcp.address.toStdString());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64 nFeeRequired = 0;
        bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);

        if(!fCreated)
        {
            if((total + nFeeRequired) > wallet->GetBalance())
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
        if(!ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString(), NULL))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }

    // Add addresses that we've sent to to the address book
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        std::string strAddress = rcp.address.toStdString();
        CRITICAL_BLOCK(wallet->cs_mapAddressBook)
        {
            if (!wallet->mapAddressBook.count(strAddress))
                wallet->SetAddressBookName(strAddress, rcp.label.toStdString());
        }
    }

    return SendCoinsReturn(OK, 0, hex);
}

OptionsModel *WalletModel::getOptionsModel()
{
    return optionsModel;
}

AddressTableModel *WalletModel::getAddressTableModel()
{
    return addressTableModel;
}

TransactionTableModel *WalletModel::getTransactionTableModel()
{
    return transactionTableModel;
}

<commit_msg>make sure address book model is up to date after sending coins<commit_after>#include "walletmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "headers.h"

#include <QTimer>
#include <QSet>

WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
    transactionTableModel(0),
    cachedBalance(0), cachedUnconfirmedBalance(0), cachedNumTransactions(0)
{
    // Until signal notifications is built into the bitcoin core,
    //  simply update everything after polling using a timer.
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(MODEL_UPDATE_DELAY);

    addressTableModel = new AddressTableModel(wallet, this);
    transactionTableModel = new TransactionTableModel(wallet, this);
}

qint64 WalletModel::getBalance() const
{
    return wallet->GetBalance();
}

qint64 WalletModel::getUnconfirmedBalance() const
{
    return wallet->GetUnconfirmedBalance();
}

int WalletModel::getNumTransactions() const
{
    int numTransactions = 0;
    CRITICAL_BLOCK(wallet->cs_mapWallet)
    {
        numTransactions = wallet->mapWallet.size();
    }
    return numTransactions;
}

void WalletModel::update()
{
    qint64 newBalance = getBalance();
    qint64 newUnconfirmedBalance = getUnconfirmedBalance();
    int newNumTransactions = getNumTransactions();

    if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance)
        emit balanceChanged(newBalance, newUnconfirmedBalance);

    if(cachedNumTransactions != newNumTransactions)
        emit numTransactionsChanged(newNumTransactions);

    cachedBalance = newBalance;
    cachedUnconfirmedBalance = newUnconfirmedBalance;
    cachedNumTransactions = newNumTransactions;

    addressTableModel->update();
}

bool WalletModel::validateAddress(const QString &address)
{
    CBitcoinAddress addressParsed(address.toStdString());
    return addressParsed.IsValid();
}

WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        uint160 hash160 = 0;

        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    if(total > getBalance())
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > getBalance())
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    CRITICAL_BLOCK(cs_main)
    CRITICAL_BLOCK(wallet->cs_mapWallet)
    {
        // Sendmany
        std::vector<std::pair<CScript, int64> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetBitcoinAddress(rcp.address.toStdString());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64 nFeeRequired = 0;
        bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);

        if(!fCreated)
        {
            if((total + nFeeRequired) > wallet->GetBalance())
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
        if(!ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString(), NULL))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }

    // Add addresses that we've sent to to the address book
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        std::string strAddress = rcp.address.toStdString();
        CRITICAL_BLOCK(wallet->cs_mapAddressBook)
        {
            if (!wallet->mapAddressBook.count(strAddress))
                wallet->SetAddressBookName(strAddress, rcp.label.toStdString());
        }
    }
    addressTableModel->updateList();

    return SendCoinsReturn(OK, 0, hex);
}

OptionsModel *WalletModel::getOptionsModel()
{
    return optionsModel;
}

AddressTableModel *WalletModel::getAddressTableModel()
{
    return addressTableModel;
}

TransactionTableModel *WalletModel::getTransactionTableModel()
{
    return transactionTableModel;
}

<|endoftext|>


<commit_before><commit_msg>Change an ASSERT_TRUE to a CHECK() to remove the gtest dependency.<commit_after><|endoftext|>


<commit_before>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2019 Axel Waggershauser
*
* 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.
*/

#include <vector>

#include "MultiFormatWriter.h"
#include "BitMatrix.h"
#include "ByteMatrix.h"

using namespace ZXing;
using namespace std::literals;

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

void savePng(const BitMatrix& matrix, BarcodeFormat format)
{
	auto bitmap = ToMatrix<uint8_t>(matrix);
	stbi_write_png((ToString(format) + ".png"s).c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0);
}

int main()
{
	std::wstring text = L"http://www.google.com/";
	for (auto format : {
		BarcodeFormat::AZTEC,
		BarcodeFormat::DATA_MATRIX,
		BarcodeFormat::PDF_417,
		BarcodeFormat::QR_CODE })
	{
		savePng(MultiFormatWriter(format).encode(text, 200, 200), format);
	}

	text = L"012345678901234567890123456789";
	using FormatSpecs = std::vector<std::pair<BarcodeFormat, size_t>>;
	for (const auto& [format, length] : FormatSpecs({
		{BarcodeFormat::CODABAR, 0},
		{BarcodeFormat::CODE_39, 0},
		{BarcodeFormat::CODE_93, 0},
		{BarcodeFormat::CODE_128, 0},
		{BarcodeFormat::EAN_8, 7},
		{BarcodeFormat::EAN_13, 12},
		{BarcodeFormat::ITF, 0},
		{BarcodeFormat::UPC_A, 11},
		{BarcodeFormat::UPC_E, 7} }))
	{
		auto input = length > 0 ? text.substr(0, length) : text;
		savePng(MultiFormatWriter(format).encode(input, 100, 100), format);
	}
}
<commit_msg>Test: prevent unnecessary memory allocation<commit_after>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2019 Axel Waggershauser
*
* 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.
*/

#include <initializer_list>

#include "MultiFormatWriter.h"
#include "BitMatrix.h"
#include "ByteMatrix.h"

using namespace ZXing;
using namespace std::literals;

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

void savePng(const BitMatrix& matrix, BarcodeFormat format)
{
	auto bitmap = ToMatrix<uint8_t>(matrix);
	stbi_write_png((ToString(format) + ".png"s).c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0);
}

int main()
{
	std::wstring text = L"http://www.google.com/";
	for (auto format : {
		BarcodeFormat::AZTEC,
		BarcodeFormat::DATA_MATRIX,
		BarcodeFormat::PDF_417,
		BarcodeFormat::QR_CODE })
	{
		savePng(MultiFormatWriter(format).encode(text, 200, 200), format);
	}

	text = L"012345678901234567890123456789";
	using FormatSpecs = std::initializer_list<std::pair<BarcodeFormat, size_t>>;
	for (const auto& [format, length] : FormatSpecs({
		{BarcodeFormat::CODABAR, 0},
		{BarcodeFormat::CODE_39, 0},
		{BarcodeFormat::CODE_93, 0},
		{BarcodeFormat::CODE_128, 0},
		{BarcodeFormat::EAN_8, 7},
		{BarcodeFormat::EAN_13, 12},
		{BarcodeFormat::ITF, 0},
		{BarcodeFormat::UPC_A, 11},
		{BarcodeFormat::UPC_E, 7} }))
	{
		auto input = length > 0 ? text.substr(0, length) : text;
		savePng(MultiFormatWriter(format).encode(input, 100, 100), format);
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dp_executable.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#include "dp_backend.h"
#include "dp_ucb.h"
#include "dp_interact.h"
#include "rtl/string.hxx"
#include "osl/file.hxx"
#include "ucbhelper/content.hxx"
#include "comphelper/servicedecl.hxx"
#include "svtools/inettype.hxx"
#include "cppuhelper/implbase1.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;

namespace dp_registry {
namespace backend {
namespace executable {
namespace {

class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
    class ExecutablePackageImpl : public ::dp_registry::backend::Package
    {
        BackendImpl * getMyBackend() const {
            return static_cast<BackendImpl *>(m_myBackend.get());
        }

        // Package
        virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
            ::osl::ResettableMutexGuard & guard,
            ::rtl::Reference<dp_misc::AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );
        virtual void processPackage_(
            ::osl::ResettableMutexGuard & guard,
            bool registerPackage,
            ::rtl::Reference<dp_misc::AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );

        bool getFileAttributes(sal_uInt64& out_Attributes);
        bool isUrlTargetInExtension();

    public:
        inline ExecutablePackageImpl(
            ::rtl::Reference<PackageRegistryBackend> const & myBackend,
            OUString const & url, OUString const & name,
            Reference<deployment::XPackageTypeInfo> const & xPackageType)
            : Package( myBackend, url, name, name /* display-name */,
                       xPackageType ) //,
            {}
    };
    friend class ExecutablePackageImpl;

    typedef ::std::hash_map< OUString, Reference<XInterface>,
                             ::rtl::OUStringHash > t_string2object;

    // PackageRegistryBackend
    virtual Reference<deployment::XPackage> bindPackage_(
        OUString const & url, OUString const & mediaType,
        Reference<XCommandEnvironment> const & xCmdEnv );

    Reference<deployment::XPackageTypeInfo> m_xExecutableTypeInfo;

public:
    BackendImpl( Sequence<Any> const & args,
                 Reference<XComponentContext> const & xComponentContext );

    // XPackageRegistry
    virtual Sequence< Reference<deployment::XPackageTypeInfo> > SAL_CALL
    getSupportedPackageTypes() throw (RuntimeException);

    using PackageRegistryBackend::disposing;
};

BackendImpl::BackendImpl(
    Sequence<Any> const & args,
    Reference<XComponentContext> const & xComponentContext )
    : PackageRegistryBackend( args, xComponentContext ),
      m_xExecutableTypeInfo(new Package::TypeInfo(
                                OUSTR("application/vnd.sun.star.executable"),
                                OUSTR(""),
                                OUSTR("Executable"),
                                RID_IMG_COMPONENT,
                                RID_IMG_COMPONENT_HC ) )
{

}

// XPackageRegistry
Sequence< Reference<deployment::XPackageTypeInfo> >
BackendImpl::getSupportedPackageTypes() throw (RuntimeException)
{
    return Sequence<Reference<deployment::XPackageTypeInfo> >(
        & m_xExecutableTypeInfo, 1);
}

// PackageRegistryBackend
Reference<deployment::XPackage> BackendImpl::bindPackage_(
    OUString const & url, OUString const & mediaType,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    if (mediaType.getLength() == 0)
    {
        throw lang::IllegalArgumentException(
            StrCannotDetectMediaType::get() + url,
            static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
    }

    String type, subType;
    INetContentTypeParameterList params;
    if (INetContentTypes::parse( mediaType, type, subType, &params ))
    {
        if (type.EqualsIgnoreCaseAscii("application"))
        {
            ::ucbhelper::Content ucbContent( url, xCmdEnv );
            const OUString name( ucbContent.getPropertyValue(
                dp_misc::StrTitle::get() ).get<OUString>() );
            if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.executable"))
            {
                return new BackendImpl::ExecutablePackageImpl(
                    this, url, name,  m_xExecutableTypeInfo);
            }
        }
    }
    return Reference<deployment::XPackage>();
}

//##############################################################################

// Package
beans::Optional< beans::Ambiguous<sal_Bool> >
BackendImpl::ExecutablePackageImpl::isRegistered_(
    ::osl::ResettableMutexGuard &,
    ::rtl::Reference<dp_misc::AbortChannel> const &,
    Reference<XCommandEnvironment> const & )
{
    //We must return Optional.isPresent = true, otherwise
    //processPackage is not called.
    //The user shall not be able to enable/disable the executable. This is not needed since
    //the executable does not affect the office. The best thing is to show no
    //status at all. See also BackendImpl::PackageImpl::isRegistered_ (dp_package.cxx)
    //On Windows there is no executable file attribute. One has to use security API for this.
    //However, on Windows we do not have the problem, that after unzipping the file cannot be
    //executed.
    return beans::Optional< beans::Ambiguous<sal_Bool> >(
            sal_True /* IsPresent */,
                beans::Ambiguous<sal_Bool>(
                   sal_True, sal_True /* IsAmbiguous */ ) );
}

void BackendImpl::ExecutablePackageImpl::processPackage_(
    ::osl::ResettableMutexGuard &,
    bool doRegisterPackage,
    ::rtl::Reference<dp_misc::AbortChannel> const & abortChannel,
    Reference<XCommandEnvironment> const & /*xCmdEnv*/ )
{
    checkAborted(abortChannel);
    if (doRegisterPackage)
    {
        if (!isUrlTargetInExtension())
        {
            OSL_ASSERT(0);
            return;
        }
        sal_uInt64 attributes = 0;
        //Setting the executable attribut does not affect executables on Windows
        if (getFileAttributes(attributes))
        {
            if(getMyBackend()->m_context.equals(OUSTR("user")))
                attributes |= osl_File_Attribute_OwnExe;
            else if (getMyBackend()->m_context.equals(OUSTR("shared")))
                attributes |= (osl_File_Attribute_OwnExe | osl_File_Attribute_GrpExe
                               | osl_File_Attribute_OthExe);
            else
                OSL_ASSERT(0);

            //This won't have affect on Windows
            if (osl::File::E_None != osl::File::setAttributes(
                    dp_misc::expandUnoRcUrl(m_url), attributes))
                OSL_ENSURE(0, "Extension Manager: Could not set executable file attribute.");
        }
    }
}

//We currently cannot check if this XPackage represents a content of a particular exension
//But we can check if we are within $UNO_USER_PACKAGES_CACHE etc.
bool BackendImpl::ExecutablePackageImpl::isUrlTargetInExtension()
{
    bool bSuccess = false;
    OUString sExtensionDir;
    if(getMyBackend()->m_context.equals(OUSTR("user")))
        sExtensionDir = dp_misc::expandUnoRcTerm(OUSTR("$UNO_USER_PACKAGES_CACHE"));
    else if (getMyBackend()->m_context.equals(OUSTR("shared")))
        sExtensionDir = dp_misc::expandUnoRcTerm(OUSTR("$UNO_SHARED_PACKAGES_CACHE"));
    else
        OSL_ASSERT(0);
    //remove file ellipses
    if (osl::File::E_None == osl::File::getAbsoluteFileURL(OUString(), sExtensionDir, sExtensionDir))
    {
        OUString sFile;
        if (osl::File::E_None == osl::File::getAbsoluteFileURL(
            OUString(), dp_misc::expandUnoRcUrl(m_url), sFile))
        {
            if (sal_True == sFile.match(sExtensionDir, 0))
                bSuccess = true;
        }
    }
    return bSuccess;
}

bool BackendImpl::ExecutablePackageImpl::getFileAttributes(sal_uInt64& out_Attributes)
{
    bool bSuccess = false;
    const OUString url(dp_misc::expandUnoRcUrl(m_url));
    osl::DirectoryItem item;
    if (osl::FileBase::E_None == osl::DirectoryItem::get(url, item))
    {
        osl::FileStatus aStatus(osl_FileStatus_Mask_Attributes);
        if( osl::FileBase::E_None == item.getFileStatus(aStatus))
        {
            out_Attributes = aStatus.getAttributes();
            bSuccess = true;
        }
    }
    return bSuccess;
}

//##############################################################################

} // anon namespace

namespace sdecl = comphelper::service_decl;
sdecl::class_<BackendImpl, sdecl::with_args<true> > serviceBI;
extern sdecl::ServiceDecl const serviceDecl(
    serviceBI,
    "com.sun.star.comp.deployment.executable.PackageRegistryBackend",
    BACKEND_SERVICE_NAME );

} // namespace component
} // namespace backend
} // namespace dp_registry

<commit_msg>INTEGRATION: CWS jl100_DEV300 (1.2.52); FILE MERGED 2008/05/13 15:08:20 jl 1.2.52.1: #156271# The package::getMyBackend functions now throw a DisposedException<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dp_executable.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#include "dp_backend.h"
#include "dp_ucb.h"
#include "dp_interact.h"
#include "rtl/string.hxx"
#include "osl/file.hxx"
#include "ucbhelper/content.hxx"
#include "comphelper/servicedecl.hxx"
#include "svtools/inettype.hxx"
#include "cppuhelper/implbase1.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;

namespace dp_registry {
namespace backend {
namespace executable {
namespace {

class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
    class ExecutablePackageImpl : public ::dp_registry::backend::Package
    {
        BackendImpl * getMyBackend() const;

        // Package
        virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
            ::osl::ResettableMutexGuard & guard,
            ::rtl::Reference<dp_misc::AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );
        virtual void processPackage_(
            ::osl::ResettableMutexGuard & guard,
            bool registerPackage,
            ::rtl::Reference<dp_misc::AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );

        bool getFileAttributes(sal_uInt64& out_Attributes);
        bool isUrlTargetInExtension();

    public:
        inline ExecutablePackageImpl(
            ::rtl::Reference<PackageRegistryBackend> const & myBackend,
            OUString const & url, OUString const & name,
            Reference<deployment::XPackageTypeInfo> const & xPackageType)
            : Package( myBackend, url, name, name /* display-name */,
                       xPackageType ) //,
            {}
    };
    friend class ExecutablePackageImpl;

    typedef ::std::hash_map< OUString, Reference<XInterface>,
                             ::rtl::OUStringHash > t_string2object;

    // PackageRegistryBackend
    virtual Reference<deployment::XPackage> bindPackage_(
        OUString const & url, OUString const & mediaType,
        Reference<XCommandEnvironment> const & xCmdEnv );

    Reference<deployment::XPackageTypeInfo> m_xExecutableTypeInfo;

public:
    BackendImpl( Sequence<Any> const & args,
                 Reference<XComponentContext> const & xComponentContext );

    // XPackageRegistry
    virtual Sequence< Reference<deployment::XPackageTypeInfo> > SAL_CALL
    getSupportedPackageTypes() throw (RuntimeException);

    using PackageRegistryBackend::disposing;
};

BackendImpl::BackendImpl(
    Sequence<Any> const & args,
    Reference<XComponentContext> const & xComponentContext )
    : PackageRegistryBackend( args, xComponentContext ),
      m_xExecutableTypeInfo(new Package::TypeInfo(
                                OUSTR("application/vnd.sun.star.executable"),
                                OUSTR(""),
                                OUSTR("Executable"),
                                RID_IMG_COMPONENT,
                                RID_IMG_COMPONENT_HC ) )
{

}

// XPackageRegistry
Sequence< Reference<deployment::XPackageTypeInfo> >
BackendImpl::getSupportedPackageTypes() throw (RuntimeException)
{
    return Sequence<Reference<deployment::XPackageTypeInfo> >(
        & m_xExecutableTypeInfo, 1);
}

// PackageRegistryBackend
Reference<deployment::XPackage> BackendImpl::bindPackage_(
    OUString const & url, OUString const & mediaType,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    if (mediaType.getLength() == 0)
    {
        throw lang::IllegalArgumentException(
            StrCannotDetectMediaType::get() + url,
            static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
    }

    String type, subType;
    INetContentTypeParameterList params;
    if (INetContentTypes::parse( mediaType, type, subType, &params ))
    {
        if (type.EqualsIgnoreCaseAscii("application"))
        {
            ::ucbhelper::Content ucbContent( url, xCmdEnv );
            const OUString name( ucbContent.getPropertyValue(
                dp_misc::StrTitle::get() ).get<OUString>() );
            if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.executable"))
            {
                return new BackendImpl::ExecutablePackageImpl(
                    this, url, name,  m_xExecutableTypeInfo);
            }
        }
    }
    return Reference<deployment::XPackage>();
}

//##############################################################################

// Package
BackendImpl * BackendImpl::ExecutablePackageImpl::getMyBackend() const
{
    BackendImpl * pBackend = static_cast<BackendImpl *>(m_myBackend.get());
    if (NULL == pBackend)
    {
        //May throw a DisposedException
        check();
        //We should never get here...
        throw RuntimeException(
            OUSTR("Failed to get the BackendImpl"),
            static_cast<OWeakObject*>(const_cast<ExecutablePackageImpl *>(this)));
    }
    return pBackend;
}

beans::Optional< beans::Ambiguous<sal_Bool> >
BackendImpl::ExecutablePackageImpl::isRegistered_(
    ::osl::ResettableMutexGuard &,
    ::rtl::Reference<dp_misc::AbortChannel> const &,
    Reference<XCommandEnvironment> const & )
{
    //We must return Optional.isPresent = true, otherwise
    //processPackage is not called.
    //The user shall not be able to enable/disable the executable. This is not needed since
    //the executable does not affect the office. The best thing is to show no
    //status at all. See also BackendImpl::PackageImpl::isRegistered_ (dp_package.cxx)
    //On Windows there is no executable file attribute. One has to use security API for this.
    //However, on Windows we do not have the problem, that after unzipping the file cannot be
    //executed.
    return beans::Optional< beans::Ambiguous<sal_Bool> >(
            sal_True /* IsPresent */,
                beans::Ambiguous<sal_Bool>(
                   sal_True, sal_True /* IsAmbiguous */ ) );
}

void BackendImpl::ExecutablePackageImpl::processPackage_(
    ::osl::ResettableMutexGuard &,
    bool doRegisterPackage,
    ::rtl::Reference<dp_misc::AbortChannel> const & abortChannel,
    Reference<XCommandEnvironment> const & /*xCmdEnv*/ )
{
    checkAborted(abortChannel);
    if (doRegisterPackage)
    {
        if (!isUrlTargetInExtension())
        {
            OSL_ASSERT(0);
            return;
        }
        sal_uInt64 attributes = 0;
        //Setting the executable attribut does not affect executables on Windows
        if (getFileAttributes(attributes))
        {
            if(getMyBackend()->m_context.equals(OUSTR("user")))
                attributes |= osl_File_Attribute_OwnExe;
            else if (getMyBackend()->m_context.equals(OUSTR("shared")))
                attributes |= (osl_File_Attribute_OwnExe | osl_File_Attribute_GrpExe
                               | osl_File_Attribute_OthExe);
            else
                OSL_ASSERT(0);

            //This won't have affect on Windows
            if (osl::File::E_None != osl::File::setAttributes(
                    dp_misc::expandUnoRcUrl(m_url), attributes))
                OSL_ENSURE(0, "Extension Manager: Could not set executable file attribute.");
        }
    }
}

//We currently cannot check if this XPackage represents a content of a particular exension
//But we can check if we are within $UNO_USER_PACKAGES_CACHE etc.
bool BackendImpl::ExecutablePackageImpl::isUrlTargetInExtension()
{
    bool bSuccess = false;
    OUString sExtensionDir;
    if(getMyBackend()->m_context.equals(OUSTR("user")))
        sExtensionDir = dp_misc::expandUnoRcTerm(OUSTR("$UNO_USER_PACKAGES_CACHE"));
    else if (getMyBackend()->m_context.equals(OUSTR("shared")))
        sExtensionDir = dp_misc::expandUnoRcTerm(OUSTR("$UNO_SHARED_PACKAGES_CACHE"));
    else
        OSL_ASSERT(0);
    //remove file ellipses
    if (osl::File::E_None == osl::File::getAbsoluteFileURL(OUString(), sExtensionDir, sExtensionDir))
    {
        OUString sFile;
        if (osl::File::E_None == osl::File::getAbsoluteFileURL(
            OUString(), dp_misc::expandUnoRcUrl(m_url), sFile))
        {
            if (sal_True == sFile.match(sExtensionDir, 0))
                bSuccess = true;
        }
    }
    return bSuccess;
}

bool BackendImpl::ExecutablePackageImpl::getFileAttributes(sal_uInt64& out_Attributes)
{
    bool bSuccess = false;
    const OUString url(dp_misc::expandUnoRcUrl(m_url));
    osl::DirectoryItem item;
    if (osl::FileBase::E_None == osl::DirectoryItem::get(url, item))
    {
        osl::FileStatus aStatus(osl_FileStatus_Mask_Attributes);
        if( osl::FileBase::E_None == item.getFileStatus(aStatus))
        {
            out_Attributes = aStatus.getAttributes();
            bSuccess = true;
        }
    }
    return bSuccess;
}

//##############################################################################

} // anon namespace

namespace sdecl = comphelper::service_decl;
sdecl::class_<BackendImpl, sdecl::with_args<true> > serviceBI;
extern sdecl::ServiceDecl const serviceDecl(
    serviceBI,
    "com.sun.star.comp.deployment.executable.PackageRegistryBackend",
    BACKEND_SERVICE_NAME );

} // namespace component
} // namespace backend
} // namespace dp_registry

<|endoftext|>


<commit_before>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2006 Refractions Research Inc.
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

// CTS.cpp : Testing class
//

#include <iostream>
#include <fstream>

#include <geos/io/WKTWriter.h>
#include <geos/io/WKTReader.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/util/GEOSException.h>

using namespace std;
using namespace geos::io;
using namespace geos::geom;
using namespace geos::util;

int
main(int /*argc*/, char** /*argv*/)
{

    try {
        ofstream out("WKTOut");
        ifstream in("WKTIn");
        string instr;
        string outstr;
        PrecisionModel pm;
        GeometryFactory::Ptr gf = GeometryFactory::create(&pm, 10);
        WKTReader* r = new WKTReader(gf.get());
        WKTWriter* w = new WKTWriter();
        Geometry* g;

        cout << "Start Testing:" << endl;
        while(!in.eof()) {
            getline(in, instr);
            if(instr != "") {
                g = r->read(instr).release();
                outstr = w->write(g);
                out << "----------" << endl;
                out << instr << endl;
                out << outstr << endl;
                out << "----------" << endl << endl;
            }
        }
        out.flush();
        out.close();
        cout << "End of Testing" << endl;

    }
    catch(const GEOSException& ge) {
        cout << ge.what() << endl;
    }

    return 0;
}
<commit_msg>SimpleWKTTester: Memory leaks<commit_after>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2006 Refractions Research Inc.
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

// CTS.cpp : Testing class
//

#include <iostream>
#include <fstream>

#include <geos/io/WKTWriter.h>
#include <geos/io/WKTReader.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/util/GEOSException.h>

using namespace std;
using namespace geos::io;
using namespace geos::geom;
using namespace geos::util;

int
main(int /*argc*/, char** /*argv*/)
{

    try {
        ofstream out("WKTOut");
        ifstream in("WKTIn");
        string instr;
        string outstr;
        PrecisionModel pm;
        GeometryFactory::Ptr gf = GeometryFactory::create(&pm, 10);
        WKTReader* r = new WKTReader(gf.get());
        WKTWriter* w = new WKTWriter();
        Geometry* g;

        cout << "Start Testing:" << endl;
        while(!in.eof()) {
            getline(in, instr);
            if(instr != "") {
                g = r->read(instr).release();
                outstr = w->write(g);
                out << "----------" << endl;
                out << instr << endl;
                out << outstr << endl;
                out << "----------" << endl << endl;
            }
        }
        out.flush();
        out.close();
        cout << "End of Testing" << endl;
		delete r;
		delete w;

    }
    catch(const GEOSException& ge) {
        cout << ge.what() << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <GeoffRenderer.h>

namespace geoff
{

	GeoffRenderer::GeoffRenderer()
	{
		glGenBuffers( 1, &_vertexBuffer );
		glGenBuffers( 1, &_indexBuffer );
	}

	GeoffRenderer::~GeoffRenderer()
	{
		glDeleteBuffers( 1, &_vertexBuffer );
		glDeleteBuffers( 1, &_indexBuffer );
	}

	void GeoffRenderer::clear( float r, float g, float b, float a )
	{
		glClearColor( r, g, b, a );
		glClear( GL_COLOR_BUFFER_BIT );
	}

	int GeoffRenderer::compileShader( ::String vsSource, ::String fsSource )
	{
		GLint status = 0;

		GLuint vs = glCreateShader( GL_VERTEX_SHADER );
		const char* vsSourceCStr = vsSource.__CStr();
		glShaderSource( vs, 1, &vsSourceCStr, &vsSource.length );
		glCompileShader( vs );
		glGetShaderiv( vs, GL_COMPILE_STATUS, &status );

		if ( status == 0 )
		{
			// There was a problem compiling the vertex shader
			glDeleteShader( vs );
			return 0;
		}

		GLuint fs = glCreateShader( GL_FRAGMENT_SHADER );
		const char* fsSourceCStr = fsSource.__CStr();
		glShaderSource( fs, 1, &fsSourceCStr, &fsSource.length );
		glCompileShader( fs );
		glGetShaderiv( vs, GL_COMPILE_STATUS, &status );

		if ( status == 0 )
		{
			// There was a problem compiling the fragment shader
			glDeleteShader( vs );
			glDeleteShader( fs );
			return 0;
		}

		GLuint program = glCreateProgram();
		glAttachShader( program, vs );
		glAttachShader( program, fs );
		glLinkProgram( program );
		glGetProgramiv( program, GL_LINK_STATUS, &status );

		glDeleteShader( vs );
		glDeleteShader( fs );

		if ( status == 0 )
		{
			// There was a problem linking the shader
			glDeleteProgram( program );
			return 0;
		}

		return program;
	}
}<commit_msg>Error codes for shader compile<commit_after>#include <GeoffRenderer.h>

namespace geoff
{

	GeoffRenderer::GeoffRenderer()
	{
		glGenBuffers( 1, &_vertexBuffer );
		glGenBuffers( 1, &_indexBuffer );
	}

	GeoffRenderer::~GeoffRenderer()
	{
		glDeleteBuffers( 1, &_vertexBuffer );
		glDeleteBuffers( 1, &_indexBuffer );
	}

	void GeoffRenderer::clear( float r, float g, float b, float a )
	{
		glClearColor( r, g, b, a );
		glClear( GL_COLOR_BUFFER_BIT );
	}

	int GeoffRenderer::compileShader( ::String vsSource, ::String fsSource )
	{
		GLint status = 0;

		GLuint vs = glCreateShader( GL_VERTEX_SHADER );
		const char* vsSourceCStr = vsSource.__CStr();
		glShaderSource( vs, 1, &vsSourceCStr, &vsSource.length );
		glCompileShader( vs );
		glGetShaderiv( vs, GL_COMPILE_STATUS, &status );

		if ( status == 0 )
		{
			// There was a problem compiling the vertex shader
			glDeleteShader( vs );
			return -1;
		}

		GLuint fs = glCreateShader( GL_FRAGMENT_SHADER );
		const char* fsSourceCStr = fsSource.__CStr();
		glShaderSource( fs, 1, &fsSourceCStr, &fsSource.length );
		glCompileShader( fs );
		glGetShaderiv( vs, GL_COMPILE_STATUS, &status );

		if ( status == 0 )
		{
			// There was a problem compiling the fragment shader
			glDeleteShader( vs );
			glDeleteShader( fs );
			return 2;
		}

		GLuint program = glCreateProgram();
		glAttachShader( program, vs );
		glAttachShader( program, fs );
		glLinkProgram( program );
		glGetProgramiv( program, GL_LINK_STATUS, &status );

		glDeleteShader( vs );
		glDeleteShader( fs );

		if ( status == 0 )
		{
			// There was a problem linking the shader
			glDeleteProgram( program );
			return -3;
		}

		return program;
	}
}<|endoftext|>