text
stringlengths 5
1.04M
|
|---|
// Copyright (c) 2012 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 "ui/compositor/layer_animation_sequence.h"
#include <algorithm>
#include <iterator>
#include "base/trace_event/trace_event.h"
#include "cc/animation/animation_events.h"
#include "cc/animation/animation_id_provider.h"
#include "ui/compositor/layer_animation_delegate.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/layer_animation_observer.h"
namespace ui {
LayerAnimationSequence::LayerAnimationSequence()
: properties_(LayerAnimationElement::UNKNOWN),
is_cyclic_(false),
last_element_(0),
waiting_for_group_start_(false),
animation_group_id_(0),
last_progressed_fraction_(0.0),
weak_ptr_factory_(this) {
}
LayerAnimationSequence::LayerAnimationSequence(LayerAnimationElement* element)
: properties_(LayerAnimationElement::UNKNOWN),
is_cyclic_(false),
last_element_(0),
waiting_for_group_start_(false),
animation_group_id_(0),
last_progressed_fraction_(0.0),
weak_ptr_factory_(this) {
AddElement(element);
}
LayerAnimationSequence::~LayerAnimationSequence() {
FOR_EACH_OBSERVER(LayerAnimationObserver,
observers_,
DetachedFromSequence(this, true));
}
void LayerAnimationSequence::Start(LayerAnimationDelegate* delegate) {
DCHECK(start_time_ != base::TimeTicks());
last_progressed_fraction_ = 0.0;
if (elements_.empty())
return;
NotifyStarted();
elements_[0]->set_requested_start_time(start_time_);
elements_[0]->Start(delegate, animation_group_id_);
}
void LayerAnimationSequence::Progress(base::TimeTicks now,
LayerAnimationDelegate* delegate) {
DCHECK(start_time_ != base::TimeTicks());
bool redraw_required = false;
if (elements_.empty())
return;
if (last_element_ == 0)
last_start_ = start_time_;
size_t current_index = last_element_ % elements_.size();
base::TimeDelta element_duration;
while (is_cyclic_ || last_element_ < elements_.size()) {
elements_[current_index]->set_requested_start_time(last_start_);
if (!elements_[current_index]->IsFinished(now, &element_duration))
break;
// Let the element we're passing finish.
if (elements_[current_index]->ProgressToEnd(delegate))
redraw_required = true;
last_start_ += element_duration;
++last_element_;
last_progressed_fraction_ =
elements_[current_index]->last_progressed_fraction();
current_index = last_element_ % elements_.size();
}
if (is_cyclic_ || last_element_ < elements_.size()) {
if (!elements_[current_index]->Started()) {
animation_group_id_ = cc::AnimationIdProvider::NextGroupId();
elements_[current_index]->Start(delegate, animation_group_id_);
}
base::WeakPtr<LayerAnimationSequence> alive(weak_ptr_factory_.GetWeakPtr());
if (elements_[current_index]->Progress(now, delegate))
redraw_required = true;
if (!alive)
return;
last_progressed_fraction_ =
elements_[current_index]->last_progressed_fraction();
}
// Since the delegate may be deleted due to the notifications below, it is
// important that we schedule a draw before sending them.
if (redraw_required)
delegate->ScheduleDrawForAnimation();
if (!is_cyclic_ && last_element_ == elements_.size()) {
last_element_ = 0;
waiting_for_group_start_ = false;
animation_group_id_ = 0;
NotifyEnded();
}
}
bool LayerAnimationSequence::IsFinished(base::TimeTicks time) {
if (is_cyclic_ || waiting_for_group_start_)
return false;
if (elements_.empty())
return true;
if (last_element_ == 0)
last_start_ = start_time_;
base::TimeTicks current_start = last_start_;
size_t current_index = last_element_;
base::TimeDelta element_duration;
while (current_index < elements_.size()) {
elements_[current_index]->set_requested_start_time(current_start);
if (!elements_[current_index]->IsFinished(time, &element_duration))
break;
current_start += element_duration;
++current_index;
}
return (current_index == elements_.size());
}
void LayerAnimationSequence::ProgressToEnd(LayerAnimationDelegate* delegate) {
bool redraw_required = false;
if (elements_.empty())
return;
size_t current_index = last_element_ % elements_.size();
while (current_index < elements_.size()) {
if (elements_[current_index]->ProgressToEnd(delegate))
redraw_required = true;
last_progressed_fraction_ =
elements_[current_index]->last_progressed_fraction();
++current_index;
++last_element_;
}
if (redraw_required)
delegate->ScheduleDrawForAnimation();
if (!is_cyclic_) {
last_element_ = 0;
waiting_for_group_start_ = false;
animation_group_id_ = 0;
NotifyEnded();
}
}
void LayerAnimationSequence::GetTargetValue(
LayerAnimationElement::TargetValue* target) const {
if (is_cyclic_)
return;
for (size_t i = last_element_; i < elements_.size(); ++i)
elements_[i]->GetTargetValue(target);
}
void LayerAnimationSequence::Abort(LayerAnimationDelegate* delegate) {
size_t current_index = last_element_ % elements_.size();
while (current_index < elements_.size()) {
elements_[current_index]->Abort(delegate);
++current_index;
}
last_element_ = 0;
waiting_for_group_start_ = false;
NotifyAborted();
}
void LayerAnimationSequence::AddElement(LayerAnimationElement* element) {
properties_ |= element->properties();
elements_.push_back(make_linked_ptr(element));
}
bool LayerAnimationSequence::HasConflictingProperty(
LayerAnimationElement::AnimatableProperties other) const {
return (properties_ & other) != LayerAnimationElement::UNKNOWN;
}
bool LayerAnimationSequence::IsFirstElementThreaded() const {
if (!elements_.empty())
return elements_[0]->IsThreaded();
return false;
}
void LayerAnimationSequence::AddObserver(LayerAnimationObserver* observer) {
if (!observers_.HasObserver(observer)) {
observers_.AddObserver(observer);
observer->AttachedToSequence(this);
}
}
void LayerAnimationSequence::RemoveObserver(LayerAnimationObserver* observer) {
observers_.RemoveObserver(observer);
observer->DetachedFromSequence(this, true);
}
void LayerAnimationSequence::OnThreadedAnimationStarted(
const cc::AnimationEvent& event) {
if (elements_.empty() || event.group_id != animation_group_id_)
return;
size_t current_index = last_element_ % elements_.size();
LayerAnimationElement::AnimatableProperties element_properties =
elements_[current_index]->properties();
LayerAnimationElement::AnimatableProperty event_property =
LayerAnimationElement::ToAnimatableProperty(event.target_property);
DCHECK(element_properties & event_property);
elements_[current_index]->set_effective_start_time(event.monotonic_time);
}
void LayerAnimationSequence::OnScheduled() {
NotifyScheduled();
}
void LayerAnimationSequence::OnAnimatorDestroyed() {
if (observers_.might_have_observers()) {
base::ObserverListBase<LayerAnimationObserver>::Iterator it(&observers_);
LayerAnimationObserver* obs;
while ((obs = it.GetNext()) != NULL) {
if (!obs->RequiresNotificationWhenAnimatorDestroyed()) {
// Remove the observer, but do not allow notifications to be sent.
observers_.RemoveObserver(obs);
obs->DetachedFromSequence(this, false);
}
}
}
}
size_t LayerAnimationSequence::size() const {
return elements_.size();
}
LayerAnimationElement* LayerAnimationSequence::FirstElement() const {
if (elements_.empty()) {
return NULL;
}
return elements_[0].get();
}
void LayerAnimationSequence::NotifyScheduled() {
FOR_EACH_OBSERVER(LayerAnimationObserver,
observers_,
OnLayerAnimationScheduled(this));
}
void LayerAnimationSequence::NotifyStarted() {
FOR_EACH_OBSERVER(LayerAnimationObserver, observers_,
OnLayerAnimationStarted(this));
}
void LayerAnimationSequence::NotifyEnded() {
FOR_EACH_OBSERVER(LayerAnimationObserver,
observers_,
OnLayerAnimationEnded(this));
}
void LayerAnimationSequence::NotifyAborted() {
FOR_EACH_OBSERVER(LayerAnimationObserver,
observers_,
OnLayerAnimationAborted(this));
}
LayerAnimationElement* LayerAnimationSequence::CurrentElement() const {
if (elements_.empty())
return NULL;
size_t current_index = last_element_ % elements_.size();
return elements_[current_index].get();
}
} // namespace ui
|
/**
* spaint: SemanticVisualiserFactory.cpp
* Copyright (c) Torr Vision Group, University of Oxford, 2016. All rights reserved.
*/
#include "visualisation/SemanticVisualiserFactory.h"
using namespace ITMLib;
using namespace ORUtils;
#include "visualisation/cpu/SemanticVisualiser_CPU.h"
#ifdef WITH_CUDA
#include "visualisation/cuda/SemanticVisualiser_CUDA.h"
#endif
namespace spaint {
//#################### PUBLIC STATIC MEMBER FUNCTIONS ####################
SemanticVisualiser_CPtr SemanticVisualiserFactory::make_semantic_visualiser(size_t maxLabelCount, DeviceType deviceType)
{
SemanticVisualiser_CPtr visualiser;
if(deviceType == DEVICE_CUDA)
{
#ifdef WITH_CUDA
visualiser.reset(new SemanticVisualiser_CUDA(maxLabelCount));
#else
// This should never happen as things stand - we set deviceType to DEVICE_CPU if CUDA support isn't available.
throw std::runtime_error("Error: CUDA support not currently available. Reconfigure in CMake with the WITH_CUDA option set to on.");
#endif
}
else
{
visualiser.reset(new SemanticVisualiser_CPU(maxLabelCount));
}
return visualiser;
}
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "feerate.h"
#include "tinyformat.h"
const std::string CURRENCY_UNIT = "BHC";
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nBytes_)
{
assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
int64_t nSize = int64_t(nBytes_);
if (nSize > 0)
nSatoshisPerK = nFeePaid * 1000 / nSize;
else
nSatoshisPerK = 0;
}
CAmount CFeeRate::GetFee(size_t nBytes_) const
{
assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
int64_t nSize = int64_t(nBytes_);
CAmount nFee = nSatoshisPerK * nSize / 1000;
if (nFee == 0 && nSize != 0) {
if (nSatoshisPerK > 0)
nFee = CAmount(1);
if (nSatoshisPerK < 0)
nFee = CAmount(-1);
}
return nFee;
}
std::string CFeeRate::ToString() const
{
return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT);
}
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Any modified source or binaries are used only with the BitShares network.
*
* 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#pragma once
#include <graphene/chain/protocol/base.hpp>
#include <graphene/chain/protocol/types.hpp>
#include <fc/smart_ref_fwd.hpp>
namespace graphene { namespace chain { struct fee_schedule; } }
/*
namespace fc {
template<typename Stream, typename T> inline void pack( Stream& s, const graphene::chain::fee_schedule& value );
template<typename Stream, typename T> inline void unpack( Stream& s, graphene::chain::fee_schedule& value );
} // namespace fc
*/
namespace graphene { namespace chain {
typedef static_variant<> parameter_extension;
struct chain_parameters
{
/** using a smart ref breaks the circular dependency created between operations and the fee schedule */
smart_ref<fee_schedule> current_fees; ///< current schedule of fees
uint8_t block_interval = GRAPHENE_DEFAULT_BLOCK_INTERVAL; ///< interval in seconds between blocks
uint32_t maintenance_interval = GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL; ///< interval in sections between blockchain maintenance events
uint8_t maintenance_skip_slots = GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS; ///< number of block_intervals to skip at maintenance time
uint32_t committee_proposal_review_period = GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC; ///< minimum time in seconds that a proposed transaction requiring committee authority may not be signed, prior to expiration
uint32_t maximum_transaction_size = GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE; ///< maximum allowable size in bytes for a transaction
uint32_t maximum_block_size = GRAPHENE_DEFAULT_MAX_BLOCK_SIZE; ///< maximum allowable size in bytes for a block
uint32_t maximum_time_until_expiration = GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION; ///< maximum lifetime in seconds for transactions to be valid, before expiring
uint32_t maximum_proposal_lifetime = GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC; ///< maximum lifetime in seconds for proposed transactions to be kept, before expiring
uint8_t maximum_asset_whitelist_authorities = GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES; ///< maximum number of accounts which an asset may list as authorities for its whitelist OR blacklist
uint8_t maximum_asset_feed_publishers = GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS; ///< the maximum number of feed publishers for a given asset
uint16_t maximum_witness_count = GRAPHENE_DEFAULT_MAX_WITNESSES; ///< maximum number of active witnesses
uint16_t maximum_committee_count = GRAPHENE_DEFAULT_MAX_COMMITTEE; ///< maximum number of active committee_members
uint16_t maximum_authority_membership = GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP; ///< largest number of keys/accounts an authority can have
uint16_t reserve_percent_of_fee = GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE; ///< the percentage of the network's allocation of a fee that is taken out of circulation
uint16_t network_percent_of_fee = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE; ///< percent of transaction fees paid to network
uint16_t lifetime_referrer_percent_of_fee = GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE; ///< percent of transaction fees paid to network
uint32_t cashback_vesting_period_seconds = GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC; ///< time after cashback rewards are accrued before they become liquid
share_type cashback_vesting_threshold = GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD; ///< the maximum cashback that can be received without vesting
bool count_non_member_votes = true; ///< set to false to restrict voting privlegages to member accounts
bool allow_non_member_whitelists = false; ///< true if non-member accounts may set whitelists and blacklists; false otherwise
share_type witness_pay_per_block = GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK; ///< CORE to be allocated to witnesses (per block)
uint32_t witness_pay_vesting_seconds = GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS; ///< vesting_seconds parameter for witness VBO's
share_type worker_budget_per_day = GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY; ///< CORE to be allocated to workers (per day)
uint16_t max_predicate_opcode = GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE; ///< predicate_opcode must be less than this number
share_type fee_liquidation_threshold = GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD; ///< value in CORE at which accumulated fees in blockchain-issued market assets should be liquidated
uint16_t accounts_per_fee_scale = GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE; ///< number of accounts between fee scalings
uint8_t account_fee_scale_bitshifts = GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS; ///< number of times to left bitshift account registration fee at each scaling
uint8_t max_authority_depth = GRAPHENE_MAX_SIG_CHECK_DEPTH;
extensions_type extensions;
/** defined in fee_schedule.cpp */
void validate()const;
};
} } // graphene::chain
FC_REFLECT( graphene::chain::chain_parameters,
(current_fees)
(block_interval)
(maintenance_interval)
(maintenance_skip_slots)
(committee_proposal_review_period)
(maximum_transaction_size)
(maximum_block_size)
(maximum_time_until_expiration)
(maximum_proposal_lifetime)
(maximum_asset_whitelist_authorities)
(maximum_asset_feed_publishers)
(maximum_witness_count)
(maximum_committee_count)
(maximum_authority_membership)
(reserve_percent_of_fee)
(network_percent_of_fee)
(lifetime_referrer_percent_of_fee)
(cashback_vesting_period_seconds)
(cashback_vesting_threshold)
(count_non_member_votes)
(allow_non_member_whitelists)
(witness_pay_per_block)
(worker_budget_per_day)
(max_predicate_opcode)
(fee_liquidation_threshold)
(accounts_per_fee_scale)
(account_fee_scale_bitshifts)
(max_authority_depth)
(extensions)
)
|
/***********************************************************************************************************************
*
* Copyright (c) 2020, ABB Schweiz AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that
* the following conditions are met:
*
* * Redistributions of source code must retain the
* above copyright notice, this list of conditions
* and the following disclaimer.
* * Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions
* and the following disclaimer in the documentation
* and/or other materials provided with the
* distribution.
* * Neither the name of ABB nor the names of its
* contributors may be used to endorse or promote
* products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***********************************************************************************************************************
*/
#include <stdexcept>
#include <ros/ros.h>
#include "abb_robot_cpp_utilities/initialization.h"
namespace
{
/**
* \brief Name for ROS logging in the 'init' context.
*/
constexpr char ROS_LOG_INIT[]{"init"};
/**
* \brief Max number of attempts when trying to connect to a robot controller via RWS.
*/
constexpr unsigned int RWS_MAX_CONNECTION_ATTEMPTS{5};
/**
* \brief Error message for failed connection attempts when trying to connect to a robot controller via RWS.
*/
constexpr char RWS_CONNECTION_ERROR_MESSAGE[]{"Failed to establish RWS connection to the robot controller"};
/**
* \brief Time [s] to wait before trying to reconnect to a robot controller via RWS.
*/
constexpr double RWS_RECONNECTION_WAIT_TIME{1.0};
}
namespace abb
{
namespace robot
{
namespace utilities
{
/***********************************************************************************************************************
* Utility function definitions
*/
RobotControllerDescription establishRWSConnection(RWSManager& rws_manager,
const std::string& robot_controller_id,
const bool no_connection_timeout)
{
ros::Duration reconnection_wait_time{RWS_RECONNECTION_WAIT_TIME};
unsigned int attempt{0};
while(ros::ok() && (no_connection_timeout || attempt++ < RWS_MAX_CONNECTION_ATTEMPTS))
{
try
{
return rws_manager.collectAndParseSystemData(robot_controller_id);
}
catch(const std::runtime_error& exception)
{
if(!no_connection_timeout)
{
ROS_WARN_STREAM_NAMED(ROS_LOG_INIT, RWS_CONNECTION_ERROR_MESSAGE << " (attempt " << attempt << "/" <<
RWS_MAX_CONNECTION_ATTEMPTS << "), reason: '" << exception.what() << "'");
}
else
{
ROS_WARN_STREAM_NAMED(ROS_LOG_INIT, RWS_CONNECTION_ERROR_MESSAGE << " (waiting indefinitely), reason: '" <<
exception.what() << "'");
}
reconnection_wait_time.sleep();
}
}
throw std::runtime_error{RWS_CONNECTION_ERROR_MESSAGE};
}
}
}
}
|
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#include "torrenthandle.h"
#include <algorithm>
#include <type_traits>
#include <QBitArray>
#include <QByteArray>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QStringList>
#include <libtorrent/address.hpp>
#include <libtorrent/alert_types.hpp>
#include <libtorrent/bencode.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/entry.hpp>
#include <libtorrent/magnet_uri.hpp>
#if LIBTORRENT_VERSION_NUM >= 10100
#include <libtorrent/time.hpp>
#endif
#include <boost/bind.hpp>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
#include "fs.h"
#include "peerinfo.h"
#include "session.h"
#include "trackerentry.h"
#include "torrentinfo.h"
const QString QB_EXT {QStringLiteral(".!qB")};
namespace libt = libtorrent;
using namespace BitTorrent;
namespace
{
using ListType = libt::entry::list_type;
ListType setToEntryList(const QSet<QString> &input)
{
ListType entryList;
foreach (const QString &setValue, input)
entryList.emplace_back(setValue.toStdString());
return entryList;
}
}
// AddTorrentData
CreateTorrentParams::CreateTorrentParams()
: restored(false)
, disableTempPath(false)
, sequential(false)
, firstLastPiecePriority(false)
, hasSeedStatus(false)
, skipChecking(false)
, hasRootFolder(true)
, forced(false)
, paused(false)
, uploadLimit(-1)
, downloadLimit(-1)
, ratioLimit(TorrentHandle::USE_GLOBAL_RATIO)
, seedingTimeLimit(TorrentHandle::USE_GLOBAL_SEEDING_TIME)
{
}
CreateTorrentParams::CreateTorrentParams(const AddTorrentParams ¶ms)
: restored(false)
, name(params.name)
, category(params.category)
, tags(params.tags)
, savePath(params.savePath)
, disableTempPath(params.disableTempPath)
, sequential(params.sequential)
, firstLastPiecePriority(params.firstLastPiecePriority)
, hasSeedStatus(params.skipChecking) // do not react on 'torrent_finished_alert' when skipping
, skipChecking(params.skipChecking)
, hasRootFolder(params.createSubfolder == TriStateBool::Undefined
? Session::instance()->isCreateTorrentSubfolder()
: params.createSubfolder == TriStateBool::True)
, forced(params.addForced == TriStateBool::True)
, paused(params.addPaused == TriStateBool::Undefined
? Session::instance()->isAddTorrentPaused()
: params.addPaused == TriStateBool::True)
, uploadLimit(params.uploadLimit)
, downloadLimit(params.downloadLimit)
, filePriorities(params.filePriorities)
, ratioLimit(params.ignoreShareLimits ? TorrentHandle::NO_RATIO_LIMIT : TorrentHandle::USE_GLOBAL_RATIO)
, seedingTimeLimit(params.ignoreShareLimits ? TorrentHandle::NO_SEEDING_TIME_LIMIT : TorrentHandle::USE_GLOBAL_SEEDING_TIME)
{
bool useAutoTMM = (params.useAutoTMM == TriStateBool::Undefined
? !Session::instance()->isAutoTMMDisabledByDefault()
: params.useAutoTMM == TriStateBool::True);
}
// TorrentHandle
const qreal TorrentHandle::USE_GLOBAL_RATIO = -2.;
const qreal TorrentHandle::NO_RATIO_LIMIT = -1.;
const int TorrentHandle::USE_GLOBAL_SEEDING_TIME = -2;
const int TorrentHandle::NO_SEEDING_TIME_LIMIT = -1;
const qreal TorrentHandle::MAX_RATIO = 9999.;
const int TorrentHandle::MAX_SEEDING_TIME = 525600;
// The new libtorrent::create_torrent constructor appeared after 1.0.11 in RC_1_0
// and after 1.1.1 in RC_1_1. Since it fixed an ABI incompatibility with previous versions
// distros might choose to backport it onto 1.0.11 and 1.1.1 respectively.
// So we need a way to detect its presence without relying solely on the LIBTORRENT_VERSION_NUM.
// Relevant links:
// 1. https://github.com/arvidn/libtorrent/issues/1696
// 2. https://github.com/qbittorrent/qBittorrent/issues/6406
// The following can be removed after one or two libtorrent releases on each branch.
namespace
{
// new constructor is available
template<typename T, typename std::enable_if<std::is_constructible<T, libt::torrent_info, bool>::value, int>::type = 0>
T makeTorrentCreator(const libtorrent::torrent_info & ti)
{
return T(ti, true);
}
// new constructor isn't available
template<typename T, typename std::enable_if<!std::is_constructible<T, libt::torrent_info, bool>::value, int>::type = 0>
T makeTorrentCreator(const libtorrent::torrent_info & ti)
{
return T(ti);
}
}
TorrentHandle::TorrentHandle(Session *session
, const libtorrent::torrent_handle &nativeHandle
, const CreateTorrentParams ¶ms)
: QObject(session)
, m_session(session)
, m_nativeHandle(nativeHandle)
, m_state(TorrentState::Unknown)
, m_renameCount(0)
, m_useAutoTMM(params.savePath.isEmpty())
, m_name(params.name)
, m_category(params.category)
, m_tags(params.tags)
, m_hasSeedStatus(params.hasSeedStatus)
, m_ratioLimit(params.ratioLimit)
, m_seedingTimeLimit(params.seedingTimeLimit)
, m_tempPathDisabled(params.disableTempPath)
, m_hasMissingFiles(false)
, m_hasRootFolder(params.hasRootFolder)
, m_needsToSetFirstLastPiecePriority(false)
, m_needsToStartForced(params.forced)
{
updateStatus();
m_hash = InfoHash(m_nativeStatus.info_hash);
// NB: the following two if statements are present because we don't want
// to set either sequential download or first/last piece priority to false
// if their respective flags in data are false when a torrent is being
// resumed. This is because, in that circumstance, this constructor is
// called with those flags set to false, even if the torrent was set to
// download sequentially or have first/last piece priority enabled when
// its resume data was saved. These two settings are restored later. But
// if we set them to false now, both will erroneously not be restored.
if (!params.restored || params.sequential)
setSequentialDownload(params.sequential);
if (!params.restored || params.firstLastPiecePriority)
setFirstLastPiecePriority(params.firstLastPiecePriority);
if (!params.restored && hasMetadata()) {
if (filesCount() == 1)
m_hasRootFolder = false;
}
// "started" means "all initialization has completed and torrent has started regular processing".
// When torrent added/restored in "paused" state it become "started" immediately after construction.
// When it is added/restored in "resumed" state, it become "started" after it is really resumed
// (i.e. after receiving "torrent resumed" alert).
if (params.paused) {
m_startupState = Started;
}
else if (!params.restored) {
// Resume torrent because it was added in "resumed" state
// but it's actually paused during initialization
m_startupState = Starting;
resume(params.forced);
}
}
TorrentHandle::~TorrentHandle() {}
bool TorrentHandle::isValid() const
{
return m_nativeHandle.is_valid();
}
InfoHash TorrentHandle::hash() const
{
return m_hash;
}
QString TorrentHandle::name() const
{
QString name = m_name;
if (name.isEmpty())
name = QString::fromStdString(m_nativeStatus.name);
if (name.isEmpty() && hasMetadata())
name = QString::fromStdString(m_torrentInfo.nativeInfo()->orig_files().name());
if (name.isEmpty())
name = m_hash;
return name;
}
QDateTime TorrentHandle::creationDate() const
{
return m_torrentInfo.creationDate();
}
QString TorrentHandle::creator() const
{
return m_torrentInfo.creator();
}
QString TorrentHandle::comment() const
{
return m_torrentInfo.comment();
}
bool TorrentHandle::isPrivate() const
{
return m_torrentInfo.isPrivate();
}
qlonglong TorrentHandle::totalSize() const
{
return m_torrentInfo.totalSize();
}
// get the size of the torrent without the filtered files
qlonglong TorrentHandle::wantedSize() const
{
return m_nativeStatus.total_wanted;
}
qlonglong TorrentHandle::completedSize() const
{
return m_nativeStatus.total_wanted_done;
}
qlonglong TorrentHandle::incompletedSize() const
{
return (m_nativeStatus.total_wanted - m_nativeStatus.total_wanted_done);
}
qlonglong TorrentHandle::pieceLength() const
{
return m_torrentInfo.pieceLength();
}
qlonglong TorrentHandle::wastedSize() const
{
return (m_nativeStatus.total_failed_bytes + m_nativeStatus.total_redundant_bytes);
}
QString TorrentHandle::currentTracker() const
{
return QString::fromStdString(m_nativeStatus.current_tracker);
}
QString TorrentHandle::savePath(bool actual) const
{
return QString();
/*if (actual)
return Utils::Fs::fromNativePath(nativeActualSavePath());
else
return Utils::Fs::fromNativePath(m_savePath);
*/
}
QString TorrentHandle::rootPath(bool actual) const
{
if ((filesCount() > 1) && !hasRootFolder())
return QString();
QString firstFilePath = filePath(0);
const int slashIndex = firstFilePath.indexOf('/');
if (slashIndex >= 0)
return QDir(savePath(actual)).absoluteFilePath(firstFilePath.left(slashIndex));
else
return QDir(savePath(actual)).absoluteFilePath(firstFilePath);
}
QString TorrentHandle::contentPath(bool actual) const
{
if (filesCount() == 1)
return QDir(savePath(actual)).absoluteFilePath(filePath(0));
else if (hasRootFolder())
return rootPath(actual);
else
return savePath(actual);
}
bool TorrentHandle::hasRootFolder() const
{
return m_hasRootFolder;
}
QString TorrentHandle::nativeActualSavePath() const
{
return QString::fromStdString(m_nativeStatus.save_path);
}
QList<TrackerEntry> TorrentHandle::trackers() const
{
QList<TrackerEntry> entries;
std::vector<libt::announce_entry> announces;
announces = m_nativeHandle.trackers();
foreach (const libt::announce_entry &tracker, announces)
entries << tracker;
return entries;
}
QHash<QString, TrackerInfo> TorrentHandle::trackerInfos() const
{
return m_trackerInfos;
}
void TorrentHandle::addTrackers(const QList<TrackerEntry> &trackers)
{
QList<TrackerEntry> addedTrackers;
foreach (const TrackerEntry &tracker, trackers) {
if (addTracker(tracker))
addedTrackers << tracker;
}
if (!addedTrackers.isEmpty())
m_session->handleTorrentTrackersAdded(this, addedTrackers);
}
void TorrentHandle::replaceTrackers(QList<TrackerEntry> trackers)
{
QList<TrackerEntry> existingTrackers = this->trackers();
QList<TrackerEntry> addedTrackers;
std::vector<libt::announce_entry> announces;
foreach (const TrackerEntry &tracker, trackers) {
announces.push_back(tracker.nativeEntry());
if (!existingTrackers.contains(tracker))
addedTrackers << tracker;
else
existingTrackers.removeOne(tracker);
}
m_nativeHandle.replace_trackers(announces);
if (addedTrackers.isEmpty() && existingTrackers.isEmpty()) {
m_session->handleTorrentTrackersChanged(this);
}
else {
if (!existingTrackers.isEmpty())
m_session->handleTorrentTrackersRemoved(this, existingTrackers);
if (!addedTrackers.isEmpty())
m_session->handleTorrentTrackersAdded(this, addedTrackers);
}
}
bool TorrentHandle::addTracker(const TrackerEntry &tracker)
{
if (trackers().contains(tracker))
return false;
m_nativeHandle.add_tracker(tracker.nativeEntry());
return true;
}
QList<QUrl> TorrentHandle::urlSeeds() const
{
QList<QUrl> urlSeeds;
std::set<std::string> seeds = m_nativeHandle.url_seeds();
foreach (const std::string &urlSeed, seeds)
urlSeeds.append(QUrl(urlSeed.c_str()));
return urlSeeds;
}
void TorrentHandle::addUrlSeeds(const QList<QUrl> &urlSeeds)
{
QList<QUrl> addedUrlSeeds;
foreach (const QUrl &urlSeed, urlSeeds) {
if (addUrlSeed(urlSeed))
addedUrlSeeds << urlSeed;
}
if (!addedUrlSeeds.isEmpty())
m_session->handleTorrentUrlSeedsAdded(this, addedUrlSeeds);
}
void TorrentHandle::removeUrlSeeds(const QList<QUrl> &urlSeeds)
{
QList<QUrl> removedUrlSeeds;
foreach (const QUrl &urlSeed, urlSeeds) {
if (removeUrlSeed(urlSeed))
removedUrlSeeds << urlSeed;
}
if (!removedUrlSeeds.isEmpty())
m_session->handleTorrentUrlSeedsRemoved(this, removedUrlSeeds);
}
bool TorrentHandle::addUrlSeed(const QUrl &urlSeed)
{
QList<QUrl> seeds = urlSeeds();
if (seeds.contains(urlSeed)) return false;
m_nativeHandle.add_url_seed(urlSeed.toString().toStdString());
return true;
}
bool TorrentHandle::removeUrlSeed(const QUrl &urlSeed)
{
QList<QUrl> seeds = urlSeeds();
if (!seeds.contains(urlSeed)) return false;
m_nativeHandle.remove_url_seed(urlSeed.toString().toStdString());
return true;
}
bool TorrentHandle::connectPeer(const PeerAddress &peerAddress)
{
libt::error_code ec;
libt::address addr = libt::address::from_string(peerAddress.ip.toString().toStdString(), ec);
if (ec) return false;
boost::asio::ip::tcp::endpoint ep(addr, peerAddress.port);
m_nativeHandle.connect_peer(ep);
return true;
}
bool TorrentHandle::needSaveResumeData() const
{
return m_nativeHandle.need_save_resume_data();
}
void TorrentHandle::saveResumeData()
{
m_nativeHandle.save_resume_data();
}
int TorrentHandle::filesCount() const
{
return m_torrentInfo.filesCount();
}
int TorrentHandle::piecesCount() const
{
return m_torrentInfo.piecesCount();
}
int TorrentHandle::piecesHave() const
{
return m_nativeStatus.num_pieces;
}
qreal TorrentHandle::progress() const
{
if (!isChecking()) {
if (!m_nativeStatus.total_wanted)
return 0.;
if (m_nativeStatus.total_wanted_done == m_nativeStatus.total_wanted)
return 1.;
qreal progress = static_cast<qreal>(m_nativeStatus.total_wanted_done) / m_nativeStatus.total_wanted;
Q_ASSERT((progress >= 0.f) && (progress <= 1.f));
return progress;
}
return m_nativeStatus.progress;
}
QDateTime TorrentHandle::addedTime() const
{
return QDateTime::fromTime_t(m_nativeStatus.added_time);
}
qreal TorrentHandle::ratioLimit() const
{
return m_ratioLimit;
}
int TorrentHandle::seedingTimeLimit() const
{
return m_seedingTimeLimit;
}
QString TorrentHandle::filePath(int index) const
{
return m_torrentInfo.filePath(index);
}
QString TorrentHandle::fileName(int index) const
{
if (!hasMetadata()) return QString();
return Utils::Fs::fileName(filePath(index));
}
qlonglong TorrentHandle::fileSize(int index) const
{
return m_torrentInfo.fileSize(index);
}
// Return a list of absolute paths corresponding
// to all files in a torrent
QStringList TorrentHandle::absoluteFilePaths() const
{
if (!hasMetadata()) return QStringList();
QDir saveDir(savePath(true));
QStringList res;
for (int i = 0; i < filesCount(); ++i)
res << Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
return res;
}
QStringList TorrentHandle::absoluteFilePathsUnwanted() const
{
if (!hasMetadata()) return QStringList();
QDir saveDir(savePath(true));
QStringList res;
std::vector<int> fp;
fp = m_nativeHandle.file_priorities();
int count = static_cast<int>(fp.size());
for (int i = 0; i < count; ++i) {
if (fp[i] == 0) {
const QString path = Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
if (path.contains(".unwanted"))
res << path;
}
}
return res;
}
QVector<int> TorrentHandle::filePriorities() const
{
std::vector<int> fp;
fp = m_nativeHandle.file_priorities();
return QVector<int>::fromStdVector(fp);
}
TorrentInfo TorrentHandle::info() const
{
return m_torrentInfo;
}
bool TorrentHandle::isPaused() const
{
return (m_nativeStatus.paused && !m_nativeStatus.auto_managed);
}
bool TorrentHandle::isResumed() const
{
return !isPaused();
}
bool TorrentHandle::isQueued() const
{
return (m_nativeStatus.paused && m_nativeStatus.auto_managed);
}
bool TorrentHandle::isChecking() const
{
return ((m_nativeStatus.state == libt::torrent_status::checking_files)
|| (m_nativeStatus.state == libt::torrent_status::checking_resume_data)
#if LIBTORRENT_VERSION_NUM < 10100
|| (m_nativeStatus.state == libt::torrent_status::queued_for_checking)
#endif
);
}
bool TorrentHandle::isDownloading() const
{
return m_state == TorrentState::Downloading
|| m_state == TorrentState::DownloadingMetadata
|| m_state == TorrentState::StalledDownloading
|| m_state == TorrentState::CheckingDownloading
|| m_state == TorrentState::PausedDownloading
|| m_state == TorrentState::QueuedDownloading
|| m_state == TorrentState::ForcedDownloading;
}
bool TorrentHandle::isUploading() const
{
return m_state == TorrentState::Uploading
|| m_state == TorrentState::StalledUploading
|| m_state == TorrentState::CheckingUploading
|| m_state == TorrentState::QueuedUploading
|| m_state == TorrentState::ForcedUploading;
}
bool TorrentHandle::isCompleted() const
{
return m_state == TorrentState::Uploading
|| m_state == TorrentState::StalledUploading
|| m_state == TorrentState::CheckingUploading
|| m_state == TorrentState::PausedUploading
|| m_state == TorrentState::QueuedUploading
|| m_state == TorrentState::ForcedUploading;
}
bool TorrentHandle::isActive() const
{
if (m_state == TorrentState::StalledDownloading)
return (uploadPayloadRate() > 0);
return m_state == TorrentState::DownloadingMetadata
|| m_state == TorrentState::Downloading
|| m_state == TorrentState::ForcedDownloading
|| m_state == TorrentState::Uploading
|| m_state == TorrentState::ForcedUploading
|| m_state == TorrentState::Moving;
}
bool TorrentHandle::isInactive() const
{
return !isActive();
}
bool TorrentHandle::isErrored() const
{
return m_state == TorrentState::MissingFiles
|| m_state == TorrentState::Error;
}
bool TorrentHandle::isSeed() const
{
// Affected by bug http://code.rasterbar.com/libtorrent/ticket/402
//bool result;
//result = m_nativeHandle.is_seed());
//return result;
// May suffer from approximation problems
//return (progress() == 1.);
// This looks safe
return ((m_nativeStatus.state == libt::torrent_status::finished)
|| (m_nativeStatus.state == libt::torrent_status::seeding));
}
bool TorrentHandle::isForced() const
{
return (!m_nativeStatus.paused && !m_nativeStatus.auto_managed);
}
bool TorrentHandle::isSequentialDownload() const
{
return m_nativeStatus.sequential_download;
}
bool TorrentHandle::hasFirstLastPiecePriority() const
{
if (!hasMetadata())
return m_needsToSetFirstLastPiecePriority;
const std::vector<int> filePriorities = nativeHandle().file_priorities();
for (int i = 0; i < static_cast<int>(filePriorities.size()); ++i) {
if (filePriorities[i] <= 0)
continue;
const TorrentInfo::PieceRange extremities = info().filePieces(i);
const int firstPiecePrio = nativeHandle().piece_priority(extremities.first());
const int lastPiecePrio = nativeHandle().piece_priority(extremities.last());
return ((firstPiecePrio == 7) && (lastPiecePrio == 7));
}
return false;
}
TorrentState TorrentHandle::state() const
{
return m_state;
}
void TorrentHandle::updateState()
{
if (m_nativeStatus.state == libt::torrent_status::checking_resume_data) {
m_state = TorrentState::CheckingResumeData;
}
else if (isMoveInProgress()) {
m_state = TorrentState::Moving;
}
else if (isPaused()) {
if (hasMissingFiles())
m_state = TorrentState::MissingFiles;
else if (hasError())
m_state = TorrentState::Error;
else
m_state = isSeed() ? TorrentState::PausedUploading : TorrentState::PausedDownloading;
}
else {
if (m_session->isQueueingSystemEnabled() && isQueued() && !isChecking()) {
m_state = isSeed() ? TorrentState::QueuedUploading : TorrentState::QueuedDownloading;
}
else {
switch (m_nativeStatus.state) {
case libt::torrent_status::finished:
case libt::torrent_status::seeding:
if (isForced())
m_state = TorrentState::ForcedUploading;
else
m_state = m_nativeStatus.upload_payload_rate > 0 ? TorrentState::Uploading : TorrentState::StalledUploading;
break;
case libt::torrent_status::allocating:
m_state = TorrentState::Allocating;
break;
#if LIBTORRENT_VERSION_NUM < 10100
case libt::torrent_status::queued_for_checking:
m_state = TorrentState::QueuedForChecking;
break;
#endif
case libt::torrent_status::checking_files:
m_state = m_hasSeedStatus ? TorrentState::CheckingUploading : TorrentState::CheckingDownloading;
break;
case libt::torrent_status::downloading_metadata:
m_state = TorrentState::DownloadingMetadata;
break;
case libt::torrent_status::downloading:
if (isForced())
m_state = TorrentState::ForcedDownloading;
else
m_state = m_nativeStatus.download_payload_rate > 0 ? TorrentState::Downloading : TorrentState::StalledDownloading;
break;
default:
qWarning("Unrecognized torrent status, should not happen!!! status was %d", m_nativeStatus.state);
m_state = TorrentState::Unknown;
}
}
}
}
bool TorrentHandle::hasMetadata() const
{
return m_nativeStatus.has_metadata;
}
bool TorrentHandle::hasMissingFiles() const
{
return m_hasMissingFiles;
}
bool TorrentHandle::hasError() const
{
#if LIBTORRENT_VERSION_NUM < 10100
return (m_nativeStatus.paused && !m_nativeStatus.error.empty());
#else
return (m_nativeStatus.paused && m_nativeStatus.errc);
#endif
}
bool TorrentHandle::hasFilteredPieces() const
{
std::vector<int> pp = m_nativeHandle.piece_priorities();
foreach (const int priority, pp)
if (priority == 0) return true;
return false;
}
int TorrentHandle::queuePosition() const
{
if (m_nativeStatus.queue_position < 0) return 0;
return 0;
//return m_nativeStatus.queue_position + 1;
}
QString TorrentHandle::error() const
{
#if LIBTORRENT_VERSION_NUM < 10100
return QString::fromStdString(m_nativeStatus.error);
#else
return QString::fromStdString(m_nativeStatus.errc.message());
#endif
}
qlonglong TorrentHandle::totalDownload() const
{
return m_nativeStatus.all_time_download;
}
qlonglong TorrentHandle::totalUpload() const
{
return m_nativeStatus.all_time_upload;
}
int TorrentHandle::activeTime() const
{
return m_nativeStatus.active_time;
}
int TorrentHandle::finishedTime() const
{
return m_nativeStatus.finished_time;
}
int TorrentHandle::seedingTime() const
{
return m_nativeStatus.seeding_time;
}
qulonglong TorrentHandle::eta() const
{
return 0;
/*
if (isPaused()) return MAX_ETA;
const SpeedSampleAvg speedAverage = m_speedMonitor.average();
if (isSeed()) {
qreal maxRatioValue = maxRatio();
int maxSeedingTimeValue = maxSeedingTime();
if ((maxRatioValue < 0) && (maxSeedingTimeValue < 0)) return MAX_ETA;
qlonglong ratioEta = MAX_ETA;
if ((speedAverage.upload > 0) && (maxRatioValue >= 0)) {
qlonglong realDL = totalDownload();
if (realDL <= 0)
realDL = wantedSize();
ratioEta = ((realDL * maxRatioValue) - totalUpload()) / speedAverage.upload;
}
qlonglong seedingTimeEta = MAX_ETA;
if (maxSeedingTimeValue >= 0) {
seedingTimeEta = (maxSeedingTimeValue * 60) - seedingTime();
if (seedingTimeEta < 0)
seedingTimeEta = 0;
}
return qMin(ratioEta, seedingTimeEta);
}
if (!speedAverage.download) return MAX_ETA;
return (wantedSize() - completedSize()) / speedAverage.download;
*/
}
QVector<qreal> TorrentHandle::filesProgress() const
{
std::vector<boost::int64_t> fp;
QVector<qreal> result;
m_nativeHandle.file_progress(fp, libt::torrent_handle::piece_granularity);
int count = static_cast<int>(fp.size());
for (int i = 0; i < count; ++i) {
qlonglong size = fileSize(i);
if ((size <= 0) || (fp[i] == size))
result << 1;
else
result << (fp[i] / static_cast<qreal>(size));
}
return result;
}
int TorrentHandle::seedsCount() const
{
return m_nativeStatus.num_seeds;
}
int TorrentHandle::peersCount() const
{
return m_nativeStatus.num_peers;
}
int TorrentHandle::leechsCount() const
{
return (m_nativeStatus.num_peers - m_nativeStatus.num_seeds);
}
int TorrentHandle::totalSeedsCount() const
{
return (m_nativeStatus.num_complete > 0) ? m_nativeStatus.num_complete : m_nativeStatus.list_seeds;
}
int TorrentHandle::totalPeersCount() const
{
int peers = m_nativeStatus.num_complete + m_nativeStatus.num_incomplete;
return (peers > 0) ? peers : m_nativeStatus.list_peers;
}
int TorrentHandle::totalLeechersCount() const
{
return (m_nativeStatus.num_incomplete > 0) ? m_nativeStatus.num_incomplete : (m_nativeStatus.list_peers - m_nativeStatus.list_seeds);
}
int TorrentHandle::completeCount() const
{
// additional info: https://github.com/qbittorrent/qBittorrent/pull/5300#issuecomment-267783646
return m_nativeStatus.num_complete;
}
int TorrentHandle::incompleteCount() const
{
// additional info: https://github.com/qbittorrent/qBittorrent/pull/5300#issuecomment-267783646
return m_nativeStatus.num_incomplete;
}
QDateTime TorrentHandle::lastSeenComplete() const
{
if (m_nativeStatus.last_seen_complete > 0)
return QDateTime::fromTime_t(m_nativeStatus.last_seen_complete);
else
return QDateTime();
}
QDateTime TorrentHandle::completedTime() const
{
if (m_nativeStatus.completed_time > 0)
return QDateTime::fromTime_t(m_nativeStatus.completed_time);
else
return QDateTime();
}
int TorrentHandle::timeSinceUpload() const
{
return m_nativeStatus.time_since_upload;
}
int TorrentHandle::timeSinceDownload() const
{
return m_nativeStatus.time_since_download;
}
int TorrentHandle::timeSinceActivity() const
{
return ((m_nativeStatus.time_since_upload < 0) != (m_nativeStatus.time_since_download < 0))
? std::max(m_nativeStatus.time_since_upload, m_nativeStatus.time_since_download)
: std::min(m_nativeStatus.time_since_upload, m_nativeStatus.time_since_download);
}
int TorrentHandle::downloadLimit() const
{
return m_nativeHandle.download_limit();
}
int TorrentHandle::uploadLimit() const
{
return m_nativeHandle.upload_limit();
}
bool TorrentHandle::superSeeding() const
{
return m_nativeStatus.super_seeding;
}
QList<PeerInfo> TorrentHandle::peers() const
{
QList<PeerInfo> peers;
std::vector<libt::peer_info> nativePeers;
m_nativeHandle.get_peer_info(nativePeers);
foreach (const libt::peer_info &peer, nativePeers)
peers << PeerInfo(this, peer);
return peers;
}
QBitArray TorrentHandle::pieces() const
{
QBitArray result(m_nativeStatus.pieces.size());
for (int i = 0; i < m_nativeStatus.pieces.size(); ++i)
result.setBit(i, m_nativeStatus.pieces.get_bit(i));
return result;
}
QBitArray TorrentHandle::downloadingPieces() const
{
QBitArray result(piecesCount());
std::vector<libt::partial_piece_info> queue;
m_nativeHandle.get_download_queue(queue);
std::vector<libt::partial_piece_info>::const_iterator it = queue.begin();
std::vector<libt::partial_piece_info>::const_iterator itend = queue.end();
for (; it != itend; ++it)
result.setBit(it->piece_index);
return result;
}
QVector<int> TorrentHandle::pieceAvailability() const
{
std::vector<int> avail;
m_nativeHandle.piece_availability(avail);
return QVector<int>::fromStdVector(avail);
}
qreal TorrentHandle::distributedCopies() const
{
return m_nativeStatus.distributed_copies;
}
qreal TorrentHandle::maxRatio() const
{
if (m_ratioLimit == USE_GLOBAL_RATIO)
return m_session->globalMaxRatio();
return m_ratioLimit;
}
int TorrentHandle::maxSeedingTime() const
{
if (m_seedingTimeLimit == USE_GLOBAL_SEEDING_TIME)
return m_session->globalMaxSeedingMinutes();
return m_seedingTimeLimit;
}
qreal TorrentHandle::realRatio() const
{
boost::int64_t upload = m_nativeStatus.all_time_upload;
// special case for a seeder who lost its stats, also assume nobody will import a 99% done torrent
boost::int64_t download = (m_nativeStatus.all_time_download < m_nativeStatus.total_done * 0.01) ? m_nativeStatus.total_done : m_nativeStatus.all_time_download;
if (download == 0)
return (upload == 0) ? 0.0 : MAX_RATIO;
qreal ratio = upload / static_cast<qreal>(download);
Q_ASSERT(ratio >= 0.0);
return (ratio > MAX_RATIO) ? MAX_RATIO : ratio;
}
int TorrentHandle::uploadPayloadRate() const
{
return m_nativeStatus.upload_payload_rate;
}
int TorrentHandle::downloadPayloadRate() const
{
return m_nativeStatus.download_payload_rate;
}
qlonglong TorrentHandle::totalPayloadUpload() const
{
return m_nativeStatus.total_payload_upload;
}
qlonglong TorrentHandle::totalPayloadDownload() const
{
return m_nativeStatus.total_payload_download;
}
int TorrentHandle::connectionsCount() const
{
return m_nativeStatus.num_connections;
}
int TorrentHandle::connectionsLimit() const
{
return m_nativeStatus.connections_limit;
}
qlonglong TorrentHandle::nextAnnounce() const
{
#if LIBTORRENT_VERSION_NUM < 10100
return m_nativeStatus.next_announce.total_seconds();
#else
return libt::duration_cast<libt::seconds>(m_nativeStatus.next_announce).count();
#endif
}
void TorrentHandle::setName(const QString &name)
{
if (m_name != name) {
m_name = name;
m_session->handleTorrentNameChanged(this);
}
}
/*
void TorrentHandle::move(QString path)
{
m_useAutoTMM = false;
m_session->handleTorrentSavingModeChanged(this);
path = Utils::Fs::fromNativePath(path.trimmed());
if (path.isEmpty())
path = m_session->defaultSavePath();
if (!path.endsWith('/'))
path += '/';
move_impl(path, false);
}
*/
/*
void TorrentHandle::move_impl(QString path, bool overwrite)
{
if (path == savePath()) return;
path = Utils::Fs::toNativePath(path);
if (!useTempPath()) {
moveStorage(path, overwrite);
}
else {
m_savePath = path;
m_session->handleTorrentSavePathChanged(this);
}
}
*/
void TorrentHandle::forceReannounce(int index)
{
m_nativeHandle.force_reannounce(0, index);
}
void TorrentHandle::forceDHTAnnounce()
{
m_nativeHandle.force_dht_announce();
}
void TorrentHandle::forceRecheck()
{
if (!hasMetadata()) return;
m_nativeHandle.force_recheck();
m_unchecked = false;
if (isPaused()) {
m_nativeHandle.stop_when_ready(true);
resume_impl(true, true);
}
}
void TorrentHandle::setSequentialDownload(bool b)
{
if (b != isSequentialDownload()) {
m_nativeHandle.set_sequential_download(b);
m_nativeStatus.sequential_download = b; // prevent return cached value
}
}
void TorrentHandle::toggleSequentialDownload()
{
setSequentialDownload(!isSequentialDownload());
}
void TorrentHandle::setFirstLastPiecePriority(const bool enabled)
{
setFirstLastPiecePriorityImpl(enabled);
}
void TorrentHandle::setFirstLastPiecePriorityImpl(const bool enabled, const QVector<int> &updatedFilePrio)
{
// Download first and last pieces first for every file in the torrent
if (!hasMetadata()) {
m_needsToSetFirstLastPiecePriority = enabled;
return;
}
// Updating file priorities is an async operation in libtorrent, when we just updated it and immediately query it
// we might get the old/wrong values, so we rely on `updatedFilePrio` in this case.
const std::vector<int> filePriorities = !updatedFilePrio.isEmpty() ? updatedFilePrio.toStdVector() : nativeHandle().file_priorities();
std::vector<int> piecePriorities = nativeHandle().piece_priorities();
for (int index = 0; index < static_cast<int>(filePriorities.size()); ++index) {
const int filePrio = filePriorities[index];
if (filePrio <= 0)
continue;
// Determine the priority to set
const int newPrio = enabled ? 7 : filePrio;
const TorrentInfo::PieceRange extremities = info().filePieces(index);
// worst case: AVI index = 1% of total file size (at the end of the file)
const int nNumPieces = std::ceil(fileSize(index) * 0.01 / pieceLength());
for (int i = 0; i < nNumPieces; ++i) {
piecePriorities[extremities.first() + i] = newPrio;
piecePriorities[extremities.last() - i] = newPrio;
}
}
m_nativeHandle.prioritize_pieces(piecePriorities);
//LogMsg(tr("Download first and last piece first: %1, torrent: '%2'")
// .arg((enabled ? tr("On") : tr("Off")), name()));
}
void TorrentHandle::toggleFirstLastPiecePriority()
{
setFirstLastPiecePriority(!hasFirstLastPiecePriority());
}
void TorrentHandle::pause()
{
if (isPaused()) return;
m_nativeHandle.auto_managed(false);
m_nativeHandle.pause();
// Libtorrent doesn't emit a torrent_paused_alert when the
// torrent is queued (no I/O)
// We test on the cached m_nativeStatus
if (isQueued())
m_session->handleTorrentPaused(this);
}
void TorrentHandle::resume(bool forced)
{
resume_impl(forced, false);
}
void TorrentHandle::resume_impl(bool forced, bool uploadMode)
{
if (hasError())
m_nativeHandle.clear_error();
if (m_hasMissingFiles) {
m_hasMissingFiles = false;
m_nativeHandle.force_recheck();
}
m_nativeHandle.auto_managed(!forced);
m_nativeHandle.set_upload_mode(uploadMode);
m_nativeHandle.resume();
}
void TorrentHandle::moveStorage(const QString &newPath, bool overwrite)
{
if (isMoveInProgress()) {
qDebug("enqueue move storage to %s", qUtf8Printable(newPath));
m_moveStorageInfo.queuedPath = newPath;
m_moveStorageInfo.queuedOverwrite = overwrite;
}
else {
const QString oldPath = nativeActualSavePath();
if (QDir(oldPath) == QDir(newPath)) return;
qDebug("move storage: %s to %s", qUtf8Printable(oldPath), qUtf8Printable(newPath));
// Actually move the storage
m_nativeHandle.move_storage(newPath.toUtf8().constData()
, (overwrite ? libt::always_replace_files : libt::dont_replace));
m_moveStorageInfo.oldPath = oldPath;
m_moveStorageInfo.newPath = newPath;
updateState();
}
}
#if LIBTORRENT_VERSION_NUM < 10100
void TorrentHandle::setTrackerLogin(const QString &username, const QString &password)
{
m_nativeHandle.set_tracker_login(std::string(username.toLocal8Bit().constData())
, std::string(password.toLocal8Bit().constData()));
}
#endif
/*
void TorrentHandle::renameFile(int index, const QString &name)
{
++m_renameCount;
qDebug() << Q_FUNC_INFO << index << name;
m_nativeHandle.rename_file(index, Utils::Fs::toNativePath(name).toStdString());
}
*/
bool TorrentHandle::saveTorrentFile(const QString &path)
{
if (!m_torrentInfo.isValid()) return false;
libt::create_torrent torrentCreator = makeTorrentCreator<libt::create_torrent>(*(m_torrentInfo.nativeInfo()));
libt::entry torrentEntry = torrentCreator.generate();
QVector<char> out;
libt::bencode(std::back_inserter(out), torrentEntry);
QFile torrentFile(path);
if (!out.empty() && torrentFile.open(QIODevice::WriteOnly))
return (torrentFile.write(&out[0], out.size()) == out.size());
return false;
}
void TorrentHandle::setFilePriority(int index, int priority)
{
std::vector<int> priorities = m_nativeHandle.file_priorities();
if ((priorities.size() > static_cast<quint64>(index)) && (priorities[index] != priority)) {
priorities[index] = priority;
prioritizeFiles(QVector<int>::fromStdVector(priorities));
}
}
void TorrentHandle::handleStateUpdate(const libt::torrent_status &nativeStatus)
{
updateStatus(nativeStatus);
}
void TorrentHandle::handleStorageMovedAlert(const libtorrent::storage_moved_alert *p)
{
}
void TorrentHandle::handleStorageMovedFailedAlert(const libtorrent::storage_moved_failed_alert *p)
{
}
void TorrentHandle::handleTrackerReplyAlert(const libtorrent::tracker_reply_alert *p)
{
#if LIBTORRENT_VERSION_NUM < 10100
QString trackerUrl = QString::fromStdString(p->url);
#else
QString trackerUrl(p->tracker_url());
#endif
qDebug("Received a tracker reply from %s (Num_peers = %d)", qUtf8Printable(trackerUrl), p->num_peers);
// Connection was successful now. Remove possible old errors
m_trackerInfos[trackerUrl].lastMessage.clear(); // Reset error/warning message
m_trackerInfos[trackerUrl].numPeers = p->num_peers;
m_session->handleTorrentTrackerReply(this, trackerUrl);
}
void TorrentHandle::handleTrackerWarningAlert(const libtorrent::tracker_warning_alert *p)
{
#if LIBTORRENT_VERSION_NUM < 10100
const QString trackerUrl = QString::fromStdString(p->url);
const QString message = QString::fromStdString(p->msg);
#else
const QString trackerUrl = p->tracker_url();
const QString message = p->warning_message();
#endif
// Connection was successful now but there is a warning message
m_trackerInfos[trackerUrl].lastMessage = message; // Store warning message
m_session->handleTorrentTrackerWarning(this, trackerUrl);
}
void TorrentHandle::handleTrackerErrorAlert(const libtorrent::tracker_error_alert *p)
{
#if LIBTORRENT_VERSION_NUM < 10100
const QString trackerUrl = QString::fromStdString(p->url);
const QString message = QString::fromStdString(p->msg);
#else
const QString trackerUrl = p->tracker_url();
const QString message = p->error_message();
#endif
m_trackerInfos[trackerUrl].lastMessage = message;
if (p->status_code == 401)
m_session->handleTorrentTrackerAuthenticationRequired(this, trackerUrl);
m_session->handleTorrentTrackerError(this, trackerUrl);
}
void TorrentHandle::handleTorrentCheckedAlert(const libtorrent::torrent_checked_alert *p)
{
Q_UNUSED(p);
qDebug("\"%s\" have just finished checking", qUtf8Printable(name()));
if (m_startupState == NotStarted) {
if (!m_hasMissingFiles) {
// Resume torrent because it was added in "resumed" state
// but it's actually paused during initialization.
m_startupState = Starting;
resume(m_needsToStartForced);
}
else {
// Torrent that has missing files is marked as "started"
// but it remains paused.
m_startupState = Started;
}
}
updateStatus();
if (!m_hasMissingFiles) {
if ((progress() < 1.0) && (wantedSize() > 0))
m_hasSeedStatus = false;
else if (progress() == 1.0)
m_hasSeedStatus = true;
}
m_session->handleTorrentChecked(this);
}
void TorrentHandle::handleTorrentFinishedAlert(const libtorrent::torrent_finished_alert *p)
{
Q_UNUSED(p);
qDebug("Got a torrent finished alert for \"%s\"", qUtf8Printable(name()));
qDebug("Torrent has seed status: %s", m_hasSeedStatus ? "yes" : "no");
if (m_hasSeedStatus) return;
updateStatus();
m_hasMissingFiles = false;
m_hasSeedStatus = true;
const bool recheckTorrentsOnCompletion = false;
if (isMoveInProgress() || (m_renameCount > 0)) {
if (recheckTorrentsOnCompletion)
m_moveFinishedTriggers.append(boost::bind(&TorrentHandle::forceRecheck, this));
m_moveFinishedTriggers.append(boost::bind(&Session::handleTorrentFinished, m_session, this));
}
else {
if (recheckTorrentsOnCompletion && m_unchecked)
forceRecheck();
m_session->handleTorrentFinished(this);
}
}
void TorrentHandle::handleTorrentPausedAlert(const libtorrent::torrent_paused_alert *p)
{
Q_UNUSED(p);
if (m_startupState == Started) {
updateStatus();
//m_speedMonitor.reset();
m_session->handleTorrentPaused(this);
}
}
void TorrentHandle::handleTorrentResumedAlert(const libtorrent::torrent_resumed_alert *p)
{
Q_UNUSED(p);
if (m_startupState == Started)
m_session->handleTorrentResumed(this);
else if (m_startupState == Starting)
m_startupState = Started;
}
void TorrentHandle::handleSaveResumeDataAlert(const libtorrent::save_resume_data_alert *p)
{
}
void TorrentHandle::handleSaveResumeDataFailedAlert(const libtorrent::save_resume_data_failed_alert *p)
{
// if torrent has no metadata we should save dummy fastresume data
// containing Magnet URI and qBittorrent own resume data only
if (p->error.value() == libt::errors::no_metadata)
handleSaveResumeDataAlert(nullptr);
else
m_session->handleTorrentResumeDataFailed(this);
}
void TorrentHandle::handleFastResumeRejectedAlert(const libtorrent::fastresume_rejected_alert *p)
{
}
void TorrentHandle::handleFileRenamedAlert(const libtorrent::file_renamed_alert *p)
{
}
void TorrentHandle::handleFileRenameFailedAlert(const libtorrent::file_rename_failed_alert *p)
{
Q_UNUSED(p);
--m_renameCount;
while (!isMoveInProgress() && (m_renameCount == 0) && !m_moveFinishedTriggers.isEmpty())
m_moveFinishedTriggers.takeFirst()();
}
void TorrentHandle::handleFileCompletedAlert(const libtorrent::file_completed_alert *p)
{
/*
// We don't really need to call updateStatus() in this place.
// All we need to do is make sure we have a valid instance of the TorrentInfo object.
m_torrentInfo = TorrentInfo {m_nativeHandle.torrent_file()};
qDebug("A file completed download in torrent \"%s\"", qUtf8Printable(name()));
if (m_session->isAppendExtensionEnabled()) {
QString name = filePath(p->index);
if (name.endsWith(QB_EXT)) {
const QString oldName = name;
name.chop(QB_EXT.size());
qDebug("Renaming %s to %s", qUtf8Printable(oldName), qUtf8Printable(name));
renameFile(p->index, name);
}
}
*/
}
void TorrentHandle::handleStatsAlert(const libtorrent::stats_alert *p)
{
/*
Q_ASSERT(p->interval >= 1000);
SpeedSample transferred(p->transferred[libt::stats_alert::download_payload] * 1000LL / p->interval,
p->transferred[libt::stats_alert::upload_payload] * 1000LL / p->interval);
m_speedMonitor.addSample(transferred);
*/
}
void TorrentHandle::handleMetadataReceivedAlert(const libt::metadata_received_alert *p)
{
Q_UNUSED(p);
qDebug("Metadata received for torrent %s.", qUtf8Printable(name()));
updateStatus();
if (m_session->isAppendExtensionEnabled())
//manageIncompleteFiles();
if (!m_hasRootFolder)
m_torrentInfo.stripRootFolder();
if (filesCount() == 1)
m_hasRootFolder = false;
m_session->handleTorrentMetadataReceived(this);
if (isPaused()) {
// XXX: Unfortunately libtorrent-rasterbar does not send a torrent_paused_alert
// and the torrent can be paused when metadata is received
//m_speedMonitor.reset();
m_session->handleTorrentPaused(this);
}
// If first/last piece priority was specified when adding this torrent, we can set it
// now that we have metadata:
if (m_needsToSetFirstLastPiecePriority) {
setFirstLastPiecePriority(true);
m_needsToSetFirstLastPiecePriority = false;
}
}
void TorrentHandle::handleAlert(libtorrent::alert *a)
{
switch (a->type()) {
case libt::stats_alert::alert_type:
handleStatsAlert(static_cast<libt::stats_alert*>(a));
break;
case libt::file_renamed_alert::alert_type:
handleFileRenamedAlert(static_cast<libt::file_renamed_alert*>(a));
break;
case libt::file_rename_failed_alert::alert_type:
handleFileRenameFailedAlert(static_cast<libt::file_rename_failed_alert*>(a));
break;
case libt::file_completed_alert::alert_type:
handleFileCompletedAlert(static_cast<libt::file_completed_alert*>(a));
break;
case libt::torrent_finished_alert::alert_type:
handleTorrentFinishedAlert(static_cast<libt::torrent_finished_alert*>(a));
break;
case libt::save_resume_data_alert::alert_type:
handleSaveResumeDataAlert(static_cast<libt::save_resume_data_alert*>(a));
break;
case libt::save_resume_data_failed_alert::alert_type:
handleSaveResumeDataFailedAlert(static_cast<libt::save_resume_data_failed_alert*>(a));
break;
case libt::storage_moved_alert::alert_type:
handleStorageMovedAlert(static_cast<libt::storage_moved_alert*>(a));
break;
case libt::storage_moved_failed_alert::alert_type:
handleStorageMovedFailedAlert(static_cast<libt::storage_moved_failed_alert*>(a));
break;
case libt::torrent_paused_alert::alert_type:
handleTorrentPausedAlert(static_cast<libt::torrent_paused_alert*>(a));
break;
case libt::torrent_resumed_alert::alert_type:
handleTorrentResumedAlert(static_cast<libt::torrent_resumed_alert*>(a));
break;
case libt::tracker_error_alert::alert_type:
handleTrackerErrorAlert(static_cast<libt::tracker_error_alert*>(a));
break;
case libt::tracker_reply_alert::alert_type:
handleTrackerReplyAlert(static_cast<libt::tracker_reply_alert*>(a));
break;
case libt::tracker_warning_alert::alert_type:
handleTrackerWarningAlert(static_cast<libt::tracker_warning_alert*>(a));
break;
case libt::metadata_received_alert::alert_type:
handleMetadataReceivedAlert(static_cast<libt::metadata_received_alert*>(a));
break;
case libt::fastresume_rejected_alert::alert_type:
handleFastResumeRejectedAlert(static_cast<libt::fastresume_rejected_alert*>(a));
break;
case libt::torrent_checked_alert::alert_type:
handleTorrentCheckedAlert(static_cast<libt::torrent_checked_alert*>(a));
break;
}
}
libtorrent::torrent_handle TorrentHandle::nativeHandle() const
{
return m_nativeHandle;
}
void TorrentHandle::updateTorrentInfo()
{
if (!hasMetadata()) return;
#if LIBTORRENT_VERSION_NUM < 10100
m_torrentInfo = TorrentInfo(m_nativeStatus.torrent_file);
#else
m_torrentInfo = TorrentInfo(m_nativeStatus.torrent_file.lock());
#endif
}
bool TorrentHandle::isMoveInProgress() const
{
return !m_moveStorageInfo.newPath.isEmpty();
}
void TorrentHandle::updateStatus()
{
updateStatus(m_nativeHandle.status());
}
void TorrentHandle::updateStatus(const libtorrent::torrent_status &nativeStatus)
{
m_nativeStatus = nativeStatus;
updateState();
updateTorrentInfo();
// NOTE: Don't change the order of these conditionals!
// Otherwise it will not work properly since torrent can be CheckingDownloading.
if (isChecking())
m_unchecked = false;
else if (isDownloading())
m_unchecked = true;
}
void TorrentHandle::setRatioLimit(qreal limit)
{
if (limit < USE_GLOBAL_RATIO)
limit = NO_RATIO_LIMIT;
else if (limit > MAX_RATIO)
limit = MAX_RATIO;
if (m_ratioLimit != limit) {
m_ratioLimit = limit;
m_session->handleTorrentShareLimitChanged(this);
}
}
void TorrentHandle::setSeedingTimeLimit(int limit)
{
if (limit < USE_GLOBAL_SEEDING_TIME)
limit = NO_SEEDING_TIME_LIMIT;
else if (limit > MAX_SEEDING_TIME)
limit = MAX_SEEDING_TIME;
if (m_seedingTimeLimit != limit) {
m_seedingTimeLimit = limit;
m_session->handleTorrentShareLimitChanged(this);
}
}
void TorrentHandle::setUploadLimit(int limit)
{
m_nativeHandle.set_upload_limit(limit);
}
void TorrentHandle::setDownloadLimit(int limit)
{
m_nativeHandle.set_download_limit(limit);
}
void TorrentHandle::setSuperSeeding(bool enable)
{
m_nativeHandle.super_seeding(enable);
}
void TorrentHandle::flushCache()
{
m_nativeHandle.flush_cache();
}
QString TorrentHandle::toMagnetUri() const
{
return QString::fromStdString(libt::make_magnet_uri(m_nativeHandle));
}
void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
{
/*
if (!hasMetadata()) return;
if (priorities.size() != filesCount()) return;
// Save first/last piece first option state
const bool firstLastPieceFirst = hasFirstLastPiecePriority();
// Reset 'm_hasSeedStatus' if needed in order to react again to
// 'torrent_finished_alert' and eg show tray notifications
QVector<qreal> progress = filesProgress();
QVector<int> oldPriorities = filePriorities();
for (int i = 0; i < oldPriorities.size(); ++i) {
if ((oldPriorities[i] == 0) && (priorities[i] > 0) && (progress[i] < 1.0)) {
m_hasSeedStatus = false;
break;
}
}
qDebug() << Q_FUNC_INFO << "Changing files priorities...";
m_nativeHandle.prioritize_files(priorities.toStdVector());
qDebug() << Q_FUNC_INFO << "Moving unwanted files to .unwanted folder and conversely...";
QString spath = savePath(true);
for (int i = 0; i < priorities.size(); ++i) {
QString filepath = filePath(i);
// Move unwanted files to a .unwanted subfolder
if (priorities[i] == 0) {
QString oldAbsPath = QDir(spath).absoluteFilePath(filepath);
QString parentAbsPath = Utils::Fs::branchPath(oldAbsPath);
// Make sure the file does not already exists
if (QDir(parentAbsPath).dirName() != ".unwanted") {
QString unwantedAbsPath = parentAbsPath + "/.unwanted";
QString newAbsPath = unwantedAbsPath + '/' + Utils::Fs::fileName(filepath);
qDebug() << "Unwanted path is" << unwantedAbsPath;
if (QFile::exists(newAbsPath)) {
qWarning() << "File" << newAbsPath << "already exists at destination.";
continue;
}
bool created = QDir().mkpath(unwantedAbsPath);
qDebug() << "unwanted folder was created:" << created;
#ifdef Q_OS_WIN
if (created) {
// Hide the folder on Windows
qDebug() << "Hiding folder (Windows)";
std::wstring winPath = Utils::Fs::toNativePath(unwantedAbsPath).toStdWString();
DWORD dwAttrs = ::GetFileAttributesW(winPath.c_str());
bool ret = ::SetFileAttributesW(winPath.c_str(), dwAttrs | FILE_ATTRIBUTE_HIDDEN);
Q_ASSERT(ret != 0); Q_UNUSED(ret);
}
#endif
QString parentPath = Utils::Fs::branchPath(filepath);
if (!parentPath.isEmpty() && !parentPath.endsWith('/'))
parentPath += '/';
renameFile(i, parentPath + ".unwanted/" + Utils::Fs::fileName(filepath));
}
}
// Move wanted files back to their original folder
if (priorities[i] > 0) {
QString parentRelPath = Utils::Fs::branchPath(filepath);
if (QDir(parentRelPath).dirName() == ".unwanted") {
QString oldName = Utils::Fs::fileName(filepath);
QString newRelPath = Utils::Fs::branchPath(parentRelPath);
if (newRelPath.isEmpty())
renameFile(i, oldName);
else
renameFile(i, QDir(newRelPath).filePath(oldName));
// Remove .unwanted directory if empty
qDebug() << "Attempting to remove .unwanted folder at " << QDir(spath + '/' + newRelPath).absoluteFilePath(".unwanted");
QDir(spath + '/' + newRelPath).rmdir(".unwanted");
}
}
}
// Restore first/last piece first option if necessary
if (firstLastPieceFirst)
setFirstLastPiecePriorityImpl(true, priorities);
*/
}
QVector<qreal> TorrentHandle::availableFileFractions() const
{
const auto filesCount = this->filesCount();
if (filesCount < 0) return {};
const QVector<int> piecesAvailability = pieceAvailability();
// libtorrent returns empty array for seeding only torrents
if (piecesAvailability.empty()) return QVector<qreal>(filesCount, -1.);
QVector<qreal> res;
res.reserve(filesCount);
TorrentInfo info = this->info();
for (int file = 0; file < filesCount; ++file) {
TorrentInfo::PieceRange filePieces = info.filePieces(file);
int availablePieces = 0;
for (int piece = filePieces.first(); piece <= filePieces.last(); ++piece) {
availablePieces += piecesAvailability[piece] > 0 ? 1 : 0;
}
res.push_back(static_cast<qreal>(availablePieces) / filePieces.size());
}
return res;
}
|
/*
** nodebuild_extract.cpp
**
** Converts the nodes, segs, and subsectors from the node builder's
** internal format to the format used by the rest of the game.
**
**---------------------------------------------------------------------------
** Copyright 2002-2006 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
** 4. When not used as part of ZDoom or a ZDoom derivative, this code will be
** covered by 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 SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include <string.h>
#include <float.h>
#include "nodebuild.h"
#include "templates.h"
#include "g_levellocals.h"
#if 0
#define D(x) x
#define DD 1
#else
#define D(x) do{}while(0)
#undef DD
#endif
void FNodeBuilder::Extract (FLevelLocals &level)
{
int i;
auto &outVerts = level.vertexes;
int vertCount = Vertices.Size ();
outVerts.Alloc(vertCount);
for (i = 0; i < vertCount; ++i)
{
outVerts[i].set(Vertices[i].x, Vertices[i].y);
}
auto &outSubs = level.subsectors;
auto subCount = Subsectors.Size();
outSubs.Alloc(subCount);
memset(&outSubs[0], 0, subCount * sizeof(subsector_t));
auto &outNodes = level.nodes;
auto nodeCount = Nodes.Size ();
outNodes.Alloc(nodeCount);
memcpy (&outNodes[0], &Nodes[0], nodeCount*sizeof(node_t));
for (unsigned i = 0; i < nodeCount; ++i)
{
D(Printf(PRINT_LOG, "Node %d: Splitter[%08x,%08x] [%08x,%08x]\n", i,
outNodes[i].x, outNodes[i].y, outNodes[i].dx, outNodes[i].dy));
// Go backwards because on 64-bit systems, both of the intchildren are
// inside the first in-game child.
for (int j = 1; j >= 0; --j)
{
if (outNodes[i].intchildren[j] & 0x80000000)
{
D(Printf(PRINT_LOG, " subsector %d\n", outNodes[i].intchildren[j] & 0x7FFFFFFF));
outNodes[i].children[j] = (uint8_t *)(&outSubs[(outNodes[i].intchildren[j] & 0x7fffffff)]) + 1;
}
else
{
D(Printf(PRINT_LOG, " node %d\n", outNodes[i].intchildren[j]));
outNodes[i].children[j] = &outNodes[outNodes[i].intchildren[j]];
}
}
for (int j = 0; j < 2; ++j)
{
for (int k = 0; k < 4; ++k)
{
outNodes[i].bbox[j][k] = FIXED2FLOAT(outNodes[i].nb_bbox[j][k]);
}
}
}
auto &outSegs = level.segs;
if (GLNodes)
{
TArray<glseg_t> segs (Segs.Size()*5/4);
for (unsigned i = 0; i < subCount; ++i)
{
uint32_t numsegs = CloseSubsector (segs, i, &outVerts[0]);
outSubs[i].numlines = numsegs;
outSubs[i].firstline = (seg_t *)(size_t)(segs.Size() - numsegs);
}
auto segCount = segs.Size ();
outSegs.Alloc(segCount);
for (unsigned i = 0; i < segCount; ++i)
{
outSegs[i] = *(seg_t *)&segs[i];
if (segs[i].Partner != UINT_MAX)
{
const uint32_t storedseg = Segs[segs[i].Partner].storedseg;
outSegs[i].PartnerSeg = UINT_MAX == storedseg ? nullptr : &outSegs[storedseg];
}
else
{
outSegs[i].PartnerSeg = nullptr;
}
}
}
else
{
memcpy (&outSubs[0], &Subsectors[0], subCount*sizeof(subsector_t));
auto segCount = Segs.Size ();
outSegs.Alloc(segCount);
for (unsigned i = 0; i < segCount; ++i)
{
const FPrivSeg *org = &Segs[SegList[i].SegNum];
seg_t *out = &outSegs[i];
D(Printf(PRINT_LOG, "Seg %d: v1(%d) -> v2(%d)\n", i, org->v1, org->v2));
out->v1 = &outVerts[org->v1];
out->v2 = &outVerts[org->v2];
out->backsector = org->backsector;
out->frontsector = org->frontsector;
out->linedef = Level.Lines + org->linedef;
out->sidedef = Level.Sides + org->sidedef;
out->PartnerSeg = nullptr;
}
}
for (unsigned i = 0; i < subCount; ++i)
{
outSubs[i].firstline = &outSegs[(size_t)outSubs[i].firstline];
}
D(Printf("%i segs, %i nodes, %i subsectors\n", segCount, nodeCount, subCount));
for (i = 0; i < Level.NumLines; ++i)
{
Level.Lines[i].v1 = &outVerts[(size_t)Level.Lines[i].v1];
Level.Lines[i].v2 = &outVerts[(size_t)Level.Lines[i].v2];
}
}
void FNodeBuilder::ExtractMini (FMiniBSP *bsp)
{
unsigned int i;
bsp->bDirty = false;
bsp->Verts.Resize(Vertices.Size());
for (i = 0; i < Vertices.Size(); ++i)
{
bsp->Verts[i].set(Vertices[i].x, Vertices[i].y);
}
bsp->Subsectors.Resize(Subsectors.Size());
memset(&bsp->Subsectors[0], 0, Subsectors.Size() * sizeof(subsector_t));
bsp->Nodes.Resize(Nodes.Size());
memcpy(&bsp->Nodes[0], &Nodes[0], Nodes.Size()*sizeof(node_t));
for (i = 0; i < Nodes.Size(); ++i)
{
D(Printf(PRINT_LOG, "Node %d:\n", i));
// Go backwards because on 64-bit systems, both of the intchildren are
// inside the first in-game child.
for (int j = 1; j >= 0; --j)
{
if (bsp->Nodes[i].intchildren[j] & 0x80000000)
{
D(Printf(PRINT_LOG, " subsector %d\n", bsp->Nodes[i].intchildren[j] & 0x7FFFFFFF));
bsp->Nodes[i].children[j] = (uint8_t *)&bsp->Subsectors[bsp->Nodes[i].intchildren[j] & 0x7fffffff] + 1;
}
else
{
D(Printf(PRINT_LOG, " node %d\n", bsp->Nodes[i].intchildren[j]));
bsp->Nodes[i].children[j] = &bsp->Nodes[bsp->Nodes[i].intchildren[j]];
}
}
for (int j = 0; j < 2; ++j)
{
for (int k = 0; k < 4; ++k)
{
bsp->Nodes[i].bbox[j][k] = FIXED2FLOAT(bsp->Nodes[i].nb_bbox[j][k]);
}
}
}
if (GLNodes)
{
TArray<glseg_t> glsegs;
for (i = 0; i < Subsectors.Size(); ++i)
{
uint32_t numsegs = CloseSubsector (glsegs, i, &bsp->Verts[0]);
bsp->Subsectors[i].numlines = numsegs;
bsp->Subsectors[i].firstline = &bsp->Segs[bsp->Segs.Size() - numsegs];
}
bsp->Segs.Resize(glsegs.Size());
for (i = 0; i < glsegs.Size(); ++i)
{
bsp->Segs[i] = *(seg_t *)&glsegs[i];
}
}
else
{
memcpy(&bsp->Subsectors[0], &Subsectors[0], Subsectors.Size()*sizeof(subsector_t));
bsp->Segs.Resize(Segs.Size());
for (i = 0; i < Segs.Size(); ++i)
{
const FPrivSeg *org = &Segs[SegList[i].SegNum];
seg_t *out = &bsp->Segs[i];
D(Printf(PRINT_LOG, "Seg %d: v1(%d) -> v2(%d)\n", i, org->v1, org->v2));
out->v1 = &bsp->Verts[org->v1];
out->v2 = &bsp->Verts[org->v2];
out->backsector = org->backsector;
out->frontsector = org->frontsector;
if (org->sidedef != int(NO_SIDE))
{
out->linedef = Level.Lines + org->linedef;
out->sidedef = Level.Sides + org->sidedef;
}
else // part of a miniseg
{
out->linedef = NULL;
out->sidedef = NULL;
}
}
for (i = 0; i < bsp->Subsectors.Size(); ++i)
{
bsp->Subsectors[i].firstline = &bsp->Segs[(size_t)bsp->Subsectors[i].firstline];
}
}
}
int FNodeBuilder::CloseSubsector (TArray<glseg_t> &segs, int subsector, vertex_t *outVerts)
{
FPrivSeg *seg, *prev;
angle_t prevAngle;
double accumx, accumy;
fixed_t midx, midy;
int firstVert;
uint32_t first, max, count, i, j;
bool diffplanes;
int firstplane;
first = (uint32_t)(size_t)Subsectors[subsector].firstline;
max = first + Subsectors[subsector].numlines;
count = 0;
accumx = accumy = 0.0;
diffplanes = false;
firstplane = Segs[SegList[first].SegNum].planenum;
// Calculate the midpoint of the subsector and also check for degenerate subsectors.
// A subsector is degenerate if it exists in only one dimension, which can be
// detected when all the segs lie in the same plane. This can happen if you have
// outward-facing lines in the void that don't point toward any sector. (Some of the
// polyobjects in Hexen are constructed like this.)
for (i = first; i < max; ++i)
{
seg = &Segs[SegList[i].SegNum];
accumx += double(Vertices[seg->v1].x) + double(Vertices[seg->v2].x);
accumy += double(Vertices[seg->v1].y) + double(Vertices[seg->v2].y);
if (firstplane != seg->planenum)
{
diffplanes = true;
}
}
midx = fixed_t(accumx / (max - first) / 2);
midy = fixed_t(accumy / (max - first) / 2);
seg = &Segs[SegList[first].SegNum];
prevAngle = PointToAngle (Vertices[seg->v1].x - midx, Vertices[seg->v1].y - midy);
seg->storedseg = PushGLSeg (segs, seg, outVerts);
count = 1;
prev = seg;
firstVert = seg->v1;
#ifdef DD
Printf(PRINT_LOG, "--%d--\n", subsector);
for (j = first; j < max; ++j)
{
seg = &Segs[SegList[j].SegNum];
angle_t ang = PointToAngle (Vertices[seg->v1].x - midx, Vertices[seg->v1].y - midy);
Printf(PRINT_LOG, "%d%c %5d(%5d,%5d)->%5d(%5d,%5d) - %3.5f %d,%d [%08x,%08x]-[%08x,%08x]\n", j,
seg->linedef == -1 ? '+' : ':',
seg->v1, Vertices[seg->v1].x>>16, Vertices[seg->v1].y>>16,
seg->v2, Vertices[seg->v2].x>>16, Vertices[seg->v2].y>>16,
double(ang/2)*180/(1<<30),
seg->planenum, seg->planefront,
Vertices[seg->v1].x, Vertices[seg->v1].y,
Vertices[seg->v2].x, Vertices[seg->v2].y);
}
#endif
if (diffplanes)
{ // A well-behaved subsector. Output the segs sorted by the angle formed by connecting
// the subsector's center to their first vertex.
D(Printf(PRINT_LOG, "Well behaved subsector\n"));
for (i = first + 1; i < max; ++i)
{
angle_t bestdiff = ANGLE_MAX;
FPrivSeg *bestseg = NULL;
uint32_t bestj = UINT_MAX;
j = first;
do
{
seg = &Segs[SegList[j].SegNum];
angle_t ang = PointToAngle (Vertices[seg->v1].x - midx, Vertices[seg->v1].y - midy);
angle_t diff = prevAngle - ang;
if (seg->v1 == prev->v2)
{
bestdiff = diff;
bestseg = seg;
bestj = j;
break;
}
if (diff < bestdiff && diff > 0)
{
bestdiff = diff;
bestseg = seg;
bestj = j;
}
}
while (++j < max);
// Is a NULL bestseg actually okay?
if (bestseg != NULL)
{
seg = bestseg;
}
if (prev->v2 != seg->v1)
{
// Add a new miniseg to connect the two segs
PushConnectingGLSeg (subsector, segs, &outVerts[prev->v2], &outVerts[seg->v1]);
count++;
}
#ifdef DD
Printf(PRINT_LOG, "+%d\n", bestj);
#endif
prevAngle -= bestdiff;
seg->storedseg = PushGLSeg (segs, seg, outVerts);
count++;
prev = seg;
if (seg->v2 == firstVert)
{
prev = seg;
break;
}
}
#ifdef DD
Printf(PRINT_LOG, "\n");
#endif
}
else
{ // A degenerate subsector. These are handled in three stages:
// Stage 1. Proceed in the same direction as the start seg until we
// hit the seg furthest from it.
// Stage 2. Reverse direction and proceed until we hit the seg
// furthest from the start seg.
// Stage 3. Reverse direction again and insert segs until we get
// to the start seg.
// A dot product serves to determine distance from the start seg.
D(Printf(PRINT_LOG, "degenerate subsector\n"));
// Stage 1. Go forward.
count += OutputDegenerateSubsector (segs, subsector, true, 0, prev, outVerts);
// Stage 2. Go backward.
count += OutputDegenerateSubsector (segs, subsector, false, DBL_MAX, prev, outVerts);
// Stage 3. Go forward again.
count += OutputDegenerateSubsector (segs, subsector, true, -DBL_MAX, prev, outVerts);
}
if (prev->v2 != firstVert)
{
PushConnectingGLSeg (subsector, segs, &outVerts[prev->v2], &outVerts[firstVert]);
count++;
}
#ifdef DD
Printf(PRINT_LOG, "Output GL subsector %d:\n", subsector);
for (i = segs.Size() - count; i < (int)segs.Size(); ++i)
{
Printf(PRINT_LOG, " Seg %5d%c(%5d,%5d)-(%5d,%5d) [%08x,%08x]-[%08x,%08x]\n", i,
segs[i].linedef == NULL ? '+' : ' ',
segs[i].v1->fixX()>>16,
segs[i].v1->fixY()>>16,
segs[i].v2->fixX()>>16,
segs[i].v2->fixY()>>16,
segs[i].v1->fixX(),
segs[i].v1->fixY(),
segs[i].v2->fixX(),
segs[i].v2->fixY());
}
#endif
return count;
}
int FNodeBuilder::OutputDegenerateSubsector (TArray<glseg_t> &segs, int subsector, bool bForward, double lastdot, FPrivSeg *&prev, vertex_t *outVerts)
{
static const double bestinit[2] = { -DBL_MAX, DBL_MAX };
FPrivSeg *seg;
int i, j, first, max, count;
double dot, x1, y1, dx, dy, dx2, dy2;
bool wantside;
first = (uint32_t)(size_t)Subsectors[subsector].firstline;
max = first + Subsectors[subsector].numlines;
count = 0;
seg = &Segs[SegList[first].SegNum];
x1 = Vertices[seg->v1].x;
y1 = Vertices[seg->v1].y;
dx = Vertices[seg->v2].x - x1;
dy = Vertices[seg->v2].y - y1;
wantside = seg->planefront ^ !bForward;
for (i = first + 1; i < max; ++i)
{
double bestdot = bestinit[bForward];
FPrivSeg *bestseg = NULL;
for (j = first + 1; j < max; ++j)
{
seg = &Segs[SegList[j].SegNum];
if (seg->planefront != wantside)
{
continue;
}
dx2 = Vertices[seg->v1].x - x1;
dy2 = Vertices[seg->v1].y - y1;
dot = dx*dx2 + dy*dy2;
if (bForward)
{
if (dot < bestdot && dot > lastdot)
{
bestdot = dot;
bestseg = seg;
}
}
else
{
if (dot > bestdot && dot < lastdot)
{
bestdot = dot;
bestseg = seg;
}
}
}
if (bestseg != NULL)
{
if (prev->v2 != bestseg->v1)
{
PushConnectingGLSeg (subsector, segs, &outVerts[prev->v2], &outVerts[bestseg->v1]);
count++;
}
seg->storedseg = PushGLSeg (segs, bestseg, outVerts);
count++;
prev = bestseg;
lastdot = bestdot;
}
}
return count;
}
uint32_t FNodeBuilder::PushGLSeg (TArray<glseg_t> &segs, const FPrivSeg *seg, vertex_t *outVerts)
{
glseg_t newseg;
newseg.v1 = outVerts + seg->v1;
newseg.v2 = outVerts + seg->v2;
newseg.backsector = seg->backsector;
newseg.frontsector = seg->frontsector;
if (seg->linedef != -1)
{
newseg.linedef = Level.Lines + seg->linedef;
newseg.sidedef = Level.Sides + seg->sidedef;
}
else
{
newseg.linedef = NULL;
newseg.sidedef = NULL;
}
newseg.Partner = seg->partner;
return (uint32_t)segs.Push (newseg);
}
void FNodeBuilder::PushConnectingGLSeg (int subsector, TArray<glseg_t> &segs, vertex_t *v1, vertex_t *v2)
{
glseg_t newseg;
newseg.v1 = v1;
newseg.v2 = v2;
newseg.backsector = NULL;
newseg.frontsector = NULL;
newseg.linedef = NULL;
newseg.sidedef = NULL;
newseg.Partner = UINT_MAX;
segs.Push (newseg);
}
|
/*
* NamespaceAndNameTest.cpp
*
* Copyright 2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 <string>
#include <unordered_map>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "AVSCommon/AVS/NamespaceAndName.h"
using namespace ::testing;
namespace alexaClientSDK {
namespace avsCommon {
namespace avs {
namespace test {
/// @c nameSpace value for testing.
static const std::string NAMESPACE_SPEECH_RECOGNIZER("SpeechRecognizer");
/// @c name value for testing.
static const std::string NAME_RECOGNIZE("Recognize");
/// @c nameSpace value for testing.
static const std::string NAMESPACE_SPEAKER("Speaker");
/// @c name value for testing.
static const std::string NAME_SET_VOLUME("SetVolume");
/// NamespaceAndNameTest
class NamespaceAndNameTest : public ::testing::Test {};
/**
* Invoke default constructor. Expect @c nameSpace and @c name properties are both empty strings.
*/
TEST_F(NamespaceAndNameTest, testDefaultConstructor) {
NamespaceAndName instance;
ASSERT_TRUE(instance.nameSpace.empty());
ASSERT_TRUE(instance.name.empty());
}
/**
* Invoke constructor with member values. Expect properties match those provided to the constructor.
*/
TEST_F(NamespaceAndNameTest, testConstructorWithValues) {
NamespaceAndName instance(NAMESPACE_SPEECH_RECOGNIZER, NAME_RECOGNIZE);
ASSERT_EQ(instance.nameSpace, NAMESPACE_SPEECH_RECOGNIZER);
ASSERT_EQ(instance.name, NAME_RECOGNIZE);
}
/**
* Create an @c std::unordered_map using NamespaceAndName values as keys. Expect that the keys map to distinct values.
*/
TEST_F(NamespaceAndNameTest, testInUnorderedMap) {
std::unordered_map<NamespaceAndName, int> testMap;
NamespaceAndName key1(NAMESPACE_SPEECH_RECOGNIZER, NAME_RECOGNIZE);
NamespaceAndName key2(NAMESPACE_SPEAKER, NAME_SET_VOLUME);
testMap[key1] = 1;
testMap[key2] = 2;
ASSERT_EQ(testMap[key1], 1);
ASSERT_EQ(testMap[key2], 2);
ASSERT_NE(testMap[key1], testMap[key2]);
}
} // namespace test
} // namespace avs
} // namespace avsCommon
} // namespace alexaClientSDK
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// XFAIL: with_system_cxx_lib=macosx10.12
// XFAIL: with_system_cxx_lib=macosx10.11
// XFAIL: with_system_cxx_lib=macosx10.10
// XFAIL: with_system_cxx_lib=macosx10.9
// XFAIL: with_system_cxx_lib=macosx10.7
// XFAIL: with_system_cxx_lib=macosx10.8
// <system_error>
// class error_category
// const error_category& generic_category();
#include <system_error>
#include <cassert>
#include <string>
#include <cerrno>
#include "test_macros.h"
void test_message_for_bad_value() {
errno = E2BIG; // something that message will never generate
const std::error_category& e_cat1 = std::generic_category();
const std::string msg = e_cat1.message(-1);
// Exact message format varies by platform.
LIBCPP_ASSERT(msg == "Unknown error -1" || msg == "Unknown error" ||
msg == "Unknown error: -1");
assert(errno == E2BIG);
}
int main()
{
const std::error_category& e_cat1 = std::generic_category();
std::string m1 = e_cat1.name();
assert(m1 == "generic");
{
test_message_for_bad_value();
}
}
|
#include "sgx_trts.h"
#include "sgx_tseal.h"
#include "string.h"
#include "Enclave_t.h"
/**
* @brief Seals the plaintext given into the sgx_sealed_data_t structure
* given.
*
* @details The plaintext can be any data. uint8_t is used to represent a
* byte. The sealed size can be determined by computing
* sizeof(sgx_sealed_data_t) + plaintext_len, since it is using
* AES-GCM which preserves length of plaintext. The size needs to be
* specified, otherwise SGX will assume the size to be just
* sizeof(sgx_sealed_data_t), not taking into account the sealed
* payload.
*
* @param plaintext The data to be sealed
* @param[in] plaintext_len The plaintext length
* @param sealed_data The pointer to the sealed data structure
* @param[in] sealed_size The size of the sealed data structure supplied
*
* @return Truthy if seal successful, falsy otherwise.
*/
sgx_status_t seal(uint8_t* plaintext, size_t plaintext_len, sgx_sealed_data_t* sealed_data, size_t sealed_size) {
sgx_status_t status = sgx_seal_data(0, NULL, plaintext_len, plaintext, sealed_size, sealed_data);
//uint32_t var = sgx_calc_sealed_data_size(0 , plaintext_len);
//ocall_print_int(var);
//const uint32_t additional_MACtext_length, 0
//const uint8_t *p_additional_MACtext, null
//const uint32_t text2encrypt_length, len
//const uint8_t *p_text2encrypt, text
//const uint32_t sealed_data_size, size
//sgx_sealed_data_t *p_sealed_data data
return status;
}
/**
* @brief Unseal the sealed_data given into c-string
*
* @details The resulting plaintext is of type uint8_t to represent a byte.
* The sizes/length of pointers need to be specified, otherwise SGX
* will assume a count of 1 for all pointers.
*
* @param sealed_data The sealed data
* @param[in] sealed_size The size of the sealed data
* @param plaintext A pointer to buffer to store the plaintext
* @param[in] plaintext_max_len The size of buffer prepared to store the
* plaintext
*
* @return Truthy if unseal successful, falsy otherwise.
*/
sgx_status_t unseal(sgx_sealed_data_t* sealed_data, size_t sealed_size, uint8_t* plaintext, uint32_t plaintext_len) {
sgx_status_t status = sgx_unseal_data(sealed_data, NULL, NULL, (uint8_t*)plaintext, &plaintext_len);
return status;
}
|
/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2015 Wu Lin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
*/
#include <shogun/optimization/ConstLearningRate.h>
using namespace shogun;
void ConstLearningRate::set_const_learning_rate(float64_t learning_rate)
{
require(learning_rate>0.0, "learning_rate ({}) must be positive",learning_rate);
m_const_learning_rate=learning_rate;
}
float64_t ConstLearningRate::get_learning_rate(int32_t iter_counter)
{
require(m_const_learning_rate>0.0,"learning_rate must set");
return m_const_learning_rate;
}
void ConstLearningRate::init()
{
m_const_learning_rate=0.0;
SG_ADD(&m_const_learning_rate, "ConstLearningRate__m_const_learning_rate",
"learning rate in ConstLearningRate");
}
|
// Copyright (c) 2014-2019, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
/*!
* \file simplewallet.cpp
*
* \brief Source file that defines simple_wallet class.
*/
#include <locale.h>
#include <thread>
#include <iostream>
#include <sstream>
#include <fstream>
#include <ctype.h>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include "include_base_utils.h"
#include "console_handler.h"
#include "common/i18n.h"
#include "common/command_line.h"
#include "common/util.h"
#include "common/dns_utils.h"
#include "common/base58.h"
#include "common/scoped_message_writer.h"
#include "cryptonote_protocol/cryptonote_protocol_handler.h"
#include "simplewallet.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "storages/http_abstract_invoke.h"
#include "rpc/core_rpc_server_commands_defs.h"
#include "rpc/rpc_payment_signature.h"
#include "crypto/crypto.h" // for crypto::secret_key definition
#include "mnemonics/electrum-words.h"
#include "rapidjson/document.h"
#include "common/json_util.h"
#include "ringct/rctSigs.h"
#include "multisig/multisig.h"
#include "wallet/wallet_args.h"
#include "version.h"
#include <stdexcept>
#include "wallet/message_store.h"
#ifdef WIN32
#include <boost/locale.hpp>
#include <boost/filesystem.hpp>
#endif
#ifdef HAVE_READLINE
#include "readline_buffer.h"
#endif
using namespace std;
using namespace epee;
using namespace cryptonote;
using boost::lexical_cast;
namespace po = boost::program_options;
typedef cryptonote::simple_wallet sw;
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "wallet.simplewallet"
#define EXTENDED_LOGS_FILE "wallet_details.log"
#define DEFAULT_MIX 10
#define MIN_RING_SIZE 11 // Used to inform user about min ring size -- does not track actual protocol
#define OLD_AGE_WARN_THRESHOLD (30 * 86400 / DIFFICULTY_TARGET) // 30 days
#define LOCK_IDLE_SCOPE() \
bool auto_refresh_enabled = m_auto_refresh_enabled.load(std::memory_order_relaxed); \
m_auto_refresh_enabled.store(false, std::memory_order_relaxed); \
/* stop any background refresh and other processes, and take over */ \
m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed); \
m_wallet->stop(); \
boost::unique_lock<boost::mutex> lock(m_idle_mutex); \
m_idle_cond.notify_all(); \
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ \
/* m_idle_mutex is still locked here */ \
m_auto_refresh_enabled.store(auto_refresh_enabled, std::memory_order_relaxed); \
m_suspend_rpc_payment_mining.store(false, std::memory_order_relaxed);; \
m_rpc_payment_checker.trigger(); \
m_idle_cond.notify_one(); \
})
#define SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(code) \
LOCK_IDLE_SCOPE(); \
boost::optional<tools::password_container> pwd_container = boost::none; \
if (m_wallet->ask_password() && !(pwd_container = get_and_verify_password())) { code; } \
tools::wallet_keys_unlocker unlocker(*m_wallet, pwd_container);
#define SCOPED_WALLET_UNLOCK() SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return true;)
#define PRINT_USAGE(usage_help) fail_msg_writer() << boost::format(tr("usage: %s")) % usage_help;
#define LONG_PAYMENT_ID_SUPPORT_CHECK() \
do { \
fail_msg_writer() << tr("Error: Long payment IDs are obsolete."); \
fail_msg_writer() << tr("Long payment IDs were not encrypted on the blockchain and would harm your privacy."); \
fail_msg_writer() << tr("If the party you're sending to still requires a long payment ID, please notify them."); \
return true; \
} while(0)
#define REFRESH_PERIOD 90 // seconds
#define CREDITS_TARGET 50000
#define MAX_PAYMENT_DIFF 10000
#define MIN_PAYMENT_RATE 0.01f // per hash
enum TransferType {
Transfer,
TransferLocked,
};
static std::string get_human_readable_timespan(std::chrono::seconds seconds);
namespace
{
const std::array<const char* const, 5> allowed_priority_strings = {{"default", "unimportant", "normal", "elevated", "priority"}};
const auto arg_wallet_file = wallet_args::arg_wallet_file();
const auto arg_rpc_client_secret_key = wallet_args::arg_rpc_client_secret_key();
const command_line::arg_descriptor<std::string> arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to <arg>"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_device = {"generate-from-device", sw::tr("Generate new wallet from device and save it to <arg>"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_view_key = {"generate-from-view-key", sw::tr("Generate incoming-only wallet from view key"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_spend_key = {"generate-from-spend-key", sw::tr("Generate deterministic wallet from spend key"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_keys = {"generate-from-keys", sw::tr("Generate wallet from private keys"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_multisig_keys = {"generate-from-multisig-keys", sw::tr("Generate a master wallet from multisig wallet keys"), ""};
const auto arg_generate_from_json = wallet_args::arg_generate_from_json();
const command_line::arg_descriptor<std::string> arg_mnemonic_language = {"mnemonic-language", sw::tr("Language for mnemonic"), ""};
const command_line::arg_descriptor<std::string> arg_electrum_seed = {"electrum-seed", sw::tr("Specify Electrum seed for wallet recovery/creation"), ""};
const command_line::arg_descriptor<bool> arg_restore_deterministic_wallet = {"restore-deterministic-wallet", sw::tr("Recover wallet using Electrum-style mnemonic seed"), false};
const command_line::arg_descriptor<bool> arg_restore_from_seed = {"restore-from-seed", sw::tr("alias for --restore-deterministic-wallet"), false};
const command_line::arg_descriptor<bool> arg_restore_multisig_wallet = {"restore-multisig-wallet", sw::tr("Recover multisig wallet using Electrum-style mnemonic seed"), false};
const command_line::arg_descriptor<bool> arg_non_deterministic = {"non-deterministic", sw::tr("Generate non-deterministic view and spend keys"), false};
const command_line::arg_descriptor<bool> arg_allow_mismatched_daemon_version = {"allow-mismatched-daemon-version", sw::tr("Allow communicating with a daemon that uses a different RPC version"), false};
const command_line::arg_descriptor<uint64_t> arg_restore_height = {"restore-height", sw::tr("Restore from specific blockchain height"), 0};
const command_line::arg_descriptor<std::string> arg_restore_date = {"restore-date", sw::tr("Restore from estimated blockchain height on specified date"), ""};
const command_line::arg_descriptor<bool> arg_do_not_relay = {"do-not-relay", sw::tr("The newly created transaction will not be relayed to the swap network"), false};
const command_line::arg_descriptor<bool> arg_create_address_file = {"create-address-file", sw::tr("Create an address file for new wallets"), false};
const command_line::arg_descriptor<std::string> arg_subaddress_lookahead = {"subaddress-lookahead", tools::wallet2::tr("Set subaddress lookahead sizes to <major>:<minor>"), ""};
const command_line::arg_descriptor<bool> arg_use_english_language_names = {"use-english-language-names", sw::tr("Display English language names"), false};
const command_line::arg_descriptor< std::vector<std::string> > arg_command = {"command", ""};
const char* USAGE_START_MINING("start_mining [<number_of_threads>] [bg_mining] [ignore_battery]");
const char* USAGE_SET_DAEMON("set_daemon <host>[:<port>] [trusted|untrusted]");
const char* USAGE_SHOW_BALANCE("balance [detail]");
const char* USAGE_INCOMING_TRANSFERS("incoming_transfers [available|unavailable] [verbose] [uses] [index=<N1>[,<N2>[,...]]]");
const char* USAGE_PAYMENTS("payments <PID_1> [<PID_2> ... <PID_N>]");
const char* USAGE_PAYMENT_ID("payment_id");
const char* USAGE_TRANSFER("transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <address> <amount>) [<payment_id>]");
const char* USAGE_LOCKED_TRANSFER("locked_transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <addr> <amount>) <lockblocks> [<payment_id (obsolete)>]");
const char* USAGE_LOCKED_SWEEP_ALL("locked_sweep_all [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <lockblocks> [<payment_id (obsolete)>]");
const char* USAGE_SWEEP_ALL("sweep_all [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]");
const char* USAGE_SWEEP_BELOW("sweep_below <amount_threshold> [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id (obsolete)>]");
const char* USAGE_SWEEP_SINGLE("sweep_single [<priority>] [<ring_size>] [outputs=<N>] <key_image> <address> [<payment_id (obsolete)>]");
const char* USAGE_DONATE("donate [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <amount> [<payment_id (obsolete)>]");
const char* USAGE_SIGN_TRANSFER("sign_transfer [export_raw]");
const char* USAGE_SET_LOG("set_log <level>|{+,-,}<categories>");
const char* USAGE_ACCOUNT("account\n"
" account new <label text with white spaces allowed>\n"
" account switch <index> \n"
" account label <index> <label text with white spaces allowed>\n"
" account tag <tag_name> <account_index_1> [<account_index_2> ...]\n"
" account untag <account_index_1> [<account_index_2> ...]\n"
" account tag_description <tag_name> <description>");
const char* USAGE_ADDRESS("address [ new <label text with white spaces allowed> | all | <index_min> [<index_max>] | label <index> <label text with white spaces allowed> | device [<index>]]");
const char* USAGE_INTEGRATED_ADDRESS("integrated_address [device] [<payment_id> | <address>]");
const char* USAGE_ADDRESS_BOOK("address_book [(add ((<address> [pid <id>])|<integrated address>) [<description possibly with whitespaces>])|(delete <index>)]");
const char* USAGE_SET_VARIABLE("set <option> [<value>]");
const char* USAGE_GET_TX_KEY("get_tx_key <txid>");
const char* USAGE_SET_TX_KEY("set_tx_key <txid> <tx_key>");
const char* USAGE_CHECK_TX_KEY("check_tx_key <txid> <txkey> <address>");
const char* USAGE_GET_TX_PROOF("get_tx_proof <txid> <address> [<message>]");
const char* USAGE_CHECK_TX_PROOF("check_tx_proof <txid> <address> <signature_file> [<message>]");
const char* USAGE_GET_SPEND_PROOF("get_spend_proof <txid> [<message>]");
const char* USAGE_CHECK_SPEND_PROOF("check_spend_proof <txid> <signature_file> [<message>]");
const char* USAGE_GET_RESERVE_PROOF("get_reserve_proof (all|<amount>) [<message>]");
const char* USAGE_CHECK_RESERVE_PROOF("check_reserve_proof <address> <signature_file> [<message>]");
const char* USAGE_SHOW_TRANSFERS("show_transfers [in|out|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
const char* USAGE_UNSPENT_OUTPUTS("unspent_outputs [index=<N1>[,<N2>,...]] [<min_amount> [<max_amount>]]");
const char* USAGE_RESCAN_BC("rescan_bc [hard|soft|keep_ki] [start_height=0]");
const char* USAGE_SET_TX_NOTE("set_tx_note <txid> [free text note]");
const char* USAGE_GET_TX_NOTE("get_tx_note <txid>");
const char* USAGE_GET_DESCRIPTION("get_description");
const char* USAGE_SET_DESCRIPTION("set_description [free text note]");
const char* USAGE_SIGN("sign <filename>");
const char* USAGE_VERIFY("verify <filename> <address> <signature>");
const char* USAGE_EXPORT_KEY_IMAGES("export_key_images [all] <filename>");
const char* USAGE_IMPORT_KEY_IMAGES("import_key_images <filename>");
const char* USAGE_HW_KEY_IMAGES_SYNC("hw_key_images_sync");
const char* USAGE_HW_RECONNECT("hw_reconnect");
const char* USAGE_EXPORT_OUTPUTS("export_outputs [all] <filename>");
const char* USAGE_IMPORT_OUTPUTS("import_outputs <filename>");
const char* USAGE_SHOW_TRANSFER("show_transfer <txid>");
const char* USAGE_MAKE_MULTISIG("make_multisig <threshold> <string1> [<string>...]");
const char* USAGE_FINALIZE_MULTISIG("finalize_multisig <string> [<string>...]");
const char* USAGE_EXCHANGE_MULTISIG_KEYS("exchange_multisig_keys <string> [<string>...]");
const char* USAGE_EXPORT_MULTISIG_INFO("export_multisig_info <filename>");
const char* USAGE_IMPORT_MULTISIG_INFO("import_multisig_info <filename> [<filename>...]");
const char* USAGE_SIGN_MULTISIG("sign_multisig <filename>");
const char* USAGE_SUBMIT_MULTISIG("submit_multisig <filename>");
const char* USAGE_EXPORT_RAW_MULTISIG_TX("export_raw_multisig_tx <filename>");
const char* USAGE_MMS("mms [<subcommand> [<subcommand_parameters>]]");
const char* USAGE_MMS_INIT("mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>");
const char* USAGE_MMS_INFO("mms info");
const char* USAGE_MMS_SIGNER("mms signer [<number> <label> [<transport_address> [<swap_address>]]]");
const char* USAGE_MMS_LIST("mms list");
const char* USAGE_MMS_NEXT("mms next [sync]");
const char* USAGE_MMS_SYNC("mms sync");
const char* USAGE_MMS_TRANSFER("mms transfer <transfer_command_arguments>");
const char* USAGE_MMS_DELETE("mms delete (<message_id> | all)");
const char* USAGE_MMS_SEND("mms send [<message_id>]");
const char* USAGE_MMS_RECEIVE("mms receive");
const char* USAGE_MMS_EXPORT("mms export <message_id>");
const char* USAGE_MMS_NOTE("mms note [<label> <text>]");
const char* USAGE_MMS_SHOW("mms show <message_id>");
const char* USAGE_MMS_SET("mms set <option_name> [<option_value>]");
const char* USAGE_MMS_SEND_SIGNER_CONFIG("mms send_signer_config");
const char* USAGE_MMS_START_AUTO_CONFIG("mms start_auto_config [<label> <label> ...]");
const char* USAGE_MMS_STOP_AUTO_CONFIG("mms stop_auto_config");
const char* USAGE_MMS_AUTO_CONFIG("mms auto_config <auto_config_token>");
const char* USAGE_PRINT_RING("print_ring <key_image> | <txid>");
const char* USAGE_SET_RING("set_ring <filename> | ( <key_image> absolute|relative <index> [<index>...] )");
const char* USAGE_UNSET_RING("unset_ring <txid> | ( <key_image> [<key_image>...] )");
const char* USAGE_SAVE_KNOWN_RINGS("save_known_rings");
const char* USAGE_MARK_OUTPUT_SPENT("mark_output_spent <amount>/<offset> | <filename> [add]");
const char* USAGE_MARK_OUTPUT_UNSPENT("mark_output_unspent <amount>/<offset>");
const char* USAGE_IS_OUTPUT_SPENT("is_output_spent <amount>/<offset>");
const char* USAGE_FREEZE("freeze <key_image>");
const char* USAGE_THAW("thaw <key_image>");
const char* USAGE_FROZEN("frozen <key_image>");
const char* USAGE_LOCK("lock");
const char* USAGE_NET_STATS("net_stats");
const char* USAGE_PUBLIC_NODES("public_nodes");
const char* USAGE_WELCOME("welcome");
const char* USAGE_RPC_PAYMENT_INFO("rpc_payment_info");
const char* USAGE_START_MINING_FOR_RPC("start_mining_for_rpc");
const char* USAGE_STOP_MINING_FOR_RPC("stop_mining_for_rpc");
const char* USAGE_VERSION("version");
const char* USAGE_HELP("help [<command>]");
std::string input_line(const std::string& prompt, bool yesno = false)
{
PAUSE_READLINE();
std::cout << prompt;
if (yesno)
std::cout << " (Y/Yes/N/No)";
std::cout << ": " << std::flush;
std::string buf;
#ifdef _WIN32
buf = tools::input_line_win();
#else
std::getline(std::cin, buf);
#endif
return epee::string_tools::trim(buf);
}
epee::wipeable_string input_secure_line(const char *prompt)
{
PAUSE_READLINE();
auto pwd_container = tools::password_container::prompt(false, prompt, false);
if (!pwd_container)
{
MERROR("Failed to read secure line");
return "";
}
epee::wipeable_string buf = pwd_container->password();
buf.trim();
return buf;
}
boost::optional<tools::password_container> password_prompter(const char *prompt, bool verify)
{
PAUSE_READLINE();
auto pwd_container = tools::password_container::prompt(verify, prompt);
if (!pwd_container)
{
tools::fail_msg_writer() << sw::tr("failed to read wallet password");
}
return pwd_container;
}
boost::optional<tools::password_container> default_password_prompter(bool verify)
{
return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify);
}
inline std::string interpret_rpc_response(bool ok, const std::string& status)
{
std::string err;
if (ok)
{
if (status == CORE_RPC_STATUS_BUSY)
{
err = sw::tr("daemon is busy. Please try again later.");
}
else if (status != CORE_RPC_STATUS_OK)
{
err = status;
}
}
else
{
err = sw::tr("possibly lost connection to daemon");
}
return err;
}
tools::scoped_message_writer success_msg_writer(bool color = false)
{
return tools::scoped_message_writer(color ? console_color_green : console_color_default, false, std::string(), el::Level::Info);
}
tools::scoped_message_writer message_writer(epee::console_colors color = epee::console_color_default, bool bright = false)
{
return tools::scoped_message_writer(color, bright);
}
tools::scoped_message_writer fail_msg_writer()
{
return tools::scoped_message_writer(console_color_red, true, sw::tr("Error: "), el::Level::Error);
}
bool parse_bool(const std::string& s, bool& result)
{
if (s == "1" || command_line::is_yes(s))
{
result = true;
return true;
}
if (s == "0" || command_line::is_no(s))
{
result = false;
return true;
}
boost::algorithm::is_iequal ignore_case{};
if (boost::algorithm::equals("true", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("true"), s, ignore_case))
{
result = true;
return true;
}
if (boost::algorithm::equals("false", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("false"), s, ignore_case))
{
result = false;
return true;
}
return false;
}
template <typename F>
bool parse_bool_and_use(const std::string& s, F func)
{
bool r;
if (parse_bool(s, r))
{
func(r);
return true;
}
else
{
fail_msg_writer() << sw::tr("invalid argument: must be either 0/1, true/false, y/n, yes/no");
return false;
}
}
const struct
{
const char *name;
tools::wallet2::RefreshType refresh_type;
} refresh_type_names[] =
{
{ "full", tools::wallet2::RefreshFull },
{ "optimize-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
{ "optimized-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
{ "no-coinbase", tools::wallet2::RefreshNoCoinbase },
{ "default", tools::wallet2::RefreshDefault },
};
bool parse_refresh_type(const std::string &s, tools::wallet2::RefreshType &refresh_type)
{
for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
{
if (s == refresh_type_names[n].name)
{
refresh_type = refresh_type_names[n].refresh_type;
return true;
}
}
fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse refresh type");
return false;
}
std::string get_refresh_type_name(tools::wallet2::RefreshType type)
{
for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
{
if (type == refresh_type_names[n].refresh_type)
return refresh_type_names[n].name;
}
return "invalid";
}
std::string get_version_string(uint32_t version)
{
return boost::lexical_cast<std::string>(version >> 16) + "." + boost::lexical_cast<std::string>(version & 0xffff);
}
std::string oa_prompter(const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)
{
if (addresses.empty())
return {};
// prompt user for confirmation.
// inform user of DNSSEC validation status as well.
std::string dnssec_str;
if (dnssec_valid)
{
dnssec_str = sw::tr("DNSSEC validation passed");
}
else
{
dnssec_str = sw::tr("WARNING: DNSSEC validation was unsuccessful, this address may not be correct!");
}
std::stringstream prompt;
prompt << sw::tr("For URL: ") << url
<< ", " << dnssec_str << std::endl
<< sw::tr(" Swap Address = ") << addresses[0]
<< std::endl
<< sw::tr("Is this OK?")
;
// prompt the user for confirmation given the dns query and dnssec status
std::string confirm_dns_ok = input_line(prompt.str(), true);
if (std::cin.eof())
{
return {};
}
if (!command_line::is_yes(confirm_dns_ok))
{
std::cout << sw::tr("you have cancelled the transfer request") << std::endl;
return {};
}
return addresses[0];
}
bool parse_subaddress_indices(const std::string& arg, std::set<uint32_t>& subaddr_indices)
{
subaddr_indices.clear();
if (arg.substr(0, 6) != "index=")
return false;
std::string subaddr_indices_str_unsplit = arg.substr(6, arg.size() - 6);
std::vector<std::string> subaddr_indices_str;
boost::split(subaddr_indices_str, subaddr_indices_str_unsplit, boost::is_any_of(","));
for (const auto& subaddr_index_str : subaddr_indices_str)
{
uint32_t subaddr_index;
if(!epee::string_tools::get_xtype_from_string(subaddr_index, subaddr_index_str))
{
fail_msg_writer() << sw::tr("failed to parse index: ") << subaddr_index_str;
subaddr_indices.clear();
return false;
}
subaddr_indices.insert(subaddr_index);
}
return true;
}
boost::optional<std::pair<uint32_t, uint32_t>> parse_subaddress_lookahead(const std::string& str)
{
auto r = tools::parse_subaddress_lookahead(str);
if (!r)
fail_msg_writer() << sw::tr("invalid format for subaddress lookahead; must be <major>:<minor>");
return r;
}
}
void simple_wallet::handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon)
{
bool warn_of_possible_attack = !trusted_daemon;
try
{
std::rethrow_exception(e);
}
catch (const tools::error::payment_required&)
{
fail_msg_writer() << tr("Payment required, see the 'rpc_payment_info' command");
m_need_payment = true;
}
catch (const tools::error::no_connection_to_daemon&)
{
fail_msg_writer() << sw::tr("no connection to daemon. Please make sure daemon is running.");
}
catch (const tools::error::daemon_busy&)
{
fail_msg_writer() << tr("daemon is busy. Please try again later.");
}
catch (const tools::error::wallet_rpc_error& e)
{
LOG_ERROR("RPC error: " << e.to_string());
fail_msg_writer() << sw::tr("RPC error: ") << e.what();
}
catch (const tools::error::get_outs_error &e)
{
fail_msg_writer() << sw::tr("failed to get random outputs to mix: ") << e.what();
}
catch (const tools::error::not_enough_unlocked_money& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
print_money(e.available()) %
print_money(e.tx_amount()));
fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
warn_of_possible_attack = false;
}
catch (const tools::error::not_enough_money& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
print_money(e.available()) %
print_money(e.tx_amount()));
fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_not_possible& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, transaction amount %s = %s + %s (fee)") %
print_money(e.available()) %
print_money(e.tx_amount() + e.fee()) %
print_money(e.tx_amount()) %
print_money(e.fee()));
fail_msg_writer() << sw::tr("Failed to find a way to create transactions. This is usually due to dust which is so small it cannot pay for itself in fees, or trying to send more money than the unlocked balance, or not leaving enough for fees");
warn_of_possible_attack = false;
}
catch (const tools::error::not_enough_outs_to_mix& e)
{
auto writer = fail_msg_writer();
writer << sw::tr("not enough outputs for specified ring size") << " = " << (e.mixin_count() + 1) << ":";
for (std::pair<uint64_t, uint64_t> outs_for_amount : e.scanty_outs())
{
writer << "\n" << sw::tr("output amount") << " = " << print_money(outs_for_amount.first) << ", " << sw::tr("found outputs to use") << " = " << outs_for_amount.second;
}
writer << sw::tr("Please use sweep_unmixable.");
}
catch (const tools::error::tx_not_constructed&)
{
fail_msg_writer() << sw::tr("transaction was not constructed");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_rejected& e)
{
fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx()));
std::string reason = e.reason();
if (!reason.empty())
fail_msg_writer() << sw::tr("Reason: ") << reason;
}
catch (const tools::error::tx_sum_overflow& e)
{
fail_msg_writer() << e.what();
warn_of_possible_attack = false;
}
catch (const tools::error::zero_destination&)
{
fail_msg_writer() << sw::tr("one of destinations is zero");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_too_big& e)
{
fail_msg_writer() << sw::tr("failed to find a suitable way to split transactions");
warn_of_possible_attack = false;
}
catch (const tools::error::transfer_error& e)
{
LOG_ERROR("unknown transfer error: " << e.to_string());
fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what();
}
catch (const tools::error::multisig_export_needed& e)
{
LOG_ERROR("Multisig error: " << e.to_string());
fail_msg_writer() << sw::tr("Multisig error: ") << e.what();
warn_of_possible_attack = false;
}
catch (const tools::error::wallet_internal_error& e)
{
LOG_ERROR("internal error: " << e.to_string());
fail_msg_writer() << sw::tr("internal error: ") << e.what();
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << sw::tr("unexpected error: ") << e.what();
}
if (warn_of_possible_attack)
fail_msg_writer() << sw::tr("There was an error, which could mean the node may be trying to get you to retry creating a transaction, and zero in on which outputs you own. Or it could be a bona fide error. It may be prudent to disconnect from this node, and not try to send a transaction immediately. Alternatively, connect to another node so the original node cannot correlate information.");
}
namespace
{
bool check_file_overwrite(const std::string &filename)
{
boost::system::error_code errcode;
if (boost::filesystem::exists(filename, errcode))
{
if (boost::ends_with(filename, ".keys"))
{
fail_msg_writer() << boost::format(sw::tr("File %s likely stores wallet private keys! Use a different file name.")) % filename;
return false;
}
return command_line::is_yes(input_line((boost::format(sw::tr("File %s already exists. Are you sure to overwrite it?")) % filename).str(), true));
}
return true;
}
void print_secret_key(const crypto::secret_key &k)
{
static constexpr const char hex[] = u8"0123456789abcdef";
const uint8_t *ptr = (const uint8_t*)k.data;
for (size_t i = 0, sz = sizeof(k); i < sz; ++i)
{
putchar(hex[*ptr >> 4]);
putchar(hex[*ptr & 15]);
++ptr;
}
}
}
bool parse_priority(const std::string& arg, uint32_t& priority)
{
auto priority_pos = std::find(
allowed_priority_strings.begin(),
allowed_priority_strings.end(),
arg);
if(priority_pos != allowed_priority_strings.end()) {
priority = std::distance(allowed_priority_strings.begin(), priority_pos);
return true;
}
return false;
}
std::string join_priority_strings(const char *delimiter)
{
std::string s;
for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
{
if (!s.empty())
s += delimiter;
s += allowed_priority_strings[n];
}
return s;
}
std::string simple_wallet::get_commands_str()
{
std::stringstream ss;
ss << tr("Commands: ") << ENDL;
std::string usage = m_cmd_binder.get_usage();
boost::replace_all(usage, "\n", "\n ");
usage.insert(0, " ");
ss << usage << ENDL;
return ss.str();
}
std::string simple_wallet::get_command_usage(const std::vector<std::string> &args)
{
std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(args);
std::stringstream ss;
if(documentation.first.empty())
{
ss << tr("Unknown command: ") << args.front();
}
else
{
std::string usage = documentation.second.empty() ? args.front() : documentation.first;
std::string description = documentation.second.empty() ? documentation.first : documentation.second;
usage.insert(0, " ");
ss << tr("Command usage: ") << ENDL << usage << ENDL << ENDL;
boost::replace_all(description, "\n", "\n ");
description.insert(0, " ");
ss << tr("Command description: ") << ENDL << description << ENDL;
}
return ss.str();
}
bool simple_wallet::viewkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
// don't log
PAUSE_READLINE();
if (m_wallet->key_on_device()) {
std::cout << "secret: On device. Not available" << std::endl;
} else {
SCOPED_WALLET_UNLOCK();
printf("secret: ");
print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
putchar('\n');
}
std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_view_public_key) << std::endl;
return true;
}
bool simple_wallet::spendkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no spend key");
return true;
}
// don't log
PAUSE_READLINE();
if (m_wallet->key_on_device()) {
std::cout << "secret: On device. Not available" << std::endl;
} else {
SCOPED_WALLET_UNLOCK();
printf("secret: ");
print_secret_key(m_wallet->get_account().get_keys().m_spend_secret_key);
putchar('\n');
}
std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_spend_public_key) << std::endl;
return true;
}
bool simple_wallet::print_seed(bool encrypted)
{
bool success = false;
epee::wipeable_string seed;
bool ready, multisig;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no seed");
return true;
}
multisig = m_wallet->multisig(&ready);
if (multisig)
{
if (!ready)
{
fail_msg_writer() << tr("wallet is multisig but not yet finalized");
return true;
}
}
SCOPED_WALLET_UNLOCK();
if (!multisig && !m_wallet->is_deterministic())
{
fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
return true;
}
epee::wipeable_string seed_pass;
if (encrypted)
{
auto pwd_container = password_prompter(tr("Enter optional seed offset passphrase, empty to see raw seed"), true);
if (std::cin.eof() || !pwd_container)
return true;
seed_pass = pwd_container->password();
}
if (multisig)
success = m_wallet->get_multisig_seed(seed, seed_pass);
else if (m_wallet->is_deterministic())
success = m_wallet->get_seed(seed, seed_pass);
if (success)
{
print_seed(seed);
}
else
{
fail_msg_writer() << tr("Failed to retrieve seed");
}
return true;
}
bool simple_wallet::seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
return print_seed(false);
}
bool simple_wallet::encrypted_seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
return print_seed(true);
}
bool simple_wallet::restore_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
success_msg_writer() << m_wallet->get_refresh_from_block_height();
return true;
}
bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("wallet is multisig and has no seed");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no seed");
return true;
}
epee::wipeable_string password;
{
SCOPED_WALLET_UNLOCK();
if (!m_wallet->is_deterministic())
{
fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
return true;
}
// we need the password, even if ask-password is unset
if (!pwd_container)
{
pwd_container = get_and_verify_password();
if (pwd_container == boost::none)
{
fail_msg_writer() << tr("Incorrect password");
return true;
}
}
password = pwd_container->password();
}
std::string mnemonic_language = get_mnemonic_language();
if (mnemonic_language.empty())
return true;
m_wallet->set_seed_language(std::move(mnemonic_language));
m_wallet->rewrite(m_wallet_file, password);
return true;
}
bool simple_wallet::change_password(const std::vector<std::string> &args)
{
const auto orig_pwd_container = get_and_verify_password();
if(orig_pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return true;
}
// prompts for a new password, pass true to verify the password
const auto pwd_container = default_password_prompter(true);
if(!pwd_container)
return true;
try
{
m_wallet->change_password(m_wallet_file, orig_pwd_container->password(), pwd_container->password());
}
catch (const tools::error::wallet_logic_error& e)
{
fail_msg_writer() << tr("Error with wallet rewrite: ") << e.what();
return true;
}
return true;
}
bool simple_wallet::payment_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
LONG_PAYMENT_ID_SUPPORT_CHECK();
crypto::hash payment_id;
if (args.size() > 0)
{
PRINT_USAGE(USAGE_PAYMENT_ID);
return true;
}
payment_id = crypto::rand<crypto::hash>();
success_msg_writer() << tr("Random payment ID: ") << payment_id;
return true;
}
bool simple_wallet::print_fee_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (!try_connect_to_daemon())
return true;
const bool per_byte = m_wallet->use_fork_rules(HF_VERSION_PER_BYTE_FEE);
const uint64_t base_fee = m_wallet->get_base_fee();
const char *base = per_byte ? "byte" : "kB";
const uint64_t typical_size = per_byte ? 2500 : 13;
const uint64_t size_granularity = per_byte ? 1 : 1024;
message_writer() << (boost::format(tr("Current fee is %s %s per %s")) % print_money(base_fee) % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % base).str();
std::vector<uint64_t> fees;
for (uint32_t priority = 1; priority <= 4; ++priority)
{
uint64_t mult = m_wallet->get_fee_multiplier(priority);
fees.push_back(base_fee * typical_size * mult);
}
std::vector<std::pair<uint64_t, uint64_t>> blocks;
try
{
uint64_t base_size = typical_size * size_granularity;
blocks = m_wallet->estimate_backlog(base_size, base_size + size_granularity - 1, fees);
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Error: failed to estimate backlog array size: ") << e.what();
return true;
}
if (blocks.size() != 4)
{
fail_msg_writer() << tr("Error: bad estimated backlog array size");
return true;
}
for (uint32_t priority = 1; priority <= 4; ++priority)
{
uint64_t nblocks_low = blocks[priority - 1].first;
uint64_t nblocks_high = blocks[priority - 1].second;
if (nblocks_low > 0)
{
std::string msg;
if (priority == m_wallet->get_default_priority() || (m_wallet->get_default_priority() == 0 && priority == 2))
msg = tr(" (current)");
uint64_t minutes_low = nblocks_low * DIFFICULTY_TARGET / 60, minutes_high = nblocks_high * DIFFICULTY_TARGET / 60;
if (nblocks_high == nblocks_low)
message_writer() << (boost::format(tr("%u block (%u minutes) backlog at priority %u%s")) % nblocks_low % minutes_low % priority % msg).str();
else
message_writer() << (boost::format(tr("%u to %u block (%u to %u minutes) backlog at priority %u")) % nblocks_low % nblocks_high % minutes_low % minutes_high % priority).str();
}
else
message_writer() << tr("No backlog at priority ") << priority;
}
return true;
}
bool simple_wallet::prepare_multisig(const std::vector<std::string> &args)
{
prepare_multisig_main(args, false);
return true;
}
bool simple_wallet::prepare_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return false;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("This wallet is already multisig");
return false;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
return false;
}
if(m_wallet->get_num_transfer_details())
{
fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
return false;
}
SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
std::string multisig_info = m_wallet->get_multisig_info();
success_msg_writer() << multisig_info;
success_msg_writer() << tr("Send this multisig info to all other participants, then use make_multisig <threshold> <info1> [<info2>...] with others' multisig info");
success_msg_writer() << tr("This includes the PRIVATE view key, so needs to be disclosed only to that multisig wallet's participants ");
if (called_by_mms)
{
get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::key_set, multisig_info);
}
return true;
}
bool simple_wallet::make_multisig(const std::vector<std::string> &args)
{
make_multisig_main(args, false);
return true;
}
bool simple_wallet::make_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return false;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("This wallet is already multisig");
return false;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
return false;
}
if(m_wallet->get_num_transfer_details())
{
fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
return false;
}
if (args.size() < 2)
{
PRINT_USAGE(USAGE_MAKE_MULTISIG);
return false;
}
// parse threshold
uint32_t threshold;
if (!string_tools::get_xtype_from_string(threshold, args[0]))
{
fail_msg_writer() << tr("Invalid threshold");
return false;
}
const auto orig_pwd_container = get_and_verify_password();
if(orig_pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return false;
}
LOCK_IDLE_SCOPE();
try
{
auto local_args = args;
local_args.erase(local_args.begin());
std::string multisig_extra_info = m_wallet->make_multisig(orig_pwd_container->password(), local_args, threshold);
if (!multisig_extra_info.empty())
{
success_msg_writer() << tr("Another step is needed");
success_msg_writer() << multisig_extra_info;
success_msg_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
if (called_by_mms)
{
get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info);
}
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Error creating multisig: ") << e.what();
return false;
}
uint32_t total;
if (!m_wallet->multisig(NULL, &threshold, &total))
{
fail_msg_writer() << tr("Error creating multisig: new wallet is not multisig");
return false;
}
success_msg_writer() << std::to_string(threshold) << "/" << total << tr(" multisig address: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
return true;
}
bool simple_wallet::finalize_multisig(const std::vector<std::string> &args)
{
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
const auto pwd_container = get_and_verify_password();
if(pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return true;
}
if (!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This wallet is not multisig");
return true;
}
if (ready)
{
fail_msg_writer() << tr("This wallet is already finalized");
return true;
}
LOCK_IDLE_SCOPE();
if (args.size() < 2)
{
PRINT_USAGE(USAGE_FINALIZE_MULTISIG);
return true;
}
try
{
if (!m_wallet->finalize_multisig(pwd_container->password(), args))
{
fail_msg_writer() << tr("Failed to finalize multisig");
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to finalize multisig: ") << e.what();
return true;
}
return true;
}
bool simple_wallet::exchange_multisig_keys(const std::vector<std::string> &args)
{
exchange_multisig_keys_main(args, false);
return true;
}
bool simple_wallet::exchange_multisig_keys_main(const std::vector<std::string> &args, bool called_by_mms) {
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return false;
}
if (!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This wallet is not multisig");
return false;
}
if (ready)
{
fail_msg_writer() << tr("This wallet is already finalized");
return false;
}
const auto orig_pwd_container = get_and_verify_password();
if(orig_pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return false;
}
if (args.size() < 2)
{
PRINT_USAGE(USAGE_EXCHANGE_MULTISIG_KEYS);
return false;
}
try
{
std::string multisig_extra_info = m_wallet->exchange_multisig_keys(orig_pwd_container->password(), args);
if (!multisig_extra_info.empty())
{
message_writer() << tr("Another step is needed");
message_writer() << multisig_extra_info;
message_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
if (called_by_mms)
{
get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info);
}
return true;
} else {
uint32_t threshold, total;
m_wallet->multisig(NULL, &threshold, &total);
success_msg_writer() << tr("Multisig wallet has been successfully created. Current wallet type: ") << threshold << "/" << total;
success_msg_writer() << tr("Multisig address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to perform multisig keys exchange: ") << e.what();
return false;
}
return true;
}
bool simple_wallet::export_multisig(const std::vector<std::string> &args)
{
export_multisig_main(args, false);
return true;
}
bool simple_wallet::export_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
{
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return false;
}
if (!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This wallet is not multisig");
return false;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return false;
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_EXPORT_MULTISIG_INFO);
return false;
}
const std::string filename = args[0];
if (!called_by_mms && m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
try
{
cryptonote::blobdata ciphertext = m_wallet->export_multisig();
if (called_by_mms)
{
get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::multisig_sync_data, ciphertext);
}
else
{
bool r = m_wallet->save_to_file(filename, ciphertext);
if (!r)
{
fail_msg_writer() << tr("failed to save file ") << filename;
return false;
}
}
}
catch (const std::exception &e)
{
LOG_ERROR("Error exporting multisig info: " << e.what());
fail_msg_writer() << tr("Error exporting multisig info: ") << e.what();
return false;
}
success_msg_writer() << tr("Multisig info exported to ") << filename;
return true;
}
bool simple_wallet::import_multisig(const std::vector<std::string> &args)
{
import_multisig_main(args, false);
return true;
}
bool simple_wallet::import_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
{
bool ready;
uint32_t threshold, total;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return false;
}
if (!m_wallet->multisig(&ready, &threshold, &total))
{
fail_msg_writer() << tr("This wallet is not multisig");
return false;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return false;
}
if (args.size() < threshold - 1)
{
PRINT_USAGE(USAGE_IMPORT_MULTISIG_INFO);
return false;
}
std::vector<cryptonote::blobdata> info;
for (size_t n = 0; n < args.size(); ++n)
{
if (called_by_mms)
{
info.push_back(args[n]);
}
else
{
const std::string &filename = args[n];
std::string data;
bool r = m_wallet->load_from_file(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return false;
}
info.push_back(std::move(data));
}
}
SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
// all read and parsed, actually import
try
{
m_in_manual_refresh.store(true, std::memory_order_relaxed);
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
size_t n_outputs = m_wallet->import_multisig(info);
// Clear line "Height xxx of xxx"
std::cout << "\r \r";
success_msg_writer() << tr("Multisig info imported");
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to import multisig info: ") << e.what();
return false;
}
if (m_wallet->is_trusted_daemon())
{
try
{
m_wallet->rescan_spent();
}
catch (const std::exception &e)
{
message_writer() << tr("Failed to update spent status after importing multisig info: ") << e.what();
return false;
}
}
else
{
message_writer() << tr("Untrusted daemon, spent status may be incorrect. Use a trusted daemon and run \"rescan_spent\"");
return false;
}
return true;
}
bool simple_wallet::accept_loaded_tx(const tools::wallet2::multisig_tx_set &txs)
{
std::string extra_message;
return accept_loaded_tx([&txs](){return txs.m_ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.m_ptx[n].construction_data;}, extra_message);
}
bool simple_wallet::sign_multisig(const std::vector<std::string> &args)
{
sign_multisig_main(args, false);
return true;
}
bool simple_wallet::sign_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
{
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return false;
}
if(!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This is not a multisig wallet");
return false;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return false;
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_SIGN_MULTISIG);
return false;
}
SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
std::string filename = args[0];
std::vector<crypto::hash> txids;
uint32_t signers = 0;
try
{
if (called_by_mms)
{
tools::wallet2::multisig_tx_set exported_txs;
std::string ciphertext;
bool r = m_wallet->load_multisig_tx(args[0], exported_txs, [&](const tools::wallet2::multisig_tx_set &tx){ signers = tx.m_signers.size(); return accept_loaded_tx(tx); });
if (r)
{
r = m_wallet->sign_multisig_tx(exported_txs, txids);
}
if (r)
{
ciphertext = m_wallet->save_multisig_tx(exported_txs);
if (ciphertext.empty())
{
r = false;
}
}
if (r)
{
mms::message_type message_type = mms::message_type::fully_signed_tx;
if (txids.empty())
{
message_type = mms::message_type::partially_signed_tx;
}
get_message_store().process_wallet_created_data(get_multisig_wallet_state(), message_type, ciphertext);
filename = "MMS"; // for the messages below
}
else
{
fail_msg_writer() << tr("Failed to sign multisig transaction");
return false;
}
}
else
{
bool r = m_wallet->sign_multisig_tx_from_file(filename, txids, [&](const tools::wallet2::multisig_tx_set &tx){ signers = tx.m_signers.size(); return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to sign multisig transaction");
return false;
}
}
}
catch (const tools::error::multisig_export_needed& e)
{
fail_msg_writer() << tr("Multisig error: ") << e.what();
return false;
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to sign multisig transaction: ") << e.what();
return false;
}
if (txids.empty())
{
uint32_t threshold;
m_wallet->multisig(NULL, &threshold);
uint32_t signers_needed = threshold - signers - 1;
success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", "
<< signers_needed << " more signer(s) needed";
return true;
}
else
{
std::string txids_as_text;
for (const auto &txid: txids)
{
if (!txids_as_text.empty())
txids_as_text += (", ");
txids_as_text += epee::string_tools::pod_to_hex(txid);
}
success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", txid " << txids_as_text;
success_msg_writer(true) << tr("It may be relayed to the network with submit_multisig");
}
return true;
}
bool simple_wallet::submit_multisig(const std::vector<std::string> &args)
{
submit_multisig_main(args, false);
return true;
}
bool simple_wallet::submit_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
{
bool ready;
uint32_t threshold;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return false;
}
if (!m_wallet->multisig(&ready, &threshold))
{
fail_msg_writer() << tr("This is not a multisig wallet");
return false;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return false;
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_SUBMIT_MULTISIG);
return false;
}
if (!try_connect_to_daemon())
return false;
SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
std::string filename = args[0];
try
{
tools::wallet2::multisig_tx_set txs;
if (called_by_mms)
{
bool r = m_wallet->load_multisig_tx(args[0], txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to load multisig transaction from MMS");
return false;
}
}
else
{
bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to load multisig transaction from file");
return false;
}
}
if (txs.m_signers.size() < threshold)
{
fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
% txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
return false;
}
// actually commit the transactions
for (auto &ptx: txs.m_ptx)
{
m_wallet->commit_tx(ptx);
success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << get_transaction_hash(ptx.tx) << ENDL
<< tr("You can check its status by using the `show_transfers` command.");
}
}
catch (const std::exception &e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
return false;
}
return true;
}
bool simple_wallet::export_raw_multisig(const std::vector<std::string> &args)
{
bool ready;
uint32_t threshold;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->multisig(&ready, &threshold))
{
fail_msg_writer() << tr("This is not a multisig wallet");
return true;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return true;
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_EXPORT_RAW_MULTISIG_TX);
return true;
}
std::string filename = args[0];
if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK();
try
{
tools::wallet2::multisig_tx_set txs;
bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to load multisig transaction from file");
return true;
}
if (txs.m_signers.size() < threshold)
{
fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
% txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
return true;
}
// save the transactions
std::string filenames;
for (auto &ptx: txs.m_ptx)
{
const crypto::hash txid = cryptonote::get_transaction_hash(ptx.tx);
const std::string filename = std::string("raw_multisig_swap_tx_") + epee::string_tools::pod_to_hex(txid);
if (!filenames.empty())
filenames += ", ";
filenames += filename;
if (!m_wallet->save_to_file(filename, cryptonote::tx_to_blob(ptx.tx)))
{
fail_msg_writer() << tr("Failed to export multisig transaction to file ") << filename;
return true;
}
}
success_msg_writer() << tr("Saved exported multisig transaction file(s): ") << filenames;
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << tr("unexpected error: ") << e.what();
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
bool simple_wallet::print_ring(const std::vector<std::string> &args)
{
crypto::key_image key_image;
crypto::hash txid;
if (args.size() != 1)
{
PRINT_USAGE(USAGE_PRINT_RING);
return true;
}
if (!epee::string_tools::hex_to_pod(args[0], key_image))
{
fail_msg_writer() << tr("Invalid key image");
return true;
}
// this one will always work, they're all 32 byte hex
if (!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("Invalid txid");
return true;
}
std::vector<uint64_t> ring;
std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> rings;
try
{
if (m_wallet->get_ring(key_image, ring))
rings.push_back({key_image, ring});
else if (!m_wallet->get_rings(txid, rings))
{
fail_msg_writer() << tr("Key image either not spent, or spent with mixin 0");
return true;
}
for (const auto &ring: rings)
{
std::stringstream str;
for (const auto &x: ring.second)
str << x<< " ";
// do NOT translate this "absolute" below, the lin can be used as input to set_ring
success_msg_writer() << epee::string_tools::pod_to_hex(ring.first) << " absolute " << str.str();
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to get key image ring: ") << e.what();
}
return true;
}
bool simple_wallet::set_ring(const std::vector<std::string> &args)
{
crypto::key_image key_image;
// try filename first
if (args.size() == 1)
{
if (!epee::file_io_utils::is_file_exist(args[0]))
{
fail_msg_writer() << tr("File doesn't exist");
return true;
}
char str[4096];
std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
if (f)
{
while (!feof(f.get()))
{
if (!fgets(str, sizeof(str), f.get()))
break;
const size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n')
str[len - 1] = 0;
if (!str[0])
continue;
char key_image_str[65], type_str[9];
int read_after_key_image = 0, read = 0;
int fields = sscanf(str, "%64[abcdefABCDEF0123456789] %n%8s %n", key_image_str, &read_after_key_image, type_str, &read);
if (fields != 2)
{
fail_msg_writer() << tr("Invalid ring specification: ") << str;
continue;
}
key_image_str[64] = 0;
type_str[8] = 0;
crypto::key_image key_image;
if (read_after_key_image == 0 || !epee::string_tools::hex_to_pod(key_image_str, key_image))
{
fail_msg_writer() << tr("Invalid key image: ") << str;
continue;
}
if (read == read_after_key_image+8 || (strcmp(type_str, "absolute") && strcmp(type_str, "relative")))
{
fail_msg_writer() << tr("Invalid ring type, expected relative or abosolute: ") << str;
continue;
}
bool relative = !strcmp(type_str, "relative");
if (read < 0 || (size_t)read > strlen(str))
{
fail_msg_writer() << tr("Error reading line: ") << str;
continue;
}
bool valid = true;
std::vector<uint64_t> ring;
const char *ptr = str + read;
while (*ptr)
{
unsigned long offset;
int elements = sscanf(ptr, "%lu %n", &offset, &read);
if (elements == 0 || read <= 0 || (size_t)read > strlen(str))
{
fail_msg_writer() << tr("Error reading line: ") << str;
valid = false;
break;
}
ring.push_back(offset);
ptr += read;
}
if (!valid)
continue;
if (ring.empty())
{
fail_msg_writer() << tr("Invalid ring: ") << str;
continue;
}
if (relative)
{
for (size_t n = 1; n < ring.size(); ++n)
{
if (ring[n] <= 0)
{
fail_msg_writer() << tr("Invalid relative ring: ") << str;
valid = false;
break;
}
}
}
else
{
for (size_t n = 1; n < ring.size(); ++n)
{
if (ring[n] <= ring[n-1])
{
fail_msg_writer() << tr("Invalid absolute ring: ") << str;
valid = false;
break;
}
}
}
if (!valid)
continue;
if (!m_wallet->set_ring(key_image, ring, relative))
fail_msg_writer() << tr("Failed to set ring for key image: ") << key_image << ". " << tr("Continuing.");
}
f.reset();
}
return true;
}
if (args.size() < 3)
{
PRINT_USAGE(USAGE_SET_RING);
return true;
}
if (!epee::string_tools::hex_to_pod(args[0], key_image))
{
fail_msg_writer() << tr("Invalid key image");
return true;
}
bool relative;
if (args[1] == "absolute")
{
relative = false;
}
else if (args[1] == "relative")
{
relative = true;
}
else
{
fail_msg_writer() << tr("Missing absolute or relative keyword");
return true;
}
std::vector<uint64_t> ring;
for (size_t n = 2; n < args.size(); ++n)
{
ring.resize(ring.size() + 1);
if (!string_tools::get_xtype_from_string(ring.back(), args[n]))
{
fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
return true;
}
if (relative)
{
if (ring.size() > 1 && !ring.back())
{
fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
return true;
}
uint64_t sum = 0;
for (uint64_t out: ring)
{
if (out > std::numeric_limits<uint64_t>::max() - sum)
{
fail_msg_writer() << tr("invalid index: indices wrap");
return true;
}
sum += out;
}
}
else
{
if (ring.size() > 1 && ring[ring.size() - 2] >= ring[ring.size() - 1])
{
fail_msg_writer() << tr("invalid index: indices should be in strictly ascending order");
return true;
}
}
}
if (!m_wallet->set_ring(key_image, ring, relative))
{
fail_msg_writer() << tr("failed to set ring");
return true;
}
return true;
}
bool simple_wallet::unset_ring(const std::vector<std::string> &args)
{
crypto::hash txid;
std::vector<crypto::key_image> key_images;
if (args.size() < 1)
{
PRINT_USAGE(USAGE_UNSET_RING);
return true;
}
key_images.resize(args.size());
for (size_t i = 0; i < args.size(); ++i)
{
if (!epee::string_tools::hex_to_pod(args[i], key_images[i]))
{
fail_msg_writer() << tr("Invalid key image or txid");
return true;
}
}
static_assert(sizeof(crypto::hash) == sizeof(crypto::key_image), "hash and key_image must have the same size");
memcpy(&txid, &key_images[0], sizeof(txid));
if (!m_wallet->unset_ring(key_images) && !m_wallet->unset_ring(txid))
{
fail_msg_writer() << tr("failed to unset ring");
return true;
}
return true;
}
bool simple_wallet::rpc_payment_info(const std::vector<std::string> &args)
{
if (!try_connect_to_daemon())
return true;
LOCK_IDLE_SCOPE();
try
{
bool payment_required;
uint64_t credits, diff, credits_per_hash_found, height, seed_height;
uint32_t cookie;
std::string hashing_blob;
crypto::hash seed_hash, next_seed_hash;
crypto::public_key pkey;
crypto::secret_key_to_public_key(m_wallet->get_rpc_client_secret_key(), pkey);
message_writer() << tr("RPC client ID: ") << pkey;
message_writer() << tr("RPC client secret key: ") << m_wallet->get_rpc_client_secret_key();
if (!m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie))
{
fail_msg_writer() << tr("Failed to query daemon");
return true;
}
if (payment_required)
{
uint64_t target = m_wallet->credits_target();
if (target == 0)
target = CREDITS_TARGET;
message_writer() << tr("Using daemon: ") << m_wallet->get_daemon_address();
message_writer() << tr("Payments required for node use, current credits: ") << credits;
message_writer() << tr("Credits target: ") << target;
uint64_t expected, discrepancy;
m_wallet->credit_report(expected, discrepancy);
message_writer() << tr("Credits spent this session: ") << expected;
if (expected)
message_writer() << tr("Credit discrepancy this session: ") << discrepancy << " (" << 100.0f * discrepancy / expected << "%)";
float cph = credits_per_hash_found / (float)diff;
message_writer() << tr("Difficulty: ") << diff << ", " << credits_per_hash_found << " " << tr("credits per hash found, ") << cph << " " << tr("credits/hash");;
const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
bool mining = (now - m_last_rpc_payment_mining_time).total_microseconds() < 1000000;
if (mining)
{
float hash_rate = m_rpc_payment_hash_rate;
if (hash_rate > 0)
{
message_writer() << (boost::format(tr("Mining for payment at %.1f H/s")) % hash_rate).str();
if (credits < target)
{
std::chrono::seconds seconds((unsigned)((target - credits) / cph / hash_rate));
std::string target_string = get_human_readable_timespan(seconds);
message_writer() << (boost::format(tr("Estimated time till %u credits target mined: %s")) % target % target_string).str();
}
}
else
message_writer() << tr("Mining for payment");
}
else
message_writer() << tr("Not mining");
}
else
message_writer() << tr("No payment needed for node use");
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << tr("unexpected error: ") << e.what();
}
return true;
}
bool simple_wallet::blackball(const std::vector<std::string> &args)
{
uint64_t amount = std::numeric_limits<uint64_t>::max(), offset, num_offsets;
if (args.size() == 0)
{
PRINT_USAGE(USAGE_MARK_OUTPUT_SPENT);
return true;
}
try
{
if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &amount, &offset) == 2)
{
m_wallet->blackball_output(std::make_pair(amount, offset));
}
else if (epee::file_io_utils::is_file_exist(args[0]))
{
std::vector<std::pair<uint64_t, uint64_t>> outputs;
char str[256];
std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
if (f)
{
while (!feof(f.get()))
{
if (!fgets(str, sizeof(str), f.get()))
break;
const size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n')
str[len - 1] = 0;
if (!str[0])
continue;
if (sscanf(str, "@%" PRIu64, &amount) == 1)
{
continue;
}
if (amount == std::numeric_limits<uint64_t>::max())
{
fail_msg_writer() << tr("First line is not an amount");
return true;
}
if (sscanf(str, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets <= std::numeric_limits<uint64_t>::max() - offset)
{
while (num_offsets--)
outputs.push_back(std::make_pair(amount, offset++));
}
else if (sscanf(str, "%" PRIu64, &offset) == 1)
{
outputs.push_back(std::make_pair(amount, offset));
}
else
{
fail_msg_writer() << tr("Invalid output: ") << str;
return true;
}
}
f.reset();
bool add = false;
if (args.size() > 1)
{
if (args[1] != "add")
{
fail_msg_writer() << tr("Bad argument: ") + args[1] + ": " + tr("should be \"add\"");
return true;
}
add = true;
}
m_wallet->set_blackballed_outputs(outputs, add);
}
else
{
fail_msg_writer() << tr("Failed to open file");
return true;
}
}
else
{
fail_msg_writer() << tr("Invalid output key, and file doesn't exist");
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to mark output spent: ") << e.what();
}
return true;
}
bool simple_wallet::unblackball(const std::vector<std::string> &args)
{
std::pair<uint64_t, uint64_t> output;
if (args.size() != 1)
{
PRINT_USAGE(USAGE_MARK_OUTPUT_UNSPENT);
return true;
}
if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
{
fail_msg_writer() << tr("Invalid output");
return true;
}
try
{
m_wallet->unblackball_output(output);
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to mark output unspent: ") << e.what();
}
return true;
}
bool simple_wallet::blackballed(const std::vector<std::string> &args)
{
std::pair<uint64_t, uint64_t> output;
if (args.size() != 1)
{
PRINT_USAGE(USAGE_IS_OUTPUT_SPENT);
return true;
}
if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
{
fail_msg_writer() << tr("Invalid output");
return true;
}
try
{
if (m_wallet->is_output_blackballed(output))
message_writer() << tr("Spent: ") << output.first << "/" << output.second;
else
message_writer() << tr("Not spent: ") << output.first << "/" << output.second;
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to check whether output is spent: ") << e.what();
}
return true;
}
bool simple_wallet::save_known_rings(const std::vector<std::string> &args)
{
try
{
LOCK_IDLE_SCOPE();
m_wallet->find_and_save_rings();
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to save known rings: ") << e.what();
}
return true;
}
bool simple_wallet::freeze_thaw(const std::vector<std::string> &args, bool freeze)
{
if (args.empty())
{
fail_msg_writer() << boost::format(tr("usage: %s <key_image>|<pubkey>")) % (freeze ? "freeze" : "thaw");
return true;
}
crypto::key_image ki;
if (!epee::string_tools::hex_to_pod(args[0], ki))
{
fail_msg_writer() << tr("failed to parse key image");
return true;
}
try
{
if (freeze)
m_wallet->freeze(ki);
else
m_wallet->thaw(ki);
}
catch (const std::exception &e)
{
fail_msg_writer() << e.what();
return true;
}
return true;
}
bool simple_wallet::freeze(const std::vector<std::string> &args)
{
return freeze_thaw(args, true);
}
bool simple_wallet::thaw(const std::vector<std::string> &args)
{
return freeze_thaw(args, false);
}
bool simple_wallet::frozen(const std::vector<std::string> &args)
{
if (args.empty())
{
size_t ntd = m_wallet->get_num_transfer_details();
for (size_t i = 0; i < ntd; ++i)
{
if (!m_wallet->frozen(i))
continue;
const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i);
message_writer() << tr("Frozen: ") << td.m_key_image << " " << cryptonote::print_money(td.amount());
}
}
else
{
crypto::key_image ki;
if (!epee::string_tools::hex_to_pod(args[0], ki))
{
fail_msg_writer() << tr("failed to parse key image");
return true;
}
if (m_wallet->frozen(ki))
message_writer() << tr("Frozen: ") << ki;
else
message_writer() << tr("Not frozen: ") << ki;
}
return true;
}
bool simple_wallet::lock(const std::vector<std::string> &args)
{
m_locked = true;
check_for_inactivity_lock(true);
return true;
}
bool simple_wallet::net_stats(const std::vector<std::string> &args)
{
message_writer() << std::to_string(m_wallet->get_bytes_sent()) + tr(" bytes sent");
message_writer() << std::to_string(m_wallet->get_bytes_received()) + tr(" bytes received");
return true;
}
bool simple_wallet::public_nodes(const std::vector<std::string> &args)
{
try
{
auto nodes = m_wallet->get_public_nodes(false);
m_claimed_cph.clear();
if (nodes.empty())
{
fail_msg_writer() << tr("No known public nodes");
return true;
}
std::sort(nodes.begin(), nodes.end(), [](const public_node &node0, const public_node &node1) {
if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash == 0)
return true;
if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash)
return node0.rpc_credits_per_hash < node1.rpc_credits_per_hash;
return false;
});
const uint64_t now = time(NULL);
message_writer() << boost::format("%32s %12s %16s") % tr("address") % tr("credits/hash") % tr("last_seen");
for (const auto &node: nodes)
{
const float cph = node.rpc_credits_per_hash / RPC_CREDITS_PER_HASH_SCALE;
char cphs[9];
snprintf(cphs, sizeof(cphs), "%.3f", cph);
const std::string last_seen = node.last_seen == 0 ? tr("never") : get_human_readable_timespan(std::chrono::seconds(now - node.last_seen));
std::string host = node.host + ":" + std::to_string(node.rpc_port);
message_writer() << boost::format("%32s %12s %16s") % host % cphs % last_seen;
m_claimed_cph[host] = node.rpc_credits_per_hash;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Error retrieving public node list: ") << e.what();
}
return true;
}
bool simple_wallet::welcome(const std::vector<std::string> &args)
{
message_writer() << tr("Welcome to Swap, the private cryptocurrency.");
message_writer() << "";
message_writer() << tr("Swap, like Bitcoin, is a cryptocurrency. That is, it is digital money.");
message_writer() << tr("Unlike Bitcoin, your Swap transactions and balance stay private and are not visible to the world by default.");
message_writer() << tr("However, you have the option of making those available to select parties if you choose to.");
message_writer() << "";
message_writer() << tr("Swap protects your privacy on the blockchain, and while Swap strives to improve all the time,");
message_writer() << tr("no privacy technology can be 100% perfect, Swap included.");
message_writer() << tr("Swap cannot protect you from malware, and it may not be as effective as we hope against powerful adversaries.");
message_writer() << tr("Flaws in Swap may be discovered in the future, and attacks may be developed to peek under some");
message_writer() << tr("of the layers of privacy Swap provides. Be safe and practice defense in depth.");
message_writer() << "";
message_writer() << tr("Welcome to Swap and financial privacy. For more information see https://xwp.one");
return true;
}
bool simple_wallet::version(const std::vector<std::string> &args)
{
message_writer() << "Swap '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")";
return true;
}
bool simple_wallet::on_unknown_command(const std::vector<std::string> &args)
{
if (args[0] == "exit" || args[0] == "q") // backward compat
return false;
fail_msg_writer() << boost::format(tr("Unknown command '%s', try 'help'")) % args.front();
return true;
}
bool simple_wallet::on_empty_command()
{
return true;
}
bool simple_wallet::on_cancelled_command()
{
check_for_inactivity_lock(false);
return true;
}
bool simple_wallet::cold_sign_tx(const std::vector<tools::wallet2::pending_tx>& ptx_vector, tools::wallet2::signed_tx_set &exported_txs, std::vector<cryptonote::address_parse_info> &dsts_info, std::function<bool(const tools::wallet2::signed_tx_set &)> accept_func)
{
std::vector<std::string> tx_aux;
message_writer(console_color_white, false) << tr("Please confirm the transaction on the device");
m_wallet->cold_sign_tx(ptx_vector, exported_txs, dsts_info, tx_aux);
if (accept_func && !accept_func(exported_txs))
{
MERROR("Transactions rejected by callback");
return false;
}
// aux info
m_wallet->cold_tx_aux_import(exported_txs.ptx, tx_aux);
// import key images
return m_wallet->import_key_images(exported_txs, 0, true);
}
bool simple_wallet::start_mining_for_rpc(const std::vector<std::string> &args)
{
if (!try_connect_to_daemon())
return true;
LOCK_IDLE_SCOPE();
bool payment_required;
uint64_t credits, diff, credits_per_hash_found, height, seed_height;
uint32_t cookie;
std::string hashing_blob;
crypto::hash seed_hash, next_seed_hash;
if (!m_wallet->get_rpc_payment_info(true, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie))
{
fail_msg_writer() << tr("Failed to query daemon");
return true;
}
if (!payment_required)
{
fail_msg_writer() << tr("Daemon does not require payment for RPC access");
return true;
}
m_rpc_payment_mining_requested = true;
m_rpc_payment_checker.trigger();
const float cph = credits_per_hash_found / (float)diff;
bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE);
success_msg_writer() << (boost::format(tr("Starting mining for RPC access: diff %llu, %f credits/hash%s")) % diff % cph % (low ? " - this is low" : "")).str();
success_msg_writer() << tr("Run stop_mining_for_rpc to stop");
return true;
}
bool simple_wallet::stop_mining_for_rpc(const std::vector<std::string> &args)
{
if (!try_connect_to_daemon())
return true;
LOCK_IDLE_SCOPE();
m_rpc_payment_mining_requested = false;
m_last_rpc_payment_mining_time = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1));
m_rpc_payment_hash_rate = -1.0f;
return true;
}
bool simple_wallet::set_always_confirm_transfers(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->always_confirm_transfers(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_print_ring_members(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->print_ring_members(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_store_tx_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot transfer");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->store_tx_info(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_default_ring_size(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot transfer");
return true;
}
try
{
if (strchr(args[1].c_str(), '-'))
{
fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE;
return true;
}
uint32_t ring_size = boost::lexical_cast<uint32_t>(args[1]);
if (ring_size < MIN_RING_SIZE && ring_size != 0)
{
fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE;
return true;
}
if (ring_size != 0 && ring_size != DEFAULT_MIX+1)
{
if (m_wallet->use_fork_rules(8, 0))
{
message_writer() << tr("WARNING: from v8, ring size will be fixed and this setting will be ignored.");
}
else
{
message_writer() << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended.");
}
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->default_mixin(ring_size > 0 ? ring_size - 1 : 0);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
catch(const boost::bad_lexical_cast &)
{
fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE;
return true;
}
catch(...)
{
fail_msg_writer() << tr("could not change default ring size");
return true;
}
}
bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint32_t priority = 0;
try
{
if (strchr(args[1].c_str(), '-'))
{
fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
return true;
}
if (args[1] == "0")
{
priority = 0;
}
else
{
bool found = false;
for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
{
if (allowed_priority_strings[n] == args[1])
{
found = true;
priority = n;
}
}
if (!found)
{
priority = boost::lexical_cast<int>(args[1]);
if (priority < 1 || priority > 4)
{
fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
return true;
}
}
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_default_priority(priority);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
catch(const boost::bad_lexical_cast &)
{
fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
return true;
}
catch(...)
{
fail_msg_writer() << tr("could not change default priority");
return true;
}
}
bool simple_wallet::set_auto_refresh(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool auto_refresh) {
m_auto_refresh_enabled.store(false, std::memory_order_relaxed);
m_wallet->auto_refresh(auto_refresh);
m_idle_mutex.lock();
m_auto_refresh_enabled.store(auto_refresh, std::memory_order_relaxed);
m_idle_cond.notify_one();
m_idle_mutex.unlock();
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_refresh_type(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
tools::wallet2::RefreshType refresh_type;
if (!parse_refresh_type(args[1], refresh_type))
{
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_refresh_type(refresh_type);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_ask_password(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
tools::wallet2::AskPasswordType ask = tools::wallet2::AskPasswordToDecrypt;
if (args[1] == "never" || args[1] == "0")
ask = tools::wallet2::AskPasswordNever;
else if (args[1] == "action" || args[1] == "1")
ask = tools::wallet2::AskPasswordOnAction;
else if (args[1] == "encrypt" || args[1] == "decrypt" || args[1] == "2")
ask = tools::wallet2::AskPasswordToDecrypt;
else
{
fail_msg_writer() << tr("invalid argument: must be either 0/never, 1/action, or 2/encrypt/decrypt");
return true;
}
const tools::wallet2::AskPasswordType cur_ask = m_wallet->ask_password();
if (!m_wallet->watch_only())
{
if (cur_ask == tools::wallet2::AskPasswordToDecrypt && ask != tools::wallet2::AskPasswordToDecrypt)
m_wallet->decrypt_keys(pwd_container->password());
else if (cur_ask != tools::wallet2::AskPasswordToDecrypt && ask == tools::wallet2::AskPasswordToDecrypt)
m_wallet->encrypt_keys(pwd_container->password());
}
m_wallet->ask_password(ask);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_unit(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const std::string &unit = args[1];
unsigned int decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
if (unit == "swap")
decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
else if (unit == "swapini")
decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 6;
else if (unit == "atoms")
decimal_point = 0;
else
{
fail_msg_writer() << tr("invalid unit");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
cryptonote::set_default_decimal_point(decimal_point);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_min_output_count(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint32_t count;
if (!string_tools::get_xtype_from_string(count, args[1]))
{
fail_msg_writer() << tr("invalid count: must be an unsigned integer");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_min_output_count(count);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_min_output_value(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint64_t value;
if (!cryptonote::parse_amount(value, args[1]))
{
fail_msg_writer() << tr("invalid value");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_min_output_value(value);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_merge_destinations(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->merge_destinations(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_confirm_backlog(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->confirm_backlog(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_confirm_backlog_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint32_t threshold;
if (!string_tools::get_xtype_from_string(threshold, args[1]))
{
fail_msg_writer() << tr("invalid count: must be an unsigned integer");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_confirm_backlog_threshold(threshold);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_confirm_export_overwrite(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->confirm_export_overwrite(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_refresh_from_block_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint64_t height;
if (!epee::string_tools::get_xtype_from_string(height, args[1]))
{
fail_msg_writer() << tr("Invalid height");
return true;
}
m_wallet->set_refresh_from_block_height(height);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_auto_low_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->auto_low_priority(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_segregate_pre_fork_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->segregate_pre_fork_outputs(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_persistent_rpc_client_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->persistent_rpc_client_id(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_auto_mine_for_rpc_payment_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
float threshold;
if (!epee::string_tools::get_xtype_from_string(threshold, args[1]) || threshold < 0.0f)
{
fail_msg_writer() << tr("Invalid threshold");
return true;
}
m_wallet->auto_mine_for_rpc_payment_threshold(threshold);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_credits_target(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint64_t target;
if (!epee::string_tools::get_xtype_from_string(target, args[1]))
{
fail_msg_writer() << tr("Invalid target");
return true;
}
m_wallet->credits_target(target);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_key_reuse_mitigation2(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->key_reuse_mitigation2(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_subaddress_lookahead(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
auto lookahead = parse_subaddress_lookahead(args[1]);
if (lookahead)
{
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
}
return true;
}
bool simple_wallet::set_segregation_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint64_t height;
if (!epee::string_tools::get_xtype_from_string(height, args[1]))
{
fail_msg_writer() << tr("Invalid height");
return true;
}
m_wallet->segregation_height(height);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_ignore_fractional_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->ignore_fractional_outputs(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_ignore_outputs_above(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint64_t amount;
if (!cryptonote::parse_amount(amount, args[1]))
{
fail_msg_writer() << tr("Invalid amount");
return true;
}
if (amount == 0)
amount = MONEY_SUPPLY;
m_wallet->ignore_outputs_above(amount);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_ignore_outputs_below(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint64_t amount;
if (!cryptonote::parse_amount(amount, args[1]))
{
fail_msg_writer() << tr("Invalid amount");
return true;
}
m_wallet->ignore_outputs_below(amount);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_track_uses(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->track_uses(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_inactivity_lock_timeout(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
#ifdef _WIN32
tools::fail_msg_writer() << tr("Inactivity lock timeout disabled on Windows");
return true;
#endif
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint32_t r;
if (epee::string_tools::get_xtype_from_string(r, args[1]))
{
m_wallet->inactivity_lock_timeout(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
else
{
tools::fail_msg_writer() << tr("Invalid number of seconds");
}
}
return true;
}
bool simple_wallet::set_setup_background_mining(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
tools::wallet2::BackgroundMiningSetupType setup = tools::wallet2::BackgroundMiningMaybe;
if (args[1] == "yes" || args[1] == "1")
setup = tools::wallet2::BackgroundMiningYes;
else if (args[1] == "no" || args[1] == "0")
setup = tools::wallet2::BackgroundMiningNo;
else
{
fail_msg_writer() << tr("invalid argument: must be either 1/yes or 0/no");
return true;
}
m_wallet->setup_background_mining(setup);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
if (setup == tools::wallet2::BackgroundMiningYes)
start_background_mining();
else
stop_background_mining();
}
return true;
}
bool simple_wallet::set_device_name(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
if (args.size() == 0){
fail_msg_writer() << tr("Device name not specified");
return true;
}
m_wallet->device_name(args[1]);
bool r = false;
try {
r = m_wallet->reconnect_device();
if (!r){
fail_msg_writer() << tr("Device reconnect failed");
}
} catch(const std::exception & e){
MWARNING("Device reconnect failed: " << e.what());
fail_msg_writer() << tr("Device reconnect failed: ") << e.what();
}
}
return true;
}
bool simple_wallet::set_export_format(const std::vector<std::string> &args/* = std::vector<std::string()*/)
{
if (args.size() < 2)
{
fail_msg_writer() << tr("Export format not specified");
return true;
}
if (boost::algorithm::iequals(args[1], "ascii"))
{
m_wallet->set_export_format(tools::wallet2::ExportFormat::Ascii);
}
else if (boost::algorithm::iequals(args[1], "binary"))
{
m_wallet->set_export_format(tools::wallet2::ExportFormat::Binary);
}
else
{
fail_msg_writer() << tr("Export format not recognized.");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::help(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if(args.empty())
{
success_msg_writer() << get_commands_str();
}
else if ((args.size() == 2) && (args.front() == "mms"))
{
// Little hack to be able to do "help mms <subcommand>"
std::vector<std::string> mms_args(1, args.front() + " " + args.back());
success_msg_writer() << get_command_usage(mms_args);
}
else
{
success_msg_writer() << get_command_usage(args);
}
return true;
}
simple_wallet::simple_wallet()
: m_allow_mismatched_daemon_version(false)
, m_refresh_progress_reporter(*this)
, m_idle_run(true)
, m_auto_refresh_enabled(false)
, m_auto_refresh_refreshing(false)
, m_in_manual_refresh(false)
, m_current_subaddress_account(0)
, m_last_activity_time(time(NULL))
, m_locked(false)
, m_in_command(false)
, m_need_payment(false)
, m_rpc_payment_mining_requested(false)
, m_last_rpc_payment_mining_time(boost::gregorian::date(1970, 1, 1))
, m_daemon_rpc_payment_message_displayed(false)
, m_rpc_payment_hash_rate(-1.0f)
, m_suspend_rpc_payment_mining(false)
{
m_cmd_binder.set_handler("start_mining",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::start_mining, _1),
tr(USAGE_START_MINING),
tr("Start mining in the daemon (bg_mining and ignore_battery are optional booleans)."));
m_cmd_binder.set_handler("stop_mining",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::stop_mining, _1),
tr("Stop mining in the daemon."));
m_cmd_binder.set_handler("set_daemon",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_daemon, _1),
tr(USAGE_SET_DAEMON),
tr("Set another daemon to connect to."));
m_cmd_binder.set_handler("save_bc",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_bc, _1),
tr("Save the current blockchain data."));
m_cmd_binder.set_handler("refresh",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::refresh, _1),
tr("Synchronize the transactions and balance."));
m_cmd_binder.set_handler("balance",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_balance, _1),
tr(USAGE_SHOW_BALANCE),
tr("Show the wallet's balance of the currently selected account."));
m_cmd_binder.set_handler("incoming_transfers",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_incoming_transfers,_1),
tr(USAGE_INCOMING_TRANSFERS),
tr("Show the incoming transfers, all or filtered by availability and address index.\n\n"
"Output format:\n"
"Amount, Spent(\"T\"|\"F\"), \"frozen\"|\"locked\"|\"unlocked\", RingCT, Global Index, Transaction Hash, Address Index, [Public Key, Key Image] "));
m_cmd_binder.set_handler("payments",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_payments,_1),
tr(USAGE_PAYMENTS),
tr("Show the payments for the given payment IDs."));
m_cmd_binder.set_handler("bc_height",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_blockchain_height, _1),
tr("Show the blockchain height."));
m_cmd_binder.set_handler("transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::transfer, _1),
tr(USAGE_TRANSFER),
tr("Transfer <amount> to <address>. If the parameter \"index=<N1>[,<N2>,...]\" is specified, the wallet uses outputs received by addresses of those indices. If omitted, the wallet randomly chooses address indices to be used. In any case, it tries its best not to combine outputs across multiple addresses. <priority> is the priority of the transaction. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability. Multiple payments can be made at once by adding URI_2 or <address_2> <amount_2> etcetera (before the payment ID, if it's included)"));
m_cmd_binder.set_handler("locked_transfer",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::locked_transfer,_1),
tr(USAGE_LOCKED_TRANSFER),
tr("Transfer <amount> to <address> and lock it for <lockblocks> (max. 1000000). If the parameter \"index=<N1>[,<N2>,...]\" is specified, the wallet uses outputs received by addresses of those indices. If omitted, the wallet randomly chooses address indices to be used. In any case, it tries its best not to combine outputs across multiple addresses. <priority> is the priority of the transaction. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability. Multiple payments can be made at once by adding URI_2 or <address_2> <amount_2> etcetera (before the payment ID, if it's included)"));
m_cmd_binder.set_handler("locked_sweep_all",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::locked_sweep_all,_1),
tr(USAGE_LOCKED_SWEEP_ALL),
tr("Send all unlocked balance to an address and lock it for <lockblocks> (max. 1000000). If the parameter \"index<N1>[,<N2>,...]\" is specified, the wallet sweeps outputs received by those address indices. If omitted, the wallet randomly chooses an address index to be used. <priority> is the priority of the sweep. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability."));
m_cmd_binder.set_handler("sweep_unmixable",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_unmixable, _1),
tr("Send all unmixable outputs to yourself with ring_size 1"));
m_cmd_binder.set_handler("sweep_all", boost::bind(&simple_wallet::sweep_all, this, _1),
tr(USAGE_SWEEP_ALL),
tr("Send all unlocked balance to an address. If the parameter \"index<N1>[,<N2>,...]\" is specified, the wallet sweeps outputs received by those address indices. If omitted, the wallet randomly chooses an address index to be used. If the parameter \"outputs=<N>\" is specified and N > 0, wallet splits the transaction into N even outputs."));
m_cmd_binder.set_handler("sweep_below",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_below, _1),
tr(USAGE_SWEEP_BELOW),
tr("Send all unlocked outputs below the threshold to an address."));
m_cmd_binder.set_handler("sweep_single",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_single, _1),
tr(USAGE_SWEEP_SINGLE),
tr("Send a single output of the given key image to an address without change."));
m_cmd_binder.set_handler("donate",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::donate, _1),
tr(USAGE_DONATE),
tr("Donate <amount> to the development team (donate.getmonero.org)."));
m_cmd_binder.set_handler("sign_transfer",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_transfer, _1),
tr(USAGE_SIGN_TRANSFER),
tr("Sign a transaction from a file. If the parameter \"export_raw\" is specified, transaction raw hex data suitable for the daemon RPC /sendrawtransaction is exported."));
m_cmd_binder.set_handler("submit_transfer",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_transfer, _1),
tr("Submit a signed transaction from a file."));
m_cmd_binder.set_handler("set_log",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_log, _1),
tr(USAGE_SET_LOG),
tr("Change the current log detail (level must be <0-4>)."));
m_cmd_binder.set_handler("account",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::account, _1),
tr(USAGE_ACCOUNT),
tr("If no arguments are specified, the wallet shows all the existing accounts along with their balances.\n"
"If the \"new\" argument is specified, the wallet creates a new account with its label initialized by the provided label text (which can be empty).\n"
"If the \"switch\" argument is specified, the wallet switches to the account specified by <index>.\n"
"If the \"label\" argument is specified, the wallet sets the label of the account specified by <index> to the provided label text.\n"
"If the \"tag\" argument is specified, a tag <tag_name> is assigned to the specified accounts <account_index_1>, <account_index_2>, ....\n"
"If the \"untag\" argument is specified, the tags assigned to the specified accounts <account_index_1>, <account_index_2> ..., are removed.\n"
"If the \"tag_description\" argument is specified, the tag <tag_name> is assigned an arbitrary text <description>."));
m_cmd_binder.set_handler("address",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_address, _1),
tr(USAGE_ADDRESS),
tr("If no arguments are specified or <index> is specified, the wallet shows the default or specified address. If \"all\" is specified, the wallet shows all the existing addresses in the currently selected account. If \"new \" is specified, the wallet creates a new address with the provided label text (which can be empty). If \"label\" is specified, the wallet sets the label of the address specified by <index> to the provided label text."));
m_cmd_binder.set_handler("integrated_address",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_integrated_address, _1),
tr(USAGE_INTEGRATED_ADDRESS),
tr("Encode a payment ID into an integrated address for the current wallet public address (no argument uses a random payment ID), or decode an integrated address to standard address and payment ID"));
m_cmd_binder.set_handler("address_book",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::address_book,_1),
tr(USAGE_ADDRESS_BOOK),
tr("Print all entries in the address book, optionally adding/deleting an entry to/from it."));
m_cmd_binder.set_handler("save",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::save, _1),
tr("Save the wallet data."));
m_cmd_binder.set_handler("save_watch_only",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_watch_only, _1),
tr("Save a watch-only keys file."));
m_cmd_binder.set_handler("viewkey",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::viewkey, _1),
tr("Display the private view key."));
m_cmd_binder.set_handler("spendkey",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::spendkey, _1),
tr("Display the private spend key."));
m_cmd_binder.set_handler("seed",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::seed, _1),
tr("Display the Electrum-style mnemonic seed"));
m_cmd_binder.set_handler("restore_height",
boost::bind(&simple_wallet::restore_height, this, _1),
tr("Display the restore height"));
m_cmd_binder.set_handler("set",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_variable, _1),
tr(USAGE_SET_VARIABLE),
tr("Available options:\n "
"seed language\n "
" Set the wallet's seed language.\n "
"always-confirm-transfers <1|0>\n "
" Whether to confirm unsplit txes.\n "
"print-ring-members <1|0>\n "
" Whether to print detailed information about ring members during confirmation.\n "
"store-tx-info <1|0>\n "
" Whether to store outgoing tx info (destination address, payment ID, tx secret key) for future reference.\n "
"default-ring-size <n>\n "
" Set the default ring size (obsolete).\n "
"auto-refresh <1|0>\n "
" Whether to automatically synchronize new blocks from the daemon.\n "
"refresh-type <full|optimize-coinbase|no-coinbase|default>\n "
" Set the wallet's refresh behaviour.\n "
"priority [0|1|2|3|4]\n "
" Set the fee to default/unimportant/normal/elevated/priority.\n "
"confirm-missing-payment-id <1|0> (obsolete)\n "
"ask-password <0|1|2 (or never|action|decrypt)>\n "
" action: ask the password before many actions such as transfer, etc\n "
" decrypt: same as action, but keeps the spend key encrypted in memory when not needed\n "
"unit <swap|swapini|atoms>\n "
" Set the default swap (sub-)unit.\n "
"min-outputs-count [n]\n "
" Try to keep at least that many outputs of value at least min-outputs-value.\n "
"min-outputs-value [n]\n "
" Try to keep at least min-outputs-count outputs of at least that value.\n "
"merge-destinations <1|0>\n "
" Whether to merge multiple payments to the same destination address.\n "
"confirm-backlog <1|0>\n "
" Whether to warn if there is transaction backlog.\n "
"confirm-backlog-threshold [n]\n "
" Set a threshold for confirm-backlog to only warn if the transaction backlog is greater than n blocks.\n "
"confirm-export-overwrite <1|0>\n "
" Whether to warn if the file to be exported already exists.\n "
"refresh-from-block-height [n]\n "
" Set the height before which to ignore blocks.\n "
"auto-low-priority <1|0>\n "
" Whether to automatically use the low priority fee level when it's safe to do so.\n "
"segregate-pre-fork-outputs <1|0>\n "
" Set this if you intend to spend outputs on both Swap AND a key reusing fork.\n "
"key-reuse-mitigation2 <1|0>\n "
" Set this if you are not sure whether you will spend on a key reusing Swap fork later.\n "
"subaddress-lookahead <major>:<minor>\n "
" Set the lookahead sizes for the subaddress hash table.\n "
"segregation-height <n>\n "
" Set to the height of a key reusing fork you want to use, 0 to use default.\n "
"ignore-fractional-outputs <1|0>\n "
" Whether to ignore fractional outputs that result in net loss when spending due to fee.\n "
"ignore-outputs-above <amount>\n "
" Ignore outputs of amount above this threshold when spending. Value 0 is translated to the maximum value (18 million) which disables this filter.\n "
"ignore-outputs-below <amount>\n "
" Ignore outputs of amount below this threshold when spending.\n "
"track-uses <1|0>\n "
" Whether to keep track of owned outputs uses.\n "
"setup-background-mining <1|0>\n "
" Whether to enable background mining. Set this to support the network and to get a chance to receive new Swap.\n "
"device-name <device_name[:device_spec]>\n "
" Device name for hardware wallet.\n "
"export-format <\"binary\"|\"ascii\">\n "
" Save all exported files as binary (cannot be copied and pasted) or ascii (can be).\n "
"persistent-client-id <1|0>\n "
" Whether to keep using the same client id for RPC payment over wallet restarts.\n"
"auto-mine-for-rpc-payment-threshold <float>\n "
" Whether to automatically start mining for RPC payment if the daemon requires it.\n"
"credits-target <unsigned int>\n"
" The RPC payment credits balance to target (0 for default)."));
m_cmd_binder.set_handler("encrypted_seed",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::encrypted_seed, _1),
tr("Display the encrypted Electrum-style mnemonic seed."));
m_cmd_binder.set_handler("rescan_spent",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_spent, _1),
tr("Rescan the blockchain for spent outputs."));
m_cmd_binder.set_handler("get_tx_key",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_key, _1),
tr(USAGE_GET_TX_KEY),
tr("Get the transaction key (r) for a given <txid>."));
m_cmd_binder.set_handler("set_tx_key",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_key, _1),
tr(USAGE_SET_TX_KEY),
tr("Set the transaction key (r) for a given <txid> in case the tx was made by some other device or 3rd party wallet."));
m_cmd_binder.set_handler("check_tx_key",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_key, _1),
tr(USAGE_CHECK_TX_KEY),
tr("Check the amount going to <address> in <txid>."));
m_cmd_binder.set_handler("get_tx_proof",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_proof, _1),
tr(USAGE_GET_TX_PROOF),
tr("Generate a signature proving funds sent to <address> in <txid>, optionally with a challenge string <message>, using either the transaction secret key (when <address> is not your wallet's address) or the view secret key (otherwise), which does not disclose the secret key."));
m_cmd_binder.set_handler("check_tx_proof",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_proof, _1),
tr(USAGE_CHECK_TX_PROOF),
tr("Check the proof for funds going to <address> in <txid> with the challenge string <message> if any."));
m_cmd_binder.set_handler("get_spend_proof",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_spend_proof, _1),
tr(USAGE_GET_SPEND_PROOF),
tr("Generate a signature proving that you generated <txid> using the spend secret key, optionally with a challenge string <message>."));
m_cmd_binder.set_handler("check_spend_proof",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_spend_proof, _1),
tr(USAGE_CHECK_SPEND_PROOF),
tr("Check a signature proving that the signer generated <txid>, optionally with a challenge string <message>."));
m_cmd_binder.set_handler("get_reserve_proof",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_reserve_proof, _1),
tr(USAGE_GET_RESERVE_PROOF),
tr("Generate a signature proving that you own at least this much, optionally with a challenge string <message>.\n"
"If 'all' is specified, you prove the entire sum of all of your existing accounts' balances.\n"
"Otherwise, you prove the reserve of the smallest possible amount above <amount> available in your current account."));
m_cmd_binder.set_handler("check_reserve_proof",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_reserve_proof, _1),
tr(USAGE_CHECK_RESERVE_PROOF),
tr("Check a signature proving that the owner of <address> holds at least this much, optionally with a challenge string <message>."));
m_cmd_binder.set_handler("show_transfers",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfers, _1),
tr(USAGE_SHOW_TRANSFERS),
// Seemingly broken formatting to compensate for the backslash before the quotes.
tr("Show the incoming/outgoing transfers within an optional height range.\n\n"
"Output format:\n"
"In or Coinbase: Block Number, \"block\"|\"in\", Time, Amount, Transaction Hash, Payment ID, Subaddress Index, \"-\", Note\n"
"Out: Block Number, \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Destinations, Input addresses**, \"-\", Note\n"
"Pool: \"pool\", \"in\", Time, Amount, Transaction Hash, Payment Id, Subaddress Index, \"-\", Note, Double Spend Note\n"
"Pending or Failed: \"failed\"|\"pending\", \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Input addresses**, \"-\", Note\n\n"
"* Excluding change and fee.\n"
"** Set of address indices used as inputs in this transfer."));
m_cmd_binder.set_handler("export_transfers",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_transfers, _1),
tr("export_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<filepath>]"),
tr("Export to CSV the incoming/outgoing transfers within an optional height range."));
m_cmd_binder.set_handler("unspent_outputs",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::unspent_outputs, _1),
tr(USAGE_UNSPENT_OUTPUTS),
tr("Show the unspent outputs of a specified address within an optional amount range."));
m_cmd_binder.set_handler("rescan_bc",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_blockchain, _1),
tr(USAGE_RESCAN_BC),
tr("Rescan the blockchain from scratch. If \"hard\" is specified, you will lose any information which can not be recovered from the blockchain itself."));
m_cmd_binder.set_handler("set_tx_note",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_note, _1),
tr(USAGE_SET_TX_NOTE),
tr("Set an arbitrary string note for a <txid>."));
m_cmd_binder.set_handler("get_tx_note",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_note, _1),
tr(USAGE_GET_TX_NOTE),
tr("Get a string note for a txid."));
m_cmd_binder.set_handler("set_description",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_description, _1),
tr(USAGE_SET_DESCRIPTION),
tr("Set an arbitrary description for the wallet."));
m_cmd_binder.set_handler("get_description",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_description, _1),
tr(USAGE_GET_DESCRIPTION),
tr("Get the description of the wallet."));
m_cmd_binder.set_handler("status",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::status, _1),
tr("Show the wallet's status."));
m_cmd_binder.set_handler("wallet_info",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::wallet_info, _1),
tr("Show the wallet's information."));
m_cmd_binder.set_handler("sign",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign, _1),
tr(USAGE_SIGN),
tr("Sign the contents of a file."));
m_cmd_binder.set_handler("verify",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::verify, _1),
tr(USAGE_VERIFY),
tr("Verify a signature on the contents of a file."));
m_cmd_binder.set_handler("export_key_images",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_key_images, _1),
tr(USAGE_EXPORT_KEY_IMAGES),
tr("Export a signed set of key images to a <filename>."));
m_cmd_binder.set_handler("import_key_images",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_key_images, _1),
tr(USAGE_IMPORT_KEY_IMAGES),
tr("Import a signed key images list and verify their spent status."));
m_cmd_binder.set_handler("hw_key_images_sync",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_key_images_sync, _1),
tr(USAGE_HW_KEY_IMAGES_SYNC),
tr("Synchronizes key images with the hw wallet."));
m_cmd_binder.set_handler("hw_reconnect",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_reconnect, _1),
tr(USAGE_HW_RECONNECT),
tr("Attempts to reconnect HW wallet."));
m_cmd_binder.set_handler("export_outputs",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_outputs, _1),
tr(USAGE_EXPORT_OUTPUTS),
tr("Export a set of outputs owned by this wallet."));
m_cmd_binder.set_handler("import_outputs",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_outputs, _1),
tr(USAGE_IMPORT_OUTPUTS),
tr("Import a set of outputs owned by this wallet."));
m_cmd_binder.set_handler("show_transfer",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfer, _1),
tr(USAGE_SHOW_TRANSFER),
tr("Show information about a transfer to/from this address."));
m_cmd_binder.set_handler("password",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::change_password, _1),
tr("Change the wallet's password."));
m_cmd_binder.set_handler("payment_id",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::payment_id, _1),
tr(USAGE_PAYMENT_ID),
tr("Generate a new random full size payment id (obsolete). These will be unencrypted on the blockchain, see integrated_address for encrypted short payment ids."));
m_cmd_binder.set_handler("fee",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_fee_info, _1),
tr("Print the information about the current fee and transaction backlog."));
m_cmd_binder.set_handler("prepare_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::prepare_multisig, _1),
tr("Export data needed to create a multisig wallet"));
m_cmd_binder.set_handler("make_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::make_multisig, _1),
tr(USAGE_MAKE_MULTISIG),
tr("Turn this wallet into a multisig wallet"));
m_cmd_binder.set_handler("finalize_multisig",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::finalize_multisig, _1),
tr(USAGE_FINALIZE_MULTISIG),
tr("Turn this wallet into a multisig wallet, extra step for N-1/N wallets"));
m_cmd_binder.set_handler("exchange_multisig_keys",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::exchange_multisig_keys, _1),
tr(USAGE_EXCHANGE_MULTISIG_KEYS),
tr("Performs extra multisig keys exchange rounds. Needed for arbitrary M/N multisig wallets"));
m_cmd_binder.set_handler("export_multisig_info",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_multisig, _1),
tr(USAGE_EXPORT_MULTISIG_INFO),
tr("Export multisig info for other participants"));
m_cmd_binder.set_handler("import_multisig_info",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_multisig, _1),
tr(USAGE_IMPORT_MULTISIG_INFO),
tr("Import multisig info from other participants"));
m_cmd_binder.set_handler("sign_multisig",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_multisig, _1),
tr(USAGE_SIGN_MULTISIG),
tr("Sign a multisig transaction from a file"));
m_cmd_binder.set_handler("submit_multisig",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_multisig, _1),
tr(USAGE_SUBMIT_MULTISIG),
tr("Submit a signed multisig transaction from a file"));
m_cmd_binder.set_handler("export_raw_multisig_tx",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_raw_multisig, _1),
tr(USAGE_EXPORT_RAW_MULTISIG_TX),
tr("Export a signed multisig transaction to a file"));
m_cmd_binder.set_handler("mms",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS),
tr("Interface with the MMS (Multisig Messaging System)\n"
"<subcommand> is one of:\n"
" init, info, signer, list, next, sync, transfer, delete, send, receive, export, note, show, set, help\n"
" send_signer_config, start_auto_config, stop_auto_config, auto_config\n"
"Get help about a subcommand with: help mms <subcommand>, or mms help <subcommand>"));
m_cmd_binder.set_handler("mms init",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_INIT),
tr("Initialize and configure the MMS for M/N = number of required signers/number of authorized signers multisig"));
m_cmd_binder.set_handler("mms info",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_INFO),
tr("Display current MMS configuration"));
m_cmd_binder.set_handler("mms signer",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_SIGNER),
tr("Set or modify authorized signer info (single-word label, transport address, Swap address), or list all signers"));
m_cmd_binder.set_handler("mms list",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_LIST),
tr("List all messages"));
m_cmd_binder.set_handler("mms next",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_NEXT),
tr("Evaluate the next possible multisig-related action(s) according to wallet state, and execute or offer for choice\n"
"By using 'sync' processing of waiting messages with multisig sync info can be forced regardless of wallet state"));
m_cmd_binder.set_handler("mms sync",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_SYNC),
tr("Force generation of multisig sync info regardless of wallet state, to recover from special situations like \"stale data\" errors"));
m_cmd_binder.set_handler("mms transfer",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_TRANSFER),
tr("Initiate transfer with MMS support; arguments identical to normal 'transfer' command arguments, for info see there"));
m_cmd_binder.set_handler("mms delete",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_DELETE),
tr("Delete a single message by giving its id, or delete all messages by using 'all'"));
m_cmd_binder.set_handler("mms send",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_SEND),
tr("Send a single message by giving its id, or send all waiting messages"));
m_cmd_binder.set_handler("mms receive",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_RECEIVE),
tr("Check right away for new messages to receive"));
m_cmd_binder.set_handler("mms export",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_EXPORT),
tr("Write the content of a message to a file \"mms_message_content\""));
m_cmd_binder.set_handler("mms note",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_NOTE),
tr("Send a one-line message to an authorized signer, identified by its label, or show any waiting unread notes"));
m_cmd_binder.set_handler("mms show",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_SHOW),
tr("Show detailed info about a single message"));
m_cmd_binder.set_handler("mms set",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_SET),
tr("Available options:\n "
"auto-send <1|0>\n "
" Whether to automatically send newly generated messages right away.\n "));
m_cmd_binder.set_handler("mms send_signer_config",
boost::bind(&simple_wallet::mms, this, _1),
tr(USAGE_MMS_SEND_SIGNER_CONFIG),
tr("Send completed signer config to all other authorized signers"));
m_cmd_binder.set_handler("mms start_auto_config",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_START_AUTO_CONFIG),
tr("Start auto-config at the auto-config manager's wallet by issuing auto-config tokens and optionally set others' labels"));
m_cmd_binder.set_handler("mms stop_auto_config",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_STOP_AUTO_CONFIG),
tr("Delete any auto-config tokens and abort a auto-config process"));
m_cmd_binder.set_handler("mms auto_config",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
tr(USAGE_MMS_AUTO_CONFIG),
tr("Start auto-config by using the token received from the auto-config manager"));
m_cmd_binder.set_handler("print_ring",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_ring, _1),
tr(USAGE_PRINT_RING),
tr("Print the ring(s) used to spend a given key image or transaction (if the ring size is > 1)\n\n"
"Output format:\n"
"Key Image, \"absolute\", list of rings"));
m_cmd_binder.set_handler("set_ring",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_ring, _1),
tr(USAGE_SET_RING),
tr("Set the ring used for a given key image, so it can be reused in a fork"));
m_cmd_binder.set_handler("unset_ring",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::unset_ring, _1),
tr(USAGE_UNSET_RING),
tr("Unsets the ring used for a given key image or transaction"));
m_cmd_binder.set_handler("save_known_rings",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_known_rings, _1),
tr(USAGE_SAVE_KNOWN_RINGS),
tr("Save known rings to the shared rings database"));
m_cmd_binder.set_handler("mark_output_spent",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackball, _1),
tr(USAGE_MARK_OUTPUT_SPENT),
tr("Mark output(s) as spent so they never get selected as fake outputs in a ring"));
m_cmd_binder.set_handler("mark_output_unspent",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::unblackball, _1),
tr(USAGE_MARK_OUTPUT_UNSPENT),
tr("Marks an output as unspent so it may get selected as a fake output in a ring"));
m_cmd_binder.set_handler("is_output_spent",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackballed, _1),
tr(USAGE_IS_OUTPUT_SPENT),
tr("Checks whether an output is marked as spent"));
m_cmd_binder.set_handler("freeze",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::freeze, _1),
tr(USAGE_FREEZE),
tr("Freeze a single output by key image so it will not be used"));
m_cmd_binder.set_handler("thaw",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::thaw, _1),
tr(USAGE_THAW),
tr("Thaw a single output by key image so it may be used again"));
m_cmd_binder.set_handler("frozen",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::frozen, _1),
tr(USAGE_FROZEN),
tr("Checks whether a given output is currently frozen by key image"));
m_cmd_binder.set_handler("lock",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::lock, _1),
tr(USAGE_LOCK),
tr("Lock the wallet console, requiring the wallet password to continue"));
m_cmd_binder.set_handler("net_stats",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::net_stats, _1),
tr(USAGE_NET_STATS),
tr("Prints simple network stats"));
m_cmd_binder.set_handler("public_nodes",
boost::bind(&simple_wallet::public_nodes, this, _1),
tr(USAGE_PUBLIC_NODES),
tr("Lists known public nodes"));
m_cmd_binder.set_handler("welcome",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::welcome, _1),
tr(USAGE_WELCOME),
tr("Prints basic info about Swap for first time users"));
m_cmd_binder.set_handler("version",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::version, _1),
tr(USAGE_VERSION),
tr("Returns version information"));
m_cmd_binder.set_handler("rpc_payment_info",
boost::bind(&simple_wallet::rpc_payment_info, this, _1),
tr(USAGE_RPC_PAYMENT_INFO),
tr("Get info about RPC payments to current node"));
m_cmd_binder.set_handler("start_mining_for_rpc",
boost::bind(&simple_wallet::start_mining_for_rpc, this, _1),
tr(USAGE_START_MINING_FOR_RPC),
tr("Start mining to pay for RPC access"));
m_cmd_binder.set_handler("stop_mining_for_rpc",
boost::bind(&simple_wallet::stop_mining_for_rpc, this, _1),
tr(USAGE_STOP_MINING_FOR_RPC),
tr("Stop mining to pay for RPC access"));
m_cmd_binder.set_handler("help",
boost::bind(&simple_wallet::on_command, this, &simple_wallet::help, _1),
tr(USAGE_HELP),
tr("Show the help section or the documentation about a <command>."));
m_cmd_binder.set_unknown_command_handler(boost::bind(&simple_wallet::on_command, this, &simple_wallet::on_unknown_command, _1));
m_cmd_binder.set_empty_command_handler(boost::bind(&simple_wallet::on_empty_command, this));
m_cmd_binder.set_cancel_handler(boost::bind(&simple_wallet::on_cancelled_command, this));
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_variable(const std::vector<std::string> &args)
{
if (args.empty())
{
std::string seed_language = m_wallet->get_seed_language();
if (m_use_english_language_names)
seed_language = crypto::ElectrumWords::get_english_name_for(seed_language);
std::string priority_string = "invalid";
uint32_t priority = m_wallet->get_default_priority();
if (priority < allowed_priority_strings.size())
priority_string = allowed_priority_strings[priority];
std::string ask_password_string = "invalid";
switch (m_wallet->ask_password())
{
case tools::wallet2::AskPasswordNever: ask_password_string = "never"; break;
case tools::wallet2::AskPasswordOnAction: ask_password_string = "action"; break;
case tools::wallet2::AskPasswordToDecrypt: ask_password_string = "decrypt"; break;
}
std::string setup_background_mining_string = "invalid";
switch (m_wallet->setup_background_mining())
{
case tools::wallet2::BackgroundMiningMaybe: setup_background_mining_string = "maybe"; break;
case tools::wallet2::BackgroundMiningYes: setup_background_mining_string = "yes"; break;
case tools::wallet2::BackgroundMiningNo: setup_background_mining_string = "no"; break;
}
success_msg_writer() << "seed = " << seed_language;
success_msg_writer() << "always-confirm-transfers = " << m_wallet->always_confirm_transfers();
success_msg_writer() << "print-ring-members = " << m_wallet->print_ring_members();
success_msg_writer() << "store-tx-info = " << m_wallet->store_tx_info();
success_msg_writer() << "default-ring-size = " << (m_wallet->default_mixin() ? m_wallet->default_mixin() + 1 : 0);
success_msg_writer() << "auto-refresh = " << m_wallet->auto_refresh();
success_msg_writer() << "refresh-type = " << get_refresh_type_name(m_wallet->get_refresh_type());
success_msg_writer() << "priority = " << priority<< " (" << priority_string << ")";
success_msg_writer() << "ask-password = " << m_wallet->ask_password() << " (" << ask_password_string << ")";
success_msg_writer() << "unit = " << cryptonote::get_unit(cryptonote::get_default_decimal_point());
success_msg_writer() << "min-outputs-count = " << m_wallet->get_min_output_count();
success_msg_writer() << "min-outputs-value = " << cryptonote::print_money(m_wallet->get_min_output_value());
success_msg_writer() << "merge-destinations = " << m_wallet->merge_destinations();
success_msg_writer() << "confirm-backlog = " << m_wallet->confirm_backlog();
success_msg_writer() << "confirm-backlog-threshold = " << m_wallet->get_confirm_backlog_threshold();
success_msg_writer() << "confirm-export-overwrite = " << m_wallet->confirm_export_overwrite();
success_msg_writer() << "refresh-from-block-height = " << m_wallet->get_refresh_from_block_height();
success_msg_writer() << "auto-low-priority = " << m_wallet->auto_low_priority();
success_msg_writer() << "segregate-pre-fork-outputs = " << m_wallet->segregate_pre_fork_outputs();
success_msg_writer() << "key-reuse-mitigation2 = " << m_wallet->key_reuse_mitigation2();
const std::pair<size_t, size_t> lookahead = m_wallet->get_subaddress_lookahead();
success_msg_writer() << "subaddress-lookahead = " << lookahead.first << ":" << lookahead.second;
success_msg_writer() << "segregation-height = " << m_wallet->segregation_height();
success_msg_writer() << "ignore-fractional-outputs = " << m_wallet->ignore_fractional_outputs();
success_msg_writer() << "ignore-outputs-above = " << cryptonote::print_money(m_wallet->ignore_outputs_above());
success_msg_writer() << "ignore-outputs-below = " << cryptonote::print_money(m_wallet->ignore_outputs_below());
success_msg_writer() << "track-uses = " << m_wallet->track_uses();
success_msg_writer() << "setup-background-mining = " << setup_background_mining_string;
success_msg_writer() << "device-name = " << m_wallet->device_name();
success_msg_writer() << "export-format = " << (m_wallet->export_format() == tools::wallet2::ExportFormat::Ascii ? "ascii" : "binary");
success_msg_writer() << "inactivity-lock-timeout = " << m_wallet->inactivity_lock_timeout()
#ifdef _WIN32
<< " (disabled on Windows)"
#endif
;
success_msg_writer() << "persistent-rpc-client-id = " << m_wallet->persistent_rpc_client_id();
success_msg_writer() << "auto-mine-for-rpc-payment-threshold = " << m_wallet->auto_mine_for_rpc_payment_threshold();
success_msg_writer() << "credits-target = " << m_wallet->credits_target();
return true;
}
else
{
#define CHECK_SIMPLE_VARIABLE(name, f, help) do \
if (args[0] == name) { \
if (args.size() <= 1) \
{ \
fail_msg_writer() << "set " << #name << ": " << tr("needs an argument") << " (" << help << ")"; \
return true; \
} \
else \
{ \
f(args); \
return true; \
} \
} while(0)
if (args[0] == "seed")
{
if (args.size() == 1)
{
fail_msg_writer() << tr("set seed: needs an argument. available options: language");
return true;
}
else if (args[1] == "language")
{
seed_set_language(args);
return true;
}
}
CHECK_SIMPLE_VARIABLE("always-confirm-transfers", set_always_confirm_transfers, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("print-ring-members", set_print_ring_members, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("store-tx-info", set_store_tx_info, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("default-ring-size", set_default_ring_size, tr("integer >= ") << MIN_RING_SIZE);
CHECK_SIMPLE_VARIABLE("auto-refresh", set_auto_refresh, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("refresh-type", set_refresh_type, tr("full (slowest, no assumptions); optimize-coinbase (fast, assumes the whole coinbase is paid to a single address); no-coinbase (fastest, assumes we receive no coinbase transaction), default (same as optimize-coinbase)"));
CHECK_SIMPLE_VARIABLE("priority", set_default_priority, tr("0, 1, 2, 3, or 4, or one of ") << join_priority_strings(", "));
CHECK_SIMPLE_VARIABLE("ask-password", set_ask_password, tr("0|1|2 (or never|action|decrypt)"));
CHECK_SIMPLE_VARIABLE("unit", set_unit, tr("swap, swapini, atoms"));
CHECK_SIMPLE_VARIABLE("min-outputs-count", set_min_output_count, tr("unsigned integer"));
CHECK_SIMPLE_VARIABLE("min-outputs-value", set_min_output_value, tr("amount"));
CHECK_SIMPLE_VARIABLE("merge-destinations", set_merge_destinations, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("confirm-backlog", set_confirm_backlog, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("confirm-backlog-threshold", set_confirm_backlog_threshold, tr("unsigned integer"));
CHECK_SIMPLE_VARIABLE("confirm-export-overwrite", set_confirm_export_overwrite, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("refresh-from-block-height", set_refresh_from_block_height, tr("block height"));
CHECK_SIMPLE_VARIABLE("auto-low-priority", set_auto_low_priority, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("segregate-pre-fork-outputs", set_segregate_pre_fork_outputs, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("key-reuse-mitigation2", set_key_reuse_mitigation2, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("subaddress-lookahead", set_subaddress_lookahead, tr("<major>:<minor>"));
CHECK_SIMPLE_VARIABLE("segregation-height", set_segregation_height, tr("unsigned integer"));
CHECK_SIMPLE_VARIABLE("ignore-fractional-outputs", set_ignore_fractional_outputs, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("ignore-outputs-above", set_ignore_outputs_above, tr("amount"));
CHECK_SIMPLE_VARIABLE("ignore-outputs-below", set_ignore_outputs_below, tr("amount"));
CHECK_SIMPLE_VARIABLE("track-uses", set_track_uses, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("inactivity-lock-timeout", set_inactivity_lock_timeout, tr("unsigned integer (seconds, 0 to disable)"));
CHECK_SIMPLE_VARIABLE("setup-background-mining", set_setup_background_mining, tr("1/yes or 0/no"));
CHECK_SIMPLE_VARIABLE("device-name", set_device_name, tr("<device_name[:device_spec]>"));
CHECK_SIMPLE_VARIABLE("export-format", set_export_format, tr("\"binary\" or \"ascii\""));
CHECK_SIMPLE_VARIABLE("persistent-rpc-client-id", set_persistent_rpc_client_id, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("auto-mine-for-rpc-payment-threshold", set_auto_mine_for_rpc_payment_threshold, tr("floating point >= 0"));
CHECK_SIMPLE_VARIABLE("credits-target", set_credits_target, tr("unsigned integer"));
}
fail_msg_writer() << tr("set: unrecognized argument(s)");
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_log(const std::vector<std::string> &args)
{
if(args.size() > 1)
{
PRINT_USAGE(USAGE_SET_LOG);
return true;
}
if(!args.empty())
{
uint16_t level = 0;
if(epee::string_tools::get_xtype_from_string(level, args[0]))
{
if(4 < level)
{
fail_msg_writer() << boost::format(tr("wrong number range, use: %s")) % USAGE_SET_LOG;
return true;
}
mlog_set_log_level(level);
}
else
{
mlog_set_log(args[0].c_str());
}
}
success_msg_writer() << "New log categories: " << mlog_get_categories();
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::ask_wallet_create_if_needed()
{
LOG_PRINT_L3("simple_wallet::ask_wallet_create_if_needed() started");
std::string wallet_path;
std::string confirm_creation;
bool wallet_name_valid = false;
bool keys_file_exists;
bool wallet_file_exists;
do{
LOG_PRINT_L3("User asked to specify wallet file name.");
wallet_path = input_line(
tr(m_restoring ? "Specify a new wallet file name for your restored wallet (e.g., MyWallet).\n"
"Wallet file name (or Ctrl-C to quit)" :
"Specify wallet file name (e.g., MyWallet). If the wallet doesn't exist, it will be created.\n"
"Wallet file name (or Ctrl-C to quit)")
);
if(std::cin.eof())
{
LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
return false;
}
if(!tools::wallet2::wallet_valid_path_format(wallet_path))
{
fail_msg_writer() << tr("Wallet name not valid. Please try again or use Ctrl-C to quit.");
wallet_name_valid = false;
}
else
{
tools::wallet2::wallet_exists(wallet_path, keys_file_exists, wallet_file_exists);
LOG_PRINT_L3("wallet_path: " << wallet_path << "");
LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha
<< " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha);
if((keys_file_exists || wallet_file_exists) && (!m_generate_new.empty() || m_restoring))
{
fail_msg_writer() << tr("Attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting.");
return false;
}
if(wallet_file_exists && keys_file_exists) //Yes wallet, yes keys
{
success_msg_writer() << tr("Wallet and key files found, loading...");
m_wallet_file = wallet_path;
return true;
}
else if(!wallet_file_exists && keys_file_exists) //No wallet, yes keys
{
success_msg_writer() << tr("Key file found but not wallet file. Regenerating...");
m_wallet_file = wallet_path;
return true;
}
else if(wallet_file_exists && !keys_file_exists) //Yes wallet, no keys
{
fail_msg_writer() << tr("Key file not found. Failed to open wallet: ") << "\"" << wallet_path << "\". Exiting.";
return false;
}
else if(!wallet_file_exists && !keys_file_exists) //No wallet, no keys
{
bool ok = true;
if (!m_restoring)
{
message_writer() << tr("No wallet found with that name. Confirm creation of new wallet named: ") << wallet_path;
confirm_creation = input_line("", true);
if(std::cin.eof())
{
LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
return false;
}
ok = command_line::is_yes(confirm_creation);
}
if (ok)
{
success_msg_writer() << tr("Generating new wallet...");
m_generate_new = wallet_path;
return true;
}
}
}
} while(!wallet_name_valid);
LOG_ERROR("Failed out of do-while loop in ask_wallet_create_if_needed()");
return false;
}
/*!
* \brief Prints the seed with a nice message
* \param seed seed to print
*/
void simple_wallet::print_seed(const epee::wipeable_string &seed)
{
success_msg_writer(true) << "\n" << boost::format(tr("NOTE: the following %s can be used to recover access to your wallet. "
"Write them down and store them somewhere safe and secure. Please do not store them in "
"your email or on file storage services outside of your immediate control.\n")) % (m_wallet->multisig() ? tr("string") : tr("25 words"));
// don't log
int space_index = 0;
size_t len = seed.size();
for (const char *ptr = seed.data(); len--; ++ptr)
{
if (*ptr == ' ')
{
if (space_index == 15 || space_index == 7)
putchar('\n');
else
putchar(*ptr);
++space_index;
}
else
putchar(*ptr);
}
putchar('\n');
fflush(stdout);
}
//----------------------------------------------------------------------------------------------------
static bool might_be_partial_seed(const epee::wipeable_string &words)
{
std::vector<epee::wipeable_string> seed;
words.split(seed);
return seed.size() < 24;
}
//----------------------------------------------------------------------------------------------------
static bool datestr_to_int(const std::string &heightstr, uint16_t &year, uint8_t &month, uint8_t &day)
{
if (heightstr.size() != 10 || heightstr[4] != '-' || heightstr[7] != '-')
{
fail_msg_writer() << tr("date format must be YYYY-MM-DD");
return false;
}
try
{
year = boost::lexical_cast<uint16_t>(heightstr.substr(0,4));
// lexical_cast<uint8_t> won't work because uint8_t is treated as character type
month = boost::lexical_cast<uint16_t>(heightstr.substr(5,2));
day = boost::lexical_cast<uint16_t>(heightstr.substr(8,2));
}
catch (const boost::bad_lexical_cast &)
{
fail_msg_writer() << tr("bad height parameter: ") << heightstr;
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::init(const boost::program_options::variables_map& vm)
{
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){
m_electrum_seed.wipe();
});
const bool testnet = tools::wallet2::has_testnet_option(vm);
const bool stagenet = tools::wallet2::has_stagenet_option(vm);
if (testnet && stagenet)
{
fail_msg_writer() << tr("Can't specify more than one of --testnet and --stagenet");
return false;
}
const network_type nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET;
epee::wipeable_string multisig_keys;
epee::wipeable_string password;
if (!handle_command_line(vm))
return false;
bool welcome = false;
if((!m_generate_new.empty()) + (!m_wallet_file.empty()) + (!m_generate_from_device.empty()) + (!m_generate_from_view_key.empty()) + (!m_generate_from_spend_key.empty()) + (!m_generate_from_keys.empty()) + (!m_generate_from_multisig_keys.empty()) + (!m_generate_from_json.empty()) > 1)
{
fail_msg_writer() << tr("can't specify more than one of --generate-new-wallet=\"wallet_name\", --wallet-file=\"wallet_name\", --generate-from-view-key=\"wallet_name\", --generate-from-spend-key=\"wallet_name\", --generate-from-keys=\"wallet_name\", --generate-from-multisig-keys=\"wallet_name\", --generate-from-json=\"jsonfilename\" and --generate-from-device=\"wallet_name\"");
return false;
}
else if (m_generate_new.empty() && m_wallet_file.empty() && m_generate_from_device.empty() && m_generate_from_view_key.empty() && m_generate_from_spend_key.empty() && m_generate_from_keys.empty() && m_generate_from_multisig_keys.empty() && m_generate_from_json.empty())
{
if(!ask_wallet_create_if_needed()) return false;
}
if (!m_generate_new.empty() || m_restoring)
{
if (!m_subaddress_lookahead.empty() && !parse_subaddress_lookahead(m_subaddress_lookahead))
return false;
std::string old_language;
// check for recover flag. if present, require electrum word list (only recovery option for now).
if (m_restore_deterministic_wallet || m_restore_multisig_wallet)
{
if (m_non_deterministic)
{
fail_msg_writer() << tr("can't specify both --restore-deterministic-wallet or --restore-multisig-wallet and --non-deterministic");
return false;
}
if (!m_wallet_file.empty())
{
if (m_restore_multisig_wallet)
fail_msg_writer() << tr("--restore-multisig-wallet uses --generate-new-wallet, not --wallet-file");
else
fail_msg_writer() << tr("--restore-deterministic-wallet uses --generate-new-wallet, not --wallet-file");
return false;
}
if (m_electrum_seed.empty())
{
if (m_restore_multisig_wallet)
{
const char *prompt = "Specify multisig seed";
m_electrum_seed = input_secure_line(prompt);
if (std::cin.eof())
return false;
if (m_electrum_seed.empty())
{
fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"multisig seed here\"");
return false;
}
}
else
{
m_electrum_seed = "";
do
{
const char *prompt = m_electrum_seed.empty() ? "Specify Electrum seed" : "Electrum seed continued";
epee::wipeable_string electrum_seed = input_secure_line(prompt);
if (std::cin.eof())
return false;
if (electrum_seed.empty())
{
fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"words list here\"");
return false;
}
m_electrum_seed += electrum_seed;
m_electrum_seed += ' ';
} while (might_be_partial_seed(m_electrum_seed));
}
}
if (m_restore_multisig_wallet)
{
const boost::optional<epee::wipeable_string> parsed = m_electrum_seed.parse_hexstr();
if (!parsed)
{
fail_msg_writer() << tr("Multisig seed failed verification");
return false;
}
multisig_keys = *parsed;
}
else
{
if (!crypto::ElectrumWords::words_to_bytes(m_electrum_seed, m_recovery_key, old_language))
{
fail_msg_writer() << tr("Electrum-style word list failed verification");
return false;
}
}
auto pwd_container = password_prompter(tr("Enter seed offset passphrase, empty if none"), false);
if (std::cin.eof() || !pwd_container)
return false;
epee::wipeable_string seed_pass = pwd_container->password();
if (!seed_pass.empty())
{
if (m_restore_multisig_wallet)
{
crypto::secret_key key;
crypto::cn_slow_hash(seed_pass.data(), seed_pass.size(), (crypto::hash&)key);
sc_reduce32((unsigned char*)key.data);
multisig_keys = m_wallet->decrypt<epee::wipeable_string>(std::string(multisig_keys.data(), multisig_keys.size()), key, true);
}
else
m_recovery_key = cryptonote::decrypt_key(m_recovery_key, seed_pass);
}
}
if (!m_generate_from_view_key.empty())
{
m_wallet_file = m_generate_from_view_key;
// parse address
std::string address_string = input_line("Standard address");
if (std::cin.eof())
return false;
if (address_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
cryptonote::address_parse_info info;
if(!get_account_address_from_str(info, nettype, address_string))
{
fail_msg_writer() << tr("failed to parse address");
return false;
}
if (info.is_subaddress)
{
fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
return false;
}
// parse view secret key
epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
if (std::cin.eof())
return false;
if (viewkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key viewkey;
if (!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
{
fail_msg_writer() << tr("failed to parse view key secret key");
return false;
}
m_wallet_file=m_generate_from_view_key;
// check the view key matches the given address
crypto::public_key pkey;
if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
fail_msg_writer() << tr("failed to verify view key secret key");
return false;
}
if (info.address.m_view_public_key != pkey) {
fail_msg_writer() << tr("view key does not match standard address");
return false;
}
auto r = new_wallet(vm, info.address, boost::none, viewkey);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
welcome = true;
}
else if (!m_generate_from_spend_key.empty())
{
m_wallet_file = m_generate_from_spend_key;
// parse spend secret key
epee::wipeable_string spendkey_string = input_secure_line("Secret spend key");
if (std::cin.eof())
return false;
if (spendkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
if (!spendkey_string.hex_to_pod(unwrap(unwrap(m_recovery_key))))
{
fail_msg_writer() << tr("failed to parse spend key secret key");
return false;
}
auto r = new_wallet(vm, m_recovery_key, true, false, "");
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
welcome = true;
}
else if (!m_generate_from_keys.empty())
{
m_wallet_file = m_generate_from_keys;
// parse address
std::string address_string = input_line("Standard address");
if (std::cin.eof())
return false;
if (address_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
cryptonote::address_parse_info info;
if(!get_account_address_from_str(info, nettype, address_string))
{
fail_msg_writer() << tr("failed to parse address");
return false;
}
if (info.is_subaddress)
{
fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
return false;
}
// parse spend secret key
epee::wipeable_string spendkey_string = input_secure_line("Secret spend key");
if (std::cin.eof())
return false;
if (spendkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key spendkey;
if (!spendkey_string.hex_to_pod(unwrap(unwrap(spendkey))))
{
fail_msg_writer() << tr("failed to parse spend key secret key");
return false;
}
// parse view secret key
epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
if (std::cin.eof())
return false;
if (viewkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key viewkey;
if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
{
fail_msg_writer() << tr("failed to parse view key secret key");
return false;
}
m_wallet_file=m_generate_from_keys;
// check the spend and view keys match the given address
crypto::public_key pkey;
if (!crypto::secret_key_to_public_key(spendkey, pkey)) {
fail_msg_writer() << tr("failed to verify spend key secret key");
return false;
}
if (info.address.m_spend_public_key != pkey) {
fail_msg_writer() << tr("spend key does not match standard address");
return false;
}
if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
fail_msg_writer() << tr("failed to verify view key secret key");
return false;
}
if (info.address.m_view_public_key != pkey) {
fail_msg_writer() << tr("view key does not match standard address");
return false;
}
auto r = new_wallet(vm, info.address, spendkey, viewkey);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
welcome = true;
}
// Asks user for all the data required to merge secret keys from multisig wallets into one master wallet, which then gets full control of the multisig wallet. The resulting wallet will be the same as any other regular wallet.
else if (!m_generate_from_multisig_keys.empty())
{
m_wallet_file = m_generate_from_multisig_keys;
unsigned int multisig_m;
unsigned int multisig_n;
// parse multisig type
std::string multisig_type_string = input_line("Multisig type (input as M/N with M <= N and M > 1)");
if (std::cin.eof())
return false;
if (multisig_type_string.empty())
{
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
if (sscanf(multisig_type_string.c_str(), "%u/%u", &multisig_m, &multisig_n) != 2)
{
fail_msg_writer() << tr("Error: expected M/N, but got: ") << multisig_type_string;
return false;
}
if (multisig_m <= 1 || multisig_m > multisig_n)
{
fail_msg_writer() << tr("Error: expected N > 1 and N <= M, but got: ") << multisig_type_string;
return false;
}
if (multisig_m != multisig_n)
{
fail_msg_writer() << tr("Error: M/N is currently unsupported. ");
return false;
}
message_writer() << boost::format(tr("Generating master wallet from %u of %u multisig wallet keys")) % multisig_m % multisig_n;
// parse multisig address
std::string address_string = input_line("Multisig wallet address");
if (std::cin.eof())
return false;
if (address_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
cryptonote::address_parse_info info;
if(!get_account_address_from_str(info, nettype, address_string))
{
fail_msg_writer() << tr("failed to parse address");
return false;
}
// parse secret view key
epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
if (std::cin.eof())
return false;
if (viewkey_string.empty())
{
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key viewkey;
if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
{
fail_msg_writer() << tr("failed to parse secret view key");
return false;
}
// check that the view key matches the given address
crypto::public_key pkey;
if (!crypto::secret_key_to_public_key(viewkey, pkey))
{
fail_msg_writer() << tr("failed to verify secret view key");
return false;
}
if (info.address.m_view_public_key != pkey)
{
fail_msg_writer() << tr("view key does not match standard address");
return false;
}
// parse multisig spend keys
crypto::secret_key spendkey;
// parsing N/N
if(multisig_m == multisig_n)
{
std::vector<crypto::secret_key> multisig_secret_spendkeys(multisig_n);
epee::wipeable_string spendkey_string;
cryptonote::blobdata spendkey_data;
// get N secret spend keys from user
for(unsigned int i=0; i<multisig_n; ++i)
{
spendkey_string = input_secure_line(tr((boost::format(tr("Secret spend key (%u of %u)")) % (i+1) % multisig_m).str().c_str()));
if (std::cin.eof())
return false;
if (spendkey_string.empty())
{
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
if(!spendkey_string.hex_to_pod(unwrap(unwrap(multisig_secret_spendkeys[i]))))
{
fail_msg_writer() << tr("failed to parse spend key secret key");
return false;
}
}
// sum the spend keys together to get the master spend key
spendkey = multisig_secret_spendkeys[0];
for(unsigned int i=1; i<multisig_n; ++i)
sc_add(reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&multisig_secret_spendkeys[i]));
}
// parsing M/N
else
{
fail_msg_writer() << tr("Error: M/N is currently unsupported");
return false;
}
// check that the spend key matches the given address
if (!crypto::secret_key_to_public_key(spendkey, pkey))
{
fail_msg_writer() << tr("failed to verify spend key secret key");
return false;
}
if (info.address.m_spend_public_key != pkey)
{
fail_msg_writer() << tr("spend key does not match standard address");
return false;
}
// create wallet
auto r = new_wallet(vm, info.address, spendkey, viewkey);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
welcome = true;
}
else if (!m_generate_from_json.empty())
{
try
{
auto rc = tools::wallet2::make_from_json(vm, false, m_generate_from_json, password_prompter);
m_wallet = std::move(rc.first);
password = rc.second.password();
m_wallet_file = m_wallet->path();
}
catch (const std::exception &e)
{
fail_msg_writer() << e.what();
return false;
}
if (!m_wallet)
return false;
}
else if (!m_generate_from_device.empty())
{
m_wallet_file = m_generate_from_device;
// create wallet
auto r = new_wallet(vm);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
welcome = true;
// if no block_height is specified, assume its a new account and start it "now"
if(m_wallet->get_refresh_from_block_height() == 0) {
{
tools::scoped_message_writer wrt = tools::msg_writer();
wrt << tr("No restore height is specified.") << " ";
wrt << tr("Assumed you are creating a new account, restore will be done from current estimated blockchain height.") << " ";
wrt << tr("Use --restore-height or --restore-date if you want to restore an already setup account from a specific height.");
}
std::string confirm = input_line(tr("Is this okay?"), true);
if (std::cin.eof() || !command_line::is_yes(confirm))
CHECK_AND_ASSERT_MES(false, false, tr("account creation aborted"));
m_wallet->set_refresh_from_block_height(m_wallet->estimate_blockchain_height());
m_wallet->explicit_refresh_from_block_height(true);
m_restore_height = m_wallet->get_refresh_from_block_height();
}
}
else
{
if (m_generate_new.empty()) {
fail_msg_writer() << tr("specify a wallet path with --generate-new-wallet (not --wallet-file)");
return false;
}
m_wallet_file = m_generate_new;
boost::optional<epee::wipeable_string> r;
if (m_restore_multisig_wallet)
r = new_wallet(vm, multisig_keys, old_language);
else
r = new_wallet(vm, m_recovery_key, m_restore_deterministic_wallet, m_non_deterministic, old_language);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
welcome = true;
}
if (m_restoring && m_generate_from_json.empty() && m_generate_from_device.empty())
{
m_wallet->explicit_refresh_from_block_height(!(command_line::is_arg_defaulted(vm, arg_restore_height) &&
command_line::is_arg_defaulted(vm, arg_restore_date)));
if (command_line::is_arg_defaulted(vm, arg_restore_height) && !command_line::is_arg_defaulted(vm, arg_restore_date))
{
uint16_t year;
uint8_t month;
uint8_t day;
if (!datestr_to_int(m_restore_date, year, month, day))
return false;
try
{
m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day);
success_msg_writer() << tr("Restore height is: ") << m_restore_height;
}
catch (const std::runtime_error& e)
{
fail_msg_writer() << e.what();
return false;
}
}
}
if (!m_wallet->explicit_refresh_from_block_height() && m_restoring)
{
uint32_t version;
bool connected = try_connect_to_daemon(false, &version);
while (true)
{
std::string heightstr;
if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
heightstr = input_line("Restore from specific blockchain height (optional, default 0)");
else
heightstr = input_line("Restore from specific blockchain height (optional, default 0),\nor alternatively from specific date (YYYY-MM-DD)");
if (std::cin.eof())
return false;
if (heightstr.empty())
{
m_restore_height = 0;
break;
}
try
{
m_restore_height = boost::lexical_cast<uint64_t>(heightstr);
break;
}
catch (const boost::bad_lexical_cast &)
{
if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
{
fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
continue;
}
uint16_t year;
uint8_t month; // 1, 2, ..., 12
uint8_t day; // 1, 2, ..., 31
try
{
if (!datestr_to_int(heightstr, year, month, day))
return false;
m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day);
success_msg_writer() << tr("Restore height is: ") << m_restore_height;
std::string confirm = input_line(tr("Is this okay?"), true);
if (std::cin.eof())
return false;
if(command_line::is_yes(confirm))
break;
}
catch (const boost::bad_lexical_cast &)
{
fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
}
catch (const std::runtime_error& e)
{
fail_msg_writer() << e.what();
}
}
}
}
if (m_restoring)
{
uint64_t estimate_height = m_wallet->estimate_blockchain_height();
if (m_restore_height >= estimate_height)
{
success_msg_writer() << tr("Restore height ") << m_restore_height << (" is not yet reached. The current estimated height is ") << estimate_height;
std::string confirm = input_line(tr("Still apply restore height?"), true);
if (std::cin.eof() || command_line::is_no(confirm))
m_restore_height = 0;
}
m_wallet->set_refresh_from_block_height(m_restore_height);
}
m_wallet->rewrite(m_wallet_file, password);
}
else
{
assert(!m_wallet_file.empty());
if (!m_subaddress_lookahead.empty())
{
fail_msg_writer() << tr("can't specify --subaddress-lookahead and --wallet-file at the same time");
return false;
}
auto r = open_wallet(vm);
CHECK_AND_ASSERT_MES(r, false, tr("failed to open account"));
password = *r;
}
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return false;
}
if (!command_line::is_arg_defaulted(vm, arg_rpc_client_secret_key))
{
crypto::secret_key rpc_client_secret_key;
if (!epee::string_tools::hex_to_pod(command_line::get_arg(vm, arg_rpc_client_secret_key), rpc_client_secret_key))
{
fail_msg_writer() << tr("RPC client secret key should be 32 byte in hex format");
return false;
}
m_wallet->set_rpc_client_secret_key(rpc_client_secret_key);
}
if (!m_wallet->is_trusted_daemon())
{
message_writer(console_color_red, true) << (boost::format(tr("Warning: using an untrusted daemon at %s")) % m_wallet->get_daemon_address()).str();
message_writer(console_color_red, true) << boost::format(tr("Using a third party daemon can be detrimental to your security and privacy"));
bool ssl = false;
if (m_wallet->check_connection(NULL, &ssl) && !ssl)
message_writer(console_color_red, true) << boost::format(tr("Using your own without SSL exposes your RPC traffic to monitoring"));
message_writer(console_color_red, true) << boost::format(tr("You are strongly encouraged to connect to the Swap network using your own daemon"));
message_writer(console_color_red, true) << boost::format(tr("If you or someone you trust are operating this daemon, you can use --trusted-daemon"));
COMMAND_RPC_GET_INFO::request req;
COMMAND_RPC_GET_INFO::response res;
bool r = m_wallet->invoke_http_json("/get_info", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (r && err.empty() && (res.was_bootstrap_ever_used || !res.bootstrap_daemon_address.empty()))
message_writer(console_color_red, true) << boost::format(tr("Moreover, a daemon is also less secure when running in bootstrap mode"));
}
if (m_wallet->get_ring_database().empty())
fail_msg_writer() << tr("Failed to initialize ring database: privacy enhancing features will be inactive");
m_wallet->callback(this);
//bool skip_check_backround_mining = !command_line::get_arg(vm, arg_command).empty();
//if (!skip_check_backround_mining)
// check_background_mining(password);
if (welcome)
message_writer(console_color_yellow, true) << tr("If you are new to Swap, type \"welcome\" for a brief overview.");
m_last_activity_time = time(NULL);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::deinit()
{
if (!m_wallet.get())
return true;
return close_wallet();
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::handle_command_line(const boost::program_options::variables_map& vm)
{
m_wallet_file = command_line::get_arg(vm, arg_wallet_file);
m_generate_new = command_line::get_arg(vm, arg_generate_new_wallet);
m_generate_from_device = command_line::get_arg(vm, arg_generate_from_device);
m_generate_from_view_key = command_line::get_arg(vm, arg_generate_from_view_key);
m_generate_from_spend_key = command_line::get_arg(vm, arg_generate_from_spend_key);
m_generate_from_keys = command_line::get_arg(vm, arg_generate_from_keys);
m_generate_from_multisig_keys = command_line::get_arg(vm, arg_generate_from_multisig_keys);
m_generate_from_json = command_line::get_arg(vm, arg_generate_from_json);
m_mnemonic_language = command_line::get_arg(vm, arg_mnemonic_language);
m_electrum_seed = command_line::get_arg(vm, arg_electrum_seed);
m_restore_deterministic_wallet = command_line::get_arg(vm, arg_restore_deterministic_wallet) || command_line::get_arg(vm, arg_restore_from_seed);
m_restore_multisig_wallet = command_line::get_arg(vm, arg_restore_multisig_wallet);
m_non_deterministic = command_line::get_arg(vm, arg_non_deterministic);
m_allow_mismatched_daemon_version = command_line::get_arg(vm, arg_allow_mismatched_daemon_version);
m_restore_height = command_line::get_arg(vm, arg_restore_height);
m_restore_date = command_line::get_arg(vm, arg_restore_date);
m_do_not_relay = command_line::get_arg(vm, arg_do_not_relay);
m_subaddress_lookahead = command_line::get_arg(vm, arg_subaddress_lookahead);
m_use_english_language_names = command_line::get_arg(vm, arg_use_english_language_names);
m_restoring = !m_generate_from_view_key.empty() ||
!m_generate_from_spend_key.empty() ||
!m_generate_from_keys.empty() ||
!m_generate_from_multisig_keys.empty() ||
!m_generate_from_json.empty() ||
!m_generate_from_device.empty() ||
m_restore_deterministic_wallet ||
m_restore_multisig_wallet;
if (!command_line::is_arg_defaulted(vm, arg_restore_date))
{
uint16_t year;
uint8_t month, day;
if (!datestr_to_int(m_restore_date, year, month, day))
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::try_connect_to_daemon(bool silent, uint32_t* version)
{
uint32_t version_ = 0;
if (!version)
version = &version_;
if (!m_wallet->check_connection(version))
{
if (!silent)
fail_msg_writer() << tr("wallet failed to connect to daemon: ") << m_wallet->get_daemon_address() << ". " <<
tr("Daemon either is not started or wrong port was passed. "
"Please make sure daemon is running or change the daemon address using the 'set_daemon' command.");
return false;
}
if (!m_allow_mismatched_daemon_version && ((*version >> 16) != CORE_RPC_VERSION_MAJOR))
{
if (!silent)
fail_msg_writer() << boost::format(tr("Daemon uses a different RPC major version (%u) than the wallet (%u): %s. Either update one of them, or use --allow-mismatched-daemon-version.")) % (*version>>16) % CORE_RPC_VERSION_MAJOR % m_wallet->get_daemon_address();
return false;
}
return true;
}
/*!
* \brief Gets the word seed language from the user.
*
* User is asked to choose from a list of supported languages.
*
* \return The chosen language.
*/
std::string simple_wallet::get_mnemonic_language()
{
std::vector<std::string> language_list_self, language_list_english;
const std::vector<std::string> &language_list = m_use_english_language_names ? language_list_english : language_list_self;
std::string language_choice;
int language_number = -1;
crypto::ElectrumWords::get_language_list(language_list_self, false);
crypto::ElectrumWords::get_language_list(language_list_english, true);
std::cout << tr("List of available languages for your wallet's seed:") << std::endl;
std::cout << tr("If your display freezes, exit blind with ^C, then run again with --use-english-language-names") << std::endl;
int ii;
std::vector<std::string>::const_iterator it;
for (it = language_list.begin(), ii = 0; it != language_list.end(); it++, ii++)
{
std::cout << ii << " : " << *it << std::endl;
}
while (language_number < 0)
{
language_choice = input_line(tr("Enter the number corresponding to the language of your choice"));
if (std::cin.eof())
return std::string();
try
{
language_number = std::stoi(language_choice);
if (!((language_number >= 0) && (static_cast<unsigned int>(language_number) < language_list.size())))
{
language_number = -1;
fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
}
}
return language_list_self[language_number];
}
//----------------------------------------------------------------------------------------------------
boost::optional<tools::password_container> simple_wallet::get_and_verify_password() const
{
auto pwd_container = default_password_prompter(m_wallet_file.empty());
if (!pwd_container)
return boost::none;
if (!m_wallet->verify_password(pwd_container->password()))
{
fail_msg_writer() << tr("invalid password");
return boost::none;
}
return pwd_container;
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
const crypto::secret_key& recovery_key, bool recover, bool two_random, const std::string &old_language)
{
std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
m_wallet = std::move(rc.first);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
bool was_deprecated_wallet = m_restore_deterministic_wallet && ((old_language == crypto::ElectrumWords::old_language_name) ||
crypto::ElectrumWords::get_is_old_style_seed(m_electrum_seed));
std::string mnemonic_language = old_language;
std::vector<std::string> language_list;
crypto::ElectrumWords::get_language_list(language_list);
if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
{
mnemonic_language = m_mnemonic_language;
}
// Ask for seed language if:
// it's a deterministic wallet AND
// a seed language is not already specified AND
// (it is not a wallet restore OR if it was a deprecated wallet
// that was earlier used before this restore)
if ((!two_random) && (mnemonic_language.empty() || mnemonic_language == crypto::ElectrumWords::old_language_name) && (!m_restore_deterministic_wallet || was_deprecated_wallet))
{
if (was_deprecated_wallet)
{
// The user had used an older version of the wallet with old style mnemonics.
message_writer(console_color_green, false) << "\n" << tr("You had been using "
"a deprecated version of the wallet. Please use the new seed that we provide.\n");
}
mnemonic_language = get_mnemonic_language();
if (mnemonic_language.empty())
return {};
}
m_wallet->set_seed_language(mnemonic_language);
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
crypto::secret_key recovery_val;
try
{
recovery_val = m_wallet->generate(m_wallet_file, std::move(rc.second).password(), recovery_key, recover, two_random, create_address_file);
message_writer(console_color_white, true) << tr("Generated new wallet: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
PAUSE_READLINE();
std::cout << tr("View key: ");
print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
putchar('\n');
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
// convert rng value to electrum-style word list
epee::wipeable_string electrum_words;
crypto::ElectrumWords::bytes_to_words(recovery_val, electrum_words, mnemonic_language);
success_msg_writer() <<
"**********************************************************************\n" <<
tr("Your wallet has been generated!\n"
"To start synchronizing with the daemon, use the \"refresh\" command.\n"
"Use the \"help\" command to see the list of available commands.\n"
"Use \"help <command>\" to see a command's documentation.\n"
"Always use the \"exit\" command when closing swap-wallet-cli to save \n"
"your current session's state. Otherwise, you might need to synchronize \n"
"your wallet again (your wallet keys are NOT at risk in any case).\n")
;
if (!two_random)
{
print_seed(electrum_words);
}
success_msg_writer() << "**********************************************************************";
return password;
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
const cryptonote::account_public_address& address, const boost::optional<crypto::secret_key>& spendkey,
const crypto::secret_key& viewkey)
{
std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
m_wallet = std::move(rc.first);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
if (m_restore_height)
m_wallet->set_refresh_from_block_height(m_restore_height);
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
try
{
if (spendkey)
{
m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, *spendkey, viewkey, create_address_file);
}
else
{
m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, viewkey, create_address_file);
}
message_writer(console_color_white, true) << tr("Generated new wallet: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
return password;
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm)
{
std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
m_wallet = std::move(rc.first);
m_wallet->callback(this);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
if (m_restore_height)
m_wallet->set_refresh_from_block_height(m_restore_height);
auto device_desc = tools::wallet2::device_name_option(vm);
auto device_derivation_path = tools::wallet2::device_derivation_path_option(vm);
try
{
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
m_wallet->device_derivation_path(device_derivation_path);
m_wallet->restore(m_wallet_file, std::move(rc.second).password(), device_desc.empty() ? "Ledger" : device_desc, create_address_file);
message_writer(console_color_white, true) << tr("Generated new wallet on hw device: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
return password;
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
const epee::wipeable_string &multisig_keys, const std::string &old_language)
{
std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
m_wallet = std::move(rc.first);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
std::string mnemonic_language = old_language;
std::vector<std::string> language_list;
crypto::ElectrumWords::get_language_list(language_list);
if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
{
mnemonic_language = m_mnemonic_language;
}
m_wallet->set_seed_language(mnemonic_language);
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
try
{
m_wallet->generate(m_wallet_file, std::move(rc.second).password(), multisig_keys, create_address_file);
bool ready;
uint32_t threshold, total;
if (!m_wallet->multisig(&ready, &threshold, &total) || !ready)
{
fail_msg_writer() << tr("failed to generate new mutlisig wallet");
return {};
}
message_writer(console_color_white, true) << boost::format(tr("Generated new %u/%u multisig wallet: ")) % threshold % total
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
return password;
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::open_wallet(const boost::program_options::variables_map& vm)
{
if (!tools::wallet2::wallet_valid_path_format(m_wallet_file))
{
fail_msg_writer() << tr("wallet file path not valid: ") << m_wallet_file;
return {};
}
bool keys_file_exists;
bool wallet_file_exists;
tools::wallet2::wallet_exists(m_wallet_file, keys_file_exists, wallet_file_exists);
if(!keys_file_exists)
{
fail_msg_writer() << tr("Key file not found. Failed to open wallet");
return {};
}
epee::wipeable_string password;
try
{
auto rc = tools::wallet2::make_from_file(vm, false, "", password_prompter);
m_wallet = std::move(rc.first);
password = std::move(std::move(rc.second).password());
if (!m_wallet)
{
return {};
}
m_wallet->callback(this);
m_wallet->load(m_wallet_file, password);
std::string prefix;
bool ready;
uint32_t threshold, total;
if (m_wallet->watch_only())
prefix = tr("Opened watch-only wallet");
else if (m_wallet->multisig(&ready, &threshold, &total))
prefix = (boost::format(tr("Opened %u/%u multisig wallet%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
else
prefix = tr("Opened wallet");
message_writer(console_color_white, true) <<
prefix << ": " << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
if (m_wallet->get_account().get_device()) {
message_writer(console_color_white, true) << "Wallet is on device: " << m_wallet->get_account().get_device().get_name();
}
// If the wallet file is deprecated, we should ask for mnemonic language again and store
// everything in the new format.
// NOTE: this is_deprecated() refers to the wallet file format before becoming JSON. It does not refer to the "old english" seed words form of "deprecated" used elsewhere.
if (m_wallet->is_deprecated())
{
bool is_deterministic;
{
SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return {};);
is_deterministic = m_wallet->is_deterministic();
}
if (is_deterministic)
{
message_writer(console_color_green, false) << "\n" << tr("You had been using "
"a deprecated version of the wallet. Please proceed to upgrade your wallet.\n");
std::string mnemonic_language = get_mnemonic_language();
if (mnemonic_language.empty())
return {};
m_wallet->set_seed_language(mnemonic_language);
m_wallet->rewrite(m_wallet_file, password);
// Display the seed
epee::wipeable_string seed;
m_wallet->get_seed(seed);
print_seed(seed);
}
else
{
message_writer(console_color_green, false) << "\n" << tr("You had been using "
"a deprecated version of the wallet. Your wallet file format is being upgraded now.\n");
m_wallet->rewrite(m_wallet_file, password);
}
}
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to load wallet: ") << e.what();
if (m_wallet)
{
// only suggest removing cache if the password was actually correct
bool password_is_correct = false;
try
{
password_is_correct = m_wallet->verify_password(password);
}
catch (...) { } // guard against I/O errors
if (password_is_correct)
fail_msg_writer() << boost::format(tr("You may want to remove the file \"%s\" and try again")) % m_wallet_file;
}
return {};
}
success_msg_writer() <<
"**********************************************************************\n" <<
tr("Use the \"help\" command to see the list of available commands.\n") <<
tr("Use \"help <command>\" to see a command's documentation.\n") <<
"**********************************************************************";
return password;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::close_wallet()
{
if (m_idle_run.load(std::memory_order_relaxed))
{
m_idle_run.store(false, std::memory_order_relaxed);
m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed);
m_wallet->stop();
{
boost::unique_lock<boost::mutex> lock(m_idle_mutex);
m_idle_cond.notify_one();
}
m_idle_thread.join();
}
bool r = m_wallet->deinit();
if (!r)
{
fail_msg_writer() << tr("failed to deinitialize wallet");
return false;
}
try
{
m_wallet->store();
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::save(const std::vector<std::string> &args)
{
try
{
LOCK_IDLE_SCOPE();
m_wallet->store();
success_msg_writer() << tr("Wallet data saved");
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::save_watch_only(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->multisig())
{
fail_msg_writer() << tr("wallet is multisig and cannot save a watch-only version");
return true;
}
const auto pwd_container = password_prompter(tr("Password for new watch-only wallet"), true);
if (!pwd_container)
{
fail_msg_writer() << tr("failed to read wallet password");
return true;
}
try
{
std::string new_keys_filename;
m_wallet->write_watch_only_wallet(m_wallet_file, pwd_container->password(), new_keys_filename);
success_msg_writer() << tr("Watch only wallet saved as: ") << new_keys_filename;
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to save watch only wallet: ") << e.what();
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::start_background_mining()
{
COMMAND_RPC_MINING_STATUS::request reqq;
COMMAND_RPC_MINING_STATUS::response resq;
bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq);
std::string err = interpret_rpc_response(r, resq.status);
if (!r)
return;
if (!err.empty())
{
fail_msg_writer() << tr("Failed to query mining status: ") << err;
return;
}
if (!resq.is_background_mining_enabled)
{
COMMAND_RPC_START_MINING::request req;
COMMAND_RPC_START_MINING::response res;
req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
req.threads_count = 1;
req.do_background_mining = true;
req.ignore_battery = false;
bool r = m_wallet->invoke_http_json("/start_mining", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (!err.empty())
{
fail_msg_writer() << tr("Failed to setup background mining: ") << err;
return;
}
}
success_msg_writer() << tr("Background mining enabled. Thank you for supporting the Swap network.");
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::stop_background_mining()
{
COMMAND_RPC_MINING_STATUS::request reqq;
COMMAND_RPC_MINING_STATUS::response resq;
bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq);
if (!r)
return;
std::string err = interpret_rpc_response(r, resq.status);
if (!err.empty())
{
fail_msg_writer() << tr("Failed to query mining status: ") << err;
return;
}
if (resq.is_background_mining_enabled)
{
COMMAND_RPC_STOP_MINING::request req;
COMMAND_RPC_STOP_MINING::response res;
bool r = m_wallet->invoke_http_json("/stop_mining", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (!err.empty())
{
fail_msg_writer() << tr("Failed to setup background mining: ") << err;
return;
}
}
message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change.");
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::check_background_mining(const epee::wipeable_string &password)
{
tools::wallet2::BackgroundMiningSetupType setup = m_wallet->setup_background_mining();
if (setup == tools::wallet2::BackgroundMiningNo)
{
message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change.");
return;
}
if (!m_wallet->is_trusted_daemon())
{
message_writer() << tr("Using an untrusted daemon, skipping background mining check");
return;
}
COMMAND_RPC_MINING_STATUS::request req;
COMMAND_RPC_MINING_STATUS::response res;
bool r = m_wallet->invoke_http_json("/mining_status", req, res);
std::string err = interpret_rpc_response(r, res.status);
bool is_background_mining_enabled = false;
if (err.empty())
is_background_mining_enabled = res.is_background_mining_enabled;
if (is_background_mining_enabled)
{
// already active, nice
m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes);
m_wallet->rewrite(m_wallet_file, password);
start_background_mining();
return;
}
if (res.active)
return;
if (setup == tools::wallet2::BackgroundMiningMaybe)
{
message_writer() << tr("The daemon is not set up to background mine.");
message_writer() << tr("With background mining enabled, the daemon will mine when idle and not on battery.");
message_writer() << tr("Enabling this supports the network you are using, and makes you eligible for receiving new Swap");
std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): "));
if (std::cin.eof() || !command_line::is_yes(accepted)) {
m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningNo);
m_wallet->rewrite(m_wallet_file, password);
message_writer(console_color_red, false) << tr("Background mining not enabled. Set setup-background-mining to 1 to change.");
return;
}
m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes);
m_wallet->rewrite(m_wallet_file, password);
start_background_mining();
}
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::start_mining(const std::vector<std::string>& args)
{
if (!m_wallet->is_trusted_daemon())
{
fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
return true;
}
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
COMMAND_RPC_START_MINING::request req = AUTO_VAL_INIT(req);
req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
bool ok = true;
size_t arg_size = args.size();
if(arg_size >= 3)
{
if (!parse_bool_and_use(args[2], [&](bool r) { req.ignore_battery = r; }))
return true;
}
if(arg_size >= 2)
{
if (!parse_bool_and_use(args[1], [&](bool r) { req.do_background_mining = r; }))
return true;
}
if(arg_size >= 1)
{
uint16_t num = 1;
ok = string_tools::get_xtype_from_string(num, args[0]);
ok = ok && 1 <= num;
req.threads_count = num;
}
else
{
req.threads_count = 1;
}
if (!ok)
{
PRINT_USAGE(USAGE_START_MINING);
return true;
}
COMMAND_RPC_START_MINING::response res;
bool r = m_wallet->invoke_http_json("/start_mining", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (err.empty())
success_msg_writer() << tr("Mining started in daemon");
else
fail_msg_writer() << tr("mining has NOT been started: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::stop_mining(const std::vector<std::string>& args)
{
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
COMMAND_RPC_STOP_MINING::request req;
COMMAND_RPC_STOP_MINING::response res;
bool r = m_wallet->invoke_http_json("/stop_mining", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (err.empty())
success_msg_writer() << tr("Mining stopped in daemon");
else
fail_msg_writer() << tr("mining has NOT been stopped: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_daemon_rpc_prices(const std::string &daemon_url, uint32_t &actual_cph, uint32_t &claimed_cph)
{
try
{
auto i = m_claimed_cph.find(daemon_url);
if (i == m_claimed_cph.end())
return false;
claimed_cph = m_claimed_cph[daemon_url];
bool payment_required;
uint64_t credits, diff, credits_per_hash_found, height, seed_height;
uint32_t cookie;
cryptonote::blobdata hashing_blob;
crypto::hash seed_hash, next_seed_hash;
if (m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie) && payment_required)
{
actual_cph = RPC_CREDITS_PER_HASH_SCALE * (credits_per_hash_found / (float)diff);
return true;
}
else
{
fail_msg_writer() << tr("Error checking daemon RPC access prices");
}
}
catch (const std::exception &e)
{
// can't check
fail_msg_writer() << tr("Error checking daemon RPC access prices: ") << e.what();
return false;
}
// no record found for this daemon
return false;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_daemon(const std::vector<std::string>& args)
{
std::string daemon_url;
if (args.size() < 1)
{
PRINT_USAGE(USAGE_SET_DAEMON);
return true;
}
boost::regex rgx("^(.*://)?([A-Za-z0-9\\-\\.]+)(:[0-9]+)?");
boost::cmatch match;
// If user input matches URL regex
if (boost::regex_match(args[0].c_str(), match, rgx))
{
if (match.length() < 4)
{
fail_msg_writer() << tr("Unexpected array length - Exited simple_wallet::set_daemon()");
return true;
}
// If no port has been provided, use the default from config
if (!match[3].length())
{
uint16_t daemon_port = get_config(m_wallet->nettype()).RPC_DEFAULT_PORT;
daemon_url = match[1] + match[2] + std::string(":") + std::to_string(daemon_port);
} else {
daemon_url = args[0];
}
LOCK_IDLE_SCOPE();
m_wallet->init(daemon_url);
if (args.size() == 2)
{
if (args[1] == "trusted")
m_wallet->set_trusted_daemon(true);
else if (args[1] == "untrusted")
m_wallet->set_trusted_daemon(false);
else
{
fail_msg_writer() << tr("Expected trusted or untrusted, got ") << args[1] << ": assuming untrusted";
m_wallet->set_trusted_daemon(false);
}
}
else
{
m_wallet->set_trusted_daemon(false);
try
{
if (tools::is_local_address(m_wallet->get_daemon_address()))
{
MINFO(tr("Daemon is local, assuming trusted"));
m_wallet->set_trusted_daemon(true);
}
}
catch (const std::exception &e) { }
}
if (!try_connect_to_daemon())
{
fail_msg_writer() << tr("Failed to connect to daemon");
return true;
}
success_msg_writer() << boost::format("Daemon set to %s, %s") % daemon_url % (m_wallet->is_trusted_daemon() ? tr("trusted") : tr("untrusted"));
// check whether the daemon's prices match the claim, and disconnect if not, to disincentivize daemons lying
uint32_t actual_cph, claimed_cph;
if (check_daemon_rpc_prices(daemon_url, actual_cph, claimed_cph))
{
if (actual_cph < claimed_cph)
{
fail_msg_writer() << tr("Daemon RPC credits/hash is less than was claimed. Either this daemon is cheating, or it changed its setup recently.");
fail_msg_writer() << tr("Claimed: ") << claimed_cph / (float)RPC_CREDITS_PER_HASH_SCALE;
fail_msg_writer() << tr("Actual: ") << actual_cph / (float)RPC_CREDITS_PER_HASH_SCALE;
}
}
m_daemon_rpc_payment_message_displayed = false;
} else {
fail_msg_writer() << tr("This does not seem to be a valid daemon URL.");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::save_bc(const std::vector<std::string>& args)
{
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
COMMAND_RPC_SAVE_BC::request req;
COMMAND_RPC_SAVE_BC::response res;
bool r = m_wallet->invoke_http_json("/save_bc", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (err.empty())
success_msg_writer() << tr("Blockchain saved");
else
fail_msg_writer() << tr("blockchain can't be saved: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_new_block(uint64_t height, const cryptonote::block& block)
{
if (m_locked)
return;
if (!m_auto_refresh_refreshing)
m_refresh_progress_reporter.update(height, false);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index, uint64_t unlock_time)
{
if (m_locked)
return;
message_writer(console_color_green, false) << "\r" <<
tr("Height ") << height << ", " <<
tr("txid ") << txid << ", " <<
print_money(amount) << ", " <<
tr("idx ") << subaddr_index;
const uint64_t warn_height = m_wallet->nettype() == TESTNET ? 1000000 : m_wallet->nettype() == STAGENET ? 50000 : 1650000;
if (height >= warn_height)
{
std::vector<tx_extra_field> tx_extra_fields;
parse_tx_extra(tx.extra, tx_extra_fields); // failure ok
tx_extra_nonce extra_nonce;
if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
{
crypto::hash payment_id = crypto::null_hash;
crypto::hash8 payment_id8 = crypto::null_hash8;
if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
{
if (payment_id8 != crypto::null_hash8)
message_writer() <<
tr("NOTE: this transaction uses an encrypted payment ID: consider using subaddresses instead");
}
else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
message_writer(console_color_red, false) <<
tr("WARNING: this transaction uses an unencrypted payment ID: these are obsolete and ignored. Use subaddresses instead.");
}
}
if (unlock_time && !cryptonote::is_coinbase(tx))
message_writer() << tr("NOTE: This transaction is locked, see details with: show_transfer ") + epee::string_tools::pod_to_hex(txid);
if (m_auto_refresh_refreshing)
m_cmd_binder.print_prompt();
else
m_refresh_progress_reporter.update(height, true);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_unconfirmed_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index)
{
if (m_locked)
return;
// Not implemented in CLI wallet
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_money_spent(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& in_tx, uint64_t amount, const cryptonote::transaction& spend_tx, const cryptonote::subaddress_index& subaddr_index)
{
if (m_locked)
return;
message_writer(console_color_magenta, false) << "\r" <<
tr("Height ") << height << ", " <<
tr("txid ") << txid << ", " <<
tr("spent ") << print_money(amount) << ", " <<
tr("idx ") << subaddr_index;
if (m_auto_refresh_refreshing)
m_cmd_binder.print_prompt();
else
m_refresh_progress_reporter.update(height, true);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_skip_transaction(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx)
{
if (m_locked)
return;
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::on_get_password(const char *reason)
{
if (m_locked)
return boost::none;
// can't ask for password from a background thread
if (!m_in_manual_refresh.load(std::memory_order_relaxed))
{
message_writer(console_color_red, false) << boost::format(tr("Password needed (%s) - use the refresh command")) % reason;
m_cmd_binder.print_prompt();
return boost::none;
}
PAUSE_READLINE();
std::string msg = tr("Enter password");
if (reason && *reason)
msg += std::string(" (") + reason + ")";
auto pwd_container = tools::password_container::prompt(false, msg.c_str());
if (!pwd_container)
{
MERROR("Failed to read password");
return boost::none;
}
return pwd_container->password();
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_device_button_request(uint64_t code)
{
message_writer(console_color_white, false) << tr("Device requires attention");
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::on_device_pin_request()
{
PAUSE_READLINE();
std::string msg = tr("Enter device PIN");
auto pwd_container = tools::password_container::prompt(false, msg.c_str());
THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device PIN"));
return pwd_container->password();
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::on_device_passphrase_request(bool on_device)
{
if (on_device){
message_writer(console_color_white, true) << tr("Please enter the device passphrase on the device");
return boost::none;
}
PAUSE_READLINE();
std::string msg = tr("Enter device passphrase");
auto pwd_container = tools::password_container::prompt(false, msg.c_str());
THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device passphrase"));
return pwd_container->password();
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_refresh_finished(uint64_t start_height, uint64_t fetched_blocks, bool is_init, bool received_money)
{
// Key image sync after the first refresh
if (!m_wallet->get_account().get_device().has_tx_cold_sign() || m_wallet->get_account().get_device().has_ki_live_refresh()) {
return;
}
if (!received_money || m_wallet->get_device_last_key_image_sync() != 0) {
return;
}
// Finished first refresh for HW device and money received -> KI sync
message_writer() << "\n" << tr("The first refresh has finished for the HW-based wallet with received money. hw_key_images_sync is needed. ");
std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): "));
if (std::cin.eof() || !command_line::is_yes(accepted)) {
message_writer(console_color_red, false) << tr("hw_key_images_sync skipped. Run command manually before a transfer.");
return;
}
key_images_sync_intern();
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bool is_init)
{
if (!try_connect_to_daemon(is_init))
return true;
LOCK_IDLE_SCOPE();
crypto::hash transfer_hash_pre{};
uint64_t height_pre = 0, height_post;
if (reset != ResetNone)
{
if (reset == ResetSoftKeepKI)
height_pre = m_wallet->hash_m_transfers(-1, transfer_hash_pre);
m_wallet->rescan_blockchain(reset == ResetHard, false, reset == ResetSoftKeepKI);
}
PAUSE_READLINE();
message_writer() << tr("Starting refresh...");
uint64_t fetched_blocks = 0;
bool received_money = false;
bool ok = false;
std::ostringstream ss;
try
{
m_in_manual_refresh.store(true, std::memory_order_relaxed);
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
m_wallet->refresh(m_wallet->is_trusted_daemon(), start_height, fetched_blocks, received_money);
if (reset == ResetSoftKeepKI)
{
m_wallet->finish_rescan_bc_keep_key_images(height_pre, transfer_hash_pre);
height_post = m_wallet->get_num_transfer_details();
if (height_pre != height_post)
{
message_writer() << tr("New transfer received since rescan was started. Key images are incomplete.");
}
}
ok = true;
// Clear line "Height xxx of xxx"
std::cout << "\r \r";
success_msg_writer(true) << tr("Refresh done, blocks received: ") << fetched_blocks;
if (is_init)
print_accounts();
show_balance_unlocked();
on_refresh_finished(start_height, fetched_blocks, is_init, received_money);
}
catch (const tools::error::daemon_busy&)
{
ss << tr("daemon is busy. Please try again later.");
}
catch (const tools::error::no_connection_to_daemon&)
{
ss << tr("no connection to daemon. Please make sure daemon is running.");
}
catch (const tools::error::payment_required&)
{
ss << tr("payment required.");
m_need_payment = true;
}
catch (const tools::error::wallet_rpc_error& e)
{
LOG_ERROR("RPC error: " << e.to_string());
ss << tr("RPC error: ") << e.what();
}
catch (const tools::error::refresh_error& e)
{
LOG_ERROR("refresh error: " << e.to_string());
ss << tr("refresh error: ") << e.what();
}
catch (const tools::error::wallet_internal_error& e)
{
LOG_ERROR("internal error: " << e.to_string());
ss << tr("internal error: ") << e.what();
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
ss << tr("unexpected error: ") << e.what();
}
catch (...)
{
LOG_ERROR("unknown error");
ss << tr("unknown error");
}
if (!ok)
{
fail_msg_writer() << tr("refresh failed: ") << ss.str() << ". " << tr("Blocks received: ") << fetched_blocks;
}
// prevent it from triggering the idle screen due to waiting for a foreground refresh
m_last_activity_time = time(NULL);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::refresh(const std::vector<std::string>& args)
{
uint64_t start_height = 0;
if(!args.empty()){
try
{
start_height = boost::lexical_cast<uint64_t>( args[0] );
}
catch(const boost::bad_lexical_cast &)
{
start_height = 0;
}
}
return refresh_main(start_height, ResetNone);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_balance_unlocked(bool detailed)
{
std::string extra;
if (m_wallet->has_multisig_partial_key_images())
extra = tr(" (Some owned outputs have partial key images - import_multisig_info needed)");
else if (m_wallet->has_unknown_key_images())
extra += tr(" (Some owned outputs have missing key images - import_key_images needed)");
success_msg_writer() << tr("Currently selected account: [") << m_current_subaddress_account << tr("] ") << m_wallet->get_subaddress_label({m_current_subaddress_account, 0});
const std::string tag = m_wallet->get_account_tags().second[m_current_subaddress_account];
success_msg_writer() << tr("Tag: ") << (tag.empty() ? std::string{tr("(No tag assigned)")} : tag);
uint64_t blocks_to_unlock;
uint64_t unlocked_balance = m_wallet->unlocked_balance(m_current_subaddress_account, false, &blocks_to_unlock);
std::string unlock_time_message;
if (blocks_to_unlock > 0)
unlock_time_message = (boost::format(" (%lu block(s) to unlock)") % blocks_to_unlock).str();
success_msg_writer() << tr("Balance: ") << print_money(m_wallet->balance(m_current_subaddress_account, false)) << ", "
<< tr("unlocked balance: ") << print_money(unlocked_balance) << unlock_time_message << extra;
std::map<uint32_t, uint64_t> balance_per_subaddress = m_wallet->balance_per_subaddress(m_current_subaddress_account, false);
std::map<uint32_t, std::pair<uint64_t, uint64_t>> unlocked_balance_per_subaddress = m_wallet->unlocked_balance_per_subaddress(m_current_subaddress_account, false);
if (!detailed || balance_per_subaddress.empty())
return true;
success_msg_writer() << tr("Balance per address:");
success_msg_writer() << boost::format("%15s %21s %21s %7s %21s") % tr("Address") % tr("Balance") % tr("Unlocked balance") % tr("Outputs") % tr("Label");
std::vector<tools::wallet2::transfer_details> transfers;
m_wallet->get_transfers(transfers);
for (const auto& i : balance_per_subaddress)
{
cryptonote::subaddress_index subaddr_index = {m_current_subaddress_account, i.first};
std::string address_str = m_wallet->get_subaddress_as_str(subaddr_index).substr(0, 6);
uint64_t num_unspent_outputs = std::count_if(transfers.begin(), transfers.end(), [&subaddr_index](const tools::wallet2::transfer_details& td) { return !td.m_spent && td.m_subaddr_index == subaddr_index; });
success_msg_writer() << boost::format(tr("%8u %6s %21s %21s %7u %21s")) % i.first % address_str % print_money(i.second) % print_money(unlocked_balance_per_subaddress[i.first].first) % num_unspent_outputs % m_wallet->get_subaddress_label(subaddr_index);
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_balance(const std::vector<std::string>& args/* = std::vector<std::string>()*/)
{
if (args.size() > 1 || (args.size() == 1 && args[0] != "detail"))
{
PRINT_USAGE(USAGE_SHOW_BALANCE);
return true;
}
LOCK_IDLE_SCOPE();
show_balance_unlocked(args.size() == 1);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_incoming_transfers(const std::vector<std::string>& args)
{
if (args.size() > 3)
{
PRINT_USAGE(USAGE_INCOMING_TRANSFERS);
return true;
}
auto local_args = args;
LOCK_IDLE_SCOPE();
bool filter = false;
bool available = false;
bool verbose = false;
bool uses = false;
if (local_args.size() > 0)
{
if (local_args[0] == "available")
{
filter = true;
available = true;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "unavailable")
{
filter = true;
available = false;
local_args.erase(local_args.begin());
}
}
while (local_args.size() > 0)
{
if (local_args[0] == "verbose")
verbose = true;
else if (local_args[0] == "uses")
uses = true;
else
{
fail_msg_writer() << tr("Invalid keyword: ") << local_args.front();
break;
}
local_args.erase(local_args.begin());
}
const uint64_t blockchain_height = m_wallet->get_blockchain_current_height();
PAUSE_READLINE();
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return true;
local_args.erase(local_args.begin());
}
if (local_args.size() > 0)
{
PRINT_USAGE(USAGE_INCOMING_TRANSFERS);
return true;
}
tools::wallet2::transfer_container transfers;
m_wallet->get_transfers(transfers);
size_t transfers_found = 0;
for (const auto& td : transfers)
{
if (!filter || available != td.m_spent)
{
if (m_current_subaddress_account != td.m_subaddr_index.major || (!subaddr_indices.empty() && subaddr_indices.count(td.m_subaddr_index.minor) == 0))
continue;
if (!transfers_found)
{
std::string verbose_string;
if (verbose)
verbose_string = (boost::format("%68s%68s") % tr("pubkey") % tr("key image")).str();
message_writer() << boost::format("%21s%8s%12s%8s%16s%68s%16s%s") % tr("amount") % tr("spent") % tr("unlocked") % tr("ringct") % tr("global index") % tr("tx id") % tr("addr index") % verbose_string;
}
std::string extra_string;
if (verbose)
extra_string += (boost::format("%68s%68s") % td.get_public_key() % (td.m_key_image_known ? epee::string_tools::pod_to_hex(td.m_key_image) : td.m_key_image_partial ? (epee::string_tools::pod_to_hex(td.m_key_image) + "/p") : std::string(64, '?'))).str();
if (uses)
{
std::vector<uint64_t> heights;
for (const auto &e: td.m_uses) heights.push_back(e.first);
const std::pair<std::string, std::string> line = show_outputs_line(heights, blockchain_height, td.m_spent_height);
extra_string += std::string("\n ") + tr("Used at heights: ") + line.first + "\n " + line.second;
}
message_writer(td.m_spent ? console_color_magenta : console_color_green, false) <<
boost::format("%21s%8s%12s%8s%16u%68s%16u%s") %
print_money(td.amount()) %
(td.m_spent ? tr("T") : tr("F")) %
(m_wallet->frozen(td) ? tr("[frozen]") : m_wallet->is_transfer_unlocked(td) ? tr("unlocked") : tr("locked")) %
(td.is_rct() ? tr("RingCT") : tr("-")) %
td.m_global_output_index %
td.m_txid %
td.m_subaddr_index.minor %
extra_string;
++transfers_found;
}
}
if (!transfers_found)
{
if (!filter)
{
success_msg_writer() << tr("No incoming transfers");
}
else if (available)
{
success_msg_writer() << tr("No incoming available transfers");
}
else
{
success_msg_writer() << tr("No incoming unavailable transfers");
}
}
else
{
success_msg_writer() << boost::format("Found %u/%u transfers") % transfers_found % transfers.size();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_payments(const std::vector<std::string> &args)
{
if(args.empty())
{
PRINT_USAGE(USAGE_PAYMENTS);
return true;
}
LOCK_IDLE_SCOPE();
PAUSE_READLINE();
message_writer() << boost::format("%68s%68s%12s%21s%16s%16s") %
tr("payment") % tr("transaction") % tr("height") % tr("amount") % tr("unlock time") % tr("addr index");
bool payments_found = false;
for(std::string arg : args)
{
crypto::hash payment_id;
if(tools::wallet2::parse_payment_id(arg, payment_id))
{
std::list<tools::wallet2::payment_details> payments;
m_wallet->get_payments(payment_id, payments);
if(payments.empty())
{
success_msg_writer() << tr("No payments with id ") << payment_id;
continue;
}
for (const tools::wallet2::payment_details& pd : payments)
{
if(!payments_found)
{
payments_found = true;
}
success_msg_writer(true) <<
boost::format("%68s%68s%12s%21s%16s%16s") %
payment_id %
pd.m_tx_hash %
pd.m_block_height %
print_money(pd.m_amount) %
pd.m_unlock_time %
pd.m_subaddr_index.minor;
}
}
else
{
fail_msg_writer() << tr("payment ID has invalid format, expected 16 or 64 character hex string: ") << arg;
}
}
return true;
}
//----------------------------------------------------------------------------------------------------
uint64_t simple_wallet::get_daemon_blockchain_height(std::string& err)
{
if (!m_wallet)
{
throw std::runtime_error("simple_wallet null wallet");
}
return m_wallet->get_daemon_blockchain_height(err);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_blockchain_height(const std::vector<std::string>& args)
{
if (!try_connect_to_daemon())
return true;
std::string err;
uint64_t bc_height = get_daemon_blockchain_height(err);
if (err.empty())
success_msg_writer() << bc_height;
else
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::rescan_spent(const std::vector<std::string> &args)
{
if (!m_wallet->is_trusted_daemon())
{
fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
return true;
}
if (!try_connect_to_daemon())
return true;
try
{
LOCK_IDLE_SCOPE();
m_wallet->rescan_spent();
}
catch (const tools::error::daemon_busy&)
{
fail_msg_writer() << tr("daemon is busy. Please try again later.");
}
catch (const tools::error::no_connection_to_daemon&)
{
fail_msg_writer() << tr("no connection to daemon. Please make sure daemon is running.");
}
catch (const tools::error::payment_required&)
{
fail_msg_writer() << tr("payment required.");
m_need_payment = true;
}
catch (const tools::error::is_key_image_spent_error&)
{
fail_msg_writer() << tr("failed to get spent status");
}
catch (const tools::error::wallet_rpc_error& e)
{
LOG_ERROR("RPC error: " << e.to_string());
fail_msg_writer() << tr("RPC error: ") << e.what();
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << tr("unexpected error: ") << e.what();
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
std::pair<std::string, std::string> simple_wallet::show_outputs_line(const std::vector<uint64_t> &heights, uint64_t blockchain_height, uint64_t highlight_height) const
{
std::stringstream ostr;
for (uint64_t h: heights)
blockchain_height = std::max(blockchain_height, h);
for (size_t j = 0; j < heights.size(); ++j)
ostr << (heights[j] == highlight_height ? " *" : " ") << heights[j];
// visualize the distribution, using the code by moneroexamples onion-monero-viewer
const uint64_t resolution = 79;
std::string ring_str(resolution, '_');
for (size_t j = 0; j < heights.size(); ++j)
{
uint64_t pos = (heights[j] * resolution) / blockchain_height;
ring_str[pos] = 'o';
}
if (highlight_height < blockchain_height)
{
uint64_t pos = (highlight_height * resolution) / blockchain_height;
ring_str[pos] = '*';
}
return std::make_pair(ostr.str(), ring_str);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::print_ring_members(const std::vector<tools::wallet2::pending_tx>& ptx_vector, std::ostream& ostr)
{
uint32_t version;
if (!try_connect_to_daemon(false, &version))
return false;
// available for RPC version 1.4 or higher
if (version < MAKE_CORE_RPC_VERSION(1, 4))
return true;
std::string err;
uint64_t blockchain_height = get_daemon_blockchain_height(err);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return false;
}
// for each transaction
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
const cryptonote::transaction& tx = ptx_vector[n].tx;
const tools::wallet2::tx_construction_data& construction_data = ptx_vector[n].construction_data;
ostr << boost::format(tr("\nTransaction %llu/%llu: txid=%s")) % (n + 1) % ptx_vector.size() % cryptonote::get_transaction_hash(tx);
// for each input
std::vector<uint64_t> spent_key_height(tx.vin.size());
std::vector<crypto::hash> spent_key_txid (tx.vin.size());
for (size_t i = 0; i < tx.vin.size(); ++i)
{
if (tx.vin[i].type() != typeid(cryptonote::txin_to_key))
continue;
const cryptonote::txin_to_key& in_key = boost::get<cryptonote::txin_to_key>(tx.vin[i]);
const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(construction_data.selected_transfers[i]);
const cryptonote::tx_source_entry *sptr = NULL;
for (const auto &src: construction_data.sources)
if (src.outputs[src.real_output].second.dest == td.get_public_key())
sptr = &src;
if (!sptr)
{
fail_msg_writer() << tr("failed to find construction data for tx input");
return false;
}
const cryptonote::tx_source_entry& source = *sptr;
ostr << boost::format(tr("\nInput %llu/%llu (%s): amount=%s")) % (i + 1) % tx.vin.size() % epee::string_tools::pod_to_hex(in_key.k_image) % print_money(source.amount);
// convert relative offsets of ring member keys into absolute offsets (indices) associated with the amount
std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key.key_offsets);
// get block heights from which those ring member keys originated
COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req);
req.outputs.resize(absolute_offsets.size());
for (size_t j = 0; j < absolute_offsets.size(); ++j)
{
req.outputs[j].amount = in_key.amount;
req.outputs[j].index = absolute_offsets[j];
}
COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res);
req.client = cryptonote::make_rpc_payment_signature(m_wallet->get_rpc_client_secret_key());
bool r = m_wallet->invoke_http_bin("/get_outs.bin", req, res);
err = interpret_rpc_response(r, res.status);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get output: ") << err;
return false;
}
// make sure that returned block heights are less than blockchain height
for (auto& res_out : res.outs)
{
if (res_out.height >= blockchain_height)
{
fail_msg_writer() << tr("output key's originating block height shouldn't be higher than the blockchain height");
return false;
}
}
ostr << tr("\nOriginating block heights: ");
spent_key_height[i] = res.outs[source.real_output].height;
spent_key_txid [i] = res.outs[source.real_output].txid;
std::vector<uint64_t> heights(absolute_offsets.size(), 0);
uint64_t highlight_height = std::numeric_limits<uint64_t>::max();
for (size_t j = 0; j < absolute_offsets.size(); ++j)
{
heights[j] = res.outs[j].height;
if (j == source.real_output)
highlight_height = heights[j];
}
std::pair<std::string, std::string> ring_str = show_outputs_line(heights, blockchain_height, highlight_height);
ostr << ring_str.first << tr("\n|") << ring_str.second << tr("|\n");
}
// warn if rings contain keys originating from the same tx or temporally very close block heights
bool are_keys_from_same_tx = false;
bool are_keys_from_close_height = false;
for (size_t i = 0; i < tx.vin.size(); ++i) {
for (size_t j = i + 1; j < tx.vin.size(); ++j)
{
if (spent_key_txid[i] == spent_key_txid[j])
are_keys_from_same_tx = true;
if (std::abs((int64_t)(spent_key_height[i] - spent_key_height[j])) < (int64_t)5)
are_keys_from_close_height = true;
}
}
if (are_keys_from_same_tx || are_keys_from_close_height)
{
ostr
<< tr("\nWarning: Some input keys being spent are from ")
<< (are_keys_from_same_tx ? tr("the same transaction") : tr("blocks that are temporally very close"))
<< tr(", which can break the anonymity of ring signature. Make sure this is intentional!");
}
ostr << ENDL;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::prompt_if_old(const std::vector<tools::wallet2::pending_tx> &ptx_vector)
{
// count the number of old outputs
std::string err;
uint64_t bc_height = get_daemon_blockchain_height(err);
if (!err.empty())
return true;
int max_n_old = 0;
for (const auto &ptx: ptx_vector)
{
int n_old = 0;
for (const auto i: ptx.selected_transfers)
{
const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i);
uint64_t age = bc_height - td.m_block_height;
if (age > OLD_AGE_WARN_THRESHOLD)
++n_old;
}
max_n_old = std::max(max_n_old, n_old);
}
if (max_n_old > 1)
{
std::stringstream prompt;
prompt << tr("Transaction spends more than one very old output. Privacy would be better if they were sent separately.");
prompt << ENDL << tr("Spend them now anyway?");
std::string accepted = input_line(prompt.str(), true);
if (std::cin.eof())
return false;
if (!command_line::is_yes(accepted))
{
return false;
}
}
return true;
}
void simple_wallet::check_for_inactivity_lock(bool user)
{
if (m_locked)
{
#ifdef HAVE_READLINE
PAUSE_READLINE();
rdln::clear_screen();
#endif
tools::clear_screen();
m_in_command = true;
if (!user)
{
const std::string speech = tr("I locked your Swap wallet to protect you while you were away");
std::vector<std::pair<std::string, size_t>> lines = tools::split_string_by_width(speech, 45);
size_t max_len = 0;
for (const auto &i: lines)
max_len = std::max(max_len, i.second);
const size_t n_u = max_len + 2;
tools::msg_writer() << " " << std::string(n_u, '_');
for (size_t i = 0; i < lines.size(); ++i)
tools::msg_writer() << (i == 0 ? "/" : i == lines.size() - 1 ? "\\" : "|") << " " << lines[i].first << std::string(max_len - lines[i].second, ' ') << " " << (i == 0 ? "\\" : i == lines.size() - 1 ? "/" : "|");
tools::msg_writer() << " " << std::string(n_u, '-') << std::endl
<< " " << std::endl
<< " " << std::endl
<< " @@@@@@@@@@@@@@/ " << std::endl
<< " @@@ %@@* " << std::endl
<< " @@( @@ " << std::endl
<< " @@ @@ " << std::endl
<< " .@* &@ @@ " << std::endl
<< " (@ @@ @@ " << std::endl
<< " *@ @@@@@ .@@@@@@ @@ " << std::endl
<< " @ @@. %@% @@ @# " << std::endl
<< " @@ @@ @@ .@ " << std::endl
<< " @# @% @. " << std::endl
<< " @, /@ @/ " << std::endl
<< " @# @@ @. " << std::endl
<< " @@ @@ @@ .@ " << std::endl
<< " @ &@( @@, @@ @% " << std::endl
<< " ,@ @@@@@ .@@@@@@ @@ " << std::endl
<< " #@ @@ @@ " << std::endl
<< " @( %@ @@ " << std::endl
<< " @@ @@ " << std::endl
<< " @@% @@ " << std::endl
<< " @@@ &@@. " << std::endl
<< " @@@@@@@@@@@@@@, " << std::endl
<< " " << std::endl
<< " " << std::endl;
}
while (1)
{
tools::msg_writer() << tr("Locked due to inactivity. The wallet password is required to unlock the console.");
try
{
if (get_and_verify_password())
break;
}
catch (...) { /* do nothing, just let the loop loop */ }
}
m_last_activity_time = time(NULL);
m_in_command = false;
m_locked = false;
}
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::on_command(bool (simple_wallet::*cmd)(const std::vector<std::string>&), const std::vector<std::string> &args)
{
const time_t now = time(NULL);
time_t dt = now - m_last_activity_time;
m_last_activity_time = time(NULL);
m_in_command = true;
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){
m_last_activity_time = time(NULL);
m_in_command = false;
});
check_for_inactivity_lock(false);
return (this->*cmd)(args);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::transfer_main(int transfer_type, const std::vector<std::string> &args_, bool called_by_mms)
{
// "transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <amount> [<payment_id>]"
if (!try_connect_to_daemon())
return false;
std::vector<std::string> local_args = args_;
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return false;
local_args.erase(local_args.begin());
}
uint32_t priority = 0;
if (local_args.size() > 0 && parse_priority(local_args[0], priority))
local_args.erase(local_args.begin());
priority = m_wallet->adjust_priority(priority);
size_t fake_outs_count = DEFAULT_MIX;
if(local_args.size() > 0) {
size_t ring_size;
if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
{
}
else if (ring_size == 0)
{
fail_msg_writer() << tr("Ring size must not be 0");
return false;
}
else
{
fake_outs_count = ring_size - 1;
local_args.erase(local_args.begin());
}
}
uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
if (adjusted_fake_outs_count > fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return false;
}
if (adjusted_fake_outs_count < fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return false;
}
const size_t min_args = (transfer_type == TransferLocked) ? 2 : 1;
if(local_args.size() < min_args)
{
fail_msg_writer() << tr("wrong number of arguments");
return false;
}
std::vector<uint8_t> extra;
bool payment_id_seen = false;
if (!local_args.empty())
{
std::string payment_id_str = local_args.back();
crypto::hash payment_id;
bool r = true;
if (tools::wallet2::parse_long_payment_id(payment_id_str, payment_id))
{
LONG_PAYMENT_ID_SUPPORT_CHECK();
std::string extra_nonce;
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
local_args.pop_back();
payment_id_seen = true;
message_writer() << tr("Warning: Unencrypted payment IDs will harm your privacy: ask the recipient to use subaddresses instead");
}
if(!r)
{
fail_msg_writer() << tr("payment id failed to encode");
return false;
}
}
uint64_t locked_blocks = 0;
if (transfer_type == TransferLocked)
{
try
{
locked_blocks = boost::lexical_cast<uint64_t>(local_args.back());
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("bad locked_blocks parameter:") << " " << local_args.back();
return false;
}
if (locked_blocks > 1000000)
{
fail_msg_writer() << tr("Locked blocks too high, max 1000000 (˜4 yrs)");
return false;
}
local_args.pop_back();
}
vector<cryptonote::address_parse_info> dsts_info;
vector<cryptonote::tx_destination_entry> dsts;
size_t num_subaddresses = 0;
for (size_t i = 0; i < local_args.size(); )
{
dsts_info.emplace_back();
cryptonote::address_parse_info & info = dsts_info.back();
cryptonote::tx_destination_entry de;
bool r = true;
// check for a URI
std::string address_uri, payment_id_uri, tx_description, recipient_name, error;
std::vector<std::string> unknown_parameters;
uint64_t amount = 0;
bool has_uri = m_wallet->parse_uri(local_args[i], address_uri, payment_id_uri, amount, tx_description, recipient_name, unknown_parameters, error);
if (has_uri)
{
r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_uri, oa_prompter);
if (payment_id_uri.size() == 16)
{
if (!tools::wallet2::parse_short_payment_id(payment_id_uri, info.payment_id))
{
fail_msg_writer() << tr("failed to parse short payment ID from URI");
return false;
}
info.has_payment_id = true;
}
de.amount = amount;
de.original = local_args[i];
++i;
}
else if (i + 1 < local_args.size())
{
r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[i], oa_prompter);
bool ok = cryptonote::parse_amount(de.amount, local_args[i + 1]);
if(!ok || 0 == de.amount)
{
fail_msg_writer() << tr("amount is wrong: ") << local_args[i] << ' ' << local_args[i + 1] <<
", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max());
return false;
}
de.original = local_args[i];
i += 2;
}
else
{
if (boost::starts_with(local_args[i], "swap:"))
fail_msg_writer() << tr("Invalid last argument: ") << local_args.back() << ": " << error;
else
fail_msg_writer() << tr("Invalid last argument: ") << local_args.back();
return false;
}
if (!r)
{
fail_msg_writer() << tr("failed to parse address");
return false;
}
de.addr = info.address;
de.is_subaddress = info.is_subaddress;
de.is_integrated = info.has_payment_id;
num_subaddresses += info.is_subaddress;
if (info.has_payment_id || !payment_id_uri.empty())
{
if (payment_id_seen)
{
fail_msg_writer() << tr("a single transaction cannot use more than one payment id");
return false;
}
crypto::hash payment_id;
std::string extra_nonce;
if (info.has_payment_id)
{
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
}
else if (tools::wallet2::parse_payment_id(payment_id_uri, payment_id))
{
LONG_PAYMENT_ID_SUPPORT_CHECK();
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
message_writer() << tr("Warning: Unencrypted payment IDs will harm your privacy: ask the recipient to use subaddresses instead");
}
else
{
fail_msg_writer() << tr("failed to parse payment id, though it was detected");
return false;
}
bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
if(!r)
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return false;
}
payment_id_seen = true;
}
dsts.push_back(de);
}
SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
try
{
// figure out what tx will be necessary
std::vector<tools::wallet2::pending_tx> ptx_vector;
uint64_t bc_height, unlock_block = 0;
std::string err;
switch (transfer_type)
{
case TransferLocked:
bc_height = get_daemon_blockchain_height(err);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return false;
}
unlock_block = bc_height + locked_blocks;
ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, unlock_block /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices);
break;
default:
LOG_ERROR("Unknown transfer method, using default");
/* FALLTHRU */
case Transfer:
ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, 0 /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices);
break;
}
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No outputs found, or daemon is not ready");
return false;
}
// if we need to check for backlog, check the worst case tx
if (m_wallet->confirm_backlog())
{
std::stringstream prompt;
double worst_fee_per_byte = std::numeric_limits<double>::max();
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
const uint64_t blob_size = cryptonote::tx_to_blob(ptx_vector[n].tx).size();
const double fee_per_byte = ptx_vector[n].fee / (double)blob_size;
if (fee_per_byte < worst_fee_per_byte)
{
worst_fee_per_byte = fee_per_byte;
}
}
try
{
std::vector<std::pair<uint64_t, uint64_t>> nblocks = m_wallet->estimate_backlog({std::make_pair(worst_fee_per_byte, worst_fee_per_byte)});
if (nblocks.size() != 1)
{
prompt << "Internal error checking for backlog. " << tr("Is this okay anyway?");
}
else
{
if (nblocks[0].first > m_wallet->get_confirm_backlog_threshold())
prompt << (boost::format(tr("There is currently a %u block backlog at that fee level. Is this okay?")) % nblocks[0].first).str();
}
}
catch (const std::exception &e)
{
prompt << tr("Failed to check for backlog: ") << e.what() << ENDL << tr("Is this okay anyway?");
}
std::string prompt_str = prompt.str();
if (!prompt_str.empty())
{
std::string accepted = input_line(prompt_str, true);
if (std::cin.eof())
return false;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return false;
}
}
}
if (!prompt_if_old(ptx_vector))
{
fail_msg_writer() << tr("transaction cancelled.");
return false;
}
// if more than one tx necessary, prompt user to confirm
if (m_wallet->always_confirm_transfers() || ptx_vector.size() > 1)
{
uint64_t total_sent = 0;
uint64_t total_fee = 0;
uint64_t dust_not_in_fee = 0;
uint64_t dust_in_fee = 0;
uint64_t change = 0;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
total_fee += ptx_vector[n].fee;
for (auto i: ptx_vector[n].selected_transfers)
total_sent += m_wallet->get_transfer_details(i).amount();
total_sent -= ptx_vector[n].change_dts.amount + ptx_vector[n].fee;
change += ptx_vector[n].change_dts.amount;
if (ptx_vector[n].dust_added_to_fee)
dust_in_fee += ptx_vector[n].dust;
else
dust_not_in_fee += ptx_vector[n].dust;
}
std::stringstream prompt;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
subaddr_indices.clear();
for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
subaddr_indices.insert(i);
for (uint32_t i : subaddr_indices)
prompt << boost::format(tr("Spending from address index %d\n")) % i;
if (subaddr_indices.size() > 1)
prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
}
prompt << boost::format(tr("Sending %s. ")) % print_money(total_sent);
if (ptx_vector.size() > 1)
{
prompt << boost::format(tr("Your transaction needs to be split into %llu transactions. "
"This will result in a transaction fee being applied to each transaction, for a total fee of %s")) %
((unsigned long long)ptx_vector.size()) % print_money(total_fee);
}
else
{
prompt << boost::format(tr("The transaction fee is %s")) %
print_money(total_fee);
}
if (dust_in_fee != 0) prompt << boost::format(tr(", of which %s is dust from change")) % print_money(dust_in_fee);
if (dust_not_in_fee != 0) prompt << tr(".") << ENDL << boost::format(tr("A total of %s from dust change will be sent to dust address"))
% print_money(dust_not_in_fee);
if (transfer_type == TransferLocked)
{
float days = locked_blocks / 720.0f;
prompt << boost::format(tr(".\nThis transaction (including %s change) will unlock on block %llu, in approximately %s days (assuming 2 minutes per block)")) % cryptonote::print_money(change) % ((unsigned long long)unlock_block) % days;
}
if (m_wallet->print_ring_members())
{
if (!print_ring_members(ptx_vector, prompt))
return false;
}
bool default_ring_size = true;
for (const auto &ptx: ptx_vector)
{
for (const auto &vin: ptx.tx.vin)
{
if (vin.type() == typeid(txin_to_key))
{
const txin_to_key& in_to_key = boost::get<txin_to_key>(vin);
if (in_to_key.key_offsets.size() != DEFAULT_MIX + 1)
default_ring_size = false;
}
}
}
if (m_wallet->confirm_non_default_ring_size() && !default_ring_size)
{
prompt << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended.");
}
prompt << ENDL << tr("Is this okay?");
std::string accepted = input_line(prompt.str(), true);
if (std::cin.eof())
return false;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return false;
}
}
// actually commit the transactions
if (m_wallet->multisig() && called_by_mms)
{
std::string ciphertext = m_wallet->save_multisig_tx(ptx_vector);
if (!ciphertext.empty())
{
get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::partially_signed_tx, ciphertext);
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to MMS");
}
}
else if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
return false;
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_swap_tx";
}
}
else if (m_wallet->get_account().get_device().has_tx_cold_sign())
{
try
{
tools::wallet2::signed_tx_set signed_tx;
if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
return false;
}
commit_or_save(signed_tx.ptx, m_do_not_relay);
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
return false;
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
return false;
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
return false;
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_swap_tx";
}
}
else
{
commit_or_save(ptx_vector, m_do_not_relay);
}
}
catch (const std::exception &e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
return false;
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::transfer(const std::vector<std::string> &args_)
{
transfer_main(Transfer, args_, false);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::locked_transfer(const std::vector<std::string> &args_)
{
transfer_main(TransferLocked, args_, false);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::locked_sweep_all(const std::vector<std::string> &args_)
{
sweep_main(0, true, args_);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_unmixable(const std::vector<std::string> &args_)
{
if (!try_connect_to_daemon())
return true;
SCOPED_WALLET_UNLOCK();
try
{
// figure out what tx will be necessary
auto ptx_vector = m_wallet->create_unmixable_sweep_transactions();
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No unmixable outputs found");
return true;
}
// give user total and fee, and prompt to confirm
uint64_t total_fee = 0, total_unmixable = 0;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
total_fee += ptx_vector[n].fee;
for (auto i: ptx_vector[n].selected_transfers)
total_unmixable += m_wallet->get_transfer_details(i).amount();
}
std::string prompt_str = tr("Sweeping ") + print_money(total_unmixable);
if (ptx_vector.size() > 1) {
prompt_str = (boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) %
print_money(total_unmixable) %
((unsigned long long)ptx_vector.size()) %
print_money(total_fee)).str();
}
else {
prompt_str = (boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
print_money(total_unmixable) %
print_money(total_fee)).str();
}
std::string accepted = input_line(prompt_str, true);
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
// actually commit the transactions
if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_swap_tx";
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_swap_tx";
}
}
else
{
commit_or_save(ptx_vector, m_do_not_relay);
}
}
catch (const tools::error::not_enough_unlocked_money& e)
{
fail_msg_writer() << tr("Not enough money in unlocked balance");
std::string accepted = input_line((boost::format(tr("Discarding %s of unmixable outputs that cannot be spent, which can be undone by \"rescan_spent\". Is this okay?")) % print_money(e.available())).str(), true);
if (std::cin.eof())
return true;
if (command_line::is_yes(accepted))
{
try
{
m_wallet->discard_unmixable_outputs();
} catch (...) {}
}
}
catch (const std::exception &e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_main(uint64_t below, bool locked, const std::vector<std::string> &args_)
{
auto print_usage = [below]()
{
if (below)
{
PRINT_USAGE(USAGE_SWEEP_BELOW);
}
else
{
PRINT_USAGE(USAGE_SWEEP_ALL);
}
};
if (args_.size() == 0)
{
fail_msg_writer() << tr("No address given");
print_usage();
return true;
}
if (!try_connect_to_daemon())
return true;
std::vector<std::string> local_args = args_;
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
{
print_usage();
return true;
}
local_args.erase(local_args.begin());
}
uint32_t priority = 0;
if (local_args.size() > 0 && parse_priority(local_args[0], priority))
local_args.erase(local_args.begin());
priority = m_wallet->adjust_priority(priority);
size_t fake_outs_count = DEFAULT_MIX;
if(local_args.size() > 0) {
size_t ring_size;
if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
{
}
else if (ring_size == 0)
{
fail_msg_writer() << tr("Ring size must not be 0");
return true;
}
else
{
fake_outs_count = ring_size - 1;
local_args.erase(local_args.begin());
}
}
uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
if (adjusted_fake_outs_count > fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
if (adjusted_fake_outs_count < fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
uint64_t unlock_block = 0;
if (locked) {
uint64_t locked_blocks = 0;
if (local_args.size() < 2) {
fail_msg_writer() << tr("missing lockedblocks parameter");
return true;
}
try
{
locked_blocks = boost::lexical_cast<uint64_t>(local_args[1]);
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("bad locked_blocks parameter");
return true;
}
if (locked_blocks > 1000000)
{
fail_msg_writer() << tr("Locked blocks too high, max 1000000 (˜4 yrs)");
return true;
}
std::string err;
uint64_t bc_height = get_daemon_blockchain_height(err);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return true;
}
unlock_block = bc_height + locked_blocks;
local_args.erase(local_args.begin() + 1);
}
size_t outputs = 1;
if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
{
if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
{
fail_msg_writer() << tr("Failed to parse number of outputs");
return true;
}
else if (outputs < 1)
{
fail_msg_writer() << tr("Amount of outputs should be greater than 0");
return true;
}
else
{
local_args.erase(local_args.begin());
}
}
std::vector<uint8_t> extra;
bool payment_id_seen = false;
if (local_args.size() >= 2)
{
std::string payment_id_str = local_args.back();
crypto::hash payment_id;
bool r = tools::wallet2::parse_long_payment_id(payment_id_str, payment_id);
if(r)
{
LONG_PAYMENT_ID_SUPPORT_CHECK();
std::string extra_nonce;
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
payment_id_seen = true;
}
if(!r && local_args.size() == 3)
{
fail_msg_writer() << tr("payment id has invalid format, expected 16 or 64 character hex string: ") << payment_id_str;
print_usage();
return true;
}
if (payment_id_seen)
local_args.pop_back();
}
cryptonote::address_parse_info info;
if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[0], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
print_usage();
return true;
}
if (info.has_payment_id)
{
if (payment_id_seen)
{
fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
return true;
}
std::string extra_nonce;
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
if(!r)
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return true;
}
payment_id_seen = true;
}
SCOPED_WALLET_UNLOCK();
try
{
// figure out what tx will be necessary
auto ptx_vector = m_wallet->create_transactions_all(below, info.address, info.is_subaddress, outputs, fake_outs_count, unlock_block /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices);
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No outputs found, or daemon is not ready");
return true;
}
if (!prompt_if_old(ptx_vector))
{
fail_msg_writer() << tr("transaction cancelled.");
return false;
}
// give user total and fee, and prompt to confirm
uint64_t total_fee = 0, total_sent = 0;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
total_fee += ptx_vector[n].fee;
for (auto i: ptx_vector[n].selected_transfers)
total_sent += m_wallet->get_transfer_details(i).amount();
}
std::ostringstream prompt;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
subaddr_indices.clear();
for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
subaddr_indices.insert(i);
for (uint32_t i : subaddr_indices)
prompt << boost::format(tr("Spending from address index %d\n")) % i;
if (subaddr_indices.size() > 1)
prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
}
if (m_wallet->print_ring_members() && !print_ring_members(ptx_vector, prompt))
return true;
if (ptx_vector.size() > 1) {
prompt << boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) %
print_money(total_sent) %
((unsigned long long)ptx_vector.size()) %
print_money(total_fee);
}
else {
prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
print_money(total_sent) %
print_money(total_fee);
}
std::string accepted = input_line(prompt.str(), true);
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
// actually commit the transactions
if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_swap_tx";
}
}
else if (m_wallet->get_account().get_device().has_tx_cold_sign())
{
try
{
tools::wallet2::signed_tx_set signed_tx;
std::vector<cryptonote::address_parse_info> dsts_info;
dsts_info.push_back(info);
if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
return true;
}
commit_or_save(signed_tx.ptx, m_do_not_relay);
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_swap_tx";
}
}
else
{
commit_or_save(ptx_vector, m_do_not_relay);
}
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_single(const std::vector<std::string> &args_)
{
if (!try_connect_to_daemon())
return true;
std::vector<std::string> local_args = args_;
uint32_t priority = 0;
if (local_args.size() > 0 && parse_priority(local_args[0], priority))
local_args.erase(local_args.begin());
priority = m_wallet->adjust_priority(priority);
size_t fake_outs_count = DEFAULT_MIX;
if(local_args.size() > 0) {
size_t ring_size;
if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
{
}
else if (ring_size == 0)
{
fail_msg_writer() << tr("Ring size must not be 0");
return true;
}
else
{
fake_outs_count = ring_size - 1;
local_args.erase(local_args.begin());
}
}
uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
if (adjusted_fake_outs_count > fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
if (adjusted_fake_outs_count < fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
size_t outputs = 1;
if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
{
if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
{
fail_msg_writer() << tr("Failed to parse number of outputs");
return true;
}
else if (outputs < 1)
{
fail_msg_writer() << tr("Amount of outputs should be greater than 0");
return true;
}
else
{
local_args.erase(local_args.begin());
}
}
std::vector<uint8_t> extra;
bool payment_id_seen = false;
if (local_args.size() == 3)
{
crypto::hash payment_id;
crypto::hash8 payment_id8;
std::string extra_nonce;
if (tools::wallet2::parse_long_payment_id(local_args.back(), payment_id))
{
LONG_PAYMENT_ID_SUPPORT_CHECK();
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
}
else
{
fail_msg_writer() << tr("failed to parse Payment ID");
return true;
}
if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return true;
}
local_args.pop_back();
payment_id_seen = true;
}
if (local_args.size() != 2)
{
PRINT_USAGE(USAGE_SWEEP_SINGLE);
return true;
}
crypto::key_image ki;
if (!epee::string_tools::hex_to_pod(local_args[0], ki))
{
fail_msg_writer() << tr("failed to parse key image");
return true;
}
cryptonote::address_parse_info info;
if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
if (info.has_payment_id)
{
if (payment_id_seen)
{
fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
return true;
}
std::string extra_nonce;
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return true;
}
payment_id_seen = true;
}
SCOPED_WALLET_UNLOCK();
try
{
// figure out what tx will be necessary
auto ptx_vector = m_wallet->create_transactions_single(ki, info.address, info.is_subaddress, outputs, fake_outs_count, 0 /* unlock_time */, priority, extra);
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No outputs found");
return true;
}
if (ptx_vector.size() > 1)
{
fail_msg_writer() << tr("Multiple transactions are created, which is not supposed to happen");
return true;
}
if (ptx_vector[0].selected_transfers.size() != 1)
{
fail_msg_writer() << tr("The transaction uses multiple or no inputs, which is not supposed to happen");
return true;
}
// give user total and fee, and prompt to confirm
uint64_t total_fee = ptx_vector[0].fee;
uint64_t total_sent = m_wallet->get_transfer_details(ptx_vector[0].selected_transfers.front()).amount();
std::ostringstream prompt;
if (!print_ring_members(ptx_vector, prompt))
return true;
prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
print_money(total_sent) %
print_money(total_fee);
std::string accepted = input_line(prompt.str(), true);
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
// actually commit the transactions
if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_swap_tx";
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_swap_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_swap_tx";
}
}
else
{
m_wallet->commit_tx(ptx_vector[0]);
success_msg_writer(true) << tr("Money successfully sent, transaction: ") << get_transaction_hash(ptx_vector[0].tx);
}
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_all(const std::vector<std::string> &args_)
{
sweep_main(0, false, args_);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_below(const std::vector<std::string> &args_)
{
uint64_t below = 0;
if (args_.size() < 1)
{
fail_msg_writer() << tr("missing threshold amount");
return true;
}
if (!cryptonote::parse_amount(below, args_[0]))
{
fail_msg_writer() << tr("invalid amount threshold");
return true;
}
sweep_main(below, false, std::vector<std::string>(++args_.begin(), args_.end()));
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::donate(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if(local_args.empty() || local_args.size() > 5)
{
PRINT_USAGE(USAGE_DONATE);
return true;
}
std::string amount_str;
std::string payment_id_str;
// get payment id and pop
crypto::hash payment_id;
crypto::hash8 payment_id8;
if (tools::wallet2::parse_long_payment_id (local_args.back(), payment_id ) ||
tools::wallet2::parse_short_payment_id(local_args.back(), payment_id8))
{
payment_id_str = local_args.back();
local_args.pop_back();
}
// get amount and pop
uint64_t amount;
bool ok = cryptonote::parse_amount(amount, local_args.back());
if (ok && amount != 0)
{
amount_str = local_args.back();
local_args.pop_back();
}
else
{
fail_msg_writer() << tr("amount is wrong: ") << local_args.back() << ", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max());
return true;
}
// push back address, amount, payment id
std::string address_str;
if (m_wallet->nettype() != cryptonote::MAINNET)
{
// if not mainnet, convert donation address string to the relevant network type
address_parse_info info;
if (!cryptonote::get_account_address_from_str(info, cryptonote::MAINNET, MONERO_DONATION_ADDR))
{
fail_msg_writer() << tr("Failed to parse donation address: ") << MONERO_DONATION_ADDR;
return true;
}
address_str = cryptonote::get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
}
else
{
address_str = MONERO_DONATION_ADDR;
}
local_args.push_back(address_str);
local_args.push_back(amount_str);
if (!payment_id_str.empty())
local_args.push_back(payment_id_str);
if (m_wallet->nettype() == cryptonote::MAINNET)
message_writer() << (boost::format(tr("Donating %s %s to The Swap Project (donate.getmonero.org or %s).")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % MONERO_DONATION_ADDR).str();
else
message_writer() << (boost::format(tr("Donating %s %s to %s.")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % address_str).str();
transfer(local_args);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::accept_loaded_tx(const std::function<size_t()> get_num_txes, const std::function<const tools::wallet2::tx_construction_data&(size_t)> &get_tx, const std::string &extra_message)
{
// gather info to ask the user
uint64_t amount = 0, amount_to_dests = 0, change = 0;
size_t min_ring_size = ~0;
std::unordered_map<cryptonote::account_public_address, std::pair<std::string, uint64_t>> dests;
int first_known_non_zero_change_index = -1;
std::string payment_id_string = "";
for (size_t n = 0; n < get_num_txes(); ++n)
{
const tools::wallet2::tx_construction_data &cd = get_tx(n);
std::vector<tx_extra_field> tx_extra_fields;
bool has_encrypted_payment_id = false;
crypto::hash8 payment_id8 = crypto::null_hash8;
if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields))
{
tx_extra_nonce extra_nonce;
if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
{
crypto::hash payment_id;
if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
{
if (!payment_id_string.empty())
payment_id_string += ", ";
// if none of the addresses are integrated addresses, it's a dummy one
bool is_dummy = true;
for (const auto &e: cd.dests)
if (e.is_integrated)
is_dummy = false;
if (is_dummy)
{
payment_id_string += std::string("dummy encrypted payment ID");
}
else
{
payment_id_string += std::string("encrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id8);
has_encrypted_payment_id = true;
}
}
else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
{
if (!payment_id_string.empty())
payment_id_string += ", ";
payment_id_string += std::string("unencrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id);
payment_id_string += " (OBSOLETE)";
}
}
}
for (size_t s = 0; s < cd.sources.size(); ++s)
{
amount += cd.sources[s].amount;
size_t ring_size = cd.sources[s].outputs.size();
if (ring_size < min_ring_size)
min_ring_size = ring_size;
}
for (size_t d = 0; d < cd.splitted_dsts.size(); ++d)
{
const tx_destination_entry &entry = cd.splitted_dsts[d];
std::string address, standard_address = get_account_address_as_str(m_wallet->nettype(), entry.is_subaddress, entry.addr);
if (has_encrypted_payment_id && !entry.is_subaddress && standard_address != entry.original)
{
address = get_account_integrated_address_as_str(m_wallet->nettype(), entry.addr, payment_id8);
address += std::string(" (" + standard_address + " with encrypted payment id " + epee::string_tools::pod_to_hex(payment_id8) + ")");
}
else
address = standard_address;
auto i = dests.find(entry.addr);
if (i == dests.end())
dests.insert(std::make_pair(entry.addr, std::make_pair(address, entry.amount)));
else
i->second.second += entry.amount;
amount_to_dests += entry.amount;
}
if (cd.change_dts.amount > 0)
{
auto it = dests.find(cd.change_dts.addr);
if (it == dests.end())
{
fail_msg_writer() << tr("Claimed change does not go to a paid address");
return false;
}
if (it->second.second < cd.change_dts.amount)
{
fail_msg_writer() << tr("Claimed change is larger than payment to the change address");
return false;
}
if (cd.change_dts.amount > 0)
{
if (first_known_non_zero_change_index == -1)
first_known_non_zero_change_index = n;
if (memcmp(&cd.change_dts.addr, &get_tx(first_known_non_zero_change_index).change_dts.addr, sizeof(cd.change_dts.addr)))
{
fail_msg_writer() << tr("Change goes to more than one address");
return false;
}
}
change += cd.change_dts.amount;
it->second.second -= cd.change_dts.amount;
if (it->second.second == 0)
dests.erase(cd.change_dts.addr);
}
}
if (payment_id_string.empty())
payment_id_string = "no payment ID";
std::string dest_string;
size_t n_dummy_outputs = 0;
for (auto i = dests.begin(); i != dests.end(); )
{
if (i->second.second > 0)
{
if (!dest_string.empty())
dest_string += ", ";
dest_string += (boost::format(tr("sending %s to %s")) % print_money(i->second.second) % i->second.first).str();
}
else
++n_dummy_outputs;
++i;
}
if (n_dummy_outputs > 0)
{
if (!dest_string.empty())
dest_string += ", ";
dest_string += std::to_string(n_dummy_outputs) + tr(" dummy output(s)");
}
if (dest_string.empty())
dest_string = tr("with no destinations");
std::string change_string;
if (change > 0)
{
std::string address = get_account_address_as_str(m_wallet->nettype(), get_tx(0).subaddr_account > 0, get_tx(0).change_dts.addr);
change_string += (boost::format(tr("%s change to %s")) % print_money(change) % address).str();
}
else
change_string += tr("no change");
uint64_t fee = amount - amount_to_dests;
std::string prompt_str = (boost::format(tr("Loaded %lu transactions, for %s, fee %s, %s, %s, with min ring size %lu, %s. %sIs this okay?")) % (unsigned long)get_num_txes() % print_money(amount) % print_money(fee) % dest_string % change_string % (unsigned long)min_ring_size % payment_id_string % extra_message).str();
return command_line::is_yes(input_line(prompt_str, true));
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::accept_loaded_tx(const tools::wallet2::unsigned_tx_set &txs)
{
std::string extra_message;
if (!txs.transfers.second.empty())
extra_message = (boost::format("%u outputs to import. ") % (unsigned)txs.transfers.second.size()).str();
return accept_loaded_tx([&txs](){return txs.txes.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.txes[n];}, extra_message);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::accept_loaded_tx(const tools::wallet2::signed_tx_set &txs)
{
std::string extra_message;
if (!txs.key_images.empty())
extra_message = (boost::format("%u key images to import. ") % (unsigned)txs.key_images.size()).str();
return accept_loaded_tx([&txs](){return txs.ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.ptx[n].construction_data;}, extra_message);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sign_transfer(const std::vector<std::string> &args_)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(m_wallet->multisig())
{
fail_msg_writer() << tr("This is a multisig wallet, it can only sign with sign_multisig");
return true;
}
if(m_wallet->watch_only())
{
fail_msg_writer() << tr("This is a watch only wallet");
return true;
}
if (args_.size() > 1 || (args_.size() == 1 && args_[0] != "export_raw"))
{
PRINT_USAGE(USAGE_SIGN_TRANSFER);
return true;
}
SCOPED_WALLET_UNLOCK();
const bool export_raw = args_.size() == 1;
std::vector<tools::wallet2::pending_tx> ptx;
try
{
bool r = m_wallet->sign_tx("unsigned_swap_tx", "signed_swap_tx", ptx, [&](const tools::wallet2::unsigned_tx_set &tx){ return accept_loaded_tx(tx); }, export_raw);
if (!r)
{
fail_msg_writer() << tr("Failed to sign transaction");
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to sign transaction: ") << e.what();
return true;
}
std::string txids_as_text;
for (const auto &t: ptx)
{
if (!txids_as_text.empty())
txids_as_text += (", ");
txids_as_text += epee::string_tools::pod_to_hex(get_transaction_hash(t.tx));
}
success_msg_writer(true) << tr("Transaction successfully signed to file ") << "signed_swap_tx" << ", txid " << txids_as_text;
if (export_raw)
{
std::string rawfiles_as_text;
for (size_t i = 0; i < ptx.size(); ++i)
{
if (i > 0)
rawfiles_as_text += ", ";
rawfiles_as_text += "signed_swap_tx_raw" + (ptx.size() == 1 ? "" : ("_" + std::to_string(i)));
}
success_msg_writer(true) << tr("Transaction raw hex data exported to ") << rawfiles_as_text;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::submit_transfer(const std::vector<std::string> &args_)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!try_connect_to_daemon())
return true;
try
{
std::vector<tools::wallet2::pending_tx> ptx_vector;
bool r = m_wallet->load_tx("signed_swap_tx", ptx_vector, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to load transaction from file");
return true;
}
commit_or_save(ptx_vector, false);
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_tx_key(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if (m_wallet->key_on_device() && m_wallet->get_account().get_device().get_type() != hw::device::TREZOR)
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(local_args.size() != 1) {
PRINT_USAGE(USAGE_GET_TX_KEY);
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(local_args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
SCOPED_WALLET_UNLOCK();
crypto::secret_key tx_key;
std::vector<crypto::secret_key> additional_tx_keys;
bool found_tx_key = m_wallet->get_tx_key(txid, tx_key, additional_tx_keys);
if (found_tx_key)
{
ostringstream oss;
oss << epee::string_tools::pod_to_hex(tx_key);
for (size_t i = 0; i < additional_tx_keys.size(); ++i)
oss << epee::string_tools::pod_to_hex(additional_tx_keys[i]);
success_msg_writer() << tr("Tx key: ") << oss.str();
return true;
}
else
{
fail_msg_writer() << tr("no tx keys found for this txid");
return true;
}
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_tx_key(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() != 2) {
PRINT_USAGE(USAGE_SET_TX_KEY);
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(local_args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::secret_key tx_key;
std::vector<crypto::secret_key> additional_tx_keys;
try
{
if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
{
fail_msg_writer() << tr("failed to parse tx_key");
return true;
}
while(true)
{
local_args[1] = local_args[1].substr(64);
if (local_args[1].empty())
break;
additional_tx_keys.resize(additional_tx_keys.size() + 1);
if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
{
fail_msg_writer() << tr("failed to parse tx_key");
return true;
}
}
}
catch (const std::out_of_range &e)
{
fail_msg_writer() << tr("failed to parse tx_key");
return true;
}
LOCK_IDLE_SCOPE();
try
{
m_wallet->set_tx_key(txid, tx_key, additional_tx_keys);
success_msg_writer() << tr("Tx key successfully stored.");
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to store tx key: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_tx_proof(const std::vector<std::string> &args)
{
if (args.size() != 2 && args.size() != 3)
{
PRINT_USAGE(USAGE_GET_TX_PROOF);
return true;
}
crypto::hash txid;
if(!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
SCOPED_WALLET_UNLOCK();
try
{
std::string sig_str = m_wallet->get_tx_proof(txid, info.address, info.is_subaddress, args.size() == 3 ? args[2] : "");
const std::string filename = "swap_tx_proof";
if (m_wallet->save_to_file(filename, sig_str, true))
success_msg_writer() << tr("signature file saved to: ") << filename;
else
fail_msg_writer() << tr("failed to save signature file");
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("error: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_tx_key(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() != 3) {
PRINT_USAGE(USAGE_CHECK_TX_KEY);
return true;
}
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
crypto::hash txid;
if(!epee::string_tools::hex_to_pod(local_args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::secret_key tx_key;
std::vector<crypto::secret_key> additional_tx_keys;
if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
{
fail_msg_writer() << tr("failed to parse tx key");
return true;
}
local_args[1] = local_args[1].substr(64);
while (!local_args[1].empty())
{
additional_tx_keys.resize(additional_tx_keys.size() + 1);
if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
{
fail_msg_writer() << tr("failed to parse tx key");
return true;
}
local_args[1] = local_args[1].substr(64);
}
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[2], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
try
{
uint64_t received;
bool in_pool;
uint64_t confirmations;
m_wallet->check_tx_key(txid, tx_key, additional_tx_keys, info.address, received, in_pool, confirmations);
if (received > 0)
{
success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid;
if (in_pool)
{
success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
}
else
{
if (confirmations != (uint64_t)-1)
{
success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
}
else
{
success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
}
}
}
else
{
fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("error: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_tx_proof(const std::vector<std::string> &args)
{
if(args.size() != 3 && args.size() != 4) {
PRINT_USAGE(USAGE_CHECK_TX_PROOF);
return true;
}
if (!try_connect_to_daemon())
return true;
// parse txid
crypto::hash txid;
if(!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
// parse address
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
// read signature file
std::string sig_str;
if (!m_wallet->load_from_file(args[2], sig_str))
{
fail_msg_writer() << tr("failed to load signature file");
return true;
}
try
{
uint64_t received;
bool in_pool;
uint64_t confirmations;
if (m_wallet->check_tx_proof(txid, info.address, info.is_subaddress, args.size() == 4 ? args[3] : "", sig_str, received, in_pool, confirmations))
{
success_msg_writer() << tr("Good signature");
if (received > 0)
{
success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid;
if (in_pool)
{
success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
}
else
{
if (confirmations != (uint64_t)-1)
{
success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
}
else
{
success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
}
}
}
else
{
fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
}
}
else
{
fail_msg_writer() << tr("Bad signature");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("error: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_spend_proof(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(args.size() != 1 && args.size() != 2) {
PRINT_USAGE(USAGE_GET_SPEND_PROOF);
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot generate the proof");
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
if (!try_connect_to_daemon())
return true;
SCOPED_WALLET_UNLOCK();
try
{
const std::string sig_str = m_wallet->get_spend_proof(txid, args.size() == 2 ? args[1] : "");
const std::string filename = "swap_spend_proof";
if (m_wallet->save_to_file(filename, sig_str, true))
success_msg_writer() << tr("signature file saved to: ") << filename;
else
fail_msg_writer() << tr("failed to save signature file");
}
catch (const std::exception &e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_spend_proof(const std::vector<std::string> &args)
{
if(args.size() != 2 && args.size() != 3) {
PRINT_USAGE(USAGE_CHECK_SPEND_PROOF);
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
if (!try_connect_to_daemon())
return true;
std::string sig_str;
if (!m_wallet->load_from_file(args[1], sig_str))
{
fail_msg_writer() << tr("failed to load signature file");
return true;
}
try
{
if (m_wallet->check_spend_proof(txid, args.size() == 3 ? args[2] : "", sig_str))
success_msg_writer() << tr("Good signature");
else
fail_msg_writer() << tr("Bad signature");
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_reserve_proof(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(args.size() != 1 && args.size() != 2) {
PRINT_USAGE(USAGE_GET_RESERVE_PROOF);
return true;
}
if (m_wallet->watch_only() || m_wallet->multisig())
{
fail_msg_writer() << tr("The reserve proof can be generated only by a full wallet");
return true;
}
boost::optional<std::pair<uint32_t, uint64_t>> account_minreserve;
if (args[0] != "all")
{
account_minreserve = std::pair<uint32_t, uint64_t>();
account_minreserve->first = m_current_subaddress_account;
if (!cryptonote::parse_amount(account_minreserve->second, args[0]))
{
fail_msg_writer() << tr("amount is wrong: ") << args[0];
return true;
}
}
if (!try_connect_to_daemon())
return true;
SCOPED_WALLET_UNLOCK();
try
{
const std::string sig_str = m_wallet->get_reserve_proof(account_minreserve, args.size() == 2 ? args[1] : "");
const std::string filename = "swap_reserve_proof";
if (m_wallet->save_to_file(filename, sig_str, true))
success_msg_writer() << tr("signature file saved to: ") << filename;
else
fail_msg_writer() << tr("failed to save signature file");
}
catch (const std::exception &e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_reserve_proof(const std::vector<std::string> &args)
{
if(args.size() != 2 && args.size() != 3) {
PRINT_USAGE(USAGE_CHECK_RESERVE_PROOF);
return true;
}
if (!try_connect_to_daemon())
return true;
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[0], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
if (info.is_subaddress)
{
fail_msg_writer() << tr("Address must not be a subaddress");
return true;
}
std::string sig_str;
if (!m_wallet->load_from_file(args[1], sig_str))
{
fail_msg_writer() << tr("failed to load signature file");
return true;
}
LOCK_IDLE_SCOPE();
try
{
uint64_t total, spent;
if (m_wallet->check_reserve_proof(info.address, args.size() == 3 ? args[2] : "", sig_str, total, spent))
{
success_msg_writer() << boost::format(tr("Good signature -- total: %s, spent: %s, unspent: %s")) % print_money(total) % print_money(spent) % print_money(total - spent);
}
else
{
fail_msg_writer() << tr("Bad signature");
}
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
static std::string get_human_readable_timespan(std::chrono::seconds seconds)
{
uint64_t ts = seconds.count();
if (ts < 60)
return std::to_string(ts) + sw::tr(" seconds");
if (ts < 3600)
return std::to_string((uint64_t)(ts / 60)) + sw::tr(" minutes");
if (ts < 3600 * 24)
return std::to_string((uint64_t)(ts / 3600)) + sw::tr(" hours");
if (ts < 3600 * 24 * 30.5)
return std::to_string((uint64_t)(ts / (3600 * 24))) + sw::tr(" days");
if (ts < 3600 * 24 * 365.25)
return std::to_string((uint64_t)(ts / (3600 * 24 * 30.5))) + sw::tr(" months");
return sw::tr("a long time");
}
//----------------------------------------------------------------------------------------------------
// mutates local_args as it parses and consumes arguments
bool simple_wallet::get_transfers(std::vector<std::string>& local_args, std::vector<transfer_view>& transfers)
{
bool in = true;
bool out = true;
bool pending = true;
bool failed = true;
bool pool = true;
bool coinbase = true;
uint64_t min_height = 0;
uint64_t max_height = (uint64_t)-1;
// optional in/out selector
if (local_args.size() > 0) {
if (local_args[0] == "in" || local_args[0] == "incoming") {
out = pending = failed = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "out" || local_args[0] == "outgoing") {
in = pool = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "pending") {
in = out = failed = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "failed") {
in = out = pending = pool = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "pool") {
in = out = pending = failed = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "coinbase") {
in = out = pending = failed = pool = false;
coinbase = true;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "all" || local_args[0] == "both") {
local_args.erase(local_args.begin());
}
}
// subaddr_index
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return false;
local_args.erase(local_args.begin());
}
// min height
if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
try {
min_height = boost::lexical_cast<uint64_t>(local_args[0]);
}
catch (const boost::bad_lexical_cast &) {
fail_msg_writer() << tr("bad min_height parameter:") << " " << local_args[0];
return false;
}
local_args.erase(local_args.begin());
}
// max height
if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
try {
max_height = boost::lexical_cast<uint64_t>(local_args[0]);
}
catch (const boost::bad_lexical_cast &) {
fail_msg_writer() << tr("bad max_height parameter:") << " " << local_args[0];
return false;
}
local_args.erase(local_args.begin());
}
const uint64_t last_block_height = m_wallet->get_blockchain_current_height();
if (in || coinbase) {
std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
m_wallet->get_payments(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second;
if (!pd.m_coinbase && !in)
continue;
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
const std::string type = pd.m_coinbase ? tr("block") : tr("in");
const bool unlocked = m_wallet->is_transfer_unlocked(pd.m_unlock_time, pd.m_block_height);
std::string locked_msg = "unlocked";
if (!unlocked)
{
locked_msg = "locked";
const uint64_t unlock_time = pd.m_unlock_time;
if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
{
uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
if (bh >= last_block_height)
locked_msg = std::to_string(bh - last_block_height) + " blks";
}
else
{
uint64_t current_time = static_cast<uint64_t>(time(NULL));
uint64_t threshold = current_time + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS;
if (threshold < pd.m_unlock_time)
locked_msg = get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold));
}
}
transfers.push_back({
type,
pd.m_block_height,
pd.m_timestamp,
type,
true,
pd.m_amount,
pd.m_tx_hash,
payment_id,
0,
{{destination, pd.m_amount}},
{pd.m_subaddr_index.minor},
note,
locked_msg
});
}
}
if (out) {
std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments;
m_wallet->get_payments_out(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::confirmed_transfer_details &pd = i->second;
uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
uint64_t fee = pd.m_amount_in - pd.m_amount_out;
std::vector<std::pair<std::string, uint64_t>> destinations;
for (const auto &d: pd.m_dests) {
destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount});
}
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(i->first);
transfers.push_back({
"out",
pd.m_block_height,
pd.m_timestamp,
"out",
true,
pd.m_amount_in - change - fee,
i->first,
payment_id,
fee,
destinations,
pd.m_subaddr_indices,
note,
"-"
});
}
}
if (pool) {
try
{
m_in_manual_refresh.store(true, std::memory_order_relaxed);
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
std::vector<std::pair<cryptonote::transaction, bool>> process_txs;
m_wallet->update_pool_state(process_txs);
if (!process_txs.empty())
m_wallet->process_pool_state(process_txs);
std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> payments;
m_wallet->get_unconfirmed_payments(payments, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second.m_pd;
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
std::string double_spend_note;
if (i->second.m_double_spend_seen)
double_spend_note = tr("[Double spend seen on the network: this transaction may or may not end up being mined] ");
transfers.push_back({
"pool",
"pool",
pd.m_timestamp,
"in",
false,
pd.m_amount,
pd.m_tx_hash,
payment_id,
0,
{{destination, pd.m_amount}},
{pd.m_subaddr_index.minor},
note + double_spend_note,
"locked"
});
}
}
catch (const std::exception& e)
{
fail_msg_writer() << "Failed to get pool state:" << e.what();
}
}
// print unconfirmed last
if (pending || failed) {
std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
uint64_t amount = pd.m_amount_in;
uint64_t fee = amount - pd.m_amount_out;
std::vector<std::pair<std::string, uint64_t>> destinations;
for (const auto &d: pd.m_dests) {
destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount});
}
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(i->first);
bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
if ((failed && is_failed) || (!is_failed && pending)) {
transfers.push_back({
(is_failed ? "failed" : "pending"),
(is_failed ? "failed" : "pending"),
pd.m_timestamp,
"out",
false,
amount - pd.m_change - fee,
i->first,
payment_id,
fee,
destinations,
pd.m_subaddr_indices,
note,
"-"
});
}
}
}
// sort by block, then by timestamp (unconfirmed last)
std::sort(transfers.begin(), transfers.end(), [](const transfer_view& a, const transfer_view& b) -> bool {
if (a.confirmed && !b.confirmed)
return true;
if (a.block == b.block)
return a.timestamp < b.timestamp;
return a.block < b.block;
});
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_transfers(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() > 4) {
fail_msg_writer() << tr("usage: show_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
return true;
}
LOCK_IDLE_SCOPE();
std::vector<transfer_view> all_transfers;
if (!get_transfers(local_args, all_transfers))
return true;
PAUSE_READLINE();
for (const auto& transfer : all_transfers)
{
const auto color = transfer.type == "failed" ? console_color_red : transfer.confirmed ? ((transfer.direction == "in" || transfer.direction == "block") ? console_color_green : console_color_magenta) : console_color_default;
std::string destinations = "-";
if (!transfer.outputs.empty())
{
destinations = "";
for (const auto& output : transfer.outputs)
{
if (!destinations.empty())
destinations += ", ";
destinations += (transfer.direction == "in" ? output.first.substr(0, 6) : output.first) + ":" + print_money(output.second);
}
}
auto formatter = boost::format("%8.8llu %6.6s %8.8s %25.25s %20.20s %s %s %14.14s %s %s - %s");
message_writer(color, false) << formatter
% transfer.block
% transfer.direction
% transfer.unlocked
% tools::get_human_readable_timestamp(transfer.timestamp)
% print_money(transfer.amount)
% string_tools::pod_to_hex(transfer.hash)
% transfer.payment_id
% print_money(transfer.fee)
% destinations
% boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
% transfer.note;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::export_transfers(const std::vector<std::string>& args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() > 5) {
fail_msg_writer() << tr("usage: export_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<path>]");
return true;
}
LOCK_IDLE_SCOPE();
std::vector<transfer_view> all_transfers;
// might consumes arguments in local_args
if (!get_transfers(local_args, all_transfers))
return true;
// output filename
std::string filename = (boost::format("output%u.csv") % m_current_subaddress_account).str();
if (local_args.size() > 0 && local_args[0].substr(0, 7) == "output=")
{
filename = local_args[0].substr(7, -1);
local_args.erase(local_args.begin());
}
std::ofstream file(filename);
// header
file <<
boost::format("%8.8s,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%100.100s,%20.20s,%s,%s") %
tr("block") % tr("direction") % tr("unlocked") % tr("timestamp") % tr("amount") % tr("running balance") % tr("hash") % tr("payment ID") % tr("fee") % tr("destination") % tr("amount") % tr("index") % tr("note")
<< std::endl;
uint64_t running_balance = 0;
auto formatter = boost::format("%8.8llu,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%100.100s,%20.20s,\"%s\",%s");
for (const auto& transfer : all_transfers)
{
// ignore unconfirmed transfers in running balance
if (transfer.confirmed)
{
if (transfer.direction == "in" || transfer.direction == "block")
running_balance += transfer.amount;
else
running_balance -= transfer.amount + transfer.fee;
}
file << formatter
% transfer.block
% transfer.direction
% transfer.unlocked
% tools::get_human_readable_timestamp(transfer.timestamp)
% print_money(transfer.amount)
% print_money(running_balance)
% string_tools::pod_to_hex(transfer.hash)
% transfer.payment_id
% print_money(transfer.fee)
% (transfer.outputs.size() ? transfer.outputs[0].first : "-")
% (transfer.outputs.size() ? print_money(transfer.outputs[0].second) : "")
% boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
% transfer.note
<< std::endl;
for (size_t i = 1; i < transfer.outputs.size(); ++i)
{
file << formatter
% ""
% ""
% ""
% ""
% ""
% ""
% ""
% ""
% ""
% transfer.outputs[i].first
% print_money(transfer.outputs[i].second)
% ""
% ""
<< std::endl;
}
}
file.close();
success_msg_writer() << tr("CSV exported to ") << filename;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::unspent_outputs(const std::vector<std::string> &args_)
{
if(args_.size() > 3)
{
PRINT_USAGE(USAGE_UNSPENT_OUTPUTS);
return true;
}
auto local_args = args_;
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return true;
local_args.erase(local_args.begin());
}
uint64_t min_amount = 0;
uint64_t max_amount = std::numeric_limits<uint64_t>::max();
if (local_args.size() > 0)
{
if (!cryptonote::parse_amount(min_amount, local_args[0]))
{
fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
if (local_args.size() > 0)
{
if (!cryptonote::parse_amount(max_amount, local_args[0]))
{
fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
}
if (min_amount > max_amount)
{
fail_msg_writer() << tr("<min_amount> should be smaller than <max_amount>");
return true;
}
}
tools::wallet2::transfer_container transfers;
m_wallet->get_transfers(transfers);
std::map<uint64_t, tools::wallet2::transfer_container> amount_to_tds;
uint64_t min_height = std::numeric_limits<uint64_t>::max();
uint64_t max_height = 0;
uint64_t found_min_amount = std::numeric_limits<uint64_t>::max();
uint64_t found_max_amount = 0;
uint64_t count = 0;
for (const auto& td : transfers)
{
uint64_t amount = td.amount();
if (td.m_spent || amount < min_amount || amount > max_amount || td.m_subaddr_index.major != m_current_subaddress_account || (subaddr_indices.count(td.m_subaddr_index.minor) == 0 && !subaddr_indices.empty()))
continue;
amount_to_tds[amount].push_back(td);
if (min_height > td.m_block_height) min_height = td.m_block_height;
if (max_height < td.m_block_height) max_height = td.m_block_height;
if (found_min_amount > amount) found_min_amount = amount;
if (found_max_amount < amount) found_max_amount = amount;
++count;
}
if (amount_to_tds.empty())
{
success_msg_writer() << tr("There is no unspent output in the specified address");
return true;
}
for (const auto& amount_tds : amount_to_tds)
{
auto& tds = amount_tds.second;
success_msg_writer() << tr("\nAmount: ") << print_money(amount_tds.first) << tr(", number of keys: ") << tds.size();
for (size_t i = 0; i < tds.size(); )
{
std::ostringstream oss;
for (size_t j = 0; j < 8 && i < tds.size(); ++i, ++j)
oss << tds[i].m_block_height << tr(" ");
success_msg_writer() << oss.str();
}
}
success_msg_writer()
<< tr("\nMin block height: ") << min_height
<< tr("\nMax block height: ") << max_height
<< tr("\nMin amount found: ") << print_money(found_min_amount)
<< tr("\nMax amount found: ") << print_money(found_max_amount)
<< tr("\nTotal count: ") << count;
const size_t histogram_height = 10;
const size_t histogram_width = 50;
double bin_size = (max_height - min_height + 1.0) / histogram_width;
size_t max_bin_count = 0;
std::vector<size_t> histogram(histogram_width, 0);
for (const auto& amount_tds : amount_to_tds)
{
for (auto& td : amount_tds.second)
{
uint64_t bin_index = (td.m_block_height - min_height + 1) / bin_size;
if (bin_index >= histogram_width)
bin_index = histogram_width - 1;
histogram[bin_index]++;
if (max_bin_count < histogram[bin_index])
max_bin_count = histogram[bin_index];
}
}
for (size_t x = 0; x < histogram_width; ++x)
{
double bin_count = histogram[x];
if (max_bin_count > histogram_height)
bin_count *= histogram_height / (double)max_bin_count;
if (histogram[x] > 0 && bin_count < 1.0)
bin_count = 1.0;
histogram[x] = bin_count;
}
std::vector<std::string> histogram_line(histogram_height, std::string(histogram_width, ' '));
for (size_t y = 0; y < histogram_height; ++y)
{
for (size_t x = 0; x < histogram_width; ++x)
{
if (y < histogram[x])
histogram_line[y][x] = '*';
}
}
double count_per_star = max_bin_count / (double)histogram_height;
if (count_per_star < 1)
count_per_star = 1;
success_msg_writer()
<< tr("\nBin size: ") << bin_size
<< tr("\nOutputs per *: ") << count_per_star;
ostringstream histogram_str;
histogram_str << tr("count\n ^\n");
for (size_t y = histogram_height; y > 0; --y)
histogram_str << tr(" |") << histogram_line[y - 1] << tr("|\n");
histogram_str
<< tr(" +") << std::string(histogram_width, '-') << tr("+--> block height\n")
<< tr(" ^") << std::string(histogram_width - 2, ' ') << tr("^\n")
<< tr(" ") << min_height << std::string(histogram_width - 8, ' ') << max_height;
success_msg_writer() << histogram_str.str();
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::rescan_blockchain(const std::vector<std::string> &args_)
{
uint64_t start_height = 0;
ResetType reset_type = ResetSoft;
if (!args_.empty())
{
if (args_[0] == "hard")
{
reset_type = ResetHard;
}
else if (args_[0] == "soft")
{
reset_type = ResetSoft;
}
else if (args_[0] == "keep_ki")
{
reset_type = ResetSoftKeepKI;
}
else
{
PRINT_USAGE(USAGE_RESCAN_BC);
return true;
}
if (args_.size() > 1)
{
try
{
start_height = boost::lexical_cast<uint64_t>( args_[1] );
}
catch(const boost::bad_lexical_cast &)
{
start_height = 0;
}
}
}
if (reset_type == ResetHard)
{
message_writer() << tr("Warning: this will lose any information which can not be recovered from the blockchain.");
message_writer() << tr("This includes destination addresses, tx secret keys, tx notes, etc");
std::string confirm = input_line(tr("Rescan anyway?"), true);
if(!std::cin.eof())
{
if (!command_line::is_yes(confirm))
return true;
}
}
const uint64_t wallet_from_height = m_wallet->get_refresh_from_block_height();
if (start_height > wallet_from_height)
{
message_writer() << tr("Warning: your restore height is higher than wallet restore height: ") << wallet_from_height;
std::string confirm = input_line(tr("Rescan anyway ? (Y/Yes/N/No): "));
if(!std::cin.eof())
{
if (!command_line::is_yes(confirm))
return true;
}
}
return refresh_main(start_height, reset_type, true);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::check_for_messages()
{
try
{
std::vector<mms::message> new_messages;
bool new_message = get_message_store().check_for_messages(get_multisig_wallet_state(), new_messages);
if (new_message)
{
message_writer(console_color_magenta, true) << tr("MMS received new message");
list_mms_messages(new_messages);
m_cmd_binder.print_prompt();
}
}
catch(...) {}
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::wallet_idle_thread()
{
const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time();
while (true)
{
boost::unique_lock<boost::mutex> lock(m_idle_mutex);
if (!m_idle_run.load(std::memory_order_relaxed))
break;
// if another thread was busy (ie, a foreground refresh thread), we'll end up here at
// some random time that's not what we slept for, so we should not call refresh now
// or we'll be leaking that fact through timing
const boost::posix_time::ptime now0 = boost::posix_time::microsec_clock::universal_time();
const uint64_t dt_actual = (now0 - start_time).total_microseconds() % 1000000;
#ifdef _WIN32
static const uint64_t threshold = 10000;
#else
static const uint64_t threshold = 2000;
#endif
if (dt_actual < threshold) // if less than a threshold... would a very slow machine always miss it ?
{
#ifndef _WIN32
m_inactivity_checker.do_call(boost::bind(&simple_wallet::check_inactivity, this));
#endif
m_refresh_checker.do_call(boost::bind(&simple_wallet::check_refresh, this));
m_mms_checker.do_call(boost::bind(&simple_wallet::check_mms, this));
m_rpc_payment_checker.do_call(boost::bind(&simple_wallet::check_rpc_payment, this));
if (!m_idle_run.load(std::memory_order_relaxed))
break;
}
// aim for the next multiple of 1 second
const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
const auto dt = (now - start_time).total_microseconds();
const auto wait = 1000000 - dt % 1000000;
m_idle_cond.wait_for(lock, boost::chrono::microseconds(wait));
}
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_inactivity()
{
// inactivity lock
if (!m_locked && !m_in_command)
{
const uint32_t seconds = m_wallet->inactivity_lock_timeout();
if (seconds > 0 && time(NULL) - m_last_activity_time > seconds)
{
m_locked = true;
m_cmd_binder.cancel_input();
}
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_refresh()
{
// auto refresh
if (m_auto_refresh_enabled)
{
m_auto_refresh_refreshing = true;
try
{
uint64_t fetched_blocks;
bool received_money;
if (try_connect_to_daemon(true))
m_wallet->refresh(m_wallet->is_trusted_daemon(), 0, fetched_blocks, received_money, false); // don't check the pool in background mode
}
catch(...) {}
m_auto_refresh_refreshing = false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_mms()
{
// Check for new MMS messages;
// For simplicity auto message check is ALSO controlled by "m_auto_refresh_enabled" and has no
// separate thread either; thread syncing is tricky enough with only this one idle thread here
if (m_auto_refresh_enabled && get_message_store().get_active())
{
check_for_messages();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_rpc_payment()
{
if (!m_rpc_payment_mining_requested && m_wallet->auto_mine_for_rpc_payment_threshold() == 0.0f)
return true;
uint64_t target = m_wallet->credits_target();
if (target == 0)
target = CREDITS_TARGET;
if (m_rpc_payment_mining_requested)
target = std::numeric_limits<uint64_t>::max();
bool need_payment = m_need_payment || m_rpc_payment_mining_requested || (m_wallet->credits() < target && m_wallet->daemon_requires_payment());
if (need_payment)
{
const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time();
auto startfunc = [this](uint64_t diff, uint64_t credits_per_hash_found)
{
const float cph = credits_per_hash_found / (float)diff;
bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE);
if (credits_per_hash_found > 0 && cph >= m_wallet->auto_mine_for_rpc_payment_threshold())
{
MINFO(std::to_string(cph) << " credits per hash is >= our threshold (" << m_wallet->auto_mine_for_rpc_payment_threshold() << "), starting mining");
return true;
}
else if (m_rpc_payment_mining_requested)
{
MINFO("Mining for RPC payment was requested, starting mining");
return true;
}
else
{
if (!m_daemon_rpc_payment_message_displayed)
{
success_msg_writer() << boost::format(tr("Daemon requests payment at diff %llu, with %f credits/hash%s. Run start_mining_for_rpc to start mining to pay for RPC access, or use another daemon")) %
diff % cph % (low ? " - this is low" : "");
m_cmd_binder.print_prompt();
m_daemon_rpc_payment_message_displayed = true;
}
return false;
}
};
auto contfunc = [&,this](unsigned n_hashes)
{
if (m_suspend_rpc_payment_mining.load(std::memory_order_relaxed))
return false;
const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
m_last_rpc_payment_mining_time = now;
if ((now - start_time).total_microseconds() >= 2 * 1000000)
m_rpc_payment_hash_rate = n_hashes / (float)((now - start_time).total_seconds());
if ((now - start_time).total_microseconds() >= REFRESH_PERIOD * 1000000)
return false;
return true;
};
auto foundfunc = [this, target](uint64_t credits)
{
m_need_payment = false;
return credits < target;
};
auto errorfunc = [this](const std::string &error)
{
fail_msg_writer() << tr("Error mining to daemon: ") << error;
m_cmd_binder.print_prompt();
};
bool ret = m_wallet->search_for_rpc_payment(target, startfunc, contfunc, foundfunc, errorfunc);
if (!ret)
{
fail_msg_writer() << tr("Failed to start mining for RPC payment");
m_cmd_binder.print_prompt();
}
}
return true;
}
//----------------------------------------------------------------------------------------------------
std::string simple_wallet::get_prompt() const
{
if (m_locked)
return std::string("[") + tr("locked due to inactivity") + "]";
std::string addr_start = m_wallet->get_subaddress_as_str({m_current_subaddress_account, 0}).substr(0, 6);
std::string prompt = std::string("[") + tr("wallet") + " " + addr_start;
if (!m_wallet->check_connection(NULL))
prompt += tr(" (no daemon)");
else if (!m_wallet->is_synced())
prompt += tr(" (out of sync)");
prompt += "]: ";
return prompt;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::run()
{
// check and display warning, but go on anyway
try_connect_to_daemon();
refresh_main(0, ResetNone, true);
m_auto_refresh_enabled = m_wallet->auto_refresh();
m_idle_thread = boost::thread([&]{wallet_idle_thread();});
message_writer(console_color_green, false) << "Background refresh thread started";
return m_cmd_binder.run_handling([this](){return get_prompt();}, "");
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::stop()
{
m_cmd_binder.stop_handling();
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::account(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
// Usage:
// account
// account new <label text with white spaces allowed>
// account switch <index>
// account label <index> <label text with white spaces allowed>
// account tag <tag_name> <account_index_1> [<account_index_2> ...]
// account untag <account_index_1> [<account_index_2> ...]
// account tag_description <tag_name> <description>
if (args.empty())
{
// print all the existing accounts
LOCK_IDLE_SCOPE();
print_accounts();
return true;
}
std::vector<std::string> local_args = args;
std::string command = local_args[0];
local_args.erase(local_args.begin());
if (command == "new")
{
// create a new account and switch to it
std::string label = boost::join(local_args, " ");
if (label.empty())
label = tr("(Untitled account)");
m_wallet->add_subaddress_account(label);
m_current_subaddress_account = m_wallet->get_num_subaddress_accounts() - 1;
// update_prompt();
LOCK_IDLE_SCOPE();
print_accounts();
}
else if (command == "switch" && local_args.size() == 1)
{
// switch to the specified account
uint32_t index_major;
if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
return true;
}
if (index_major >= m_wallet->get_num_subaddress_accounts())
{
fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddress_accounts() - 1);
return true;
}
m_current_subaddress_account = index_major;
// update_prompt();
show_balance();
}
else if (command == "label" && local_args.size() >= 1)
{
// set label of the specified account
uint32_t index_major;
if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
std::string label = boost::join(local_args, " ");
try
{
m_wallet->set_subaddress_label({index_major, 0}, label);
LOCK_IDLE_SCOPE();
print_accounts();
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else if (command == "tag" && local_args.size() >= 2)
{
const std::string tag = local_args[0];
std::set<uint32_t> account_indices;
for (size_t i = 1; i < local_args.size(); ++i)
{
uint32_t account_index;
if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
return true;
}
account_indices.insert(account_index);
}
try
{
m_wallet->set_account_tag(account_indices, tag);
print_accounts(tag);
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else if (command == "untag" && local_args.size() >= 1)
{
std::set<uint32_t> account_indices;
for (size_t i = 0; i < local_args.size(); ++i)
{
uint32_t account_index;
if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
return true;
}
account_indices.insert(account_index);
}
try
{
m_wallet->set_account_tag(account_indices, "");
print_accounts();
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else if (command == "tag_description" && local_args.size() >= 1)
{
const std::string tag = local_args[0];
std::string description;
if (local_args.size() > 1)
{
local_args.erase(local_args.begin());
description = boost::join(local_args, " ");
}
try
{
m_wallet->set_account_tag_description(tag, description);
print_accounts(tag);
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else
{
PRINT_USAGE(USAGE_ACCOUNT);
}
return true;
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::print_accounts()
{
const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
size_t num_untagged_accounts = m_wallet->get_num_subaddress_accounts();
for (const std::pair<std::string, std::string>& p : account_tags.first)
{
const std::string& tag = p.first;
print_accounts(tag);
num_untagged_accounts -= std::count(account_tags.second.begin(), account_tags.second.end(), tag);
success_msg_writer() << "";
}
if (num_untagged_accounts > 0)
print_accounts("");
if (num_untagged_accounts < m_wallet->get_num_subaddress_accounts())
success_msg_writer() << tr("\nGrand total:\n Balance: ") << print_money(m_wallet->balance_all(false)) << tr(", unlocked balance: ") << print_money(m_wallet->unlocked_balance_all(false));
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::print_accounts(const std::string& tag)
{
const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
if (tag.empty())
{
success_msg_writer() << tr("Untagged accounts:");
}
else
{
if (account_tags.first.count(tag) == 0)
{
fail_msg_writer() << boost::format(tr("Tag %s is unregistered.")) % tag;
return;
}
success_msg_writer() << tr("Accounts with tag: ") << tag;
success_msg_writer() << tr("Tag's description: ") << account_tags.first.find(tag)->second;
}
success_msg_writer() << boost::format(" %15s %21s %21s %21s") % tr("Account") % tr("Balance") % tr("Unlocked balance") % tr("Label");
uint64_t total_balance = 0, total_unlocked_balance = 0;
for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index)
{
if (account_tags.second[account_index] != tag)
continue;
success_msg_writer() << boost::format(tr(" %c%8u %6s %21s %21s %21s"))
% (m_current_subaddress_account == account_index ? '*' : ' ')
% account_index
% m_wallet->get_subaddress_as_str({account_index, 0}).substr(0, 6)
% print_money(m_wallet->balance(account_index, false))
% print_money(m_wallet->unlocked_balance(account_index, false))
% m_wallet->get_subaddress_label({account_index, 0});
total_balance += m_wallet->balance(account_index, false);
total_unlocked_balance += m_wallet->unlocked_balance(account_index, false);
}
success_msg_writer() << tr("----------------------------------------------------------------------------------");
success_msg_writer() << boost::format(tr("%15s %21s %21s")) % "Total" % print_money(total_balance) % print_money(total_unlocked_balance);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::print_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
// Usage:
// address
// address new <label text with white spaces allowed>
// address all
// address <index_min> [<index_max>]
// address label <index> <label text with white spaces allowed>
// address device [<index>]
std::vector<std::string> local_args = args;
tools::wallet2::transfer_container transfers;
m_wallet->get_transfers(transfers);
auto print_address_sub = [this, &transfers](uint32_t index)
{
bool used = std::find_if(
transfers.begin(), transfers.end(),
[this, &index](const tools::wallet2::transfer_details& td) {
return td.m_subaddr_index == cryptonote::subaddress_index{ m_current_subaddress_account, index };
}) != transfers.end();
success_msg_writer() << index << " " << m_wallet->get_subaddress_as_str({m_current_subaddress_account, index}) << " " << (index == 0 ? tr("Primary address") : m_wallet->get_subaddress_label({m_current_subaddress_account, index})) << " " << (used ? tr("(used)") : "");
};
uint32_t index = 0;
if (local_args.empty())
{
print_address_sub(index);
}
else if (local_args.size() == 1 && local_args[0] == "all")
{
local_args.erase(local_args.begin());
for (; index < m_wallet->get_num_subaddresses(m_current_subaddress_account); ++index)
print_address_sub(index);
}
else if (local_args[0] == "new")
{
local_args.erase(local_args.begin());
std::string label;
if (local_args.size() > 0)
label = boost::join(local_args, " ");
if (label.empty())
label = tr("(Untitled address)");
m_wallet->add_subaddress(m_current_subaddress_account, label);
print_address_sub(m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
m_wallet->device_show_address(m_current_subaddress_account, m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1, boost::none);
}
else if (local_args.size() >= 2 && local_args[0] == "label")
{
if (!epee::string_tools::get_xtype_from_string(index, local_args[1]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[1];
return true;
}
if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
{
fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
return true;
}
local_args.erase(local_args.begin());
local_args.erase(local_args.begin());
std::string label = boost::join(local_args, " ");
m_wallet->set_subaddress_label({m_current_subaddress_account, index}, label);
print_address_sub(index);
}
else if (local_args.size() <= 2 && epee::string_tools::get_xtype_from_string(index, local_args[0]))
{
local_args.erase(local_args.begin());
uint32_t index_min = index;
uint32_t index_max = index_min;
if (local_args.size() > 0)
{
if (!epee::string_tools::get_xtype_from_string(index_max, local_args[0]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
}
if (index_max < index_min)
std::swap(index_min, index_max);
if (index_min >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
{
fail_msg_writer() << tr("<index_min> is already out of bound");
return true;
}
if (index_max >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
{
message_writer() << tr("<index_max> exceeds the bound");
index_max = m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1;
}
for (index = index_min; index <= index_max; ++index)
print_address_sub(index);
}
else if (local_args[0] == "device")
{
index = 0;
local_args.erase(local_args.begin());
if (local_args.size() > 0)
{
if (!epee::string_tools::get_xtype_from_string(index, local_args[0]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
return true;
}
if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
{
fail_msg_writer() << tr("<index> is out of bounds");
return true;
}
}
print_address_sub(index);
m_wallet->device_show_address(m_current_subaddress_account, index, boost::none);
}
else
{
PRINT_USAGE(USAGE_ADDRESS);
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::print_integrated_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
crypto::hash8 payment_id;
bool display_on_device = false;
std::vector<std::string> local_args = args;
if (local_args.size() > 0 && local_args[0] == "device")
{
local_args.erase(local_args.begin());
display_on_device = true;
}
auto device_show_integrated = [this, display_on_device](crypto::hash8 payment_id)
{
if (display_on_device)
{
m_wallet->device_show_address(m_current_subaddress_account, 0, payment_id);
}
};
if (local_args.size() > 1)
{
PRINT_USAGE(USAGE_INTEGRATED_ADDRESS);
return true;
}
if (local_args.size() == 0)
{
if (m_current_subaddress_account != 0)
{
fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
return true;
}
payment_id = crypto::rand<crypto::hash8>();
success_msg_writer() << tr("Random payment ID: ") << payment_id;
success_msg_writer() << tr("Matching integrated address: ") << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
device_show_integrated(payment_id);
return true;
}
if(tools::wallet2::parse_short_payment_id(local_args.back(), payment_id))
{
if (m_current_subaddress_account != 0)
{
fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
return true;
}
success_msg_writer() << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
device_show_integrated(payment_id);
return true;
}
else {
address_parse_info info;
if(get_account_address_from_str(info, m_wallet->nettype(), local_args.back()))
{
if (info.has_payment_id)
{
success_msg_writer() << boost::format(tr("Integrated address: %s, payment ID: %s")) %
get_account_address_as_str(m_wallet->nettype(), false, info.address) % epee::string_tools::pod_to_hex(info.payment_id);
device_show_integrated(info.payment_id);
}
else
{
success_msg_writer() << (info.is_subaddress ? tr("Subaddress: ") : tr("Standard address: ")) << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
}
return true;
}
}
fail_msg_writer() << tr("failed to parse payment ID or address");
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::address_book(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (args.size() == 0)
{
}
else if (args.size() == 1 || (args[0] != "add" && args[0] != "delete"))
{
PRINT_USAGE(USAGE_ADDRESS_BOOK);
return true;
}
else if (args[0] == "add")
{
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
crypto::hash payment_id = crypto::null_hash;
size_t description_start = 2;
if (info.has_payment_id)
{
memcpy(payment_id.data, info.payment_id.data, 8);
}
else if (!info.has_payment_id && args.size() >= 4 && args[2] == "pid")
{
if (tools::wallet2::parse_long_payment_id(args[3], payment_id))
{
LONG_PAYMENT_ID_SUPPORT_CHECK();
description_start += 2;
}
else if (tools::wallet2::parse_short_payment_id(args[3], info.payment_id))
{
fail_msg_writer() << tr("Short payment IDs are to be used within an integrated address only");
return true;
}
else
{
fail_msg_writer() << tr("failed to parse payment ID");
return true;
}
}
std::string description;
for (size_t i = description_start; i < args.size(); ++i)
{
if (i > description_start)
description += " ";
description += args[i];
}
m_wallet->add_address_book_row(info.address, payment_id, description, info.is_subaddress);
}
else
{
size_t row_id;
if(!epee::string_tools::get_xtype_from_string(row_id, args[1]))
{
fail_msg_writer() << tr("failed to parse index");
return true;
}
m_wallet->delete_address_book_row(row_id);
}
auto address_book = m_wallet->get_address_book();
if (address_book.empty())
{
success_msg_writer() << tr("Address book is empty.");
}
else
{
for (size_t i = 0; i < address_book.size(); ++i) {
auto& row = address_book[i];
success_msg_writer() << tr("Index: ") << i;
success_msg_writer() << tr("Address: ") << get_account_address_as_str(m_wallet->nettype(), row.m_is_subaddress, row.m_address);
success_msg_writer() << tr("Payment ID: ") << row.m_payment_id << " (OBSOLETE)";
success_msg_writer() << tr("Description: ") << row.m_description << "\n";
}
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_tx_note(const std::vector<std::string> &args)
{
if (args.size() == 0)
{
PRINT_USAGE(USAGE_SET_TX_NOTE);
return true;
}
cryptonote::blobdata txid_data;
if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
std::string note = "";
for (size_t n = 1; n < args.size(); ++n)
{
if (n > 1)
note += " ";
note += args[n];
}
m_wallet->set_tx_note(txid, note);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_tx_note(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
PRINT_USAGE(USAGE_GET_TX_NOTE);
return true;
}
cryptonote::blobdata txid_data;
if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
std::string note = m_wallet->get_tx_note(txid);
if (note.empty())
success_msg_writer() << "no note found";
else
success_msg_writer() << "note found: " << note;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_description(const std::vector<std::string> &args)
{
// 0 arguments allowed, for setting the description to empty string
std::string description = "";
for (size_t n = 0; n < args.size(); ++n)
{
if (n > 0)
description += " ";
description += args[n];
}
m_wallet->set_description(description);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_description(const std::vector<std::string> &args)
{
if (args.size() != 0)
{
PRINT_USAGE(USAGE_GET_DESCRIPTION);
return true;
}
std::string description = m_wallet->get_description();
if (description.empty())
success_msg_writer() << tr("no description found");
else
success_msg_writer() << tr("description found: ") << description;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::status(const std::vector<std::string> &args)
{
uint64_t local_height = m_wallet->get_blockchain_current_height();
uint32_t version = 0;
bool ssl = false;
if (!m_wallet->check_connection(&version, &ssl))
{
success_msg_writer() << "Refreshed " << local_height << "/?, no daemon connected";
return true;
}
std::string err;
uint64_t bc_height = get_daemon_blockchain_height(err);
if (err.empty())
{
bool synced = local_height == bc_height;
success_msg_writer() << "Refreshed " << local_height << "/" << bc_height << ", " << (synced ? "synced" : "syncing")
<< ", daemon RPC v" << get_version_string(version) << ", " << (ssl ? "SSL" : "no SSL");
}
else
{
fail_msg_writer() << "Refreshed " << local_height << "/?, daemon connection error";
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::wallet_info(const std::vector<std::string> &args)
{
bool ready;
uint32_t threshold, total;
std::string description = m_wallet->get_description();
if (description.empty())
{
description = "<Not set>";
}
message_writer() << tr("Filename: ") << m_wallet->get_wallet_file();
message_writer() << tr("Description: ") << description;
message_writer() << tr("Address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
std::string type;
if (m_wallet->watch_only())
type = tr("Watch only");
else if (m_wallet->multisig(&ready, &threshold, &total))
type = (boost::format(tr("%u/%u multisig%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
else
type = tr("Normal");
message_writer() << tr("Type: ") << type;
message_writer() << tr("Network type: ") << (
m_wallet->nettype() == cryptonote::TESTNET ? tr("Testnet") :
m_wallet->nettype() == cryptonote::STAGENET ? tr("Stagenet") : tr("Mainnet"));
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sign(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_SIGN);
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot sign");
return true;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("This wallet is multisig and cannot sign");
return true;
}
std::string filename = args[0];
std::string data;
bool r = m_wallet->load_from_file(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return true;
}
SCOPED_WALLET_UNLOCK();
std::string signature = m_wallet->sign(data);
success_msg_writer() << signature;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::verify(const std::vector<std::string> &args)
{
if (args.size() != 3)
{
PRINT_USAGE(USAGE_VERIFY);
return true;
}
std::string filename = args[0];
std::string address_string = args[1];
std::string signature= args[2];
std::string data;
bool r = m_wallet->load_from_file(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return true;
}
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_string, oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
r = m_wallet->verify(data, info.address, signature);
if (!r)
{
fail_msg_writer() << tr("Bad signature from ") << address_string;
}
else
{
success_msg_writer() << tr("Good signature from ") << address_string;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::export_key_images(const std::vector<std::string> &args_)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
auto args = args_;
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot export key images");
return true;
}
bool all = false;
if (args.size() >= 2 && args[0] == "all")
{
all = true;
args.erase(args.begin());
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_EXPORT_KEY_IMAGES);
return true;
}
std::string filename = args[0];
if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK();
try
{
if (!m_wallet->export_key_images(filename, all))
{
fail_msg_writer() << tr("failed to save file ") << filename;
return true;
}
}
catch (const std::exception &e)
{
LOG_ERROR("Error exporting key images: " << e.what());
fail_msg_writer() << "Error exporting key images: " << e.what();
return true;
}
success_msg_writer() << tr("Signed key images exported to ") << filename;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::import_key_images(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->is_trusted_daemon())
{
fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
return true;
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_IMPORT_KEY_IMAGES);
return true;
}
std::string filename = args[0];
LOCK_IDLE_SCOPE();
try
{
uint64_t spent = 0, unspent = 0;
uint64_t height = m_wallet->import_key_images(filename, spent, unspent);
success_msg_writer() << "Signed key images imported to height " << height << ", "
<< print_money(spent) << " spent, " << print_money(unspent) << " unspent";
}
catch (const std::exception &e)
{
fail_msg_writer() << "Failed to import key images: " << e.what();
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::hw_key_images_sync(const std::vector<std::string> &args)
{
if (!m_wallet->key_on_device())
{
fail_msg_writer() << tr("command only supported by HW wallet");
return true;
}
if (!m_wallet->get_account().get_device().has_ki_cold_sync())
{
fail_msg_writer() << tr("hw wallet does not support cold KI sync");
return true;
}
LOCK_IDLE_SCOPE();
key_images_sync_intern();
return true;
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::key_images_sync_intern(){
try
{
message_writer(console_color_white, false) << tr("Please confirm the key image sync on the device");
uint64_t spent = 0, unspent = 0;
uint64_t height = m_wallet->cold_key_image_sync(spent, unspent);
if (height > 0)
{
success_msg_writer() << tr("Key images synchronized to height ") << height;
if (!m_wallet->is_trusted_daemon())
{
message_writer() << tr("Running untrusted daemon, cannot determine which transaction output is spent. Use a trusted daemon with --trusted-daemon and run rescan_spent");
} else
{
success_msg_writer() << print_money(spent) << tr(" spent, ") << print_money(unspent) << tr(" unspent");
}
}
else {
fail_msg_writer() << tr("Failed to import key images");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to import key images: ") << e.what();
}
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::hw_reconnect(const std::vector<std::string> &args)
{
if (!m_wallet->key_on_device())
{
fail_msg_writer() << tr("command only supported by HW wallet");
return true;
}
LOCK_IDLE_SCOPE();
try
{
bool r = m_wallet->reconnect_device();
if (!r){
fail_msg_writer() << tr("Failed to reconnect device");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to reconnect device: ") << tr(e.what());
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::export_outputs(const std::vector<std::string> &args_)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
auto args = args_;
bool all = false;
if (args.size() >= 2 && args[0] == "all")
{
all = true;
args.erase(args.begin());
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_EXPORT_OUTPUTS);
return true;
}
std::string filename = args[0];
if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK();
try
{
std::string data = m_wallet->export_outputs_to_str(all);
bool r = m_wallet->save_to_file(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to save file ") << filename;
return true;
}
}
catch (const std::exception &e)
{
LOG_ERROR("Error exporting outputs: " << e.what());
fail_msg_writer() << "Error exporting outputs: " << e.what();
return true;
}
success_msg_writer() << tr("Outputs exported to ") << filename;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::import_outputs(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (args.size() != 1)
{
PRINT_USAGE(USAGE_IMPORT_OUTPUTS);
return true;
}
std::string filename = args[0];
std::string data;
bool r = m_wallet->load_from_file(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return true;
}
try
{
SCOPED_WALLET_UNLOCK();
size_t n_outputs = m_wallet->import_outputs_from_str(data);
success_msg_writer() << boost::lexical_cast<std::string>(n_outputs) << " outputs imported";
}
catch (const std::exception &e)
{
fail_msg_writer() << "Failed to import outputs " << filename << ": " << e.what();
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_transfer(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
PRINT_USAGE(USAGE_SHOW_TRANSFER);
return true;
}
cryptonote::blobdata txid_data;
if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
const uint64_t last_block_height = m_wallet->get_blockchain_current_height();
std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
m_wallet->get_payments(payments, 0, (uint64_t)-1, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second;
if (pd.m_tx_hash == txid) {
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
success_msg_writer() << "Incoming transaction found";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Height: " << pd.m_block_height;
success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(pd.m_amount);
success_msg_writer() << "Payment ID: " << payment_id;
if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
{
uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
uint64_t last_block_reward = m_wallet->get_last_block_reward();
uint64_t suggested_threshold = last_block_reward ? (pd.m_amount + last_block_reward - 1) / last_block_reward : 0;
if (bh >= last_block_height)
success_msg_writer() << "Locked: " << (bh - last_block_height) << " blocks to unlock";
else if (suggested_threshold > 0)
success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations (" << suggested_threshold << " suggested threshold)";
else
success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations";
}
else
{
uint64_t current_time = static_cast<uint64_t>(time(NULL));
uint64_t threshold = current_time + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS;
if (threshold >= pd.m_unlock_time)
success_msg_writer() << "unlocked for " << get_human_readable_timespan(std::chrono::seconds(threshold - pd.m_unlock_time));
else
success_msg_writer() << "locked for " << get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold));
}
success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
return true;
}
}
std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments_out;
m_wallet->get_payments_out(payments_out, 0, (uint64_t)-1, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments_out.begin(); i != payments_out.end(); ++i) {
if (i->first == txid)
{
const tools::wallet2::confirmed_transfer_details &pd = i->second;
uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
uint64_t fee = pd.m_amount_in - pd.m_amount_out;
std::string dests;
for (const auto &d: pd.m_dests) {
if (!dests.empty())
dests += ", ";
dests += d.address(m_wallet->nettype(), pd.m_payment_id) + ": " + print_money(d.amount);
}
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
success_msg_writer() << "Outgoing transaction found";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Height: " << pd.m_block_height;
success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(pd.m_amount_in - change - fee);
success_msg_writer() << "Payment ID: " << payment_id;
success_msg_writer() << "Change: " << print_money(change);
success_msg_writer() << "Fee: " << print_money(fee);
success_msg_writer() << "Destinations: " << dests;
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
return true;
}
}
try
{
std::vector<std::pair<cryptonote::transaction, bool>> process_txs;
m_wallet->update_pool_state(process_txs);
if (!process_txs.empty())
m_wallet->process_pool_state(process_txs);
std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> pool_payments;
m_wallet->get_unconfirmed_payments(pool_payments, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = pool_payments.begin(); i != pool_payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second.m_pd;
if (pd.m_tx_hash == txid)
{
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
success_msg_writer() << "Unconfirmed incoming transaction found in the txpool";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(pd.m_amount);
success_msg_writer() << "Payment ID: " << payment_id;
success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
if (i->second.m_double_spend_seen)
success_msg_writer() << tr("Double spend seen on the network: this transaction may or may not end up being mined");
return true;
}
}
}
catch (...)
{
fail_msg_writer() << "Failed to get pool state";
}
std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
if (i->first == txid)
{
const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
uint64_t amount = pd.m_amount_in;
uint64_t fee = amount - pd.m_amount_out;
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
success_msg_writer() << (is_failed ? "Failed" : "Pending") << " outgoing transaction found";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(amount - pd.m_change - fee);
success_msg_writer() << "Payment ID: " << payment_id;
success_msg_writer() << "Change: " << print_money(pd.m_change);
success_msg_writer() << "Fee: " << print_money(fee);
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
return true;
}
}
fail_msg_writer() << tr("Transaction ID not found");
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::process_command(const std::vector<std::string> &args)
{
return m_cmd_binder.process_command_vec(args);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::interrupt()
{
if (m_in_manual_refresh.load(std::memory_order_relaxed))
{
m_wallet->stop();
}
else
{
stop();
}
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::commit_or_save(std::vector<tools::wallet2::pending_tx>& ptx_vector, bool do_not_relay)
{
size_t i = 0;
while (!ptx_vector.empty())
{
auto & ptx = ptx_vector.back();
const crypto::hash txid = get_transaction_hash(ptx.tx);
if (do_not_relay)
{
cryptonote::blobdata blob;
tx_to_blob(ptx.tx, blob);
const std::string blob_hex = epee::string_tools::buff_to_hex_nodelimer(blob);
const std::string filename = "raw_swap_tx" + (ptx_vector.size() == 1 ? "" : ("_" + std::to_string(i++)));
if (m_wallet->save_to_file(filename, blob_hex, true))
success_msg_writer(true) << tr("Transaction successfully saved to ") << filename << tr(", txid ") << txid;
else
fail_msg_writer() << tr("Failed to save transaction to ") << filename << tr(", txid ") << txid;
}
else
{
m_wallet->commit_tx(ptx);
success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << txid << ENDL
<< tr("You can check its status by using the `show_transfers` command.");
}
// if no exception, remove element from vector
ptx_vector.pop_back();
}
}
//----------------------------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
TRY_ENTRY();
#ifdef WIN32
// Activate UTF-8 support for Boost filesystem classes on Windows
std::locale::global(boost::locale::generator().generate(""));
boost::filesystem::path::imbue(std::locale());
#endif
setlocale(LC_CTYPE, "");
po::options_description desc_params(wallet_args::tr("Wallet options"));
tools::wallet2::init_options(desc_params);
command_line::add_arg(desc_params, arg_wallet_file);
command_line::add_arg(desc_params, arg_generate_new_wallet);
command_line::add_arg(desc_params, arg_generate_from_device);
command_line::add_arg(desc_params, arg_generate_from_view_key);
command_line::add_arg(desc_params, arg_generate_from_spend_key);
command_line::add_arg(desc_params, arg_generate_from_keys);
command_line::add_arg(desc_params, arg_generate_from_multisig_keys);
command_line::add_arg(desc_params, arg_generate_from_json);
command_line::add_arg(desc_params, arg_mnemonic_language);
command_line::add_arg(desc_params, arg_command);
command_line::add_arg(desc_params, arg_restore_deterministic_wallet );
command_line::add_arg(desc_params, arg_restore_from_seed );
command_line::add_arg(desc_params, arg_restore_multisig_wallet );
command_line::add_arg(desc_params, arg_non_deterministic );
command_line::add_arg(desc_params, arg_electrum_seed );
command_line::add_arg(desc_params, arg_allow_mismatched_daemon_version);
command_line::add_arg(desc_params, arg_restore_height);
command_line::add_arg(desc_params, arg_restore_date);
command_line::add_arg(desc_params, arg_do_not_relay);
command_line::add_arg(desc_params, arg_create_address_file);
command_line::add_arg(desc_params, arg_subaddress_lookahead);
command_line::add_arg(desc_params, arg_use_english_language_names);
command_line::add_arg(desc_params, arg_rpc_client_secret_key);
po::positional_options_description positional_options;
positional_options.add(arg_command.name, -1);
boost::optional<po::variables_map> vm;
bool should_terminate = false;
std::tie(vm, should_terminate) = wallet_args::main(
argc, argv,
"swap-wallet-cli [--wallet-file=<file>|--generate-new-wallet=<file>] [<COMMAND>]",
sw::tr("This is the command line swap wallet. It needs to connect to a swap\ndaemon to work correctly.\nWARNING: Do not reuse your Swap keys on another fork, UNLESS this fork has key reuse mitigations built in. Doing so will harm your privacy."),
desc_params,
positional_options,
[](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; },
"swap-wallet-cli.log"
);
if (!vm)
{
return 1;
}
if (should_terminate)
{
return 0;
}
cryptonote::simple_wallet w;
const bool r = w.init(*vm);
CHECK_AND_ASSERT_MES(r, 1, sw::tr("Failed to initialize wallet"));
std::vector<std::string> command = command_line::get_arg(*vm, arg_command);
if (!command.empty())
{
if (!w.process_command(command))
fail_msg_writer() << sw::tr("Unknown command: ") << command.front();
w.stop();
w.deinit();
}
else
{
tools::signal_handler::install([&w](int type) {
if (tools::password_container::is_prompting.load())
{
// must be prompting for password so return and let the signal stop prompt
return;
}
#ifdef WIN32
if (type == CTRL_C_EVENT)
#else
if (type == SIGINT)
#endif
{
// if we're pressing ^C when refreshing, just stop refreshing
w.interrupt();
}
else
{
w.stop();
}
});
w.run();
w.deinit();
}
return 0;
CATCH_ENTRY_L0("main", 1);
}
// MMS ---------------------------------------------------------------------------------------------------
// Access to the message store, or more exactly to the list of the messages that can be changed
// by the idle thread, is guarded by the same mutex-based mechanism as access to the wallet
// as a whole and thus e.g. uses the "LOCK_IDLE_SCOPE" macro. This is a little over-cautious, but
// simple and safe. Care has to be taken however where MMS methods call other simplewallet methods
// that use "LOCK_IDLE_SCOPE" as this cannot be nested!
// Methods for commands like "export_multisig_info" usually read data from file(s) or write data
// to files. The MMS calls now those methods as well, to produce data for messages and to process data
// from messages. As it would be quite inconvenient for the MMS to write data for such methods to files
// first or get data out of result files after the call, those methods detect a call from the MMS and
// expect data as arguments instead of files and give back data by calling 'process_wallet_created_data'.
bool simple_wallet::user_confirms(const std::string &question)
{
std::string answer = input_line(question + tr(" (Y/Yes/N/No): "));
return !std::cin.eof() && command_line::is_yes(answer);
}
bool simple_wallet::get_number_from_arg(const std::string &arg, uint32_t &number, const uint32_t lower_bound, const uint32_t upper_bound)
{
bool valid = false;
try
{
number = boost::lexical_cast<uint32_t>(arg);
valid = (number >= lower_bound) && (number <= upper_bound);
}
catch(const boost::bad_lexical_cast &)
{
}
return valid;
}
bool simple_wallet::choose_mms_processing(const std::vector<mms::processing_data> &data_list, uint32_t &choice)
{
size_t choices = data_list.size();
if (choices == 1)
{
choice = 0;
return true;
}
mms::message_store& ms = m_wallet->get_message_store();
message_writer() << tr("Choose processing:");
std::string text;
for (size_t i = 0; i < choices; ++i)
{
const mms::processing_data &data = data_list[i];
text = std::to_string(i+1) + ": ";
switch (data.processing)
{
case mms::message_processing::sign_tx:
text += tr("Sign tx");
break;
case mms::message_processing::send_tx:
{
mms::message m;
ms.get_message_by_id(data.message_ids[0], m);
if (m.type == mms::message_type::fully_signed_tx)
{
text += tr("Send the tx for submission to ");
}
else
{
text += tr("Send the tx for signing to ");
}
mms::authorized_signer signer = ms.get_signer(data.receiving_signer_index);
text += ms.signer_to_string(signer, 50);
break;
}
case mms::message_processing::submit_tx:
text += tr("Submit tx");
break;
default:
text += tr("unknown");
break;
}
message_writer() << text;
}
std::string line = input_line(tr("Choice: "));
if (std::cin.eof() || line.empty())
{
return false;
}
bool choice_ok = get_number_from_arg(line, choice, 1, choices);
if (choice_ok)
{
choice--;
}
else
{
fail_msg_writer() << tr("Wrong choice");
}
return choice_ok;
}
void simple_wallet::list_mms_messages(const std::vector<mms::message> &messages)
{
message_writer() << boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") % tr("Id") % tr("I/O") % tr("Authorized Signer")
% tr("Message Type") % tr("Height") % tr("R") % tr("Message State") % tr("Since");
mms::message_store& ms = m_wallet->get_message_store();
uint64_t now = (uint64_t)time(NULL);
for (size_t i = 0; i < messages.size(); ++i)
{
const mms::message &m = messages[i];
const mms::authorized_signer &signer = ms.get_signer(m.signer_index);
bool highlight = (m.state == mms::message_state::ready_to_send) || (m.state == mms::message_state::waiting);
message_writer(m.direction == mms::message_direction::out ? console_color_green : console_color_magenta, highlight) <<
boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") %
m.id %
ms.message_direction_to_string(m.direction) %
ms.signer_to_string(signer, 30) %
ms.message_type_to_string(m.type) %
m.wallet_height %
m.round %
ms.message_state_to_string(m.state) %
(tools::get_human_readable_timestamp(m.modified) + ", " + get_human_readable_timespan(std::chrono::seconds(now - m.modified)) + tr(" ago"));
}
}
void simple_wallet::list_signers(const std::vector<mms::authorized_signer> &signers)
{
message_writer() << boost::format("%2s %-20s %-s") % tr("#") % tr("Label") % tr("Transport Address");
message_writer() << boost::format("%2s %-20s %-s") % "" % tr("Auto-Config Token") % tr("Swap Address");
for (size_t i = 0; i < signers.size(); ++i)
{
const mms::authorized_signer &signer = signers[i];
std::string label = signer.label.empty() ? tr("<not set>") : signer.label;
std::string monero_address;
if (signer.monero_address_known)
{
monero_address = get_account_address_as_str(m_wallet->nettype(), false, signer.monero_address);
}
else
{
monero_address = tr("<not set>");
}
std::string transport_address = signer.transport_address.empty() ? tr("<not set>") : signer.transport_address;
message_writer() << boost::format("%2s %-20s %-s") % (i + 1) % label % transport_address;
message_writer() << boost::format("%2s %-20s %-s") % "" % signer.auto_config_token % monero_address;
message_writer() << "";
}
}
void simple_wallet::add_signer_config_messages()
{
mms::message_store& ms = m_wallet->get_message_store();
std::string signer_config;
ms.get_signer_config(signer_config);
const std::vector<mms::authorized_signer> signers = ms.get_all_signers();
mms::multisig_wallet_state state = get_multisig_wallet_state();
uint32_t num_authorized_signers = ms.get_num_authorized_signers();
for (uint32_t i = 1 /* without me */; i < num_authorized_signers; ++i)
{
ms.add_message(state, i, mms::message_type::signer_config, mms::message_direction::out, signer_config);
}
}
void simple_wallet::show_message(const mms::message &m)
{
mms::message_store& ms = m_wallet->get_message_store();
const mms::authorized_signer &signer = ms.get_signer(m.signer_index);
bool display_content;
std::string sanitized_text;
switch (m.type)
{
case mms::message_type::key_set:
case mms::message_type::additional_key_set:
case mms::message_type::note:
display_content = true;
ms.get_sanitized_message_text(m, sanitized_text);
break;
default:
display_content = false;
}
uint64_t now = (uint64_t)time(NULL);
message_writer() << "";
message_writer() << tr("Message ") << m.id;
message_writer() << tr("In/out: ") << ms.message_direction_to_string(m.direction);
message_writer() << tr("Type: ") << ms.message_type_to_string(m.type);
message_writer() << tr("State: ") << boost::format(tr("%s since %s, %s ago")) %
ms.message_state_to_string(m.state) % tools::get_human_readable_timestamp(m.modified) % get_human_readable_timespan(std::chrono::seconds(now - m.modified));
if (m.sent == 0)
{
message_writer() << tr("Sent: Never");
}
else
{
message_writer() << boost::format(tr("Sent: %s, %s ago")) %
tools::get_human_readable_timestamp(m.sent) % get_human_readable_timespan(std::chrono::seconds(now - m.sent));
}
message_writer() << tr("Authorized signer: ") << ms.signer_to_string(signer, 100);
message_writer() << tr("Content size: ") << m.content.length() << tr(" bytes");
message_writer() << tr("Content: ") << (display_content ? sanitized_text : tr("(binary data)"));
if (m.type == mms::message_type::note)
{
// Showing a note and read its text is "processing" it: Set the state accordingly
// which will also delete it from Bitmessage as a side effect
// (Without this little "twist" it would never change the state, and never get deleted)
ms.set_message_processed_or_sent(m.id);
}
}
void simple_wallet::ask_send_all_ready_messages()
{
mms::message_store& ms = m_wallet->get_message_store();
std::vector<mms::message> ready_messages;
const std::vector<mms::message> &messages = ms.get_all_messages();
for (size_t i = 0; i < messages.size(); ++i)
{
const mms::message &m = messages[i];
if (m.state == mms::message_state::ready_to_send)
{
ready_messages.push_back(m);
}
}
if (ready_messages.size() != 0)
{
list_mms_messages(ready_messages);
bool send = ms.get_auto_send();
if (!send)
{
send = user_confirms(tr("Send these messages now?"));
}
if (send)
{
mms::multisig_wallet_state state = get_multisig_wallet_state();
for (size_t i = 0; i < ready_messages.size(); ++i)
{
ms.send_message(state, ready_messages[i].id);
ms.set_message_processed_or_sent(ready_messages[i].id);
}
success_msg_writer() << tr("Queued for sending.");
}
}
}
bool simple_wallet::get_message_from_arg(const std::string &arg, mms::message &m)
{
mms::message_store& ms = m_wallet->get_message_store();
bool valid_id = false;
uint32_t id;
try
{
id = (uint32_t)boost::lexical_cast<uint32_t>(arg);
valid_id = ms.get_message_by_id(id, m);
}
catch (const boost::bad_lexical_cast &)
{
}
if (!valid_id)
{
fail_msg_writer() << tr("Invalid message id");
}
return valid_id;
}
void simple_wallet::mms_init(const std::vector<std::string> &args)
{
if (args.size() != 3)
{
fail_msg_writer() << tr("usage: mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>");
return;
}
mms::message_store& ms = m_wallet->get_message_store();
if (ms.get_active())
{
if (!user_confirms(tr("The MMS is already initialized. Re-initialize by deleting all signer info and messages?")))
{
return;
}
}
uint32_t num_required_signers;
uint32_t num_authorized_signers;
const std::string &mn = args[0];
std::vector<std::string> numbers;
boost::split(numbers, mn, boost::is_any_of("/"));
bool mn_ok = (numbers.size() == 2)
&& get_number_from_arg(numbers[1], num_authorized_signers, 2, 100)
&& get_number_from_arg(numbers[0], num_required_signers, 2, num_authorized_signers);
if (!mn_ok)
{
fail_msg_writer() << tr("Error in the number of required signers and/or authorized signers");
return;
}
LOCK_IDLE_SCOPE();
ms.init(get_multisig_wallet_state(), args[1], args[2], num_authorized_signers, num_required_signers);
}
void simple_wallet::mms_info(const std::vector<std::string> &args)
{
mms::message_store& ms = m_wallet->get_message_store();
if (ms.get_active())
{
message_writer() << boost::format("The MMS is active for %s/%s multisig.")
% ms.get_num_required_signers() % ms.get_num_authorized_signers();
}
else
{
message_writer() << tr("The MMS is not active.");
}
}
void simple_wallet::mms_signer(const std::vector<std::string> &args)
{
mms::message_store& ms = m_wallet->get_message_store();
const std::vector<mms::authorized_signer> &signers = ms.get_all_signers();
if (args.size() == 0)
{
// Without further parameters list all defined signers
list_signers(signers);
return;
}
uint32_t index;
bool index_valid = get_number_from_arg(args[0], index, 1, ms.get_num_authorized_signers());
if (index_valid)
{
index--;
}
else
{
fail_msg_writer() << tr("Invalid signer number ") + args[0];
return;
}
if ((args.size() < 2) || (args.size() > 4))
{
fail_msg_writer() << tr("mms signer [<number> <label> [<transport_address> [<swap_address>]]]");
return;
}
boost::optional<string> label = args[1];
boost::optional<string> transport_address;
if (args.size() >= 3)
{
transport_address = args[2];
}
boost::optional<cryptonote::account_public_address> monero_address;
LOCK_IDLE_SCOPE();
mms::multisig_wallet_state state = get_multisig_wallet_state();
if (args.size() == 4)
{
cryptonote::address_parse_info info;
bool ok = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[3], oa_prompter);
if (!ok)
{
fail_msg_writer() << tr("Invalid Swap address");
return;
}
monero_address = info.address;
const std::vector<mms::message> &messages = ms.get_all_messages();
if ((messages.size() > 0) || state.multisig)
{
fail_msg_writer() << tr("Wallet state does not allow changing Swap addresses anymore");
return;
}
}
ms.set_signer(state, index, label, transport_address, monero_address);
}
void simple_wallet::mms_list(const std::vector<std::string> &args)
{
mms::message_store& ms = m_wallet->get_message_store();
if (args.size() != 0)
{
fail_msg_writer() << tr("Usage: mms list");
return;
}
LOCK_IDLE_SCOPE();
const std::vector<mms::message> &messages = ms.get_all_messages();
list_mms_messages(messages);
}
void simple_wallet::mms_next(const std::vector<std::string> &args)
{
mms::message_store& ms = m_wallet->get_message_store();
if ((args.size() > 1) || ((args.size() == 1) && (args[0] != "sync")))
{
fail_msg_writer() << tr("Usage: mms next [sync]");
return;
}
bool avail = false;
std::vector<mms::processing_data> data_list;
bool force_sync = false;
uint32_t choice = 0;
{
LOCK_IDLE_SCOPE();
if ((args.size() == 1) && (args[0] == "sync"))
{
// Force the MMS to process any waiting sync info although on its own it would just ignore
// those messages because no need to process them can be seen
force_sync = true;
}
string wait_reason;
{
avail = ms.get_processable_messages(get_multisig_wallet_state(), force_sync, data_list, wait_reason);
}
if (avail)
{
avail = choose_mms_processing(data_list, choice);
}
else if (!wait_reason.empty())
{
message_writer() << tr("No next step: ") << wait_reason;
}
}
if (avail)
{
mms::processing_data data = data_list[choice];
bool command_successful = false;
switch(data.processing)
{
case mms::message_processing::prepare_multisig:
message_writer() << tr("prepare_multisig");
command_successful = prepare_multisig_main(std::vector<std::string>(), true);
break;
case mms::message_processing::make_multisig:
{
message_writer() << tr("make_multisig");
size_t number_of_key_sets = data.message_ids.size();
std::vector<std::string> sig_args(number_of_key_sets + 1);
sig_args[0] = std::to_string(ms.get_num_required_signers());
for (size_t i = 0; i < number_of_key_sets; ++i)
{
mms::message m = ms.get_message_by_id(data.message_ids[i]);
sig_args[i+1] = m.content;
}
command_successful = make_multisig_main(sig_args, true);
break;
}
case mms::message_processing::exchange_multisig_keys:
{
message_writer() << tr("exchange_multisig_keys");
size_t number_of_key_sets = data.message_ids.size();
// Other than "make_multisig" only the key sets as parameters, no num_required_signers
std::vector<std::string> sig_args(number_of_key_sets);
for (size_t i = 0; i < number_of_key_sets; ++i)
{
mms::message m = ms.get_message_by_id(data.message_ids[i]);
sig_args[i] = m.content;
}
command_successful = exchange_multisig_keys_main(sig_args, true);
break;
}
case mms::message_processing::create_sync_data:
{
message_writer() << tr("export_multisig_info");
std::vector<std::string> export_args;
export_args.push_back("MMS"); // dummy filename
command_successful = export_multisig_main(export_args, true);
break;
}
case mms::message_processing::process_sync_data:
{
message_writer() << tr("import_multisig_info");
std::vector<std::string> import_args;
for (size_t i = 0; i < data.message_ids.size(); ++i)
{
mms::message m = ms.get_message_by_id(data.message_ids[i]);
import_args.push_back(m.content);
}
command_successful = import_multisig_main(import_args, true);
break;
}
case mms::message_processing::sign_tx:
{
message_writer() << tr("sign_multisig");
std::vector<std::string> sign_args;
mms::message m = ms.get_message_by_id(data.message_ids[0]);
sign_args.push_back(m.content);
command_successful = sign_multisig_main(sign_args, true);
break;
}
case mms::message_processing::submit_tx:
{
message_writer() << tr("submit_multisig");
std::vector<std::string> submit_args;
mms::message m = ms.get_message_by_id(data.message_ids[0]);
submit_args.push_back(m.content);
command_successful = submit_multisig_main(submit_args, true);
break;
}
case mms::message_processing::send_tx:
{
message_writer() << tr("Send tx");
mms::message m = ms.get_message_by_id(data.message_ids[0]);
LOCK_IDLE_SCOPE();
ms.add_message(get_multisig_wallet_state(), data.receiving_signer_index, m.type, mms::message_direction::out,
m.content);
command_successful = true;
break;
}
case mms::message_processing::process_signer_config:
{
message_writer() << tr("Process signer config");
LOCK_IDLE_SCOPE();
mms::message m = ms.get_message_by_id(data.message_ids[0]);
mms::authorized_signer me = ms.get_signer(0);
mms::multisig_wallet_state state = get_multisig_wallet_state();
if (!me.auto_config_running)
{
// If no auto-config is running, the config sent may be unsolicited or problematic
// so show what arrived and ask for confirmation before taking it in
std::vector<mms::authorized_signer> signers;
ms.unpack_signer_config(state, m.content, signers);
list_signers(signers);
if (!user_confirms(tr("Replace current signer config with the one displayed above?")))
{
break;
}
}
ms.process_signer_config(state, m.content);
ms.stop_auto_config();
list_signers(ms.get_all_signers());
command_successful = true;
break;
}
case mms::message_processing::process_auto_config_data:
{
message_writer() << tr("Process auto config data");
LOCK_IDLE_SCOPE();
for (size_t i = 0; i < data.message_ids.size(); ++i)
{
ms.process_auto_config_data_message(data.message_ids[i]);
}
ms.stop_auto_config();
list_signers(ms.get_all_signers());
add_signer_config_messages();
command_successful = true;
break;
}
default:
message_writer() << tr("Nothing ready to process");
break;
}
if (command_successful)
{
{
LOCK_IDLE_SCOPE();
ms.set_messages_processed(data);
ask_send_all_ready_messages();
}
}
}
}
void simple_wallet::mms_sync(const std::vector<std::string> &args)
{
mms::message_store& ms = m_wallet->get_message_store();
if (args.size() != 0)
{
fail_msg_writer() << tr("Usage: mms sync");
return;
}
// Force the start of a new sync round, for exceptional cases where something went wrong
// Can e.g. solve the problem "This signature was made with stale data" after trying to
// create 2 transactions in a row somehow
// Code is identical to the code for 'message_processing::create_sync_data'
message_writer() << tr("export_multisig_info");
std::vector<std::string> export_args;
export_args.push_back("MMS"); // dummy filename
export_multisig_main(export_args, true);
ask_send_all_ready_messages();
}
void simple_wallet::mms_transfer(const std::vector<std::string> &args)
{
// It's too complicated to check any arguments here, just let 'transfer_main' do the whole job
transfer_main(Transfer, args, true);
}
void simple_wallet::mms_delete(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
fail_msg_writer() << tr("Usage: mms delete (<message_id> | all)");
return;
}
LOCK_IDLE_SCOPE();
mms::message_store& ms = m_wallet->get_message_store();
if (args[0] == "all")
{
if (user_confirms(tr("Delete all messages?")))
{
ms.delete_all_messages();
}
}
else
{
mms::message m;
bool valid_id = get_message_from_arg(args[0], m);
if (valid_id)
{
// If only a single message and not all delete even if unsent / unprocessed
ms.delete_message(m.id);
}
}
}
void simple_wallet::mms_send(const std::vector<std::string> &args)
{
if (args.size() == 0)
{
ask_send_all_ready_messages();
return;
}
else if (args.size() != 1)
{
fail_msg_writer() << tr("Usage: mms send [<message_id>]");
return;
}
LOCK_IDLE_SCOPE();
mms::message_store& ms = m_wallet->get_message_store();
mms::message m;
bool valid_id = get_message_from_arg(args[0], m);
if (valid_id)
{
ms.send_message(get_multisig_wallet_state(), m.id);
}
}
void simple_wallet::mms_receive(const std::vector<std::string> &args)
{
if (args.size() != 0)
{
fail_msg_writer() << tr("Usage: mms receive");
return;
}
std::vector<mms::message> new_messages;
LOCK_IDLE_SCOPE();
mms::message_store& ms = m_wallet->get_message_store();
bool avail = ms.check_for_messages(get_multisig_wallet_state(), new_messages);
if (avail)
{
list_mms_messages(new_messages);
}
}
void simple_wallet::mms_export(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
fail_msg_writer() << tr("Usage: mms export <message_id>");
return;
}
LOCK_IDLE_SCOPE();
mms::message_store& ms = m_wallet->get_message_store();
mms::message m;
bool valid_id = get_message_from_arg(args[0], m);
if (valid_id)
{
const std::string filename = "mms_message_content";
if (m_wallet->save_to_file(filename, m.content))
{
success_msg_writer() << tr("Message content saved to: ") << filename;
}
else
{
fail_msg_writer() << tr("Failed to to save message content");
}
}
}
void simple_wallet::mms_note(const std::vector<std::string> &args)
{
mms::message_store& ms = m_wallet->get_message_store();
if (args.size() == 0)
{
LOCK_IDLE_SCOPE();
const std::vector<mms::message> &messages = ms.get_all_messages();
for (size_t i = 0; i < messages.size(); ++i)
{
const mms::message &m = messages[i];
if ((m.type == mms::message_type::note) && (m.state == mms::message_state::waiting))
{
show_message(m);
}
}
return;
}
if (args.size() < 2)
{
fail_msg_writer() << tr("Usage: mms note [<label> <text>]");
return;
}
uint32_t signer_index;
bool found = ms.get_signer_index_by_label(args[0], signer_index);
if (!found)
{
fail_msg_writer() << tr("No signer found with label ") << args[0];
return;
}
std::string note = "";
for (size_t n = 1; n < args.size(); ++n)
{
if (n > 1)
{
note += " ";
}
note += args[n];
}
LOCK_IDLE_SCOPE();
ms.add_message(get_multisig_wallet_state(), signer_index, mms::message_type::note,
mms::message_direction::out, note);
ask_send_all_ready_messages();
}
void simple_wallet::mms_show(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
fail_msg_writer() << tr("Usage: mms show <message_id>");
return;
}
LOCK_IDLE_SCOPE();
mms::message_store& ms = m_wallet->get_message_store();
mms::message m;
bool valid_id = get_message_from_arg(args[0], m);
if (valid_id)
{
show_message(m);
}
}
void simple_wallet::mms_set(const std::vector<std::string> &args)
{
bool set = args.size() == 2;
bool query = args.size() == 1;
if (!set && !query)
{
fail_msg_writer() << tr("Usage: mms set <option_name> [<option_value>]");
return;
}
mms::message_store& ms = m_wallet->get_message_store();
LOCK_IDLE_SCOPE();
if (args[0] == "auto-send")
{
if (set)
{
bool result;
bool ok = parse_bool(args[1], result);
if (ok)
{
ms.set_auto_send(result);
}
else
{
fail_msg_writer() << tr("Wrong option value");
}
}
else
{
message_writer() << (ms.get_auto_send() ? tr("Auto-send is on") : tr("Auto-send is off"));
}
}
else
{
fail_msg_writer() << tr("Unknown option");
}
}
void simple_wallet::mms_help(const std::vector<std::string> &args)
{
if (args.size() > 1)
{
fail_msg_writer() << tr("Usage: mms help [<subcommand>]");
return;
}
std::vector<std::string> help_args;
help_args.push_back("mms");
if (args.size() == 1)
{
help_args.push_back(args[0]);
}
help(help_args);
}
void simple_wallet::mms_send_signer_config(const std::vector<std::string> &args)
{
if (args.size() != 0)
{
fail_msg_writer() << tr("Usage: mms send_signer_config");
return;
}
mms::message_store& ms = m_wallet->get_message_store();
if (!ms.signer_config_complete())
{
fail_msg_writer() << tr("Signer config not yet complete");
return;
}
LOCK_IDLE_SCOPE();
add_signer_config_messages();
ask_send_all_ready_messages();
}
void simple_wallet::mms_start_auto_config(const std::vector<std::string> &args)
{
mms::message_store& ms = m_wallet->get_message_store();
uint32_t other_signers = ms.get_num_authorized_signers() - 1;
size_t args_size = args.size();
if ((args_size != 0) && (args_size != other_signers))
{
fail_msg_writer() << tr("Usage: mms start_auto_config [<label> <label> ...]");
return;
}
if ((args_size == 0) && !ms.signer_labels_complete())
{
fail_msg_writer() << tr("There are signers without a label set. Complete labels before auto-config or specify them as parameters here.");
return;
}
mms::authorized_signer me = ms.get_signer(0);
if (me.auto_config_running)
{
if (!user_confirms(tr("Auto-config is already running. Cancel and restart?")))
{
return;
}
}
LOCK_IDLE_SCOPE();
mms::multisig_wallet_state state = get_multisig_wallet_state();
if (args_size != 0)
{
// Set (or overwrite) all the labels except "me" from the arguments
for (uint32_t i = 1; i < (other_signers + 1); ++i)
{
ms.set_signer(state, i, args[i - 1], boost::none, boost::none);
}
}
ms.start_auto_config(state);
// List the signers to show the generated auto-config tokens
list_signers(ms.get_all_signers());
}
void simple_wallet::mms_stop_auto_config(const std::vector<std::string> &args)
{
if (args.size() != 0)
{
fail_msg_writer() << tr("Usage: mms stop_auto_config");
return;
}
if (!user_confirms(tr("Delete any auto-config tokens and stop auto-config?")))
{
return;
}
mms::message_store& ms = m_wallet->get_message_store();
LOCK_IDLE_SCOPE();
ms.stop_auto_config();
}
void simple_wallet::mms_auto_config(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
fail_msg_writer() << tr("Usage: mms auto_config <auto_config_token>");
return;
}
mms::message_store& ms = m_wallet->get_message_store();
std::string adjusted_token;
if (!ms.check_auto_config_token(args[0], adjusted_token))
{
fail_msg_writer() << tr("Invalid auto-config token");
return;
}
mms::authorized_signer me = ms.get_signer(0);
if (me.auto_config_running)
{
if (!user_confirms(tr("Auto-config already running. Cancel and restart?")))
{
return;
}
}
LOCK_IDLE_SCOPE();
ms.add_auto_config_data_message(get_multisig_wallet_state(), adjusted_token);
ask_send_all_ready_messages();
}
bool simple_wallet::mms(const std::vector<std::string> &args)
{
try
{
m_wallet->get_multisig_wallet_state();
}
catch(const std::exception &e)
{
fail_msg_writer() << tr("MMS not available in this wallet");
return true;
}
try
{
mms::message_store& ms = m_wallet->get_message_store();
if (args.size() == 0)
{
mms_info(args);
return true;
}
const std::string &sub_command = args[0];
std::vector<std::string> mms_args = args;
mms_args.erase(mms_args.begin());
if (sub_command == "init")
{
mms_init(mms_args);
return true;
}
if (!ms.get_active())
{
fail_msg_writer() << tr("The MMS is not active. Activate using the \"mms init\" command");
return true;
}
else if (sub_command == "info")
{
mms_info(mms_args);
}
else if (sub_command == "signer")
{
mms_signer(mms_args);
}
else if (sub_command == "list")
{
mms_list(mms_args);
}
else if (sub_command == "next")
{
mms_next(mms_args);
}
else if (sub_command == "sync")
{
mms_sync(mms_args);
}
else if (sub_command == "transfer")
{
mms_transfer(mms_args);
}
else if (sub_command == "delete")
{
mms_delete(mms_args);
}
else if (sub_command == "send")
{
mms_send(mms_args);
}
else if (sub_command == "receive")
{
mms_receive(mms_args);
}
else if (sub_command == "export")
{
mms_export(mms_args);
}
else if (sub_command == "note")
{
mms_note(mms_args);
}
else if (sub_command == "show")
{
mms_show(mms_args);
}
else if (sub_command == "set")
{
mms_set(mms_args);
}
else if (sub_command == "help")
{
mms_help(mms_args);
}
else if (sub_command == "send_signer_config")
{
mms_send_signer_config(mms_args);
}
else if (sub_command == "start_auto_config")
{
mms_start_auto_config(mms_args);
}
else if (sub_command == "stop_auto_config")
{
mms_stop_auto_config(mms_args);
}
else if (sub_command == "auto_config")
{
mms_auto_config(mms_args);
}
else
{
fail_msg_writer() << tr("Invalid MMS subcommand");
}
}
catch (const tools::error::no_connection_to_daemon &e)
{
fail_msg_writer() << tr("Error in MMS command: ") << e.what() << " " << e.request();
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Error in MMS command: ") << e.what();
PRINT_USAGE(USAGE_MMS);
return true;
}
return true;
}
// End MMS ------------------------------------------------------------------------------------------------
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03
// <atomic>
// template <class T>
// struct atomic
// {
// atomic(const atomic&) = delete;
// atomic& operator=(const atomic&) = delete;
// atomic& operator=(const atomic&) volatile = delete;
// };
// template <class T>
// struct atomic<T*>
// {
// atomic(const atomic&) = delete;
// atomic& operator=(const atomic&) = delete;
// atomic& operator=(const atomic&) volatile = delete;
// };
#include <atomic>
#include <type_traits>
template <typename T>
using is_volatile_copy_assignable = std::is_assignable<volatile T&, const T&>;
int main(int, char**)
{
static_assert(!std::is_copy_constructible<std::atomic<int> >::value, "");
static_assert(!std::is_copy_assignable<std::atomic<int> >::value, "");
static_assert(!is_volatile_copy_assignable<std::atomic<int> >::value, "");
static_assert(!std::is_copy_constructible<std::atomic<int*> >::value, "");
static_assert(!std::is_copy_assignable<std::atomic<int*> >::value, "");
static_assert(!is_volatile_copy_assignable<std::atomic<int*> >::value, "");
return 0;
}
|
/* Copyright (c) 2020, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql/join_optimizer/make_join_hypergraph.h"
#include <assert.h>
#include <stddef.h>
#include <algorithm>
#include <array>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
#include "limits.h"
#include "mem_root_deque.h"
#include "my_alloc.h"
#include "my_inttypes.h"
#include "my_sys.h"
#include "my_table_map.h"
#include "mysqld_error.h"
#include "sql/current_thd.h"
#include "sql/item.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/estimate_selectivity.h"
#include "sql/join_optimizer/hypergraph.h"
#include "sql/join_optimizer/print_utils.h"
#include "sql/join_optimizer/subgraph_enumeration.h"
#include "sql/nested_join.h"
#include "sql/sql_class.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_optimizer.h"
#include "sql/table.h"
#include "template_utils.h"
using hypergraph::Hyperedge;
using hypergraph::Hypergraph;
using hypergraph::NodeMap;
using std::array;
using std::string;
using std::vector;
namespace {
RelationalExpression *MakeRelationalExpressionFromJoinList(
THD *thd, const mem_root_deque<TABLE_LIST *> &join_list);
RelationalExpression *MakeRelationalExpression(THD *thd, const TABLE_LIST *tl) {
if (tl->nested_join == nullptr) {
// A single table.
RelationalExpression *ret = new (thd->mem_root) RelationalExpression(thd);
ret->type = RelationalExpression::TABLE;
ret->table = tl;
ret->tables_in_subtree = tl->map();
return ret;
} else {
// A join or multijoin.
return MakeRelationalExpressionFromJoinList(thd,
tl->nested_join->join_list);
}
}
/**
Convert the SELECT_LEX's join lists into a RelationalExpression,
ie., a join tree with tables at the leaves.
*/
RelationalExpression *MakeRelationalExpressionFromJoinList(
THD *thd, const mem_root_deque<TABLE_LIST *> &join_list) {
assert(!join_list.empty());
RelationalExpression *ret = nullptr;
for (auto it = join_list.rbegin(); it != join_list.rend();
++it) { // The list goes backwards.
const TABLE_LIST *tl = *it;
if (ret == nullptr) {
// The first table in the list.
ret = MakeRelationalExpression(thd, tl);
continue;
}
RelationalExpression *join = new (thd->mem_root) RelationalExpression(thd);
join->left = ret;
if (tl->is_sj_or_aj_nest()) {
join->right =
MakeRelationalExpressionFromJoinList(thd, tl->nested_join->join_list);
join->type = tl->is_sj_nest() ? RelationalExpression::SEMIJOIN
: RelationalExpression::ANTIJOIN;
} else {
join->right = MakeRelationalExpression(thd, tl);
join->type = tl->outer_join ? RelationalExpression::LEFT_JOIN
: RelationalExpression::INNER_JOIN;
}
if (tl->is_aj_nest()) {
assert(tl->join_cond() != nullptr);
}
if (tl->join_cond() != nullptr) {
ExtractConditions(tl->join_cond(), &join->join_conditions);
}
join->tables_in_subtree =
join->left->tables_in_subtree | join->right->tables_in_subtree;
ret = join;
}
return ret;
}
string PrintRelationalExpression(RelationalExpression *expr, int level) {
string result;
for (int i = 0; i < level * 2; ++i) result += ' ';
switch (expr->type) {
case RelationalExpression::TABLE:
result += StringPrintf("* %s\n", expr->table->alias);
// Do not try to descend further.
return result;
case RelationalExpression::CARTESIAN_PRODUCT:
result += "* Cartesian product";
break;
case RelationalExpression::INNER_JOIN:
result += "* Inner join";
break;
case RelationalExpression::LEFT_JOIN:
result += "* Left join";
break;
case RelationalExpression::SEMIJOIN:
result += "* Semijoin";
break;
case RelationalExpression::ANTIJOIN:
result += "* Antijoin";
break;
}
if (expr->type != RelationalExpression::CARTESIAN_PRODUCT) {
if (expr->equijoin_conditions.empty() && expr->join_conditions.empty()) {
result += " (no join conditions)";
} else if (!expr->equijoin_conditions.empty()) {
result += StringPrintf(" (equijoin condition = %s)",
ItemsToString(expr->equijoin_conditions).c_str());
} else if (!expr->join_conditions.empty()) {
result += StringPrintf(" (extra join condition = %s)",
ItemsToString(expr->join_conditions).c_str());
} else {
result += StringPrintf(" (equijoin condition = %s, extra = %s)",
ItemsToString(expr->equijoin_conditions).c_str(),
ItemsToString(expr->join_conditions).c_str());
}
}
result += '\n';
result += PrintRelationalExpression(expr->left, level + 1);
result += PrintRelationalExpression(expr->right, level + 1);
return result;
}
/**
Go through all inner joins that have no (non-degenerate) join conditions,
and mark them as Cartesian products. This is currently mostly for display
purposes, but it will be important for proper conflict detection later.
*/
void MakeCartesianProducts(RelationalExpression *expr) {
if (expr->type == RelationalExpression::TABLE) {
return;
}
if (expr->type == RelationalExpression::INNER_JOIN &&
expr->equijoin_conditions.empty()) {
// See if any of the non-equijoin conditions are non-degenerate.
bool any_join_condition = false;
for (Item *cond : expr->join_conditions) {
if (Overlaps(cond->used_tables(), expr->left->tables_in_subtree) &&
Overlaps(cond->used_tables(), expr->right->tables_in_subtree)) {
any_join_condition = true;
break;
}
}
if (!any_join_condition) {
expr->type = RelationalExpression::CARTESIAN_PRODUCT;
}
}
// Recurse further down into the tree.
MakeCartesianProducts(expr->left);
MakeCartesianProducts(expr->right);
}
/**
Try to push down the condition “cond” down in the join tree given by “expr”,
as far as possible. cond is either a join condition on expr
(is_join_condition_for_expr=true), or a filter which is applied at some point
after expr (...=false).
Returns false if cond was pushed down and stored as a join condition on some
lower place than it started.
*/
bool PushDownCondition(Item *cond, RelationalExpression *expr,
bool is_join_condition_for_expr) {
// PushDownAsMuchAsPossible() only calls us for join conditions,
// so we should never hit a single table.
assert(expr->type != RelationalExpression::TABLE);
assert(
!Overlaps(expr->left->tables_in_subtree, expr->right->tables_in_subtree));
table_map used_tables =
cond->used_tables() & ~(OUTER_REF_TABLE_BIT | INNER_TABLE_BIT);
// See if we can push down into the left side, ie., it only touches
// tables on the left side of the join.
//
// If the condition is a filter, we can do this for all join types
// except FULL OUTER JOIN, which we don't support yet. If it's a join
// condition for this join, we cannot push it for outer joins and
// antijoins, since that would remove rows that should otherwise
// be output (as NULL-complemented ones in the case if outer joins).
if (IsSubset(used_tables, expr->left->tables_in_subtree)) {
if (expr->type != RelationalExpression::INNER_JOIN &&
expr->type != RelationalExpression::SEMIJOIN &&
is_join_condition_for_expr) {
return true;
}
return PushDownCondition(cond, expr->left,
/*is_join_condition_for_expr=*/false);
}
// See if we can push down into the right side. For inner joins,
// we can always do this, assuming the condition refers to the right
// side only. For outer joins and antijoins, we cannot push conditions
// _through_ them; that is, we can push them if they come directly from said
// node's join condition, but not otherwise. (This is, incidentally, the exact
// opposite condition from pushing into the left side.)
//
// Normally, this also goes for semijoins, except that MySQL's semijoin
// rewriting causes conditions to appear higher up in the tree that we
// _must_ push back down and through them for correctness. Thus, we have
// no choice but to just trust that these conditions are pushable.
// (The user cannot cannot specify semijoins directly, so all such conditions
// come from ourselves.)
if (IsSubset(used_tables, expr->right->tables_in_subtree)) {
if (expr->type != RelationalExpression::INNER_JOIN &&
expr->type != RelationalExpression::SEMIJOIN &&
!is_join_condition_for_expr) {
return true;
}
return PushDownCondition(cond, expr->right,
/*is_join_condition_for_expr=*/false);
}
// It's not a subset of left, it's not a subset of right,
// so it's a filter that must either stay after this join,
// or it can be promoted to a join condition for it.
if (is_join_condition_for_expr) {
// We were already a join condition on this join, so there's nothing to do.
return true;
}
// We cannot promote filters to join conditions for outer joins
// and antijoins, but we can on inner joins and semijoins.
if (expr->type == RelationalExpression::LEFT_JOIN ||
expr->type == RelationalExpression::ANTIJOIN) {
return true;
}
// Promote the filter to a join condition on this join.
// If it's an equijoin condition, MakeHashJoinConditions() will convert it to
// one (in expr->equijoin_conditions) when it runs later.
assert(expr->equijoin_conditions.empty());
expr->join_conditions.push_back(cond);
return false;
}
/**
Push down as many of the conditions in “conditions” as we can, into the join
tree under “expr”. The parts that could not be pushed are returned.
The conditions are nominally taken to be from higher up the tree than “expr”
(e.g., WHERE conditions, or join conditions from a higher join), unless
is_join_condition_for_expr is true, in which case they are taken to be
posted as join conditions posted on “expr” itself. This causes them to be
returned as remaining if “expr” is indeed their final lowest place
in the tree (otherwise, they might get lost).
*/
Mem_root_array<Item *> PushDownAsMuchAsPossible(
THD *thd, Mem_root_array<Item *> conditions, RelationalExpression *expr,
bool is_join_condition_for_expr) {
Mem_root_array<Item *> remaining_parts(thd->mem_root);
for (Item *item : conditions) {
if (IsSingleBitSet(item->used_tables() & ~PSEUDO_TABLE_BITS)) {
// Only push down join conditions, not filters; they will stay in WHERE,
// as we handle them separately in FoundSingleNode() and
// FoundSubgraphPair().
remaining_parts.push_back(item);
} else {
if (PushDownCondition(item, expr, is_join_condition_for_expr)) {
// Pushdown failed.
remaining_parts.push_back(item);
}
}
}
return remaining_parts;
}
/**
For each condition posted as a join condition on “expr”, try to push
all of them further down the tree, as far as we can; then recurse to
the child nodes, if any.
This is needed because the initial optimization steps (before the join
optimizer) try to hoist join conditions as far _up_ the tree as possible,
normally all the way up to the WHERE, but could be stopped by outer joins and
antijoins. E.g. assume what the user wrote was
a LEFT JOIN (B JOIN C on b.x=c.x)
This would be pulled up to
a LEFT JOIN (B JOIN C) ON b.x=c.x
ie., a pushable join condition posted on the LEFT JOIN, that could not go into
the WHERE. When this function is called on the said join, it will push the
join condition down again.
*/
void PushDownJoinConditions(THD *thd, RelationalExpression *expr) {
if (expr->type == RelationalExpression::TABLE) {
return;
}
assert(expr->equijoin_conditions
.empty()); // MakeHashJoinConditions() has not run yet.
if (!expr->join_conditions.empty()) {
expr->join_conditions =
PushDownAsMuchAsPossible(thd, std::move(expr->join_conditions), expr,
/*is_join_condition_for_expr=*/true);
}
PushDownJoinConditions(thd, expr->left);
PushDownJoinConditions(thd, expr->right);
}
/**
For all join conditions on “expr”, go through and figure out which ones are
equijoin conditions, ie., suitable for hash join. An equijoin condition for us
is one that is an equality comparison (=) and pulls in relations from both
sides of the tree (so is not degenerate, and pushed as far down as possible).
We also demand that it does not use row comparison, as our hash join
implementation currently does not support that. Any condition that is found to
be an equijoin condition is moved from expr->join_conditions to
expr->equijoin_conditions.
The function recurses down the join tree.
*/
void MakeHashJoinConditions(THD *thd, RelationalExpression *expr) {
if (expr->type == RelationalExpression::TABLE) {
return;
}
if (!expr->join_conditions.empty()) {
assert(expr->equijoin_conditions.empty());
Mem_root_array<Item *> extra_conditions(thd->mem_root);
for (Item *item : expr->join_conditions) {
// See if this is a (non-degenerate) equijoin condition.
if ((item->used_tables() & expr->left->tables_in_subtree) &&
(item->used_tables() & expr->right->tables_in_subtree) &&
(item->type() == Item::FUNC_ITEM ||
item->type() == Item::COND_ITEM)) {
Item_func *func_item = down_cast<Item_func *>(item);
if (func_item->contains_only_equi_join_condition()) {
Item_func_eq *join_condition = down_cast<Item_func_eq *>(func_item);
// Join conditions with items that returns row values (subqueries or
// row value expression) are set up with multiple child comparators,
// one for each column in the row. As long as the row contains only
// one column, use it as a join condition. If it has more than one
// column, attach it as an extra condition. Note that join
// conditions that does not return row values are not set up with
// any child comparators, meaning that get_child_comparator_count()
// will return 0.
if (join_condition->get_comparator()->get_child_comparator_count() <
2) {
expr->equijoin_conditions.push_back(
down_cast<Item_func_eq *>(func_item));
continue;
}
}
}
// It was not.
extra_conditions.push_back(item);
}
expr->join_conditions = std::move(extra_conditions);
}
MakeHashJoinConditions(thd, expr->left);
MakeHashJoinConditions(thd, expr->right);
}
/**
Convert multi-equalities to simple equalities. This is a hack until we get
real handling of multi-equalities (in which case it would be done much later,
after the join order has been determined); however, note that
remove_eq_conds() also does some constant conversion/folding work that is
important for correctness in general.
*/
bool ConcretizeMultipleEquals(THD *thd, Mem_root_array<Item *> *conditions) {
for (auto it = conditions->begin(); it != conditions->end();) {
Item::cond_result res;
if (remove_eq_conds(thd, *it, &*it, &res)) {
return true;
}
if (res == Item::COND_TRUE) {
it = conditions->erase(it);
} else if (res == Item::COND_FALSE) {
conditions->clear();
conditions->push_back(new Item_int(0));
return false;
} else {
++it;
}
}
return false;
}
/**
Convert all multi-equalities in join conditions under “expr” into simple
equalities. See ConcretizeMultipleEquals() for more information.
*/
bool ConcretizeAllMultipleEquals(THD *thd, RelationalExpression *expr) {
if (expr->type == RelationalExpression::TABLE) {
return false;
}
assert(expr->equijoin_conditions
.empty()); // MakeHashJoinConditions() has not run yet.
if (ConcretizeMultipleEquals(thd, &expr->join_conditions)) {
return true;
}
PushDownJoinConditions(thd, expr->left);
PushDownJoinConditions(thd, expr->right);
return false;
}
string PrintJoinList(const mem_root_deque<TABLE_LIST *> &join_list, int level) {
string str;
const char *join_types[] = {"inner", "left", "right"};
std::vector<TABLE_LIST *> list(join_list.begin(), join_list.end());
for (TABLE_LIST *tbl : list) {
for (int i = 0; i < level * 2; ++i) str += ' ';
if (tbl->join_cond() != nullptr) {
str += StringPrintf("* %s %s join_type=%s\n", tbl->alias,
ItemToString(tbl->join_cond()).c_str(),
join_types[tbl->outer_join]);
} else {
str += StringPrintf("* %s join_type=%s\n", tbl->alias,
join_types[tbl->outer_join]);
}
if (tbl->nested_join != nullptr) {
str += PrintJoinList(tbl->nested_join->join_list, level + 1);
}
}
return str;
}
NodeMap GetNodeMapFromTableMap(
table_map table_map, const array<int, MAX_TABLES> &table_num_to_node_num) {
NodeMap ret = 0;
for (int table_num : BitsSetIn(table_map)) {
assert(table_num_to_node_num[table_num] != -1);
ret |= TableBitmap(table_num_to_node_num[table_num]);
}
return ret;
}
/**
For a condition with the SES (Syntactic Eligibility Set) “used_tables”,
find all relations in or under “expr” that are part of the condition's TES
(Total Eligibility Set). The SES contains all relations that are directly
referenced by the predicate; the TES contains all relations that are needed
to be available before the predicate can be evaluated.
The TES always contains at least SES, but may be bigger. For instance,
given the join tree (a LEFT JOIN b), a condition such as b.x IS NULL
would have a SES of {b}, but a TES of {a,b}, since joining in a could
synthesize NULLs from b. However, given (a JOIN b) (ie., an inner join
instead of an outer join), the TES would be {b}, identical to the SES.
NOTE: The terms SES and TES are often used about join conditions;
the use here is for general conditions beyond just those.
NOTE: This returns a table_map, which is later converted to a NodeMap.
*/
table_map FindTESForCondition(table_map used_tables,
RelationalExpression *expr) {
if (expr->type == RelationalExpression::TABLE) {
// We're at the bottom of an inner join stack; nothing to see here.
// (We could just as well return 0, but this at least makes sure the
// SES is included in the TES.)
return used_tables;
} else if (expr->type == RelationalExpression::LEFT_JOIN ||
expr->type == RelationalExpression::ANTIJOIN) {
table_map tes = used_tables;
if (Overlaps(used_tables, expr->left->tables_in_subtree)) {
tes |= FindTESForCondition(used_tables, expr->left);
}
if (Overlaps(used_tables, expr->right->tables_in_subtree)) {
tes |= FindTESForCondition(used_tables, expr->right);
// The predicate needs a table from the right-hand side, but this join can
// cause that table to become NULL, so we need to delay until the join has
// happened. Notwithstanding any reordering on the left side, the join
// cannot happen until all the join condition's used tables are in place,
// so for non-degenerate conditions, that is a neccessary and sufficient
// condition for the predicate to be applied.
for (Item *condition : expr->equijoin_conditions) {
tes |= condition->used_tables();
}
for (Item *condition : expr->join_conditions) {
tes |= condition->used_tables();
}
// If all conditions were degenerate (and not left-degenerate, ie.,
// referenced the left-hand side only), simply add all tables from the
// left-hand side as required, so that it will not be pushed into the
// right-hand side in any case.
if (!Overlaps(tes, expr->left->tables_in_subtree)) {
tes |= expr->left->tables_in_subtree;
}
}
return tes;
} else {
table_map tes = used_tables;
if (Overlaps(used_tables, expr->left->tables_in_subtree)) {
tes |= FindTESForCondition(used_tables, expr->left);
}
if (Overlaps(used_tables, expr->right->tables_in_subtree)) {
tes |= FindTESForCondition(used_tables, expr->right);
}
return tes;
}
}
/**
Returns whether there are only inner joins in the join tree under “expr”.
*/
bool ConsistsOfInnerJoinsOnly(const RelationalExpression *expr) {
if (expr->type == RelationalExpression::TABLE) {
return true;
}
if (expr->type != RelationalExpression::INNER_JOIN &&
expr->type != RelationalExpression::CARTESIAN_PRODUCT) {
return false;
}
return ConsistsOfInnerJoinsOnly(expr->left) &&
ConsistsOfInnerJoinsOnly(expr->right);
}
/**
For the given hypergraph, make a textual representation in the form
of a dotty graph. You can save this to a file and then use Graphviz
to render this it a graphical representation of the hypergraph for
easier debugging, e.g. like this:
dot -Tps graph.dot > graph.ps
display graph.ps
See also Dbug_table_list_dumper.
*/
string PrintDottyHypergraph(const JoinHypergraph &graph) {
string digraph;
digraph =
StringPrintf("digraph G { # %zu edges\n", graph.graph.edges.size() / 2);
for (size_t edge_idx = 0; edge_idx < graph.graph.edges.size();
edge_idx += 2) {
const Hyperedge &e = graph.graph.edges[edge_idx];
string label = GenerateExpressionLabel(graph.edges[edge_idx / 2].expr);
if (IsSingleBitSet(e.left) && IsSingleBitSet(e.right)) {
// Simple edge.
int left_node = FindLowestBitSet(e.left);
int right_node = FindLowestBitSet(e.right);
digraph += StringPrintf(" %s -> %s [label=\"%s\"]\n",
graph.nodes[left_node]->alias,
graph.nodes[right_node]->alias, label.c_str());
} else {
// Hyperedge; draw it as a tiny “virtual node”.
digraph += StringPrintf(
" e%zu [shape=circle,width=.001,height=.001,label=\"\"]\n",
edge_idx);
// Print the label only once.
string left_label, right_label;
if (IsSingleBitSet(e.right) && !IsSingleBitSet(e.left)) {
right_label = label;
} else {
left_label = label;
}
// Left side of the edge.
for (int left_node : BitsSetIn(e.left)) {
digraph += StringPrintf(" %s -> e%zu [arrowhead=none,label=\"%s\"]\n",
graph.nodes[left_node]->alias, edge_idx,
left_label.c_str());
left_label = "";
}
// Right side of the edge.
for (int right_node : BitsSetIn(e.right)) {
digraph +=
StringPrintf(" e%zu -> %s [label=\"%s\"]\n", edge_idx,
graph.nodes[right_node]->alias, right_label.c_str());
right_label = "";
}
}
}
digraph += "}\n";
return digraph;
}
/**
Convert a join rooted at “expr” into a join hypergraph that encapsulates
the constraints given by the relational expressions (e.g. inner joins are
more freely reorderable than outer joins).
Making a hypergraph that accurately and minimally expresses the constraints
of a given join tree is nontrivial (see “On the correct and complete
enumeration of the core search space” by Moerkotte et al). Since this a
prototype, we make no attempt at optimality; that will come later.
Instead, we opt for a conservative approach, where outer joins block all
reordering (and inner joins are freely reorderable). This keeps us from
producing all valid join orders, but makes sure we do not create any invalid
ones.
*/
void MakeJoinGraphFromRelationalExpression(const RelationalExpression *expr,
string *trace,
JoinHypergraph *graph) {
if (expr->type == RelationalExpression::TABLE) {
graph->graph.AddNode();
graph->nodes.push_back(expr->table->table);
assert(expr->table->tableno() < MAX_TABLES);
graph->table_num_to_node_num[expr->table->tableno()] =
graph->graph.nodes.size() - 1;
return;
}
MakeJoinGraphFromRelationalExpression(expr->left, trace, graph);
MakeJoinGraphFromRelationalExpression(expr->right, trace, graph);
table_map used_tables = 0;
for (Item *condition : expr->join_conditions) {
used_tables |= condition->used_tables();
}
for (Item *condition : expr->equijoin_conditions) {
used_tables |= condition->used_tables();
}
// Very conservative conflict detector.
NodeMap left =
GetNodeMapFromTableMap(used_tables & expr->left->tables_in_subtree,
graph->table_num_to_node_num);
NodeMap right =
GetNodeMapFromTableMap(used_tables & expr->right->tables_in_subtree,
graph->table_num_to_node_num);
NodeMap left_full = GetNodeMapFromTableMap(expr->left->tables_in_subtree,
graph->table_num_to_node_num);
NodeMap right_full = GetNodeMapFromTableMap(expr->right->tables_in_subtree,
graph->table_num_to_node_num);
if (expr->type == RelationalExpression::INNER_JOIN) {
// Reordering is fine, although not into parts that may contain
// outer joins. For instance, reordering (a LEFT JOIN b) JOIN c
// is not fine if the outermost join condition can depend on
// a NULL-complemented row from b.
if (!ConsistsOfInnerJoinsOnly(expr->left)) {
left = left_full;
}
if (!ConsistsOfInnerJoinsOnly(expr->right)) {
right = right_full;
}
} else {
// Absolutely no reordering. (We can't even always reorder on
// the left side, e.g. for (a LEFT JOIN b) SEMIJOIN c ON b.x=c.x,
// we really need {a,b} on the left side, not just {b}.)
left = left_full;
right = right_full;
}
// On degenerate predicates, stop all reordering for now.
if (left == 0 || right == 0) {
left = left_full;
right = right_full;
}
assert(left != 0);
assert(right != 0);
graph->graph.AddEdge(left, right);
if (trace != nullptr) {
*trace += StringPrintf("Selectivity of join %s:\n",
GenerateExpressionLabel(expr).c_str());
}
double selectivity = 1.0;
for (Item *item : expr->equijoin_conditions) {
selectivity *= EstimateSelectivity(current_thd, item, trace);
}
for (Item *item : expr->join_conditions) {
selectivity *= EstimateSelectivity(current_thd, item, trace);
}
if (trace != nullptr &&
expr->equijoin_conditions.size() + expr->join_conditions.size() > 1) {
*trace += StringPrintf(" - total: %.3f\n", selectivity);
}
graph->edges.push_back(JoinPredicate{expr, selectivity});
}
} // namespace
bool MakeJoinHypergraph(THD *thd, SELECT_LEX *select_lex, string *trace,
JoinHypergraph *graph) {
JOIN *join = select_lex->join;
if (trace != nullptr) {
// TODO(sgunders): Do we want to keep this in the trace indefinitely?
// It's only useful for debugging, not as much for understanding what's
// going on.
*trace += "Join list after simplification:\n";
*trace += PrintJoinList(select_lex->top_join_list, /*level=*/0);
*trace += "\n";
}
RelationalExpression *root =
MakeRelationalExpressionFromJoinList(thd, select_lex->top_join_list);
if (trace != nullptr) {
// TODO(sgunders): Same question as above; perhaps the version after
// pushdown is sufficient.
*trace +=
StringPrintf("Made this relational tree; WHERE condition is %s:\n",
ItemToString(join->where_cond).c_str());
*trace += PrintRelationalExpression(root, 0);
*trace += "\n";
}
// Split up WHERE conditions, and push them down into the tree as much as
// we can. (They have earlier been hoisted up as far as possible; see
// comments on PushDownAsMuchAsPossible() and PushDownJoinConditions().)
Mem_root_array<Item *> where_conditions(thd->mem_root);
if (join->where_cond != nullptr) {
ExtractConditions(join->where_cond, &where_conditions);
if (ConcretizeMultipleEquals(thd, &where_conditions)) {
return true;
}
where_conditions =
PushDownAsMuchAsPossible(thd, std::move(where_conditions), root,
/*is_join_condition_for_expr=*/false);
}
if (ConcretizeAllMultipleEquals(thd, root)) {
return true;
}
PushDownJoinConditions(thd, root);
MakeHashJoinConditions(thd, root);
MakeCartesianProducts(root);
if (trace != nullptr) {
*trace +=
StringPrintf("After pushdown; remaining WHERE conditions are %s:\n",
ItemsToString(where_conditions).c_str());
*trace += PrintRelationalExpression(root, 0);
*trace += '\n';
}
// Construct the hypergraph from the relational expression.
#ifndef DBUG_OFF
std::fill(begin(graph->table_num_to_node_num),
end(graph->table_num_to_node_num), -1);
#endif
MakeJoinGraphFromRelationalExpression(root, trace, graph);
if (trace != nullptr) {
*trace += "\nConstructed hypergraph:\n";
*trace += PrintDottyHypergraph(*graph);
if (DEBUGGING_DPHYP) {
// DPhyp printouts talk mainly about R1, R2, etc., so if debugging
// the algorithm, it is useful to have a link to the table names.
*trace += "Node mappings, for reference:\n";
for (size_t i = 0; i < graph->nodes.size(); ++i) {
*trace += StringPrintf(" R%zu = %s\n", i + 1, graph->nodes[i]->alias);
}
}
*trace += "\n";
}
// Find TES and selectivity for each WHERE predicate that was not pushed
// down earlier.
for (Item *condition : where_conditions) {
Predicate pred;
pred.condition = condition;
table_map total_eligibility_set =
FindTESForCondition(condition->used_tables(), root) &
~(INNER_TABLE_BIT | OUTER_REF_TABLE_BIT);
pred.total_eligibility_set =
GetNodeMapFromTableMap(total_eligibility_set & ~RAND_TABLE_BIT,
graph->table_num_to_node_num) |
(total_eligibility_set & RAND_TABLE_BIT);
pred.selectivity = EstimateSelectivity(thd, condition, trace);
graph->predicates.push_back(pred);
if (trace != nullptr) {
*trace += StringPrintf("Total eligibility set for %s: {",
ItemToString(condition).c_str());
bool first = true;
for (TABLE_LIST *tl = select_lex->leaf_tables; tl != nullptr;
tl = tl->next_leaf) {
if (tl->map() & total_eligibility_set) {
if (!first) *trace += ',';
*trace += tl->alias;
first = false;
}
}
*trace += "}\n";
}
}
if (graph->predicates.size() > sizeof(table_map) * CHAR_BIT) {
my_error(ER_HYPERGRAPH_NOT_SUPPORTED_YET, MYF(0),
"more than 64 WHERE/ON predicates");
return true;
}
return false;
}
|
// -----------------------------------------------------------------------------
// Copyright 2020 Rui Liu (liurui39660) and Siddharth Bhatia (bhatiasiddharth)
//
// 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.
// -----------------------------------------------------------------------------
#pragma once
#include <cmath>
#include "CountMinSketch.hpp"
namespace MIDAS {
struct FilteringCore {
const float threshold;
int timestamp = 1;
const float factor;
const int lenData;
int* const indexEdge; // Pre-compute the index to-be-modified, thanks to the Same-Layout Assumption
int* const indexSource;
int* const indexDestination;
CountMinSketch numCurrentEdge, numTotalEdge, scoreEdge;
CountMinSketch numCurrentSource, numTotalSource, scoreSource;
CountMinSketch numCurrentDestination, numTotalDestination, scoreDestination;
float timestampReciprocal = 0;
bool* const shouldMerge;
FilteringCore(int numRow, int numColumn, float threshold, float factor = 0.5):
threshold(threshold),
factor(factor),
lenData(numRow * numColumn), // I assume all CMSs have same size, but Same-Layout Assumption is not that strict
indexEdge(new int[numRow]),
indexSource(new int[numRow]),
indexDestination(new int[numRow]),
numCurrentEdge(numRow, numColumn),
numTotalEdge(numCurrentEdge),
scoreEdge(numCurrentEdge),
numCurrentSource(numRow, numColumn),
numTotalSource(numCurrentSource),
scoreSource(numCurrentSource),
numCurrentDestination(numRow, numColumn),
numTotalDestination(numCurrentDestination),
scoreDestination(numCurrentDestination),
shouldMerge(new bool[numRow * numColumn]) { }
virtual ~FilteringCore() {
delete[] indexEdge;
delete[] indexSource;
delete[] indexDestination;
delete[] shouldMerge;
}
static float ComputeScore(float a, float s, float t) {
return s == 0 ? 0 : pow(a + s - a * t, 2) / (s * (t - 1)); // If t == 1, then s == 0, so no need to check twice
}
void ConditionalMerge(const float* current, float* total, const float* score) const {
for (int i = 0; i < lenData; i++)
shouldMerge[i] = score[i] < threshold;
for (int i = 0, I = lenData; i < I; i++) // Vectorization
total[i] += shouldMerge[i] * current[i] + (true - shouldMerge[i]) * total[i] * timestampReciprocal;
}
float operator()(int source, int destination, int timestamp) {
if (this->timestamp < timestamp) {
ConditionalMerge(numCurrentEdge.data, numTotalEdge.data, scoreEdge.data);
ConditionalMerge(numCurrentSource.data, numTotalSource.data, scoreSource.data);
ConditionalMerge(numCurrentDestination.data, numTotalDestination.data, scoreDestination.data);
numCurrentEdge.MultiplyAll(factor);
numCurrentSource.MultiplyAll(factor);
numCurrentDestination.MultiplyAll(factor);
timestampReciprocal = 1.f / (timestamp - 1); // So I can skip an if-statement
this->timestamp = timestamp;
}
numCurrentEdge.Hash(indexEdge, source, destination);
numCurrentEdge.Add(indexEdge);
numCurrentSource.Hash(indexSource, source);
numCurrentSource.Add(indexSource);
numCurrentDestination.Hash(indexDestination, destination);
numCurrentDestination.Add(indexDestination);
return std::max({
scoreEdge.Assign(indexEdge, ComputeScore(numCurrentEdge(indexEdge), numTotalEdge(indexEdge), timestamp)),
scoreSource.Assign(indexSource, ComputeScore(numCurrentSource(indexSource), numTotalSource(indexSource), timestamp)),
scoreDestination.Assign(indexDestination, ComputeScore(numCurrentDestination(indexDestination), numTotalDestination(indexDestination), timestamp)),
});
}
};
}
|
/******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the New BSD License, (the "License").
******************************************************************************/
#include "command.h"
#include <avogadro/qtgui/avogadropython.h>
#include <avogadro/qtgui/filebrowsewidget.h>
#include <avogadro/qtgui/fileformatdialog.h>
#include <avogadro/qtgui/interfacescript.h>
#include <avogadro/qtgui/interfacewidget.h>
#include <avogadro/qtgui/molecule.h>
#include <avogadro/qtgui/scriptloader.h>
#include <avogadro/qtgui/utilities.h>
#include <QtWidgets/QAction>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QProgressDialog>
#include <QtWidgets/QVBoxLayout>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QStandardPaths>
#include <QtCore/QStringList>
#include <QtCore/QtPlugin>
namespace Avogadro {
namespace QtPlugins {
using Avogadro::QtGui::InterfaceScript;
using Avogadro::QtGui::InterfaceWidget;
Command::Command(QObject* parent_)
: ExtensionPlugin(parent_), m_molecule(nullptr), m_currentDialog(nullptr),
m_currentInterface(nullptr), m_currentScript(nullptr), m_progress(nullptr),
m_outputFormat(nullptr)
{
refreshScripts();
}
Command::~Command()
{
qDeleteAll(m_dialogs.values());
m_dialogs.clear();
}
QList<QAction*> Command::actions() const
{
return m_actions;
}
QStringList Command::menuPath(QAction* action) const
{
QString scriptFileName = action->data().toString();
QStringList path;
// if we're passed the "Set Python" action
if (scriptFileName.isEmpty()) {
path << tr("&Extensions") << tr("Scripts");
return path;
}
// otherwise, we have a script name, so ask it
InterfaceScript gen(scriptFileName);
path = gen.menuPath().split('|');
if (gen.hasErrors()) {
path << tr("&Extensions") << tr("Scripts");
qWarning() << "Command: Unable to retrieve menu "
"name for: "
<< scriptFileName << "." << gen.errorList().join("\n\n");
return path;
}
return path;
}
void Command::setMolecule(QtGui::Molecule* mol)
{
if (m_molecule == mol)
return;
m_molecule = mol;
foreach (InterfaceWidget* dlg, m_dialogs.values())
dlg->setMolecule(mol);
}
bool Command::readMolecule(QtGui::Molecule& mol)
{
Io::FileFormat* reader = m_outputFormat->newInstance();
bool success = reader->readFile(m_outputFileName.toStdString(), mol);
if (!success) {
QMessageBox::information(qobject_cast<QWidget*>(parent()), tr("Error"),
tr("Error reading output file '%1':\n%2")
.arg(m_outputFileName)
.arg(QString::fromStdString(reader->error())));
}
m_outputFormat = nullptr;
m_outputFileName.clear();
return success;
}
void Command::refreshScripts()
{
updateScripts();
updateActions();
}
void Command::menuActivated()
{
QAction* theSender = qobject_cast<QAction*>(sender());
if (!theSender)
return;
QString scriptFileName = theSender->data().toString();
QWidget* theParent = qobject_cast<QWidget*>(parent());
if (m_currentDialog) {
delete m_currentDialog->layout();
if (m_currentInterface)
m_currentInterface->hide();
}
// check if there are any options before this song-and-dance
InterfaceWidget* widget = m_dialogs.value(scriptFileName, nullptr);
if (!widget) {
widget = new InterfaceWidget(scriptFileName, theParent);
m_dialogs.insert(scriptFileName, widget);
}
widget->setMolecule(m_molecule);
m_currentInterface = widget; // remember this when we get the run() signal
if (widget->isEmpty()) {
run(); // no options, do it immediately
return;
}
m_currentDialog = new QDialog(theParent);
QString title;
QtGui::ScriptLoader::queryProgramName(scriptFileName, title);
m_currentDialog->setWindowTitle(title);
QVBoxLayout* vbox = new QVBoxLayout();
widget->show();
vbox->addWidget(widget);
QDialogButtonBox* buttonBox =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(run()));
connect(buttonBox, SIGNAL(rejected()), m_currentDialog, SLOT(reject()));
vbox->addWidget(buttonBox);
m_currentDialog->setLayout(vbox);
m_currentDialog->exec();
}
void Command::run()
{
if (m_currentDialog)
m_currentDialog->accept();
if (m_progress)
m_progress->deleteLater();
if (m_currentScript) {
disconnect(m_currentScript, SIGNAL(finished()), this,
SLOT(processFinished()));
m_currentScript->deleteLater();
}
if (m_currentInterface) {
QJsonObject options = m_currentInterface->collectOptions();
// @todo - need a cleaner way to get a script pointer from the widget
QString scriptFilePath =
m_currentInterface->interfaceScript().scriptFilePath();
m_currentScript = new InterfaceScript(scriptFilePath, parent());
connect(m_currentScript, SIGNAL(finished()), this, SLOT(processFinished()));
// no cancel button - just an indication we're waiting...
QString title = tr("Processing %1").arg(m_currentScript->displayName());
m_progress = new QProgressDialog(title, QString(), 0, 0, qobject_cast<QWidget*>(parent()));
m_progress->setMinimumDuration(1000); // 1 second
m_currentScript->runCommand(options, m_molecule);
}
}
void Command::processFinished()
{
if (m_currentScript == nullptr)
return;
if (m_progress) {
m_progress->close();
m_progress->deleteLater();
m_progress = nullptr;
}
m_currentScript->processCommand(m_molecule);
// collect errors
if (m_currentScript->hasErrors()) {
qWarning() << m_currentScript->errorList();
}
}
void Command::configurePython()
{
// Create objects
QSettings settings;
QDialog dlg(qobject_cast<QWidget*>(parent()));
QLabel* label = new QLabel;
QVBoxLayout* layout = new QVBoxLayout;
QtGui::FileBrowseWidget* browser = new QtGui::FileBrowseWidget;
QDialogButtonBox* buttonBox = new QDialogButtonBox;
// Configure objects
// Check for python interpreter in env var
QString pythonInterp =
QString::fromLocal8Bit(qgetenv("AVO_PYTHON_INTERPRETER"));
if (pythonInterp.isEmpty()) {
// Check settings
pythonInterp = settings.value("interpreters/python", QString()).toString();
}
// Use compile-time default if still not found.
if (pythonInterp.isEmpty())
pythonInterp = QString(pythonInterpreterPath);
browser->setMode(QtGui::FileBrowseWidget::ExecutableFile);
browser->setFileName(pythonInterp);
buttonBox->setStandardButtons(QDialogButtonBox::Ok |
QDialogButtonBox::Cancel);
dlg.setWindowTitle(tr("Set path to Python interpreter:"));
label->setText(
tr("Select the python interpreter to run external scripts.\n"
"Avogadro must be restarted for any changes to take effect."));
// Build layout
layout->addWidget(label);
layout->addWidget(browser);
layout->addWidget(buttonBox);
dlg.setLayout(layout);
// Connect
connect(buttonBox, SIGNAL(accepted()), &dlg, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), &dlg, SLOT(reject()));
// Show dialog
QDialog::DialogCode response = static_cast<QDialog::DialogCode>(dlg.exec());
if (response != QDialog::Accepted)
return;
// Handle response
settings.setValue("interpreters/python", browser->fileName());
}
void Command::updateScripts()
{
m_commandScripts = QtGui::ScriptLoader::scriptList("commands");
}
void Command::updateActions()
{
m_actions.clear();
// QAction* action = new QAction(tr("Set Python Path..."), this);
// connect(action, SIGNAL(triggered()), SLOT(configurePython()));
// m_actions << action;
foreach (const QString& programName, m_commandScripts.uniqueKeys()) {
QStringList scripts = m_commandScripts.values(programName);
// Include the full path if there are multiple generators with the same
// name.
if (scripts.size() == 1) {
addAction(programName, scripts.first());
} else {
foreach (const QString& filePath, scripts) {
addAction(QString("%1 (%2)").arg(programName, filePath), filePath);
}
}
}
}
void Command::addAction(const QString& label, const QString& scriptFilePath)
{
QAction* action = new QAction(label, this);
action->setData(scriptFilePath);
action->setEnabled(true);
connect(action, SIGNAL(triggered()), SLOT(menuActivated()));
m_actions << action;
}
} // namespace QtPlugins
} // namespace Avogadro
|
/*
* Copyright 2017 WebAssembly Community Group participants
*
* 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 "src/lexer-source-line-finder.h"
#include <algorithm>
#include "src/lexer-source.h"
namespace wabt {
LexerSourceLineFinder::LexerSourceLineFinder(
std::unique_ptr<LexerSource> source)
: source_(std::move(source)),
next_line_start_(0),
last_cr_(false),
eof_(false) {
// Line 0 should not be used; but it makes indexing simpler.
line_ranges_.emplace_back(0, 0);
}
Result LexerSourceLineFinder::GetSourceLine(const Location& loc,
Offset max_line_length,
SourceLine* out_source_line) {
ColumnRange column_range(loc.first_column, loc.last_column);
OffsetRange original;
CHECK_RESULT(GetLineOffsets(loc.line, &original));
OffsetRange clamped =
ClampSourceLineOffsets(original, column_range, max_line_length);
bool has_start_ellipsis = original.start != clamped.start;
bool has_end_ellipsis = original.end != clamped.end;
out_source_line->column_offset = clamped.start - original.start;
if (has_start_ellipsis) {
out_source_line->line += "...";
clamped.start += 3;
}
if (has_end_ellipsis)
clamped.end -= 3;
std::vector<char> read_line;
CHECK_RESULT(source_->ReadRange(clamped, &read_line));
out_source_line->line.append(read_line.begin(), read_line.end());
if (has_end_ellipsis)
out_source_line->line += "...";
return Result::Ok;
}
bool LexerSourceLineFinder::IsLineCached(int line) const {
return static_cast<size_t>(line) < line_ranges_.size();
}
OffsetRange LexerSourceLineFinder::GetCachedLine(int line) const {
assert(IsLineCached(line));
return line_ranges_[line];
}
Result LexerSourceLineFinder::GetLineOffsets(int find_line,
OffsetRange* out_range) {
if (IsLineCached(find_line)) {
*out_range = GetCachedLine(find_line);
return Result::Ok;
}
const size_t kBufferSize = 1 << 16;
std::vector<char> buffer(kBufferSize);
assert(!line_ranges_.empty());
Offset buffer_file_offset = 0;
while (!IsLineCached(find_line) && !eof_) {
CHECK_RESULT(source_->Tell(&buffer_file_offset));
size_t read_size = source_->Fill(buffer.data(), buffer.size());
if (read_size < buffer.size())
eof_ = true;
for (auto iter = buffer.begin(), end = iter + read_size; iter < end;
++iter) {
if (*iter == '\n') {
// Don't include \n or \r in the line range.
Offset line_offset =
buffer_file_offset + (iter - buffer.begin()) - last_cr_;
line_ranges_.emplace_back(next_line_start_, line_offset);
next_line_start_ = line_offset + last_cr_ + 1;
}
last_cr_ = *iter == '\r';
}
if (eof_) {
// Add the final line as an empty range.
Offset end = buffer_file_offset + read_size;
line_ranges_.emplace_back(next_line_start_, end);
}
}
if (IsLineCached(find_line)) {
*out_range = GetCachedLine(find_line);
return Result::Ok;
} else {
assert(eof_);
return Result::Error;
}
}
// static
OffsetRange LexerSourceLineFinder::ClampSourceLineOffsets(
OffsetRange offset_range,
ColumnRange column_range,
Offset max_line_length) {
Offset line_length = offset_range.size();
if (line_length > max_line_length) {
size_t column_count = column_range.size();
size_t center_on;
if (column_count > max_line_length) {
// The column range doesn't fit, just center on first_column.
center_on = column_range.start - 1;
} else {
// the entire range fits, display it all in the center.
center_on = (column_range.start + column_range.end) / 2 - 1;
}
if (center_on > max_line_length / 2)
offset_range.start += center_on - max_line_length / 2;
offset_range.start =
std::min(offset_range.start, offset_range.end - max_line_length);
offset_range.end = offset_range.start + max_line_length;
}
return offset_range;
}
} // namespace wabt
|
/* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <string.h>
#include <list>
#include <memory>
#include <queue>
#include <vector>
#include BOSS_WEBRTC_U_modules__video_coding__encoded_frame_h //original-code:"modules/video_coding/encoded_frame.h"
#include BOSS_WEBRTC_U_modules__video_coding__packet_h //original-code:"modules/video_coding/packet.h"
#include BOSS_WEBRTC_U_modules__video_coding__receiver_h //original-code:"modules/video_coding/receiver.h"
#include "modules/video_coding/test/stream_generator.h"
#include "modules/video_coding/test/test_util.h"
#include BOSS_WEBRTC_U_modules__video_coding__timing_h //original-code:"modules/video_coding/timing.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_system_wrappers__include__clock_h //original-code:"system_wrappers/include/clock.h"
#include "test/gtest.h"
namespace webrtc {
class TestVCMReceiver : public ::testing::Test {
protected:
TestVCMReceiver()
: clock_(new SimulatedClock(0)),
timing_(clock_.get()),
receiver_(&timing_, clock_.get(), &event_factory_) {
stream_generator_.reset(
new StreamGenerator(0, clock_->TimeInMilliseconds()));
}
virtual void SetUp() { receiver_.Reset(); }
int32_t InsertPacket(int index) {
VCMPacket packet;
bool packet_available = stream_generator_->GetPacket(&packet, index);
EXPECT_TRUE(packet_available);
if (!packet_available)
return kGeneralError; // Return here to avoid crashes below.
return receiver_.InsertPacket(packet);
}
int32_t InsertPacketAndPop(int index) {
VCMPacket packet;
bool packet_available = stream_generator_->PopPacket(&packet, index);
EXPECT_TRUE(packet_available);
if (!packet_available)
return kGeneralError; // Return here to avoid crashes below.
return receiver_.InsertPacket(packet);
}
int32_t InsertFrame(FrameType frame_type, bool complete) {
int num_of_packets = complete ? 1 : 2;
stream_generator_->GenerateFrame(
frame_type, (frame_type != kEmptyFrame) ? num_of_packets : 0,
(frame_type == kEmptyFrame) ? 1 : 0, clock_->TimeInMilliseconds());
int32_t ret = InsertPacketAndPop(0);
if (!complete) {
// Drop the second packet.
VCMPacket packet;
stream_generator_->PopPacket(&packet, 0);
}
clock_->AdvanceTimeMilliseconds(kDefaultFramePeriodMs);
return ret;
}
bool DecodeNextFrame() {
VCMEncodedFrame* frame = receiver_.FrameForDecoding(0, false);
if (!frame)
return false;
receiver_.ReleaseFrame(frame);
return true;
}
std::unique_ptr<SimulatedClock> clock_;
VCMTiming timing_;
NullEventFactory event_factory_;
VCMReceiver receiver_;
std::unique_ptr<StreamGenerator> stream_generator_;
};
TEST_F(TestVCMReceiver, NonDecodableDuration_Empty) {
// Enable NACK and with no RTT thresholds for disabling retransmission delay.
receiver_.SetNackMode(kNack, -1, -1);
const size_t kMaxNackListSize = 1000;
const int kMaxPacketAgeToNack = 1000;
const int kMaxNonDecodableDuration = 500;
const int kMinDelayMs = 500;
receiver_.SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack,
kMaxNonDecodableDuration);
EXPECT_GE(InsertFrame(kVideoFrameKey, true), kNoError);
// Advance time until it's time to decode the key frame.
clock_->AdvanceTimeMilliseconds(kMinDelayMs);
EXPECT_TRUE(DecodeNextFrame());
bool request_key_frame = false;
std::vector<uint16_t> nack_list = receiver_.NackList(&request_key_frame);
EXPECT_FALSE(request_key_frame);
}
TEST_F(TestVCMReceiver, NonDecodableDuration_NoKeyFrame) {
// Enable NACK and with no RTT thresholds for disabling retransmission delay.
receiver_.SetNackMode(kNack, -1, -1);
const size_t kMaxNackListSize = 1000;
const int kMaxPacketAgeToNack = 1000;
const int kMaxNonDecodableDuration = 500;
receiver_.SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack,
kMaxNonDecodableDuration);
const int kNumFrames = kDefaultFrameRate * kMaxNonDecodableDuration / 1000;
for (int i = 0; i < kNumFrames; ++i) {
EXPECT_GE(InsertFrame(kVideoFrameDelta, true), kNoError);
}
bool request_key_frame = false;
std::vector<uint16_t> nack_list = receiver_.NackList(&request_key_frame);
EXPECT_TRUE(request_key_frame);
}
TEST_F(TestVCMReceiver, NonDecodableDuration_OneIncomplete) {
// Enable NACK and with no RTT thresholds for disabling retransmission delay.
receiver_.SetNackMode(kNack, -1, -1);
const size_t kMaxNackListSize = 1000;
const int kMaxPacketAgeToNack = 1000;
const int kMaxNonDecodableDuration = 500;
const int kMaxNonDecodableDurationFrames =
(kDefaultFrameRate * kMaxNonDecodableDuration + 500) / 1000;
const int kMinDelayMs = 500;
receiver_.SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack,
kMaxNonDecodableDuration);
receiver_.SetMinReceiverDelay(kMinDelayMs);
int64_t key_frame_inserted = clock_->TimeInMilliseconds();
EXPECT_GE(InsertFrame(kVideoFrameKey, true), kNoError);
// Insert an incomplete frame.
EXPECT_GE(InsertFrame(kVideoFrameDelta, false), kNoError);
// Insert enough frames to have too long non-decodable sequence.
for (int i = 0; i < kMaxNonDecodableDurationFrames; ++i) {
EXPECT_GE(InsertFrame(kVideoFrameDelta, true), kNoError);
}
// Advance time until it's time to decode the key frame.
clock_->AdvanceTimeMilliseconds(kMinDelayMs - clock_->TimeInMilliseconds() -
key_frame_inserted);
EXPECT_TRUE(DecodeNextFrame());
// Make sure we get a key frame request.
bool request_key_frame = false;
std::vector<uint16_t> nack_list = receiver_.NackList(&request_key_frame);
EXPECT_TRUE(request_key_frame);
}
TEST_F(TestVCMReceiver, NonDecodableDuration_NoTrigger) {
// Enable NACK and with no RTT thresholds for disabling retransmission delay.
receiver_.SetNackMode(kNack, -1, -1);
const size_t kMaxNackListSize = 1000;
const int kMaxPacketAgeToNack = 1000;
const int kMaxNonDecodableDuration = 500;
const int kMaxNonDecodableDurationFrames =
(kDefaultFrameRate * kMaxNonDecodableDuration + 500) / 1000;
const int kMinDelayMs = 500;
receiver_.SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack,
kMaxNonDecodableDuration);
receiver_.SetMinReceiverDelay(kMinDelayMs);
int64_t key_frame_inserted = clock_->TimeInMilliseconds();
EXPECT_GE(InsertFrame(kVideoFrameKey, true), kNoError);
// Insert an incomplete frame.
EXPECT_GE(InsertFrame(kVideoFrameDelta, false), kNoError);
// Insert all but one frame to not trigger a key frame request due to
// too long duration of non-decodable frames.
for (int i = 0; i < kMaxNonDecodableDurationFrames - 1; ++i) {
EXPECT_GE(InsertFrame(kVideoFrameDelta, true), kNoError);
}
// Advance time until it's time to decode the key frame.
clock_->AdvanceTimeMilliseconds(kMinDelayMs - clock_->TimeInMilliseconds() -
key_frame_inserted);
EXPECT_TRUE(DecodeNextFrame());
// Make sure we don't get a key frame request since we haven't generated
// enough frames.
bool request_key_frame = false;
std::vector<uint16_t> nack_list = receiver_.NackList(&request_key_frame);
EXPECT_FALSE(request_key_frame);
}
TEST_F(TestVCMReceiver, NonDecodableDuration_NoTrigger2) {
// Enable NACK and with no RTT thresholds for disabling retransmission delay.
receiver_.SetNackMode(kNack, -1, -1);
const size_t kMaxNackListSize = 1000;
const int kMaxPacketAgeToNack = 1000;
const int kMaxNonDecodableDuration = 500;
const int kMaxNonDecodableDurationFrames =
(kDefaultFrameRate * kMaxNonDecodableDuration + 500) / 1000;
const int kMinDelayMs = 500;
receiver_.SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack,
kMaxNonDecodableDuration);
receiver_.SetMinReceiverDelay(kMinDelayMs);
int64_t key_frame_inserted = clock_->TimeInMilliseconds();
EXPECT_GE(InsertFrame(kVideoFrameKey, true), kNoError);
// Insert enough frames to have too long non-decodable sequence, except that
// we don't have any losses.
for (int i = 0; i < kMaxNonDecodableDurationFrames; ++i) {
EXPECT_GE(InsertFrame(kVideoFrameDelta, true), kNoError);
}
// Insert an incomplete frame.
EXPECT_GE(InsertFrame(kVideoFrameDelta, false), kNoError);
// Advance time until it's time to decode the key frame.
clock_->AdvanceTimeMilliseconds(kMinDelayMs - clock_->TimeInMilliseconds() -
key_frame_inserted);
EXPECT_TRUE(DecodeNextFrame());
// Make sure we don't get a key frame request since the non-decodable duration
// is only one frame.
bool request_key_frame = false;
std::vector<uint16_t> nack_list = receiver_.NackList(&request_key_frame);
EXPECT_FALSE(request_key_frame);
}
TEST_F(TestVCMReceiver, NonDecodableDuration_KeyFrameAfterIncompleteFrames) {
// Enable NACK and with no RTT thresholds for disabling retransmission delay.
receiver_.SetNackMode(kNack, -1, -1);
const size_t kMaxNackListSize = 1000;
const int kMaxPacketAgeToNack = 1000;
const int kMaxNonDecodableDuration = 500;
const int kMaxNonDecodableDurationFrames =
(kDefaultFrameRate * kMaxNonDecodableDuration + 500) / 1000;
const int kMinDelayMs = 500;
receiver_.SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack,
kMaxNonDecodableDuration);
receiver_.SetMinReceiverDelay(kMinDelayMs);
int64_t key_frame_inserted = clock_->TimeInMilliseconds();
EXPECT_GE(InsertFrame(kVideoFrameKey, true), kNoError);
// Insert an incomplete frame.
EXPECT_GE(InsertFrame(kVideoFrameDelta, false), kNoError);
// Insert enough frames to have too long non-decodable sequence.
for (int i = 0; i < kMaxNonDecodableDurationFrames; ++i) {
EXPECT_GE(InsertFrame(kVideoFrameDelta, true), kNoError);
}
EXPECT_GE(InsertFrame(kVideoFrameKey, true), kNoError);
// Advance time until it's time to decode the key frame.
clock_->AdvanceTimeMilliseconds(kMinDelayMs - clock_->TimeInMilliseconds() -
key_frame_inserted);
EXPECT_TRUE(DecodeNextFrame());
// Make sure we don't get a key frame request since we have a key frame
// in the list.
bool request_key_frame = false;
std::vector<uint16_t> nack_list = receiver_.NackList(&request_key_frame);
EXPECT_FALSE(request_key_frame);
}
// A simulated clock, when time elapses, will insert frames into the jitter
// buffer, based on initial settings.
class SimulatedClockWithFrames : public SimulatedClock {
public:
SimulatedClockWithFrames(StreamGenerator* stream_generator,
VCMReceiver* receiver)
: SimulatedClock(0),
stream_generator_(stream_generator),
receiver_(receiver) {}
virtual ~SimulatedClockWithFrames() {}
// If |stop_on_frame| is true and next frame arrives between now and
// now+|milliseconds|, the clock will be advanced to the arrival time of next
// frame.
// Otherwise, the clock will be advanced by |milliseconds|.
//
// For both cases, a frame will be inserted into the jitter buffer at the
// instant when the clock time is timestamps_.front().arrive_time.
//
// Return true if some frame arrives between now and now+|milliseconds|.
bool AdvanceTimeMilliseconds(int64_t milliseconds, bool stop_on_frame) {
return AdvanceTimeMicroseconds(milliseconds * 1000, stop_on_frame);
}
bool AdvanceTimeMicroseconds(int64_t microseconds, bool stop_on_frame) {
int64_t start_time = TimeInMicroseconds();
int64_t end_time = start_time + microseconds;
bool frame_injected = false;
while (!timestamps_.empty() &&
timestamps_.front().arrive_time <= end_time) {
RTC_DCHECK(timestamps_.front().arrive_time >= start_time);
SimulatedClock::AdvanceTimeMicroseconds(timestamps_.front().arrive_time -
TimeInMicroseconds());
GenerateAndInsertFrame((timestamps_.front().render_time + 500) / 1000);
timestamps_.pop();
frame_injected = true;
if (stop_on_frame)
return frame_injected;
}
if (TimeInMicroseconds() < end_time) {
SimulatedClock::AdvanceTimeMicroseconds(end_time - TimeInMicroseconds());
}
return frame_injected;
}
// Input timestamps are in unit Milliseconds.
// And |arrive_timestamps| must be positive and in increasing order.
// |arrive_timestamps| determine when we are going to insert frames into the
// jitter buffer.
// |render_timestamps| are the timestamps on the frame.
void SetFrames(const int64_t* arrive_timestamps,
const int64_t* render_timestamps,
size_t size) {
int64_t previous_arrive_timestamp = 0;
for (size_t i = 0; i < size; i++) {
RTC_CHECK(arrive_timestamps[i] >= previous_arrive_timestamp);
timestamps_.push(TimestampPair(arrive_timestamps[i] * 1000,
render_timestamps[i] * 1000));
previous_arrive_timestamp = arrive_timestamps[i];
}
}
private:
struct TimestampPair {
TimestampPair(int64_t arrive_timestamp, int64_t render_timestamp)
: arrive_time(arrive_timestamp), render_time(render_timestamp) {}
int64_t arrive_time;
int64_t render_time;
};
void GenerateAndInsertFrame(int64_t render_timestamp_ms) {
VCMPacket packet;
stream_generator_->GenerateFrame(FrameType::kVideoFrameKey,
1, // media packets
0, // empty packets
render_timestamp_ms);
bool packet_available = stream_generator_->PopPacket(&packet, 0);
EXPECT_TRUE(packet_available);
if (!packet_available)
return; // Return here to avoid crashes below.
receiver_->InsertPacket(packet);
}
std::queue<TimestampPair> timestamps_;
StreamGenerator* stream_generator_;
VCMReceiver* receiver_;
};
// Use a SimulatedClockWithFrames
// Wait call will do either of these:
// 1. If |stop_on_frame| is true, the clock will be turned to the exact instant
// that the first frame comes and the frame will be inserted into the jitter
// buffer, or the clock will be turned to now + |max_time| if no frame comes in
// the window.
// 2. If |stop_on_frame| is false, the clock will be turn to now + |max_time|,
// and all the frames arriving between now and now + |max_time| will be
// inserted into the jitter buffer.
//
// This is used to simulate the JitterBuffer getting packets from internet as
// time elapses.
class FrameInjectEvent : public EventWrapper {
public:
FrameInjectEvent(SimulatedClockWithFrames* clock, bool stop_on_frame)
: clock_(clock), stop_on_frame_(stop_on_frame) {}
bool Set() override { return true; }
EventTypeWrapper Wait(unsigned long max_time) override { // NOLINT
if (clock_->AdvanceTimeMilliseconds(max_time, stop_on_frame_) &&
stop_on_frame_) {
return EventTypeWrapper::kEventSignaled;
} else {
return EventTypeWrapper::kEventTimeout;
}
}
private:
SimulatedClockWithFrames* clock_;
bool stop_on_frame_;
};
class VCMReceiverTimingTest : public ::testing::Test {
protected:
VCMReceiverTimingTest()
: clock_(&stream_generator_, &receiver_),
stream_generator_(0, clock_.TimeInMilliseconds()),
timing_(&clock_),
receiver_(
&timing_,
&clock_,
std::unique_ptr<EventWrapper>(new FrameInjectEvent(&clock_, false)),
std::unique_ptr<EventWrapper>(
new FrameInjectEvent(&clock_, true))) {}
virtual void SetUp() { receiver_.Reset(); }
SimulatedClockWithFrames clock_;
StreamGenerator stream_generator_;
VCMTiming timing_;
VCMReceiver receiver_;
};
// Test whether VCMReceiver::FrameForDecoding handles parameter
// |max_wait_time_ms| correctly:
// 1. The function execution should never take more than |max_wait_time_ms|.
// 2. If the function exit before now + |max_wait_time_ms|, a frame must be
// returned.
TEST_F(VCMReceiverTimingTest, FrameForDecoding) {
const size_t kNumFrames = 100;
const int kFramePeriod = 40;
int64_t arrive_timestamps[kNumFrames];
int64_t render_timestamps[kNumFrames];
// Construct test samples.
// render_timestamps are the timestamps stored in the Frame;
// arrive_timestamps controls when the Frame packet got received.
for (size_t i = 0; i < kNumFrames; i++) {
// Preset frame rate to 25Hz.
// But we add a reasonable deviation to arrive_timestamps to mimic Internet
// fluctuation.
arrive_timestamps[i] =
(i + 1) * kFramePeriod + (i % 10) * ((i % 2) ? 1 : -1);
render_timestamps[i] = (i + 1) * kFramePeriod;
}
clock_.SetFrames(arrive_timestamps, render_timestamps, kNumFrames);
// Record how many frames we finally get out of the receiver.
size_t num_frames_return = 0;
const int64_t kMaxWaitTime = 30;
// Ideally, we should get all frames that we input in InitializeFrames.
// In the case that FrameForDecoding kills frames by error, we rely on the
// build bot to kill the test.
while (num_frames_return < kNumFrames) {
int64_t start_time = clock_.TimeInMilliseconds();
VCMEncodedFrame* frame = receiver_.FrameForDecoding(kMaxWaitTime, false);
int64_t end_time = clock_.TimeInMilliseconds();
// In any case the FrameForDecoding should not wait longer than
// max_wait_time.
// In the case that we did not get a frame, it should have been waiting for
// exactly max_wait_time. (By the testing samples we constructed above, we
// are sure there is no timing error, so the only case it returns with NULL
// is that it runs out of time.)
if (frame) {
receiver_.ReleaseFrame(frame);
++num_frames_return;
EXPECT_GE(kMaxWaitTime, end_time - start_time);
} else {
EXPECT_EQ(kMaxWaitTime, end_time - start_time);
}
}
}
// Test whether VCMReceiver::FrameForDecoding handles parameter
// |prefer_late_decoding| and |max_wait_time_ms| correctly:
// 1. The function execution should never take more than |max_wait_time_ms|.
// 2. If the function exit before now + |max_wait_time_ms|, a frame must be
// returned and the end time must be equal to the render timestamp - delay
// for decoding and rendering.
TEST_F(VCMReceiverTimingTest, FrameForDecodingPreferLateDecoding) {
const size_t kNumFrames = 100;
const int kFramePeriod = 40;
int64_t arrive_timestamps[kNumFrames];
int64_t render_timestamps[kNumFrames];
int render_delay_ms;
int max_decode_ms;
int dummy;
timing_.GetTimings(&dummy, &max_decode_ms, &dummy, &dummy, &dummy, &dummy,
&render_delay_ms);
// Construct test samples.
// render_timestamps are the timestamps stored in the Frame;
// arrive_timestamps controls when the Frame packet got received.
for (size_t i = 0; i < kNumFrames; i++) {
// Preset frame rate to 25Hz.
// But we add a reasonable deviation to arrive_timestamps to mimic Internet
// fluctuation.
arrive_timestamps[i] =
(i + 1) * kFramePeriod + (i % 10) * ((i % 2) ? 1 : -1);
render_timestamps[i] = (i + 1) * kFramePeriod;
}
clock_.SetFrames(arrive_timestamps, render_timestamps, kNumFrames);
// Record how many frames we finally get out of the receiver.
size_t num_frames_return = 0;
const int64_t kMaxWaitTime = 30;
bool prefer_late_decoding = true;
while (num_frames_return < kNumFrames) {
int64_t start_time = clock_.TimeInMilliseconds();
VCMEncodedFrame* frame =
receiver_.FrameForDecoding(kMaxWaitTime, prefer_late_decoding);
int64_t end_time = clock_.TimeInMilliseconds();
if (frame) {
EXPECT_EQ(frame->RenderTimeMs() - max_decode_ms - render_delay_ms,
end_time);
receiver_.ReleaseFrame(frame);
++num_frames_return;
} else {
EXPECT_EQ(kMaxWaitTime, end_time - start_time);
}
}
}
} // namespace webrtc
|
// Copyright (c) 2012-2018 The Elastos Open Source Project
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <arpa/inet.h>
#include <Core/BRPeer.h>
#include "BRPeer.h"
#include "BRPeerMessages.h"
#include "BRPeerManager.h"
#include "BRArray.h"
#include "AddressMessage.h"
namespace Elastos {
namespace ElaWallet {
AddressMessage::AddressMessage() {
}
int AddressMessage::Accept(BRPeer *peer, const uint8_t *msg, size_t msgLen) {
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0;
size_t count = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
int r = 1;
if (off == 0 || off + count*30 > msgLen) {
peer_log(peer, "malformed addr message, length is %zu, should be %zu for %zu address(es)", msgLen,
BRVarIntSize(count) + 30*count, count);
r = 0;
}
else if (count > 1000) {
peer_log(peer, "dropping addr message, %zu is too many addresses, max is 1000", count);
}
else if (ctx->sentGetaddr) { // simple anti-tarpitting tactic, don't accept unsolicited addresses
BRPeer peers[count], p;
size_t peersCount = 0;
time_t now = time(NULL);
peer_log(peer, "got addr with %zu address(es)", count);
for (size_t i = 0; i < count; i++) {
p.timestamp = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
p.services = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
UInt128Get(&p.address, &msg[off]);
off += sizeof(UInt128);
p.port = UInt16GetLE(&msg[off]);
off += sizeof(uint16_t);
char host[INET6_ADDRSTRLEN] = {0};
if ((p.address.u64[0] == 0 && p.address.u16[4] == 0 && p.address.u16[5] == 0xffff))
inet_ntop(AF_INET, &p.address.u32[3], host, sizeof(host));
else
inet_ntop(AF_INET6, &p.address, host, sizeof(host));
peer_dbg(peer, "peers[%zu] = %s, timestamp = %llu, port = %d, services = %llu",
i, host, p.timestamp, p.port, p.services);
if (! (p.services & SERVICES_NODE_NETWORK)) continue; // skip peers that don't carry full blocks
if (! (p.address.u64[0] == 0 && p.address.u16[4] == 0 && p.address.u16[5] == 0xffff))
continue; // ignore IPv6 for now
if (p.address.u64[0] == 0 && p.address.u16[4] == 0 && p.address.u16[5] == 0xffff &&
p.address.u8[12] == 127 && p.address.u8[13] == 0 &&
p.address.u8[14] == 0 && p.address.u8[15] == 1) {
peer_log(peer, "drop peers[%zu]", i);
continue;
}
// if address time is more than 10 min in the future or unknown, set to 5 days old
if (p.timestamp > now + 10*60 || p.timestamp == 0) p.timestamp = now - 5*24*60*60;
p.timestamp -= 2*60*60; // subtract two hours
peers[peersCount++] = p; // add it to the list
}
if (peersCount > 0 && ctx->relayedPeers) ctx->relayedPeers(ctx->info, peers, peersCount);
}
return r;
}
void AddressMessage::Send(BRPeer *peer) {
uint8_t msg[BRVarIntSize(0)];
size_t msgLen = BRVarIntSet(msg, sizeof(msg), 0);
//TODO: send peer addresses we know about
// BRPeerSendMessage(peer, msg, msgLen, MSG_ADDR);
}
}
}
|
//
// Created by lukas on 06.08.20.
//
#ifndef LATTICEMODELIMPLEMENTATIONS_HYBRID_MONTE_CARLO_HPP
#define LATTICEMODELIMPLEMENTATIONS_HYBRID_MONTE_CARLO_HPP
#include "boost/numeric/odeint/stepper/symplectic_rkn_sb3a_mclachlan.hpp"
#include "boost/numeric/odeint/integrate/integrate_n_steps.hpp"
#include "../../mcmc_update_base.hpp"
namespace lm_impl {
namespace mcmc_update {
template<typename T, typename ModelParameters, typename SamplerCl>
class HybridMonteCarloUpdate;
template<typename T, typename ModelParameters, typename SamplerCl>
class HybridMonteCarloUpdateParameters : public MCMCUpdateBaseParameters {
public:
explicit HybridMonteCarloUpdateParameters(const json params_) : MCMCUpdateBaseParameters(params_),
dt(get_entry<double>("dt", 0.01)),
n(get_entry<int>("n", 20)),
m(get_entry<double>("m", 1.0)) {}
explicit HybridMonteCarloUpdateParameters(const double dt_, const int n_, const double m_=1.0
) : HybridMonteCarloUpdateParameters(json{
{"dt", dt_},
{"n", n_},
{"m", m_}}) {}
static std::string name() {
return "HybridMonteCarloUpdate";
}
typedef HybridMonteCarloUpdate<T, ModelParameters, SamplerCl> MCMCUpdate;
typedef typename ModelParameters::Model Model;
protected:
friend class HybridMonteCarloUpdate<T, ModelParameters, SamplerCl>;
const double dt;
const int n;
const double m;
};
template<typename T, typename ModelParameters, typename SamplerCl>
class HybridMonteCarloUpdate
: public MCMCUpdateBase<HybridMonteCarloUpdate<T, ModelParameters, SamplerCl>, SamplerCl> {
public:
explicit HybridMonteCarloUpdate(const HybridMonteCarloUpdateParameters<T, ModelParameters, SamplerCl> &up_,
typename ModelParameters::Model &model_)
: MCMCUpdateBase<HybridMonteCarloUpdate<T, ModelParameters, SamplerCl>, SamplerCl>(up_.eps),
up(up_), model(model_) {
normal = std::normal_distribution<double>(0.0, 1.0);
rand = std::uniform_real_distribution<double>(0, 1);
}
template<typename Lattice>
void initialize_mcmc_update(const Lattice &lattice) {
momenta = std::vector<double>(lattice.size(), 0.0);
backup_momenta = std::vector<double>(lattice.size(), 0.0);
}
template<typename Lattice>
void operator()(Lattice &lattice) {
auto current_energy = lattice.energy();
auto current_lattice_grid(lattice.get_system_representation());
// Sample momenta
std::generate(momenta.begin(), momenta.end(), [this]() { return normal(mcmc::util::gen); });
std::copy(momenta.begin(), momenta.end(), backup_momenta.begin());
HamiltonianSystemMomentum hamiltonian_system_momentum(model, lattice.get_neighbours());
HamiltonianSystemCoor hamiltonian_system_coor(up.m);
boost::numeric::odeint::integrate_n_steps(symplectic_stepper(),
std::make_pair(hamiltonian_system_coor, hamiltonian_system_momentum),
std::make_pair(boost::ref(lattice.get_system_representation()),
boost::ref(momenta)),
0.0, up.dt, up.n);
lattice.normalize(lattice.get_system_representation());
auto proposal_energy = lattice.energy();
auto kinetic_term = std::inner_product(backup_momenta.begin(), backup_momenta.end(), backup_momenta.begin(), 0.0);
auto proposal_kinetic_term = std::inner_product(momenta.begin(), momenta.end(), momenta.begin(), 0.0);
// Accept/Reject step
if (rand(mcmc::util::gen) >= std::min(1.0, std::exp(
-1.0 * (proposal_energy - current_energy) - 0.5 * (proposal_kinetic_term - kinetic_term) / up.m))) {
auto &lattice_grid = lattice.get_system_representation();
lattice_grid = current_lattice_grid;
}
}
typedef boost::numeric::odeint::symplectic_rkn_sb3a_mclachlan<std::vector<T> > symplectic_stepper;
protected:
struct HamiltonianSystemMomentum {
HamiltonianSystemMomentum(typename ModelParameters::Model &model_,
const std::vector<std::vector<T *> > &neighbours_) : hmc_model(model_),
hmc_neighbours(neighbours_) {}
void operator()(const std::vector<T> &q, std::vector<T> &dpdt) const {
for (uint i = 0; i < q.size(); i++) {
dpdt[i] = -1.0 * hmc_model.get_drift_term(q[i], hmc_neighbours[i]);
}
}
typename ModelParameters::Model &hmc_model;
const std::vector<std::vector<T *> > &hmc_neighbours;
};
struct HamiltonianSystemCoor {
HamiltonianSystemCoor(const double m_) : m(m_) {}
void operator()(const std::vector<T> &p, std::vector<T> &dqdt) const {
for (uint i = 0; i < p.size(); i++) {
dqdt[i] = p[i] / m;
}
}
const double m;
};
const HybridMonteCarloUpdateParameters<T, ModelParameters, SamplerCl> &up;
typename ModelParameters::Model &model;
std::vector<double> momenta;
std::vector<double> backup_momenta;
std::normal_distribution<double> normal;
std::uniform_real_distribution<double> rand;
};
}
}
#endif //LATTICEMODELIMPLEMENTATIONS_HYBRID_MONTE_CARLO_HPP
|
#include "NiGeometry.h"
#include "GameAPI.h"
void NiGeometryData::AllocateVerts(UInt32 numVerts)
{
m_pkVertex = (NiPoint3 *)FormHeap_Allocate(sizeof(NiPoint3) * numVerts);
m_pkTexture = (NiPoint2 *)FormHeap_Allocate(sizeof(NiPoint2) * numVerts);
memset(m_pkVertex, 0, sizeof(NiPoint3) * numVerts);
memset(m_pkTexture, 0, sizeof(NiPoint2) * numVerts);
}
void NiGeometryData::AllocateNormals(UInt32 numVerts)
{
m_pkNormal = (NiPoint3 *)FormHeap_Allocate(sizeof(NiPoint3) * numVerts);
memset(m_pkNormal, 0, sizeof(NiPoint3) * numVerts);
}
void NiGeometryData::AllocateNBT(UInt32 numVerts)
{
m_pkNormal = (NiPoint3 *)FormHeap_Allocate(sizeof(NiPoint3) * 3 * numVerts);
memset(m_pkNormal, 0, sizeof(NiPoint3) * 3 * numVerts);
}
void NiGeometryData::AllocateColors(UInt32 numVerts)
{
m_pkColor = (NiColorA *)FormHeap_Allocate(sizeof(NiColorA) * numVerts);
memset(m_pkColor, 0, sizeof(NiColorA) * numVerts);
}
void NiSkinPartition::Partition::AllocateWeights(UInt32 numVerts)
{
m_pfWeights = (float *)FormHeap_Allocate(sizeof(float) * 4 * numVerts);
m_pucBonePalette = (UInt8 *)FormHeap_Allocate(sizeof(UInt8) * 4 * numVerts);
memset(m_pfWeights, 0, sizeof(float) * 4 * numVerts);
memset(m_pucBonePalette, 0, sizeof(UInt8) * 4 * numVerts);
}
void NiSkinData::BoneData::AllocateWeights(UInt32 numWeights)
{
m_pkBoneVertData = (BoneVertData *)FormHeap_Allocate(sizeof(BoneVertData) * numWeights);
memset(m_pkBoneVertData, 0, sizeof(BoneVertData) * numWeights);
}
void NiGeometry::SetEffectState(NiProperty * effectState)
{
m_spEffectState = effectState; // handled by NiPointer now
}
void NiGeometry::SetSkinInstance(NiSkinInstance * skinInstance)
{
m_spSkinInstance = skinInstance; // handled by NiPointer now
}
void NiGeometry::SetModelData(NiGeometryData * modelData)
{
m_spModelData = modelData; // handled by NiPointer now
}
NiTriShape * NiTriShape::Create(NiTriShapeData * geometry)
{
void* memory = FormHeap_Allocate(sizeof(NiTriShape));
memset(memory, 0, sizeof(NiTriShape));
NiTriShape* xData = (NiTriShape*)memory;
CALL_MEMBER_FN(xData, ctor)(geometry);
return xData;
}
NiSkinInstance * NiSkinInstance::Create()
{
void* memory = FormHeap_Allocate(sizeof(NiSkinInstance));
memset(memory, 0, sizeof(NiSkinInstance));
NiSkinInstance* xData = (NiSkinInstance*)memory;
CALL_MEMBER_FN(xData, ctor)();
return xData;
}
BSDismemberSkinInstance * BSDismemberSkinInstance::Create()
{
void* memory = FormHeap_Allocate(sizeof(BSDismemberSkinInstance));
memset(memory, 0, sizeof(BSDismemberSkinInstance));
BSDismemberSkinInstance* xData = (BSDismemberSkinInstance*)memory;
CALL_MEMBER_FN(xData, ctor)();
return xData;
}
|
#pragma once
#ifndef __SRC_LIB_BASIS_HPP__
#define __SRC_LIB_BASIS_HPP__
#include <map>
#include <vector>
#include "instance.hpp"
#include "pricing.hpp"
#include "runtime.hpp"
#include "util/HFactor.h"
#include "util/HVector.h"
#include "util/HVectorBase.h"
#include "snippets.hpp"
enum class BasisStatus {
Default,
ActiveAtLower = 1,
ActiveAtUpper,
ActiveAtZero,
Inactive
};
class Basis {
HVector buffer_vec2hvec;
HVector& vec2hvec(const Vector& vec) {
buffer_vec2hvec.clear();
for (HighsInt i = 0; i < vec.num_nz; i++) {
buffer_vec2hvec.index[i] = vec.index[i];
buffer_vec2hvec.array[vec.index[i]] = vec.value[vec.index[i]];
}
buffer_vec2hvec.count = vec.num_nz;
buffer_vec2hvec.packFlag = true;
return buffer_vec2hvec;
}
Vector& hvec2vec(const HVector& hvec, Vector& target) {
target.reset();
for (HighsInt i = 0; i < hvec.count; i++) {
target.index[i] = hvec.index[i];
target.value[target.index[i]] = hvec.array[hvec.index[i]];
}
// for (HighsInt i = 0; i < hvec.size; i++) {
// target.index[i] = hvec.index[i];
// target.value[i] = hvec.array[i];
// }
target.num_nz = hvec.count;
return target;
}
Vector hvec2vec(const HVector& hvec) {
Vector vec(hvec.size);
return hvec2vec(hvec, vec);
}
Runtime& runtime;
HFactor basisfactor;
HighsInt updatessinceinvert = 0;
MatrixBase Atran;
// indices of active constraints in basis
std::vector<HighsInt> activeconstraintidx;
// ids of constraints that are in the basis but not active
// I need to extract those columns to get Z
std::vector<HighsInt> nonactiveconstraintsidx;
// ids of constraints that are in the basis
// std::vector<HighsInt> baseindex;
HighsInt* baseindex;
std::map<int, BasisStatus> basisstatus;
// index i: -1 if constraint not in basis, [0, num_var] if
// constraint in basis (active or not)
std::vector<HighsInt> constraintindexinbasisfactor;
void build();
void rebuild();
// buffer to avoid recreating vectors
Vector buffer_column_aq;
Vector buffer_row_ep;
// buffers to prevent multiple btran/ftran
HighsInt buffered_q = -1;
HighsInt buffered_p = -1;
HVector row_ep;
HVector col_aq;
public:
Basis(Runtime& rt, std::vector<HighsInt> active,
std::vector<BasisStatus> atlower, std::vector<HighsInt> inactive);
HighsInt getnupdatessinceinvert() { return updatessinceinvert; }
HighsInt getnumactive() const { return activeconstraintidx.size(); };
HighsInt getnuminactive() const { return nonactiveconstraintsidx.size(); };
const std::vector<HighsInt>& getactive() const {
return activeconstraintidx;
};
const std::vector<HighsInt>& getinactive() const {
return nonactiveconstraintsidx;
};
const std::vector<HighsInt>& getindexinfactor() const {
return constraintindexinbasisfactor;
};
BasisStatus getstatus(HighsInt conid) { return basisstatus[conid]; };
void report();
// move that constraint into V section basis (will correspond to
// Nullspace from now on)
void deactivate(HighsInt conid);
void activate(Runtime& rt, HighsInt conid, BasisStatus atlower,
HighsInt nonactivetoremove, Pricing* pricing);
void updatebasis(Runtime& rt, HighsInt newactivecon, HighsInt droppedcon,
Pricing* pricing);
Vector btran(const Vector& rhs, bool buffer = false, HighsInt p = -1);
Vector ftran(const Vector& rhs, bool buffer = false, HighsInt q = -1);
Vector& btran(const Vector& rhs, Vector& target, bool buffer = false,
HighsInt p = -1);
Vector& ftran(const Vector& rhs, Vector& target, bool buffer = false,
HighsInt q = -1);
Vector recomputex(const Instance& inst);
void write(std::string filename);
Vector& Ztprod(const Vector& rhs, Vector& target, bool buffer = false,
HighsInt q = -1);
Vector& Zprod(const Vector& rhs, Vector& target);
};
#endif
|
//========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file calculate_fluxes.cpp
// \brief Calculate hydro/MHD fluxes
// C/C++ headers
#include <algorithm> // min,max
// Athena++ headers
#include "hydro.hpp"
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../coordinates/coordinates.hpp"
#include "../field/field.hpp"
#include "../mesh/mesh.hpp"
#include "../bvals/bvals.hpp"
#include "../reconstruct/reconstruction.hpp"
// OpenMP header
#ifdef OPENMP_PARALLEL
#include <omp.h>
#endif
//----------------------------------------------------------------------------------------
//! \fn void Hydro::CalculateFluxes
// \brief Calculate Hydrodynamic Fluxes using the Riemann solver
void Hydro::CalculateFluxes(AthenaArray<Real> &w, FaceField &b,
AthenaArray<Real> &bcc, int reconstruct_order)
{
MeshBlock *pmb=pmy_block;
AthenaArray<Real> &x1flux=flux[X1DIR];
AthenaArray<Real> &x2flux=flux[X2DIR];
AthenaArray<Real> &x3flux=flux[X3DIR];
int is = pmb->is; int js = pmb->js; int ks = pmb->ks;
int ie = pmb->ie; int je = pmb->je; int ke = pmb->ke;
int il, iu, jl, ju, kl, ku;
AthenaArray<Real> b1,b2,b3,ei_x1f,ei_x2f,ei_x3f,w_x1f,w_x2f,w_x3f;
if (MAGNETIC_FIELDS_ENABLED) {
b1.InitWithShallowCopy(b.x1f);
b2.InitWithShallowCopy(b.x2f);
b3.InitWithShallowCopy(b.x3f);
ei_x1f.InitWithShallowCopy(pmb->pfield->ei.x1f);
ei_x2f.InitWithShallowCopy(pmb->pfield->ei.x2f);
ei_x3f.InitWithShallowCopy(pmb->pfield->ei.x3f);
w_x1f.InitWithShallowCopy(pmb->pfield->wght.x1f);
w_x2f.InitWithShallowCopy(pmb->pfield->wght.x2f);
w_x3f.InitWithShallowCopy(pmb->pfield->wght.x3f);
}
int tid=0;
int nthreads = pmb->pmy_mesh->GetNumMeshThreads();
#pragma omp parallel default(shared) private(tid) num_threads(nthreads)
{
#ifdef OPENMP_PARALLEL
tid=omp_get_thread_num();
#endif
AthenaArray<Real> wl, wr, flx, dxw;
wl.InitWithShallowSlice(wl_,3,tid,1);
wr.InitWithShallowSlice(wr_,3,tid,1);
flx.InitWithShallowSlice(flx_,3,tid,1);
dxw.InitWithShallowSlice(dxw_,2,tid,1);
//----------------------------------------------------------------------------------------
// i-direction
// set the loop limits
jl=js, ju=je, kl=ks, ku=ke;
if (MAGNETIC_FIELDS_ENABLED) {
if(pmb->block_size.nx2 > 1) {
if(pmb->block_size.nx3 == 1) // 2D
jl=js-1, ju=je+1, kl=ks, ku=ke;
else // 3D
jl=js-1, ju=je+1, kl=ks-1, ku=ke+1;
}
}
for (int k=kl; k<=ku; ++k){
#pragma omp for schedule(static)
for (int j=jl; j<=ju; ++j){
// reconstruct L/R states
if (reconstruct_order == 1) {
pmb->precon->DonorCellX1(k,j,is,ie+1,w,bcc,wl,wr);
} else {
pmb->precon->PiecewiseLinearX1(k,j,is,ie+1,w,bcc,wl,wr);
}
// compute fluxes
RiemannSolver(k,j,is,ie+1,IVX,b1,wl,wr,flx);
// store fluxes
if(k>=ks && k<=ke && j>=js && j<=je) {
for(int n=0; n<NHYDRO; n++) {
#pragma simd
for(int i=is; i<=ie+1; i++)
x1flux(n,k,j,i)=flx(n,i);
}
}
// store electric fields, compute weights for GS07 CT algorithm
// no correction to the EMFs is required; they are corrected later
if (MAGNETIC_FIELDS_ENABLED) {
pmb->pcoord->CenterWidth1(k,j,is,ie+1,dxw);
#pragma simd
for (int i=is; i<=ie+1; ++i){
ei_x1f(X1E3,k,j,i) = -flx(IBY,i); // flux(IBY) = (v1*b2 - v2*b1) = -EMFZ
ei_x1f(X1E2,k,j,i) = flx(IBZ,i); // flux(IBZ) = (v1*b3 - v3*b1) = EMFY
Real v_over_c = (1024.0)*(pmb->pmy_mesh->dt)*flx(IDN,i)
/ (dxw(i)*(wl(IDN,i) + wr(IDN,i)));
Real tmp_min = std::min(0.5,v_over_c);
w_x1f(k,j,i) = 0.5 + std::max(-0.5,tmp_min);
}
}
}
}
//----------------------------------------------------------------------------------------
// j-direction
if (pmb->block_size.nx2 > 1) {
// set the loop limits
il=is, iu=ie, kl=ks, ku=ke;
if (MAGNETIC_FIELDS_ENABLED) {
if(pmb->block_size.nx3 == 1) // 2D
il=is-1, iu=ie+1, kl=ks, ku=ke;
else // 3D
il=is-1, iu=ie+1, kl=ks-1, ku=ke+1;
}
for (int k=kl; k<=ku; ++k){
#pragma omp for schedule(static)
for (int j=js; j<=je+1; ++j){
// reconstruct L/R states at j
if (reconstruct_order == 1) {
pmb->precon->DonorCellX2(k,j,il,iu,w,bcc,wl,wr);
} else {
pmb->precon->PiecewiseLinearX2(k,j,il,iu,w,bcc,wl,wr);
}
// compute fluxes at j
RiemannSolver(k,j,il,iu,IVY,b2,wl,wr,flx);
// store fluxes
if(k>=ks && k<=ke) {
for(int n=0; n<NHYDRO; n++) {
#pragma simd
for(int i=is; i<=ie; i++)
x2flux(n,k,j,i)=flx(n,i);
}
}
// store electric fields, compute weights for GS07 CT algorithm
// no correction to the EMFs is required; they are corrected later
if (MAGNETIC_FIELDS_ENABLED) {
pmb->pcoord->CenterWidth2(k,j,il,iu,dxw);
#pragma simd
for (int i=il; i<=iu; ++i){
ei_x2f(X2E1,k,j,i) = -flx(IBY,i); // flx(IBY) = (v2*b3 - v3*b2) = -EMFX
ei_x2f(X2E3,k,j,i) = flx(IBZ,i); // flx(IBZ) = (v2*b1 - v1*b2) = EMFZ
Real v_over_c = (1024.0)*(pmb->pmy_mesh->dt)*flx(IDN,i)
/ (dxw(i)*(wl(IDN,i) + wr(IDN,i)));
Real tmp_min = std::min(0.5,v_over_c);
w_x2f(k,j,i) = 0.5 + std::max(-0.5,tmp_min);
}
}
}
}
}
//----------------------------------------------------------------------------------------
// k-direction
if (pmb->block_size.nx3 > 1) {
// set the loop limits
il=is, iu=ie, jl=js, ju=je;
if (MAGNETIC_FIELDS_ENABLED)
il=is-1, iu=ie+1, jl=js-1, ju=je+1;
#pragma omp for schedule(static)
for (int k=ks; k<=ke+1; ++k){
for (int j=jl; j<=ju; ++j){
// reconstruct L/R states at k
if (reconstruct_order == 1) {
pmb->precon->DonorCellX3(k,j,il,iu,w,bcc,wl,wr);
} else {
pmb->precon->PiecewiseLinearX3(k,j,il,iu,w,bcc,wl,wr);
}
// compute fluxes at k
RiemannSolver(k,j,il,iu,IVZ,b3,wl,wr,flx);
if(j>=js && j<=je) {
for(int n=0; n<NHYDRO; n++) {
#pragma simd
for(int i=is; i<=ie; i++)
x3flux(n,k,j,i)=flx(n,i);
}
}
// store electric fields, compute weights for GS07 CT algorithm
// no correction to the EMFs is required; they are corrected later
if (MAGNETIC_FIELDS_ENABLED) {
pmb->pcoord->CenterWidth3(k,j,il,iu,dxw);
#pragma simd
for (int i=il; i<=iu; ++i){
ei_x3f(X3E2,k,j,i) = -flx(IBY,i); // flx(IBY) = (v3*b1 - v1*b3) = -EMFY
ei_x3f(X3E1,k,j,i) = flx(IBZ,i); // flx(IBZ) = (v3*b2 - v2*b3) = EMFX
Real v_over_c = (1024.0)*(pmb->pmy_mesh->dt)*flx(IDN,i)
/ (dxw(i)*(wl(IDN,i) + wr(IDN,i)));
Real tmp_min = std::min(0.5,v_over_c);
w_x3f(k,j,i) = 0.5 + std::max(-0.5,tmp_min);
}
}
}
}
}
} // end of omp parallel region
return;
}
|
// Copyright (c) 2021 PaddlePaddle Authors. 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.
#include "paddle/fluid/distributed/fleet_executor/fleet_executor.h"
#include "paddle/fluid/distributed/fleet_executor/carrier.h"
#include "paddle/fluid/distributed/fleet_executor/message_bus.h"
#include "paddle/fluid/distributed/fleet_executor/runtime_graph.h"
#include "paddle/fluid/distributed/fleet_executor/task_node.h"
#include "paddle/fluid/framework/executor_gc_helper.h"
#include "paddle/fluid/framework/op_desc.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/variable_helper.h"
namespace paddle {
namespace distributed {
FleetExecutor::FleetExecutor(const std::string& exe_desc_str) {
bool parse_flag = exe_desc_.ParseFromString(exe_desc_str);
PADDLE_ENFORCE(parse_flag, platform::errors::PreconditionNotMet(
"Error occurs while parsing string to proto"));
}
FleetExecutor::~FleetExecutor() {
root_scope_->DropKids();
GetCarrier().Release();
}
Carrier& FleetExecutor::GetCarrier() {
static Carrier carrier;
return carrier;
}
void FleetExecutor::Init(
const framework::ProgramDesc& program_desc, framework::Scope* scope,
const platform::Place& place, const std::vector<TaskNode*>& task_nodes,
const std::unordered_map<int64_t, int64_t>& task_id_to_rank) {
PADDLE_ENFORCE_GT(task_nodes.size(), 0,
platform::errors::InvalidArgument(
"Fleet executor is inited with empty task node"));
// TODO(fleet_exe devs): the unused_vars should be got from run time graph
std::vector<std::unique_ptr<framework::OperatorBase>> ops;
for (auto task_node : task_nodes) {
for (auto op : task_node->ops()) {
ops.emplace_back(std::unique_ptr<framework::OperatorBase>(op));
}
}
auto unused_vars = framework::GetUnusedVars(program_desc.Block(0), ops, {});
runtime_graph_ = std::make_shared<RuntimeGraph>();
std::unordered_map<int64_t, TaskNode*> interceptor_id_to_task;
for (auto task_node : task_nodes) {
task_node->SetUnusedVars(unused_vars);
int64_t interceptor_id = task_node->task_id();
interceptor_id_to_task.emplace(interceptor_id, task_node);
}
runtime_graph_->SetInterceptorIdToRank(task_id_to_rank);
runtime_graph_->SetInterceptorIdToNode(interceptor_id_to_task);
for (auto& unique_op : ops) {
unique_op.release();
}
root_scope_ = scope;
place_ = place;
PADDLE_ENFORCE_NOT_NULL(root_scope_, platform::errors::InvalidArgument(
"root_scope_ can not be nullptr"));
minibatch_scope_ = &root_scope_->NewScope();
int64_t num_micro_batches = exe_desc_.num_micro_batches();
microbatch_scopes_.resize(num_micro_batches);
for (int i = 0; i < num_micro_batches; ++i) {
microbatch_scopes_[i] = &minibatch_scope_->NewScope();
CopyParameters(i, program_desc);
}
VLOG(5) << runtime_graph_->DebugString();
msg_bus_ = std::make_shared<MessageBus>();
InitCarrier();
InitMessageBus();
}
void FleetExecutor::InitCarrier() {
Carrier& carrier = GetCarrier();
if (!carrier.IsInit()) {
carrier.SetMsgBus(msg_bus_);
carrier.Init(runtime_graph_, root_scope_, minibatch_scope_,
microbatch_scopes_, place_);
}
}
void FleetExecutor::InitMessageBus() {
std::stringstream ss;
ss << "\nThe DNS table of the message bus is: \n";
int64_t cur_rank = exe_desc_.cur_rank();
std::unordered_map<int64_t, std::string> rank_to_addr;
std::string addr;
for (const auto& rank_info : exe_desc_.cluster_info()) {
// init the dns map
int64_t rank = rank_info.rank();
std::string ip_port = rank_info.ip_port();
ss << rank << "\t->\t" << ip_port << "\n";
rank_to_addr.insert(std::make_pair(rank, ip_port));
if (rank == cur_rank) {
addr = ip_port;
}
}
if (addr == "") {
PADDLE_ENFORCE_EQ(
rank_to_addr.size(), 1,
platform::errors::NotFound("Empty address is not valid for "
"paddle.distributed.launch method."));
PADDLE_ENFORCE_EQ(
cur_rank, 0,
platform::errors::NotFound("Address is empty but cur rank is not 0."));
}
VLOG(3) << "Current rank is " << cur_rank << " and the ip_port is "
<< (addr == "" ? "empty" : addr) << ".";
VLOG(3) << "The number of ranks are "
<< (rank_to_addr.size() == 0 ? 1 : rank_to_addr.size()) << ".";
VLOG(5) << ss.str();
if (!msg_bus_->IsInit()) {
msg_bus_->Init(runtime_graph_->intercepter_id_to_rank(), rank_to_addr,
addr);
}
}
void FleetExecutor::Run() {
// Run
Carrier& carrier = GetCarrier();
PADDLE_ENFORCE_EQ(
carrier.IsInit(), true,
platform::errors::Unavailable("Carrier has not been init yet."));
PADDLE_ENFORCE_EQ(
msg_bus_->IsInit(), true,
platform::errors::Unavailable("MessageBus has not been init yet."));
carrier.Start();
for (auto* micro_scop : microbatch_scopes_) {
// By default, we should delete all kid scopes after run executor because
// some operators may create local scope when running, such as while_op.
// But when while_op also create a local executor to run it's sub block,
// the sub scopes it created should not be dropped immediately, because
// while_grad_op will use some variables created during while_op run, so
// we need to keep the kids and wait for the outer executor to drop them.
micro_scop->DropKids();
}
}
void FleetExecutor::CopyParameters(int microbatch_id,
const framework::ProgramDesc& program) {
auto& global_block = program.Block(0);
for (auto& var : global_block.AllVars()) {
if (var->Persistable() && microbatch_id == 0) {
auto* ptr = root_scope_->Var(var->Name());
InitializeVariable(ptr, var->GetType());
VLOG(5) << "Create persistable var: " << var->Name()
<< ", which pointer is " << ptr;
} else if (!var->Persistable()) {
auto* ptr = microbatch_scopes_[microbatch_id]->Var(var->Name());
VLOG(5) << "Create variable " << var->Name() << " for microbatch "
<< microbatch_id << ", which pointer is " << ptr << ".";
InitializeVariable(ptr, var->GetType());
}
}
}
} // namespace distributed
} // namespace paddle
|
//Author: Austin Whaley, APW5450, 2019-04-13
//Class: CMPSC 121
//Activity: 24
//File: cmpsc121/homework/module_13/M13A24_apw5450.cpp
//Purpose: Fun with Vectors
/********************************************************************\
* Academic Integrity Affidavit: *
* I certify that, this program code is my work. Others may have *
* assisted me with planning and concepts, but the code was written, *
* solely, by me. *
* I understand that submitting code which is totally or partially *
* the product of other individuals is a violation of the Academic *
* Integrity Policy and accepted ethical precepts. Falsified *
* execution results are also results of improper activities. Such *
* violations may result in zero credit for the assignment, reduced *
* credit for the assignment, or course failure. *
\********************************************************************/
/*
Write program using parallel vectors and a function which fills each of them
with 500 random numbers between 1 and 100.
Then pass both vectors to a function which will return an integer indicating
a count of how many times both vectors had even number in the same location
*/
#include <iostream>
#include <vector>
#include <ctime> // time()
#include <cstdlib> // srand(), rand()
using namespace std;
//Function Prototypes
int count_even_in_same_position(vector<int>, vector<int>);
int main() {
const int MIN = 1, MAX = 100;
vector<int> parallel_1(500, 0); //Initialize 500 elements of 0
vector<int> parallel_2(500, 0); //Initialize 500 elements of 0
int r, count;
unsigned seed = time(0);
srand(seed);
for(int i = 0; i < 500; i++){
r = (rand() % (MAX - MIN + 1)) + MIN;
parallel_1[i] = r;
r = (rand() % (MAX - MIN + 1)) + MIN;
parallel_2[i] = r;
}
//cout << "Size parallel_1: " << parallel_1.size() << endl; //DEBUG
//cout << "Size parallel_2: " << parallel_2.size() << endl; //DEBUG
count = count_even_in_same_position(parallel_1, parallel_2);
cout << "The Vector contains " << count << " elements where both values are even" \
<< endl;
return 0;
} // end main
// Functions
int count_even_in_same_position(vector<int> p1, vector<int> p2){
int count=0;
for (int i = 0; i < p1.size(); i++){
if (p1[i]%2==0 && p2[i]%2==0){
count+=1;
} // end if-statement
} // end for-loop
return count;
}
/* Execution Sample
The Vector contains 130 elements where both values are even
*/
|
/*
-----------------------------------------------------------------------------------------------
Copyright (C) 2013 Henry van Merode. All rights reserved.
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.
-----------------------------------------------------------------------------------------------
*/
#include "ParticleUniversePCH.h"
#ifndef PARTICLE_UNIVERSE_EXPORTS
#define PARTICLE_UNIVERSE_EXPORTS
#endif
#include "ParticleRenderers/ParticleUniverseBoxSet.h"
#include "ParticleRenderers/ParticleUniverseBox.h"
#include "OgreNode.h"
#include "OgreHardwareBufferManager.h"
#include "OgreRoot.h"
namespace ParticleUniverse
{
//-----------------------------------------------------------------------
BoxSet::BoxSet(void) :
PrimitiveShapeSet(),
mAutoExtendPool(true),
mVertexData(0),
mIndexData(0),
mBuffersCreated(false),
mPoolSize(0),
mExternalData(false)
{
setDefaultDimensions(100, 100, 100);
_initTextCoord();
}
//-----------------------------------------------------------------------
BoxSet::BoxSet(const String& name, unsigned int poolSize, bool externalData) :
PrimitiveShapeSet(name, poolSize, externalData),
mAutoExtendPool(true),
mVertexData(0),
mIndexData(0),
mBuffersCreated(false),
mPoolSize(poolSize),
mExternalData(externalData)
{
setDefaultDimensions(100, 100, 100);
setPoolSize(poolSize);
_initTextCoord();
}
//-----------------------------------------------------------------------
BoxSet::~BoxSet(void)
{
// Free pool items
BoxPool::iterator i;
for (i = mBoxPool.begin(); i != mBoxPool.end(); ++i)
{
PU_DELETE *i;
}
// Delete buffers
_destroyBuffers();
}
//-----------------------------------------------------------------------
Box* BoxSet::createBox(const Vector3& position)
{
if(mFreeBoxes.empty())
{
if(mAutoExtendPool)
{
setPoolSize(getPoolSize() * 2);
}
else
{
return 0;
}
}
// Get a new box
Box* newBox = mFreeBoxes.front();
mActiveBoxes.splice(mActiveBoxes.end(), mFreeBoxes, mFreeBoxes.begin());
newBox->setPosition(position);
newBox->resetDimensions();
newBox->_notifyOwner(this);
// Merge
Real adjust = std::max(mDefaultWidth, mDefaultHeight);
adjust = std::max(adjust, mDefaultDepth);
Vector3 vecAdjust(adjust, adjust, adjust);
Vector3 newMin = position - vecAdjust;
Vector3 newMax = position + vecAdjust;
mAABB.merge(newMin);
mAABB.merge(newMax);
Real sqlen = std::max(newMin.squaredLength(), newMax.squaredLength());
mBoundingRadius = std::max(mBoundingRadius, Math::Sqrt(sqlen));
return newBox;
}
//-----------------------------------------------------------------------
Box* BoxSet::createBox(Real x, Real y, Real z)
{
return createBox(Vector3( x, y, z ));
}
//-----------------------------------------------------------------------
unsigned int BoxSet::getNumBoxes(void) const
{
return static_cast<int>(mActiveBoxes.size());
}
//-----------------------------------------------------------------------
void BoxSet::clear(void)
{
mFreeBoxes.splice(mFreeBoxes.end(), mActiveBoxes);
}
//-----------------------------------------------------------------------
Box* BoxSet::getBox(unsigned int index) const
{
assert(index < mActiveBoxes.size() && "Box index out of bounds." );
ActiveBoxList::const_iterator it;
if(index >= (mActiveBoxes.size() >> 1))
{
index = static_cast<unsigned int>(mActiveBoxes.size()) - index;
for(it = mActiveBoxes.end(); index; --index, --it );
}
else
{
for(it = mActiveBoxes.begin(); index; --index, ++it );
}
return *it;
}
//-----------------------------------------------------------------------
void BoxSet::removeBox(unsigned int index)
{
assert(index < mActiveBoxes.size() && "Box index out of bounds." );
ActiveBoxList::iterator it;
if(index >= (mActiveBoxes.size() >> 1 ))
{
index = static_cast<unsigned int>(mActiveBoxes.size()) - index;
for(it = mActiveBoxes.end(); index; --index, --it );
}
else
{
for(it = mActiveBoxes.begin(); index; --index, ++it );
}
mFreeBoxes.splice(mFreeBoxes.end(), mActiveBoxes, it);
}
//-----------------------------------------------------------------------
void BoxSet::removeBox(Box* box)
{
ActiveBoxList::iterator it = std::find(mActiveBoxes.begin(), mActiveBoxes.end(), box);
assert(it != mActiveBoxes.end() && "Box isn't in the active list." );
mFreeBoxes.splice(mFreeBoxes.end(), mActiveBoxes, it);
}
//-----------------------------------------------------------------------
void BoxSet::setDefaultDimensions(Real width, Real height, Real depth)
{
mDefaultWidth = width;
mDefaultHeight = height;
mDefaultDepth = depth;
mDefaultHalfWidth = 0.5f * width;
mDefaultHalfHeight = 0.5f * height;
mDefaultHalfDepth = 0.5f * depth;
_genDefaultCorners();
}
//-----------------------------------------------------------------------
void BoxSet::setDefaultWidth(Real width)
{
mDefaultWidth = width;
mDefaultHalfWidth = 0.5f * width;
_genDefaultCorners();
}
//-----------------------------------------------------------------------
Real BoxSet::getDefaultWidth(void) const
{
return mDefaultWidth;
}
//-----------------------------------------------------------------------
void BoxSet::setDefaultHeight(Real height)
{
mDefaultHeight = height;
mDefaultHalfHeight = 0.5f * height;
_genDefaultCorners();
}
//-----------------------------------------------------------------------
Real BoxSet::getDefaultHeight(void) const
{
return mDefaultHeight;
}
//-----------------------------------------------------------------------
void BoxSet::setDefaultDepth(Real depth)
{
mDefaultDepth = depth;
mDefaultHalfDepth = 0.5f * depth;
_genDefaultCorners();
}
//-----------------------------------------------------------------------
Real BoxSet::getDefaultDepth(void) const
{
return mDefaultDepth;
}
//-----------------------------------------------------------------------
void BoxSet::beginBoxes(size_t numBoxes)
{
// Create vertex / index buffers
if(!mBuffersCreated)
_createBuffers();
mNumVisibleBoxes = 0;
if (numBoxes)
{
size_t boxSize;
numBoxes = std::min(mPoolSize, numBoxes);
// Corners of the box + extra vertices for texture mapping
boxSize = mMainBuf->getVertexSize() * 16;
assert (numBoxes * boxSize <= mMainBuf->getSizeInBytes());
mLockPtr = static_cast<float*>(
mMainBuf->lock(0, numBoxes * boxSize,
Ogre::HardwareBuffer::HBL_DISCARD));
}
else // lock the entire thing
mLockPtr = static_cast<float*>(
mMainBuf->lock(Ogre::HardwareBuffer::HBL_DISCARD) );
}
//-----------------------------------------------------------------------
void BoxSet::injectBox(Box& box)
{
if (mNumVisibleBoxes == mPoolSize) return;
if (!boxVisible(mCurrentCamera, box)) return;
// Generate vertices
_genVertices(box);
mNumVisibleBoxes++;
}
//-----------------------------------------------------------------------
void BoxSet::endBoxes(void)
{
mMainBuf->unlock();
}
//-----------------------------------------------------------------------
void BoxSet::setBounds(const AxisAlignedBox& box, Real radius)
{
mAABB = box;
mBoundingRadius = radius;
}
//-----------------------------------------------------------------------
void BoxSet::_updateBounds(void)
{
if (mActiveBoxes.empty())
{
// No boxes
mAABB.setNull();
mBoundingRadius = 0.0f;
}
else
{
Real maxSqLen = -1.0f;
Vector3 min(Math::POS_INFINITY, Math::POS_INFINITY, Math::POS_INFINITY);
Vector3 max(Math::NEG_INFINITY, Math::NEG_INFINITY, Math::NEG_INFINITY);
ActiveBoxList::iterator i, iend;
iend = mActiveBoxes.end();
for (i = mActiveBoxes.begin(); i != iend; ++i)
{
const Vector3& pos = (*i)->getPosition();
min.makeFloor(pos);
max.makeCeil(pos);
maxSqLen = std::max(maxSqLen, pos.squaredLength());
}
Real adjust = std::max(mDefaultWidth, mDefaultHeight);
Vector3 vecAdjust(adjust, adjust, adjust);
min -= vecAdjust;
max += vecAdjust;
mAABB.setExtents(min, max);
mBoundingRadius = Math::Sqrt(maxSqLen);
}
if (mParentNode)
mParentNode->needUpdate();
}
//-----------------------------------------------------------------------
void BoxSet::_updateRenderQueue(Ogre::RenderQueue* queue)
{
if (!mExternalData)
{
beginBoxes(mActiveBoxes.size());
ActiveBoxList::iterator it;
ActiveBoxList::iterator itEnd = mActiveBoxes.end();
for(it = mActiveBoxes.begin(); it != itEnd; ++it)
{
injectBox(*(*it));
}
endBoxes();
}
if( mRenderQueueIDSet )
{
queue->addRenderable(this, mRenderQueueID);
}
else
{
queue->addRenderable(this);
}
}
//-----------------------------------------------------------------------
void BoxSet::getRenderOperation(Ogre::RenderOperation& op)
{
op.vertexData = mVertexData;
op.vertexData->vertexStart = 0;
op.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
op.useIndexes = true;
op.vertexData->vertexCount = mNumVisibleBoxes * 16;
op.indexData = mIndexData;
op.indexData->indexCount = mNumVisibleBoxes * 36; // 36 indices
op.indexData->indexStart = 0;
}
//-----------------------------------------------------------------------
void BoxSet::setAutoextend(bool autoextend)
{
mAutoExtendPool = autoextend;
}
//-----------------------------------------------------------------------
bool BoxSet::isAutoextend(void) const
{
return mAutoExtendPool;
}
//-----------------------------------------------------------------------
void BoxSet::setPoolSize(size_t size)
{
if (!mExternalData)
{
size_t currSize = mBoxPool.size();
if (currSize >= size)
return;
this->increasePool(size);
for(size_t i = currSize; i < size; ++i)
{
// Add new items to the queue
mFreeBoxes.push_back(mBoxPool[i]);
}
}
mPoolSize = size;
_destroyBuffers();
}
//-----------------------------------------------------------------------
void BoxSet::_createBuffers(void)
{
// Create vertex buffer
mVertexData = PU_NEW Ogre::VertexData();
mVertexData->vertexCount = mPoolSize * 16;
mVertexData->vertexStart = 0;
Ogre::VertexDeclaration* decl = mVertexData->vertexDeclaration;
Ogre::VertexBufferBinding* binding = mVertexData->vertexBufferBinding;
// Create Vertices, Colour and Texture Coordinates
size_t offset = 0;
decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
// decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL);
// offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
decl->addElement(0, offset, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE);
offset += Ogre::VertexElement::getTypeSize(Ogre::VET_COLOUR);
decl->addElement(0, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, 0);
mMainBuf =
Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(0),
mVertexData->vertexCount,
Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
// Bind
binding->setBinding(0, mMainBuf);
// Create indices
const size_t ibufCount = 36;
mIndexData = PU_NEW Ogre::IndexData();
mIndexData->indexStart = 0;
mIndexData->indexCount = mPoolSize * ibufCount;
mIndexData->indexBuffer = Ogre::HardwareBufferManager::getSingleton().
createIndexBuffer(Ogre::HardwareIndexBuffer::IT_16BIT,
mIndexData->indexCount,
Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
ushort* pIdx = static_cast<ushort*>(
mIndexData->indexBuffer->lock(0,
mIndexData->indexBuffer->getSizeInBytes(),
Ogre::HardwareBuffer::HBL_DISCARD));
for(size_t idx, idxOff, box = 0; box < mPoolSize; ++box)
{
// Do indexes
idx = box * ibufCount;
idxOff = box * 16;
pIdx[idx] = static_cast<unsigned short>(idxOff + 4);
pIdx[idx+1] = static_cast<unsigned short>(idxOff + 6);
pIdx[idx+2] = static_cast<unsigned short>(idxOff + 2);
pIdx[idx+3] = static_cast<unsigned short>(idxOff + 2);
pIdx[idx+4] = static_cast<unsigned short>(idxOff + 0);
pIdx[idx+5] = static_cast<unsigned short>(idxOff + 4);
pIdx[idx+6] = static_cast<unsigned short>(idxOff + 1);
pIdx[idx+7] = static_cast<unsigned short>(idxOff + 3);
pIdx[idx+8] = static_cast<unsigned short>(idxOff + 7);
pIdx[idx+9] = static_cast<unsigned short>(idxOff + 7);
pIdx[idx+10] = static_cast<unsigned short>(idxOff + 5);
pIdx[idx+11] = static_cast<unsigned short>(idxOff + 1);
pIdx[idx+12] = static_cast<unsigned short>(idxOff + 8);
pIdx[idx+13] = static_cast<unsigned short>(idxOff + 9);
pIdx[idx+14] = static_cast<unsigned short>(idxOff + 13);
pIdx[idx+15] = static_cast<unsigned short>(idxOff + 13);
pIdx[idx+16] = static_cast<unsigned short>(idxOff + 12);
pIdx[idx+17] = static_cast<unsigned short>(idxOff + 8);
pIdx[idx+18] = static_cast<unsigned short>(idxOff + 10);
pIdx[idx+19] = static_cast<unsigned short>(idxOff + 14);
pIdx[idx+20] = static_cast<unsigned short>(idxOff + 15);
pIdx[idx+21] = static_cast<unsigned short>(idxOff + 15);
pIdx[idx+22] = static_cast<unsigned short>(idxOff + 11);
pIdx[idx+23] = static_cast<unsigned short>(idxOff + 10);
pIdx[idx+24] = static_cast<unsigned short>(idxOff + 8);
pIdx[idx+25] = static_cast<unsigned short>(idxOff + 10);
pIdx[idx+26] = static_cast<unsigned short>(idxOff + 11);
pIdx[idx+27] = static_cast<unsigned short>(idxOff + 11);
pIdx[idx+28] = static_cast<unsigned short>(idxOff + 9);
pIdx[idx+29] = static_cast<unsigned short>(idxOff + 8);
pIdx[idx+30] = static_cast<unsigned short>(idxOff + 4);
pIdx[idx+31] = static_cast<unsigned short>(idxOff + 5);
pIdx[idx+32] = static_cast<unsigned short>(idxOff + 7);
pIdx[idx+33] = static_cast<unsigned short>(idxOff + 7);
pIdx[idx+34] = static_cast<unsigned short>(idxOff + 6);
pIdx[idx+35] = static_cast<unsigned short>(idxOff + 4);
}
mIndexData->indexBuffer->unlock();
mBuffersCreated = true;
}
//-----------------------------------------------------------------------
void BoxSet::_destroyBuffers(void)
{
if (mVertexData)
{
PU_DELETE mVertexData;
mVertexData = 0;
}
if (mIndexData)
{
PU_DELETE mIndexData;
mIndexData = 0;
}
mMainBuf.reset();
mBuffersCreated = false;
}
//-----------------------------------------------------------------------
unsigned int BoxSet::getPoolSize(void) const
{
return static_cast<unsigned int>(mBoxPool.size());
}
//-----------------------------------------------------------------------
bool BoxSet::boxVisible(Camera* cam, const Box& box)
{
// If not individually culled it is always visible
if (!mCullIndividual) return true;
// Culling based on sphere
SimpleSphere sph;
Ogre::Matrix4 xworld;
getWorldTransforms(&xworld);
sph.setCenter(xworld*box.mPosition);
if (box.mOwnDimensions)
{
Real max = std::max(box.mWidth, box.mHeight);
max = std::max(box.mDepth, max);
sph.setRadius(max);
}
else
{
Real max = std::max(mDefaultWidth, mDefaultHeight);
max = std::max(mDefaultDepth, max);
sph.setRadius(max);
}
return cam->isVisible(sph);
}
//-----------------------------------------------------------------------
void BoxSet::increasePool(size_t size)
{
size_t oldSize = mBoxPool.size();
// Increase size
mBoxPool.reserve(size);
mBoxPool.resize(size);
// Create new boxes
for(size_t i = oldSize; i < size; ++i)
mBoxPool[i] = PU_NEW Box();
}
//-----------------------------------------------------------------------
void BoxSet::_genDefaultCorners(void)
{
mDefaultCorners[0].x = - mDefaultHalfWidth;
mDefaultCorners[0].y = - mDefaultHalfHeight;
mDefaultCorners[0].z = - mDefaultHalfDepth;
mDefaultCorners[1].x = mDefaultHalfWidth;
mDefaultCorners[1].y = - mDefaultHalfHeight;
mDefaultCorners[1].z = - mDefaultHalfDepth;
mDefaultCorners[2].x = - mDefaultHalfWidth;
mDefaultCorners[2].y = mDefaultHalfHeight;
mDefaultCorners[2].z = - mDefaultHalfDepth;
mDefaultCorners[3].x = mDefaultHalfWidth;
mDefaultCorners[3].y = mDefaultHalfHeight;
mDefaultCorners[3].z = - mDefaultHalfDepth;
mDefaultCorners[4].x = - mDefaultHalfWidth;
mDefaultCorners[4].y = - mDefaultHalfHeight;
mDefaultCorners[4].z = mDefaultHalfDepth;
mDefaultCorners[5].x = mDefaultHalfWidth;
mDefaultCorners[5].y = - mDefaultHalfHeight;
mDefaultCorners[5].z = mDefaultHalfDepth;
mDefaultCorners[6].x = - mDefaultHalfWidth;
mDefaultCorners[6].y = mDefaultHalfHeight;
mDefaultCorners[6].z = mDefaultHalfDepth;
mDefaultCorners[7].x = mDefaultHalfWidth;
mDefaultCorners[7].y = mDefaultHalfHeight;
mDefaultCorners[7].z = mDefaultHalfDepth;
mDefaultCorners[8].x = - mDefaultHalfWidth;
mDefaultCorners[8].y = - mDefaultHalfHeight;
mDefaultCorners[8].z = - mDefaultHalfDepth;
mDefaultCorners[9].x = mDefaultHalfWidth;
mDefaultCorners[9].y = - mDefaultHalfHeight;
mDefaultCorners[9].z = - mDefaultHalfDepth;
mDefaultCorners[10].x = - mDefaultHalfWidth;
mDefaultCorners[10].y = mDefaultHalfHeight;
mDefaultCorners[10].z = - mDefaultHalfDepth;
mDefaultCorners[11].x = mDefaultHalfWidth;
mDefaultCorners[11].y = mDefaultHalfHeight;
mDefaultCorners[11].z = - mDefaultHalfDepth;
mDefaultCorners[12].x = - mDefaultHalfWidth;
mDefaultCorners[12].y = - mDefaultHalfHeight;
mDefaultCorners[12].z = mDefaultHalfDepth;
mDefaultCorners[13].x = mDefaultHalfWidth;
mDefaultCorners[13].y = - mDefaultHalfHeight;
mDefaultCorners[13].z = mDefaultHalfDepth;
mDefaultCorners[14].x = - mDefaultHalfWidth;
mDefaultCorners[14].y = mDefaultHalfHeight;
mDefaultCorners[14].z = mDefaultHalfDepth;
mDefaultCorners[15].x = mDefaultHalfWidth;
mDefaultCorners[15].y = mDefaultHalfHeight;
mDefaultCorners[15].z = mDefaultHalfDepth;
}
//-----------------------------------------------------------------------
void BoxSet::_genVertices(Box& box)
{
Ogre::RGBA colour;
Ogre::Root::getSingleton().convertColourValue(box.mColour, &colour);
Ogre::RGBA* pCol;
if (!box.mOwnDimensions)
{
for (size_t i = 0; i < 16; ++i)
{
// Vertex
Ogre::Vector3 corner = Ogre::Vector3::ZERO;
if (box.mOrientation == Ogre::Quaternion::IDENTITY)
{
// Boxes didn�t rotate
corner = mDefaultCorners[i];
}
else
{
// Take box orientation into account
corner = box.mOrientation * mDefaultCorners[i];
}
*mLockPtr++ = corner.x + box.mPosition.x;
*mLockPtr++ = corner.y + box.mPosition.y;
*mLockPtr++ = corner.z + box.mPosition.z;
// Colour
pCol = static_cast<Ogre::RGBA*>(static_cast<void*>(mLockPtr));
*pCol++ = colour;
mLockPtr = static_cast<float*>(static_cast<void*>(pCol));
// Texture Coordinates
*mLockPtr++ = mTextCoord[i].x;
*mLockPtr++ = mTextCoord[i].y;
}
}
else
{
/** Loop twice through the corners of the box, because we have duplicated the number of
vertices, because of the texture mapping.
*/
size_t t = 0;
for (size_t i = 0; i < 2; ++i)
{
for (size_t j = 0; j < 8; ++j)
{
// Vertex: The box itself takes position and orientation into account
*mLockPtr++ = box.getWorldspaceCorner(j).x;
*mLockPtr++ = box.getWorldspaceCorner(j).y;
*mLockPtr++ = box.getWorldspaceCorner(j).z;
// Colour
pCol = static_cast<Ogre::RGBA*>(static_cast<void*>(mLockPtr));
*pCol++ = colour;
mLockPtr = static_cast<float*>(static_cast<void*>(pCol));
// Texture Coordinates
*mLockPtr++ = mTextCoord[t].x;
*mLockPtr++ = mTextCoord[t].y;
t++;
}
}
}
}
//-----------------------------------------------------------------------
const String& BoxSet::getMovableType(void) const
{
return BoxSetFactory::PU_FACTORY_TYPE_NAME;
}
//-----------------------------------------------------------------------
void BoxSet::_initTextCoord(void)
{
mTextCoord [0] = Vector2(0.0f, 0.0f);
mTextCoord [1] = Vector2(0.0f, 1.0f);
mTextCoord [2] = Vector2(0.5f, 0.0f);
mTextCoord [3] = Vector2(0.5f, 1.0f);
mTextCoord [4] = Vector2(0.0f, 0.33f);
mTextCoord [5] = Vector2(0.0f, 0.66f);
mTextCoord [6] = Vector2(0.5f, 0.33f);
mTextCoord [7] = Vector2(0.5f, 0.66f);
mTextCoord [8] = Vector2(0.5f, 0.33f);
mTextCoord [9] = Vector2(1.0f, 0.33f);
mTextCoord [10] = Vector2(0.5f, 0.66f);
mTextCoord [11] = Vector2(1.0f, 0.66f);
mTextCoord [12] = Vector2(0.5f, 0.0f);
mTextCoord [13] = Vector2(1.0f, 0.0f);
mTextCoord [14] = Vector2(0.5f, 1.0f);
mTextCoord [15] = Vector2(1.0f, 1.0f);
}
//-----------------------------------------------------------------------
String BoxSetFactory::PU_FACTORY_TYPE_NAME = "BoxSet";
//-----------------------------------------------------------------------
const String& BoxSetFactory::getType(void) const
{
return PU_FACTORY_TYPE_NAME;
}
//-----------------------------------------------------------------------
Ogre::MovableObject* BoxSetFactory::createInstanceImpl(const String& name, const Ogre::NameValuePairList* params)
{
bool externalData = false;
unsigned int poolSize = 0;
if (params != 0)
{
Ogre::NameValuePairList::const_iterator ni = params->find("poolSize");
if (ni != params->end())
{
poolSize = StringConverter::parseUnsignedInt(ni->second);
}
ni = params->find("externalData");
if (ni != params->end())
{
externalData = StringConverter::parseBool(ni->second);
}
}
if (poolSize > 0)
{
return PU_NEW BoxSet(name, poolSize, externalData);
}
else
{
return PU_NEW BoxSet(name);
}
}
//-----------------------------------------------------------------------
void BoxSetFactory::destroyInstance(Ogre::MovableObject* obj)
{
PU_DELETE obj;
}
}
|
#include "TcpRecorder.hpp"
#include <QDataStream>
#include <QDebug>
#include <QElapsedTimer>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkDatagram>
TcpRecorder::TcpRecorder(QObject *parent) : QThread(parent) {}
TcpRecorder::~TcpRecorder() { stop(); }
void TcpRecorder::start() { QThread::start(); }
void TcpRecorder::stop() {
quit();
wait();
}
void TcpRecorder::restart() {
stop();
start();
}
qint64 TcpRecorder::getCurrentTime() const {
QReadLocker locker(&mLock);
return mTimer.isNull() || !mTimer->isValid() ? 0 : mTimer->elapsed();
}
qint64 TcpRecorder::getCurrentFileSize() const {
QReadLocker locker(&mLock);
return mFile.isNull() ? 0 : mFile->size() - 1000;
}
void TcpRecorder::setPort(int port) {
QWriteLocker locker(&mLock);
mPort = port;
}
void TcpRecorder::setHostAddress(const QHostAddress &address) {
QWriteLocker locker(&mLock);
mHostAddress = address;
}
void TcpRecorder::setFileName(const QString &fileName) {
QWriteLocker locker(&mLock);
mFileName = fileName;
}
void TcpRecorder::readData() {
auto socket = qobject_cast<QTcpSocket *>(sender());
if (mTimer->isValid()) {
*mDataStream << mTimer->elapsed();
*mDataStream << socket->readAll();
}
}
void TcpRecorder::showError(QAbstractSocket::SocketError error) {
qWarning() << error;
}
void TcpRecorder::run() {
mFile = QSharedPointer<QFile>::create();
mDataStream = QSharedPointer<QDataStream>::create();
mTcpSocket = QSharedPointer<QTcpSocket>::create();
mTimer = QSharedPointer<QElapsedTimer>::create();
{
QReadLocker locker(&mLock);
mFile->setFileName(mFileName);
}
if (!mFile->open(QFile::WriteOnly)) {
QReadLocker locker(&mLock);
qWarning() << "Can not open file: " + mFileName;
return;
}
// FIXME: why can not connect this signal?
// connect(mUdpSocket.data(), &QUdpSocket::error, this,
// &UdpRecorder::showError);
{
QReadLocker locker(&mLock);
if (!mTcpSocket->bind(mHostAddress, quint16(mPort))) {
qWarning() << "Can not bind udp server: " + QString::number(mPort)
<< mTcpSocket->error();
return;
}
}
connect(mTcpSocket.data(), &QTcpSocket::readyRead, this,
&TcpRecorder::readData);
// Fill up data info segments with zero
mFile->write(QByteArray(1000, '0'));
mDataStream->setDevice(mFile.data());
mTimer->start();
exec();
auto time = mTimer->elapsed();
mTimer->invalidate();
// Data info
QJsonObject info;
info["FileSize"] = mFile->size();
info["TimeLength"] = time;
mFile->seek(0);
mFile->write(QJsonDocument(info).toJson(QJsonDocument::Compact));
mTcpSocket->close();
mFile->close();
mTcpSocket.clear();
mDataStream.clear();
mFile.clear();
mTimer.clear();
}
|
#include <et/app/application.h>
#include <et/core/notifytimer.h>
#include <et-ext/sensor/orientation.h>
namespace et
{
class OrientationManagerPrivate : public EventReceiver
{
public:
OrientationManagerPrivate(OrientationManager* m) :
_man(m), accelEnabled(false), gyroEnabled(false)
{
_timerAccel.expired.connect(this, &OrientationManagerPrivate::onTimerExpired);
_timerGyro.expired.connect(this, &OrientationManagerPrivate::onTimerExpired);
}
void setGyroEnabled(bool e)
{
if (gyroEnabled == e) return;
gyroEnabled = e;
if (gyroEnabled)
_timerGyro.start(mainTimerPool(), 1.0f, NotifyTimer::RepeatForever);
else
_timerGyro.cancelUpdates();
}
void setAccelEnabled(bool e)
{
if (accelEnabled == e) return;
accelEnabled = e;
if (accelEnabled)
_timerAccel.start(mainTimerPool(), 1.0f, NotifyTimer::RepeatForever);
else
_timerAccel.cancelUpdates();
}
void onTimerExpired(NotifyTimer* t)
{
if (t == &_timerAccel)
{
_man->accelerometerDataUpdated.invoke(_defaultAcceleration);
}
else if (t == &_timerGyro)
{
_man->gyroscopeDataUpdated.invoke(_defaultGyro);
}
}
public:
NotifyTimer _timerAccel;
NotifyTimer _timerGyro;
AccelerometerData _defaultAcceleration;
GyroscopeData _defaultGyro;
OrientationManager* _man = nullptr;
bool accelEnabled = false;
bool gyroEnabled = false;
};
}
using namespace et;
OrientationManager::OrientationManager()
{
ET_PIMPL_INIT(OrientationManager, this);
}
OrientationManager::~OrientationManager()
{
ET_PIMPL_FINALIZE(OrientationManager)
}
void OrientationManager::setAccelerometerEnabled(bool e)
{ _private->setAccelEnabled(e); }
bool OrientationManager::accelerometerEnabled() const
{ return _private->accelEnabled; }
void OrientationManager::setGyroscopeEnabled(bool e)
{ _private->setGyroEnabled(e); }
bool OrientationManager::gyroscopeEnabled() const
{ return _private->gyroEnabled; }
|
#include "gtest/gtest.h"
#include "gmock/gmock.h"
// Simple test, does not use gmock
TEST(Dummy, foobar) { EXPECT_EQ(1, 1); }
// Real class we want to mock
class TeaBreak {
public:
virtual ~TeaBreak() {}
// Return minutes taken to make the drinks
int morningTea() {
return makeCoffee(true, 1) + makeCoffee(false, 0.5) + makeHerbalTea();
}
private:
virtual int makeCoffee(bool milk, double sugars) = 0;
virtual int makeHerbalTea() = 0;
};
// Mock class
class MockTeaBreak : public TeaBreak {
public:
MOCK_METHOD2(makeCoffee, int(bool milk, double sugars));
MOCK_METHOD0(makeHerbalTea, int());
};
using ::testing::_;
using ::testing::Return;
// Mocked test
TEST(TeaBreakTest, MorningTea) {
MockTeaBreak teaBreak;
EXPECT_CALL(teaBreak, makeCoffee(_, _))
.WillOnce(Return(2))
.WillOnce(Return(1));
EXPECT_CALL(teaBreak, makeHerbalTea()).WillOnce(Return(3));
EXPECT_LE(teaBreak.morningTea(), 6);
}
|
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include "Configuration.hh"
#include "Environment.hh"
#include "Parameters.hh"
#include "Parser.hh"
#include "Executor.hh"
#include "config.hh"
void usage(const std::string& binary_name)
{
std::cerr << "Usage: " << binary_name << " <config_name>" << std::endl;
}
int main(int argc, char* argv[])
{
std::vector<std::string> arguments(argv, argv + argc);
if (arguments.size() != 2) {
usage(arguments.at(0));
return EXIT_FAILURE;
}
try {
Configuration c{CONFIGURATION_PATH, CONFIGURATION_EXTENSION, arguments.at(1)};
const Parser p{};
const Parameters ps{p.parseStream(c.getStream())};
const Environment env{"DISPLAY", "TMP", "TMPDIR", "USER", "XAUTHORITY"};
const Executor exe{QEMU_BINARY_PATH, env, ps};
exe.execute();
} catch (const std::runtime_error& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
#include "Monitor.h"
namespace WPEFramework {
namespace Plugin {
SERVICE_REGISTRATION(Monitor, 1, 0);
static Core::ProxyPoolType<Web::JSONBodyType<Core::JSON::ArrayType<Monitor::Data>>> jsonBodyDataFactory(2);
static Core::ProxyPoolType<Web::JSONBodyType<Monitor::Data>> jsonBodyParamFactory(2);
static Core::ProxyPoolType<Web::JSONBodyType<Monitor::Data::MetaData>> jsonMemoryBodyDataFactory(2);
/* virtual */ const string Monitor::Initialize(PluginHost::IShell* service)
{
_config.FromString(service->ConfigLine());
_skipURL = static_cast<uint8_t>(service->WebPrefix().length());
Core::JSON::ArrayType<Config::Entry>::Iterator index(_config.Observables.Elements());
// Create a list of plugins to monitor..
_monitor->Open(service, index);
// During the registartion, all Plugins, currently active are reported to the sink.
service->Register(_monitor);
// On succes return a name as a Callsign to be used in the URL, after the "service"prefix
return (_T(""));
}
/* virtual */ void Monitor::Deinitialize(PluginHost::IShell* service)
{
_monitor->Close();
service->Unregister(_monitor);
}
/* virtual */ string Monitor::Information() const
{
// No additional info to report.
return (nullptr);
}
/* virtual */ void Monitor::Inbound(Web::Request& request)
{
if ((request.Verb == Web::Request::HTTP_PUT) || (request.Verb == Web::Request::HTTP_POST))
request.Body(jsonBodyParamFactory.Element());
}
// <GET> ../ Get all Memory Measurments
// <GET> ../<Callsign> Get the Memory Measurements for Callsign
// <PUT> ../<Callsign> Reset the Memory measurements for Callsign
/* virtual */ Core::ProxyType<Web::Response> Monitor::Process(const Web::Request& request)
{
ASSERT(_skipURL <= request.Path.length());
Core::ProxyType<Web::Response> result(PluginHost::Factories::Instance().Response());
Core::TextSegmentIterator index(Core::TextFragment(request.Path, _skipURL, request.Path.length() - _skipURL), false, '/');
// If there is an entry, the first one will alwys be a '/', skip this one..
index.Next();
// By default, we assume everything works..
result->ErrorCode = Web::STATUS_OK;
result->Message = "OK";
if (request.Verb == Web::Request::HTTP_GET) {
// Let's list them all....
if (index.Next() == false) {
if (_monitor->Length() > 0) {
Core::ProxyType<Web::JSONBodyType<Core::JSON::ArrayType<Monitor::Data>>> response(jsonBodyDataFactory.Element());
_monitor->Snapshot(*response);
result->Body(Core::proxy_cast<Web::IBody>(response));
}
} else {
MetaData memoryInfo;
// Seems we only want 1 name
if (_monitor->Snapshot(index.Current().Text(), memoryInfo) == true) {
Core::ProxyType<Web::JSONBodyType<Monitor::Data::MetaData>> response(jsonMemoryBodyDataFactory.Element());
*response = memoryInfo;
result->Body(Core::proxy_cast<Web::IBody>(response));
}
}
result->ContentType = Web::MIME_JSON;
} else if ((request.Verb == Web::Request::HTTP_PUT) && (index.Next() == true)) {
MetaData memoryInfo;
// Seems we only want 1 name
if (_monitor->Reset(index.Current().Text(), memoryInfo) == true) {
Core::ProxyType<Web::JSONBodyType<Monitor::Data::MetaData>> response(jsonMemoryBodyDataFactory.Element());
*response = memoryInfo;
result->Body(Core::proxy_cast<Web::IBody>(response));
}
result->ContentType = Web::MIME_JSON;
} else if ((request.Verb == Web::Request::HTTP_POST) && (request.HasBody())) {
Core::ProxyType<const Monitor::Data> body(request.Body<const Monitor::Data>());
string observable = body->Observable.Value();
MonitorObjects::MonitorObject::RestartSettings operationalRestartSettings;
operationalRestartSettings.Limit = body->OperationalRestartSettings.Limit.Value();
operationalRestartSettings.WindowSeconds = body->OperationalRestartSettings.WindowSeconds.Value();
MonitorObjects::MonitorObject::RestartSettings memoryRestartSettings;
memoryRestartSettings.Limit = body->MemoryRestartSettings.Limit.Value();
memoryRestartSettings.WindowSeconds = body->MemoryRestartSettings.WindowSeconds.Value();
TRACE(Trace::Information, (_T("Sets Restart Limits: MEMORY:[LIMIT:%d, WINDOW:%d], OPERATIONAL:[LIMIT:%d, WINDOW:%d]"), memoryRestartSettings.Limit, memoryRestartSettings.WindowSeconds, operationalRestartSettings.Limit, operationalRestartSettings.WindowSeconds));
_monitor->Update(observable, operationalRestartSettings, memoryRestartSettings);
} else {
result->ErrorCode = Web::STATUS_BAD_REQUEST;
result->Message = _T(" could not handle your request.");
}
return (result);
}
}
}
|
#include "RectCollision.h"
#include "BaseCollision.h"
#include "BallCollision.h"
#include "Component.h"
#include <vector>
#include "raylib.h"
#include "../../include/raylib-cpp/include/raylib-cpp.hpp"
namespace pong
{
RectCollision::RectCollision(float w, float h) : width(w), height(h) {}
RectCollision::RectCollision(Vector2* pos, float w,float h) : RectCollision(w,h) { position = pos;}
RectCollision::~RectCollision() {}
void RectCollision::Update() { DrawDebug(); }
void RectCollision::Start() { position = &GetEntity()->position; }
void RectCollision::DrawDebug(raylib::Color col)
{
DrawRectangle(position->x, position->y, width, height, col);
DrawRectangleLines(position->x, position->y, width, height, col);
}
Rectangle RectCollision::GetRect()
{
return (Rectangle){position->x, position->y, width, height};
}
bool RectCollision::CheckCollision(Component *other) { return other->CheckCollision(this); }
bool RectCollision::CheckCollision(BaseCollision *other) { return other->CheckCollision(this); }
// Rect-ball collision
bool RectCollision::CheckCollision(BallCollision *other)
{
Rectangle rect = this->GetRect();
return CheckCollisionCircleRec(*other->position, other->radius, rect);
}
// Rect-Rect collision
bool RectCollision::CheckCollision(RectCollision *other)
{
return CheckCollisionRecs(this->GetRect(), other->GetRect());
}
bool RectCollision::IsNotOnScreen()
{
return CheckCollisionRecs(this->GetRect(), raylib::Rectangle(0, 0, GetScreenWidth(), GetScreenHeight()));
}
} // namespace pong
|
/*****************************************************************************
*
* Rokko: Integrated Interface for libraries of eigenvalue decomposition
*
* Copyright (C) 2017 by Rokko Developers https://github.com/t-sakashita/rokko
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*****************************************************************************/
#ifndef ROKKO_LAPACK_GETRS_HPP
#define ROKKO_LAPACK_GETRS_HPP
#include <complex>
#ifdef I
# undef I
#endif
#include <stdexcept>
#include <boost/type_traits/is_same.hpp>
#include <lapacke.h>
#include <rokko/traits/value_t.hpp>
#include "complex_cast.hpp"
namespace rokko {
namespace lapack {
namespace {
template<typename T> struct getrs_dispatch;
template<>
struct getrs_dispatch<float> {
template<typename MATRIX0, typename MATRIX1, typename VECTOR>
static lapack_int getrs(int matrix_layout, char trans, lapack_int n, lapack_int nrhs,
MATRIX0& a, VECTOR& ipiv, MATRIX1& b) {
return LAPACKE_sgetrs(matrix_layout, trans, n, nrhs, storage(a), ld(a), storage(ipiv),
storage(b), ld(b));
}
};
template<>
struct getrs_dispatch<double> {
template<typename MATRIX0, typename MATRIX1, typename VECTOR>
static lapack_int getrs(int matrix_layout, char trans, lapack_int n, lapack_int nrhs,
MATRIX0& a, VECTOR& ipiv, MATRIX1& b) {
return LAPACKE_dgetrs(matrix_layout, trans, n, nrhs, storage(a), ld(a), storage(ipiv),
storage(b), ld(b));
}
};
template<>
struct getrs_dispatch<std::complex<float>> {
template<typename MATRIX0, typename MATRIX1, typename VECTOR>
static lapack_int getrs(int matrix_layout, char trans, lapack_int n, lapack_int nrhs,
MATRIX0& a, VECTOR& ipiv, MATRIX1& b) {
return LAPACKE_cgetrs(matrix_layout, trans, n, nrhs, complex_cast(storage(a)), ld(a),
storage(ipiv), complex_cast(storage(b)), ld(b));
}
};
template<>
struct getrs_dispatch<std::complex<double>> {
template<typename MATRIX0, typename MATRIX1, typename VECTOR>
static lapack_int getrs(int matrix_layout, char trans, lapack_int n, lapack_int nrhs,
MATRIX0& a, VECTOR& ipiv, MATRIX1& b) {
return LAPACKE_zgetrs(matrix_layout, trans, n, nrhs, complex_cast(storage(a)), ld(a),
storage(ipiv), complex_cast(storage(b)), ld(b));
}
};
}
template<typename MATRIX0, typename MATRIX1, typename VECTOR>
lapack_int getrs(char trans, lapack_int nrhs, MATRIX0 const& a,
VECTOR const& ipiv, MATRIX1& b) {
static_assert(std::is_same<value_t<VECTOR>, lapack_int>::value, "");
static_assert(std::is_same<value_t<MATRIX0>, value_t<MATRIX1>>::value, "");
lapack_int n = rows(a);
if (rows(a) != cols(a))
throw std::invalid_argument("matrix A size mismatch");
if (size(ipiv) != n)
throw std::invalid_argument("vector ipiv size mismatch");
if (rows(b) != n || cols(b) != nrhs)
throw std::invalid_argument("matrix B size mismatch");
return getrs_dispatch<value_t<MATRIX0>>
::getrs((is_col_major(a) ? LAPACK_COL_MAJOR : LAPACK_ROW_MAJOR), trans, n, nrhs, a,
ipiv, b);
}
} // end namespace lapack
} // end namespace rokko
#endif // ROKKO_LAPACK_GETRS_HPP
|
#include <G2048pp/Block.hpp>
Block::Block()
{
using Random = effolkronium::random_static;
m_num = 2 * Random::get(1,2);
}
int Block::GetNum() const
{
return m_num;
}
void Block::DoubleNum()
{
m_num *= 2;
}
|
#include <errno.h>
#include <appctl/options.hpp>
#include <appctl/commands.hpp>
using namespace centauri::appctl::common;
using centauri::appctl::common::commands::vifstabOpts_t;
namespace centauri {
namespace appctl {
namespace vifstab {
int command::run(commandOptions_t *_options) {
vifstabOpts_t *options = (vifstabOpts_t *) _options;
return ENOSYS;
}
}
}
}
|
#include<stdio.h>
#include<ctype.h>
void Find_First(char[], char);
void Array_Manipulation(char[], char);
int limit;
char production[25][25];
int main()
{
char option;
char ch;
char array[25];
int count;
printf("\nEnter Total Number of Productions:\t");
scanf("%d", &limit);
for(count = 0; count < limit; count++)
{
printf("\nValue of Production Number [%d]:\t", count + 1);
scanf("%s", production[count]);
}
do
{
printf("\nEnter a Value to Find First:\t");
scanf(" %c", &ch);
Find_First(array, ch);
printf("\nFirst Value of %c:\t{ ", ch);
for(count = 0; array[count] != '\0'; count++)
{
printf(" %c ", array[count]);
}
printf("}\n");
printf("To Continue, Press Y:\t");
scanf(" %c", &option);
}while(option == 'y' || option == 'Y');
return 0;
}
void Find_First(char* array, char ch)
{
int count, j, k;
char temporary_result[20];
int x;
temporary_result[0] = '\0';
array[0] = '\0';
if(!(isupper(ch)))
{
Array_Manipulation(array, ch);
return ;
}
for(count = 0; count < limit; count++)
{
if(production[count][0] == ch)
{
if(production[count][2] == '$')
{
Array_Manipulation(array, '$');
}
else
{
j = 2;
while(production[count][j] != '\0')
{
x = 0;
Find_First(temporary_result, production[count][j]);
for(k = 0; temporary_result[k] != '\0'; k++)
{
Array_Manipulation(array,temporary_result[k]);
}
for(k = 0; temporary_result[k] != '\0'; k++)
{
if(temporary_result[k] == '$')
{
x = 1;
break;
}
}
if(!x)
{
break;
}
j++;
}
}
}
}
return;
}
void Array_Manipulation(char array[], char value)
{
int temp;
for(temp = 0; array[temp] != '\0'; temp++)
{
if(array[temp] == value)
{
return;
}
}
array[temp] = value;
array[temp + 1] = '\0';
}
|
// Copyright 2014 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include "packager/media/formats/mp4/single_segment_segmenter.h"
#include <algorithm>
#include "packager/file/file.h"
#include "packager/file/file_util.h"
#include "packager/media/base/buffer_writer.h"
#include "packager/media/base/muxer_options.h"
#include "packager/media/event/progress_listener.h"
#include "packager/media/formats/mp4/box_definitions.h"
#include "packager/media/formats/mp4/key_frame_info.h"
namespace shaka {
namespace media {
namespace mp4 {
SingleSegmentSegmenter::SingleSegmentSegmenter(const MuxerOptions& options,
std::unique_ptr<FileType> ftyp,
std::unique_ptr<Movie> moov)
: Segmenter(options, std::move(ftyp), std::move(moov)) {}
SingleSegmentSegmenter::~SingleSegmentSegmenter() {
if (temp_file_)
temp_file_.release()->Close();
if (!temp_file_name_.empty()) {
if (!File::Delete(temp_file_name_.c_str()))
LOG(ERROR) << "Unable to delete temporary file " << temp_file_name_;
}
}
bool SingleSegmentSegmenter::GetInitRange(size_t* offset, size_t* size) {
// In Finalize, ftyp and moov gets written first so offset must be 0.
*offset = 0;
*size = ftyp()->ComputeSize() + moov()->ComputeSize();
return true;
}
bool SingleSegmentSegmenter::GetIndexRange(size_t* offset, size_t* size) {
// Index range is right after init range so the offset must be the size of
// ftyp and moov.
*offset = ftyp()->ComputeSize() + moov()->ComputeSize();
*size = options().mp4_params.generate_sidx_in_media_segments
? vod_sidx_->ComputeSize()
: 0;
return true;
}
std::vector<Range> SingleSegmentSegmenter::GetSegmentRanges() {
std::vector<Range> ranges;
uint64_t next_offset = ftyp()->ComputeSize() + moov()->ComputeSize() +
(options().mp4_params.generate_sidx_in_media_segments
? vod_sidx_->ComputeSize()
: 0) +
vod_sidx_->first_offset;
for (const SegmentReference& segment_reference : vod_sidx_->references) {
Range r;
r.start = next_offset;
// Ranges are inclusive, so -1 to the size.
r.end = r.start + segment_reference.referenced_size - 1;
next_offset = r.end + 1;
ranges.push_back(r);
}
return ranges;
}
Status SingleSegmentSegmenter::DoInitialize() {
// Single segment segmentation involves two stages:
// Stage 1: Create media subsegments from media samples
// Stage 2: Update media header (moov) which involves copying of media
// subsegments
// Assumes stage 2 takes similar amount of time as stage 1. The previous
// progress_target was set for stage 1. Times two to account for stage 2.
set_progress_target(progress_target() * 2);
if (!TempFilePath(options().temp_dir, &temp_file_name_))
return Status(error::FILE_FAILURE, "Unable to create temporary file.");
temp_file_.reset(File::Open(temp_file_name_.c_str(), "w"));
return temp_file_
? Status::OK
: Status(error::FILE_FAILURE,
"Cannot open file to write " + temp_file_name_);
}
Status SingleSegmentSegmenter::DoFinalize() {
DCHECK(temp_file_);
DCHECK(ftyp());
DCHECK(moov());
DCHECK(vod_sidx_);
// Close the temp file to prepare for reading later.
if (!temp_file_.release()->Close()) {
return Status(
error::FILE_FAILURE,
"Cannot close the temp file " + temp_file_name_ +
", possibly file permission issue or running out of disk space.");
}
std::unique_ptr<File, FileCloser> file(
File::Open(options().output_file_name.c_str(), "w"));
if (file == NULL) {
return Status(error::FILE_FAILURE,
"Cannot open file to write " + options().output_file_name);
}
LOG(INFO) << "Update media header (moov) and rewrite the file to '"
<< options().output_file_name << "'.";
// Write ftyp, moov and sidx to output file.
std::unique_ptr<BufferWriter> buffer(new BufferWriter());
ftyp()->Write(buffer.get());
moov()->Write(buffer.get());
if (options().mp4_params.generate_sidx_in_media_segments)
vod_sidx_->Write(buffer.get());
Status status = buffer->WriteToFile(file.get());
if (!status.ok())
return status;
// Load the temp file and write to output file.
std::unique_ptr<File, FileCloser> temp_file(
File::Open(temp_file_name_.c_str(), "r"));
if (temp_file == NULL) {
return Status(error::FILE_FAILURE,
"Cannot open file to read " + temp_file_name_);
}
// The target of 2nd stage of single segment segmentation.
const uint64_t re_segment_progress_target = progress_target() * 0.5;
const int kBufSize = 0x200000; // 2MB.
std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufSize]);
while (true) {
int64_t size = temp_file->Read(buf.get(), kBufSize);
if (size == 0) {
break;
} else if (size < 0) {
return Status(error::FILE_FAILURE,
"Failed to read file " + temp_file_name_);
}
int64_t size_written = file->Write(buf.get(), size);
if (size_written != size) {
return Status(error::FILE_FAILURE,
"Failed to write file " + options().output_file_name);
}
UpdateProgress(static_cast<double>(size) / temp_file->Size() *
re_segment_progress_target);
}
if (!temp_file.release()->Close()) {
return Status(error::FILE_FAILURE, "Cannot close the temp file " +
temp_file_name_ + " after reading.");
}
if (!file.release()->Close()) {
return Status(
error::FILE_FAILURE,
"Cannot close file " + options().output_file_name +
", possibly file permission issue or running out of disk space.");
}
SetComplete();
return Status::OK;
}
Status SingleSegmentSegmenter::DoFinalizeSegment() {
DCHECK(sidx());
DCHECK(fragment_buffer());
// sidx() contains pre-generated segment references with one reference per
// fragment. In VOD, this segment is converted into a subsegment, i.e. one
// reference, which contains all the fragments in sidx().
std::vector<SegmentReference>& refs = sidx()->references;
SegmentReference& vod_ref = refs[0];
int64_t first_sap_time =
refs[0].sap_delta_time + refs[0].earliest_presentation_time;
for (uint32_t i = 1; i < refs.size(); ++i) {
vod_ref.referenced_size += refs[i].referenced_size;
// NOTE: We calculate subsegment duration based on the total duration of
// this subsegment instead of subtracting earliest_presentation_time as
// indicated in the spec.
vod_ref.subsegment_duration += refs[i].subsegment_duration;
vod_ref.earliest_presentation_time = std::min(
vod_ref.earliest_presentation_time, refs[i].earliest_presentation_time);
if (vod_ref.sap_type == SegmentReference::TypeUnknown &&
refs[i].sap_type != SegmentReference::TypeUnknown) {
vod_ref.sap_type = refs[i].sap_type;
first_sap_time =
refs[i].sap_delta_time + refs[i].earliest_presentation_time;
}
}
// Calculate sap delta time w.r.t. earliest_presentation_time.
if (vod_ref.sap_type != SegmentReference::TypeUnknown) {
vod_ref.sap_delta_time =
first_sap_time - vod_ref.earliest_presentation_time;
}
// Create segment if it does not exist yet.
if (vod_sidx_ == NULL) {
vod_sidx_.reset(new SegmentIndex());
vod_sidx_->reference_id = sidx()->reference_id;
vod_sidx_->timescale = sidx()->timescale;
vod_sidx_->earliest_presentation_time = vod_ref.earliest_presentation_time;
}
vod_sidx_->references.push_back(vod_ref);
if (muxer_listener()) {
for (const KeyFrameInfo& key_frame_info : key_frame_infos()) {
// Unlike multisegment-segmenter, there is no (sub)segment header (styp,
// sidx), so this is already the offset within the (sub)segment.
muxer_listener()->OnKeyFrame(key_frame_info.timestamp,
key_frame_info.start_byte_offset,
key_frame_info.size);
}
}
// Append fragment buffer to temp file.
size_t segment_size = fragment_buffer()->Size();
Status status = fragment_buffer()->WriteToFile(temp_file_.get());
if (!status.ok()) return status;
UpdateProgress(vod_ref.subsegment_duration);
if (muxer_listener()) {
muxer_listener()->OnSampleDurationReady(sample_duration());
muxer_listener()->OnNewSegment(options().output_file_name,
vod_ref.earliest_presentation_time,
vod_ref.subsegment_duration, segment_size);
}
return Status::OK;
}
} // namespace mp4
} // namespace media
} // namespace shaka
|
// Copyright (c) 2012-2016, The CryptoNote developers, The Bytecoin developers
// Copyright (c) 2014-2016 XDN developers
// Copyright (c) 2016-2018 Karbowanec developers
// Copyright (c) 2017-2019, The CROAT.community developers
//
// This file is part of Bytecoin.
//
// Bytecoin 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 3 of the License, or
// (at your option) any later version.
//
// Bytecoin 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 Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "HttpServer.h"
#include <boost/scope_exit.hpp>
#include <Common/Base64.h>
#include <HTTP/HttpParser.h>
#include <System/InterruptedException.h>
#include <System/TcpStream.h>
#include <System/Ipv4Address.h>
using namespace Logging;
namespace {
void fillUnauthorizedResponse(CryptoNote::HttpResponse& response) {
response.setStatus(CryptoNote::HttpResponse::STATUS_401);
response.addHeader("WWW-Authenticate", "Basic realm=\"RPC\"");
response.addHeader("Content-Type", "text/plain");
response.setBody("Authorization required");
}
}
namespace CryptoNote {
HttpServer::HttpServer(System::Dispatcher& dispatcher, Logging::ILogger& log)
: m_dispatcher(dispatcher), workingContextGroup(dispatcher), logger(log, "HttpServer") {
}
void HttpServer::start(const std::string& address, uint16_t port, const std::string& user, const std::string& password) {
m_listener = System::TcpListener(m_dispatcher, System::Ipv4Address(address), port);
workingContextGroup.spawn(std::bind(&HttpServer::acceptLoop, this));
if (!user.empty() || !password.empty()) {
m_credentials = Tools::Base64::encode(user + ":" + password);
}
}
void HttpServer::stop() {
workingContextGroup.interrupt();
workingContextGroup.wait();
}
void HttpServer::acceptLoop() {
try {
System::TcpConnection connection;
bool accepted = false;
while (!accepted) {
try {
connection = m_listener.accept();
accepted = true;
} catch (System::InterruptedException&) {
throw;
} catch (std::exception&) {
// try again
}
}
m_connections.insert(&connection);
BOOST_SCOPE_EXIT_ALL(this, &connection) {
m_connections.erase(&connection); };
workingContextGroup.spawn(std::bind(&HttpServer::acceptLoop, this));
//auto addr = connection.getPeerAddressAndPort();
auto addr = std::pair<System::Ipv4Address, uint16_t>(static_cast<System::Ipv4Address>(0), 0);
try {
addr = connection.getPeerAddressAndPort();
} catch (std::runtime_error&) {
logger(WARNING) << "Could not get IP of connection";
}
logger(DEBUGGING) << "Incoming connection from " << addr.first.toDottedDecimal() << ":" << addr.second;
System::TcpStreambuf streambuf(connection);
std::iostream stream(&streambuf);
HttpParser parser;
for (;;) {
HttpRequest req;
HttpResponse resp;
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("content-type", "application/json");
parser.receiveRequest(stream, req);
if (authenticate(req)) {
processRequest(req, resp);
}
else {
logger(WARNING) << "Authorization required " << addr.first.toDottedDecimal() << ":" << addr.second;
fillUnauthorizedResponse(resp);
}
stream << resp;
stream.flush();
if (stream.peek() == std::iostream::traits_type::eof()) {
break;
}
}
logger(DEBUGGING) << "Closing connection from " << addr.first.toDottedDecimal() << ":" << addr.second << " total=" << m_connections.size();
} catch (System::InterruptedException&) {
} catch (std::exception& e) {
logger(DEBUGGING) << "Connection error: " << e.what();
}
}
bool HttpServer::authenticate(const HttpRequest& request) const {
if (!m_credentials.empty()) {
auto headerIt = request.getHeaders().find("authorization");
if (headerIt == request.getHeaders().end()) {
return false;
}
if (headerIt->second.substr(0, 6) != "Basic ") {
return false;
}
if (headerIt->second.substr(6) != m_credentials) {
return false;
}
}
return true;
}
size_t HttpServer::get_connections_count() const {
return m_connections.size();
}
}
|
// Copyright 2010-2012 RethinkDB, all rights reserved.
#ifndef CONFIG_ARGS_HPP_
#define CONFIG_ARGS_HPP_
#define KILOBYTE 1024LL
#define MEGABYTE (KILOBYTE * 1024LL)
#define GIGABYTE (MEGABYTE * 1024LL)
#define TERABYTE (GIGABYTE * 1024LL)
#define THOUSAND 1000LL
#define MILLION (THOUSAND * THOUSAND)
#define BILLION (THOUSAND * MILLION)
/*!
* Name strings
*/
#define SOFTWARE_NAME_STRING "RethinkDB"
/**
* Basic configuration parameters.
*/
// The number of hash-based CPU shards per table.
// This "must" be hard-coded because a cluster cannot run with
// differing cpu sharding factors.
#define CPU_SHARDING_FACTOR 8
// Defines the maximum size of the batch of IO events to process on
// each loop iteration. A larger number will increase throughput but
// decrease concurrency
#define MAX_IO_EVENT_PROCESSING_BATCH_SIZE 50
// The io batch factor ensures a minimum number of i/o operations
// which are picked from any specific i/o account consecutively.
// A higher value might be advantageous for throughput if seek times
// matter on the underlying i/o system. A low value improves latency.
// The advantage only holds as long as each account has a tendentially
// sequential set of i/o operations though. If access patterns are random
// for all accounts, a low io batch factor does just as well (as bad) when it comes
// to the number of random seeks, but might still provide a lower latency
// than a high batch factor. Our serializer now groups data writes into
// a single large write operation by itself, making a high value here less
// useful.
#define DEFAULT_IO_BATCH_FACTOR 1
// I/O priority of index writes in the log serializer
#define INDEX_WRITE_IO_PRIORITY 128
// Each cache uses its own I/O account for reads.
// Writes use the default I/O account, which in practice is going to be overridden
// by a common account in the merger_serializer_t.
//
// By adjusting the priority of the read account, relative to
// MERGER_BLOCK_WRITE_IO_PRIORITY below, reads can be prioritized over writes
// or the other way around.
//
// In practice we want to prioritize reads, so reads can pass ahead of
// flushes. The rationale behind this is that reads are almost always blocking
// operations. Writes, on the other hand, can be non-blocking (from the user's
// perspective) if they are soft-durability or noreply writes.
#define CACHE_READS_IO_PRIORITY (512 / CPU_SHARDING_FACTOR)
// The cache priority to use for secondary index post construction
// 100 = same priority as all other read operations in the cache together.
// 0 = minimal priority
#define SINDEX_POST_CONSTRUCTION_CACHE_PRIORITY 5
// Size of the buffer used to perform IO operations (in bytes).
#define IO_BUFFER_SIZE (4 * KILOBYTE)
// Size of the device block size (in bytes)
#define DEVICE_BLOCK_SIZE 512
// Size of each btree node (in bytes) on disk
#define DEFAULT_BTREE_BLOCK_SIZE (4 * KILOBYTE)
// Size of each extent (in bytes)
// This should not be too small, or garbage collection will become
// inefficient (especially on rotational drives).
#define DEFAULT_EXTENT_SIZE (2 * MEGABYTE)
// Ratio of free ram to use for the cache by default
#define DEFAULT_MAX_CACHE_RATIO 2
// The maximum number of concurrently active
// index writes per merger serializer.
// The smaller the number, the more effective
// the merger serializer is in merging index writes
// together. This is favorable especially on rotational drives.
// There is a theoretic chance of increased latencies on SSDs for
// small values of this variable.
#define MERGER_SERIALIZER_MAX_ACTIVE_WRITES 1
// I/O priority of block writes in the merger_serializer_t
#define MERGER_BLOCK_WRITE_IO_PRIORITY 64
// Maximum number of threads we support
// TODO: make this dynamic where possible
#define MAX_THREADS 128
// Ticks (in milliseconds) the internal timed tasks are performed at
#define TIMER_TICKS_IN_MS 5
// How many times the page replacement algorithm tries to find an eligible page before giving up.
// Note that (MAX_UNSAVED_DATA_LIMIT_FRACTION ** PAGE_REPL_NUM_TRIES) is the probability that the
// page replacement algorithm will succeed on a given try, and if that probability is less than 1/2
// then the page replacement algorithm will on average be unable to evict pages from the cache.
#define PAGE_REPL_NUM_TRIES 10
// How large can the key be, in bytes? This value needs to fit in a byte.
#define MAX_KEY_SIZE 250
// Special block IDs. These don't really belong here because they're
// more magic constants than tunable parameters.
// The btree superblock, which has a reference to the root node block
// id.
#define SUPERBLOCK_ID 0
// If the size of the LBA on a given disk exceeds LBA_MIN_SIZE_FOR_GC, then the fraction of the
// entries that are live and not garbage should be at least LBA_MIN_UNGARBAGE_FRACTION.
#define LBA_MIN_SIZE_FOR_GC (MEGABYTE * 1)
#define LBA_MIN_UNGARBAGE_FRACTION 0.5
// I/O priority for LBA garbage collection
#define LBA_GC_IO_PRIORITY 8
// How many block ids should the LBA garbage collector rewrite before yielding?
#define LBA_GC_BATCH_SIZE (1024 * 8)
// How many LBA structures to have for each file (This value defines the disk format!
// It can't change unless you're very careful.)
#define LBA_SHARD_FACTOR 4
// How many bytes of buffering space we can use per disk when reading the LBA. If it's set
// too high, then RethinkDB will eat a lot of memory at startup. This is bad because tcmalloc
// doesn't return memory to the OS. If it's set too low, startup will take a longer time.
#define LBA_READ_BUFFER_SIZE (128 * MEGABYTE)
// After the LBA has been read, we reconstruct the in-memory LBA index.
// For huge tables, this can take some considerable CPU time. We break the reconstruction
// up into smaller batches, each batch reconstructing up to `LBA_RECONSTRUCTION_BATCH_SIZE`
// block infos.
#define LBA_RECONSTRUCTION_BATCH_SIZE 1024
#define COROUTINE_STACK_SIZE 131072
/**
* Message scheduler configuration
*/
// Each message on the message hup can have a priority between
// MESSAGE_SCHEDULER_MIN_PRIORITY and MESSAGE_SCHEDULER_MAX_PRIORITY (both inclusive).
#define MESSAGE_SCHEDULER_MIN_PRIORITY (-2)
#define MESSAGE_SCHEDULER_MAX_PRIORITY 2
// If no priority is specified, messages will get MESSAGE_SCHEDULER_DEFAULT_PRIORITY.
#define MESSAGE_SCHEDULER_DEFAULT_PRIORITY 0
// Ordered messages cannot currently have different priorities, because that would mean
// that ordered messages of a high priority could bypass those of a lower priority.
// (our current implementation does not support re-ordering messages within a given
// priority)
// MESSAGE_SCHEDULER_ORDERED_PRIORITY is the effective priority at which ordered
// messages are scheduled.
#define MESSAGE_SCHEDULER_ORDERED_PRIORITY 0
// MESSAGE_SCHEDULER_GRANULARITY specifies how many messages (of
// MESSAGE_SCHEDULER_MAX_PRIORITY) the message scheduler processes before it
// can take in new incoming messages. A smaller value means that high-priority
// messages can bypass lower-priority ones faster, but decreases the efficiency
// of the message hub.
// MESSAGE_SCHEDULER_GRANULARITY should be least
// 2^(MESSAGE_SCHEDULER_MAX_PRIORITY - MESSAGE_SCHEDULER_MIN_PRIORITY + 1)
#define MESSAGE_SCHEDULER_GRANULARITY 32
// Priorities for specific tasks
#define CORO_PRIORITY_SINDEX_CONSTRUCTION (-2)
#define CORO_PRIORITY_BACKFILL_SENDER (-2)
#define CORO_PRIORITY_BACKFILL_RECEIVER (-2)
#define CORO_PRIORITY_RESET_DATA (-2)
#define CORO_PRIORITY_DIRECTORY_CHANGES (-2)
#define CORO_PRIORITY_LBA_GC (-2)
#endif // CONFIG_ARGS_HPP_
|
#include <gmock/gmock.h>
#include <string>
#include <utility>
#include <vector>
#include "info/info_service_impl.h"
#include "info/mocks/info_mock.h"
namespace {
using testing::_;
using testing::NiceMock;
using testing::Return;
using MockInfo = NiceMock<mavsdk::testing::MockInfo>;
using InfoServiceImpl = mavsdk::mavsdk_server::InfoServiceImpl<MockInfo>;
using InfoResult = mavsdk::rpc::info::InfoResult;
using InputPair = std::pair<std::string, mavsdk::Info::Result>;
static constexpr int ARBITRARY_SW_VERSION_MAJOR = 1;
static constexpr int ARBITRARY_SW_VERSION_MINOR = 2;
static constexpr int ARBITRARY_SW_VERSION_PATCH = 3;
static constexpr int ARBITRARY_SW_VERSION_VENDOR_MAJOR = 1;
static constexpr int ARBITRARY_SW_VERSION_VENDOR_MINOR = 2;
static constexpr int ARBITRARY_SW_VERSION_VENDOR_PATCH = 3;
static constexpr int ARBITRARY_SW_VERSION_OS_MAJOR = 4;
static constexpr int ARBITRARY_SW_VERSION_OS_MINOR = 5;
static constexpr int ARBITRARY_SW_VERSION_OS_PATCH = 6;
std::vector<mavsdk::Info::Result> generateResults();
class InfoServiceImplTest : public ::testing::TestWithParam<mavsdk::Info::Result> {};
mavsdk::Info::Result translateFromRpcResult(const mavsdk::rpc::info::InfoResult::Result result)
{
switch (result) {
default:
// FALLTHROUGH
case mavsdk::rpc::info::InfoResult_Result_RESULT_UNKNOWN:
return mavsdk::Info::Result::Unknown;
case mavsdk::rpc::info::InfoResult_Result_RESULT_SUCCESS:
return mavsdk::Info::Result::Success;
case mavsdk::rpc::info::InfoResult_Result_RESULT_INFORMATION_NOT_RECEIVED_YET:
return mavsdk::Info::Result::InformationNotReceivedYet;
}
}
TEST_F(InfoServiceImplTest, getVersionCallsGetter)
{
MockInfo info;
InfoServiceImpl infoService(info);
EXPECT_CALL(info, get_version()).Times(1);
mavsdk::rpc::info::GetVersionResponse response;
infoService.GetVersion(nullptr, nullptr, &response);
}
TEST_P(InfoServiceImplTest, getsCorrectVersion)
{
MockInfo info;
InfoServiceImpl infoService(info);
mavsdk::Info::Version arbitrary_version;
arbitrary_version.flight_sw_major = ARBITRARY_SW_VERSION_MAJOR;
arbitrary_version.flight_sw_minor = ARBITRARY_SW_VERSION_MINOR;
arbitrary_version.flight_sw_patch = ARBITRARY_SW_VERSION_PATCH;
arbitrary_version.flight_sw_vendor_major = ARBITRARY_SW_VERSION_VENDOR_MAJOR;
arbitrary_version.flight_sw_vendor_minor = ARBITRARY_SW_VERSION_VENDOR_MINOR;
arbitrary_version.flight_sw_vendor_patch = ARBITRARY_SW_VERSION_VENDOR_PATCH;
arbitrary_version.os_sw_major = ARBITRARY_SW_VERSION_OS_MAJOR;
arbitrary_version.os_sw_minor = ARBITRARY_SW_VERSION_OS_MINOR;
arbitrary_version.os_sw_patch = ARBITRARY_SW_VERSION_OS_PATCH;
const auto expected_pair = std::make_pair<>(GetParam(), arbitrary_version);
ON_CALL(info, get_version()).WillByDefault(Return(expected_pair));
mavsdk::rpc::info::GetVersionResponse response;
infoService.GetVersion(nullptr, nullptr, &response);
EXPECT_EQ(GetParam(), translateFromRpcResult(response.info_result().result()));
EXPECT_EQ(expected_pair.second.flight_sw_major, response.version().flight_sw_major());
EXPECT_EQ(expected_pair.second.flight_sw_minor, response.version().flight_sw_minor());
EXPECT_EQ(expected_pair.second.flight_sw_patch, response.version().flight_sw_patch());
EXPECT_EQ(
expected_pair.second.flight_sw_vendor_major, response.version().flight_sw_vendor_major());
EXPECT_EQ(
expected_pair.second.flight_sw_vendor_minor, response.version().flight_sw_vendor_minor());
EXPECT_EQ(
expected_pair.second.flight_sw_vendor_patch, response.version().flight_sw_vendor_patch());
EXPECT_EQ(expected_pair.second.os_sw_major, response.version().os_sw_major());
EXPECT_EQ(expected_pair.second.os_sw_minor, response.version().os_sw_minor());
EXPECT_EQ(expected_pair.second.os_sw_patch, response.version().os_sw_patch());
}
TEST_F(InfoServiceImplTest, getVersionDoesNotCrashWithNullResponse)
{
MockInfo info;
InfoServiceImpl infoService(info);
infoService.GetVersion(nullptr, nullptr, nullptr);
}
INSTANTIATE_TEST_SUITE_P(
InfoResultCorrespondences, InfoServiceImplTest, ::testing::ValuesIn(generateResults()));
std::vector<mavsdk::Info::Result> generateResults()
{
std::vector<mavsdk::Info::Result> results;
results.push_back(mavsdk::Info::Result::Success);
results.push_back(mavsdk::Info::Result::InformationNotReceivedYet);
results.push_back(mavsdk::Info::Result::Unknown);
return results;
}
} // namespace
|
// Copyright John McFarlane 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file ../LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cnl/_impl/type_traits/identical.h>
#include <cnl/elastic_scaled_integer.h>
#include <cnl/rounding.h>
using cnl::_impl::identical;
namespace {
namespace test_native_round_down {
static constexpr auto expected = cnl::elastic_scaled_integer<4, -1>{0.0};
static constexpr auto actual = cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag, cnl::elastic_scaled_integer<4, -1>>(
cnl::elastic_scaled_integer<8, -4>{0.3125});
static_assert(
identical(expected, actual), "cnl::convert<cnl::native_rounding_tag, cnl::power<>, "
"cnl::elastic_scaled_integer, cnl::elastic_scaled_integer>");
}
namespace test_native_round_up {
static constexpr auto expected = cnl::elastic_scaled_integer<4, -2>{0.25};
static constexpr auto actual = cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag, cnl::elastic_scaled_integer<4, -2>>(
cnl::elastic_scaled_integer<8, -4>{0.3125});
static_assert(
identical(expected, actual), "cnl::convert<cnl::native_rounding_tag, cnl::power<>, "
"cnl::elastic_scaled_integer, cnl::elastic_scaled_integer>");
}
namespace elastic_scaled_integer_native_rounding {
// Positive
static_assert(
identical(
cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag,
cnl::elastic_scaled_integer<16, 0>>(cnl::elastic_scaled_integer<16, -4>{
5.25}),
cnl::elastic_scaled_integer<16, 0>{5.0}));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -4>{5.25}), 84));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, 0>{5.0}), 5));
static_assert(
identical(
cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag,
cnl::elastic_scaled_integer<16, 0>>(cnl::elastic_scaled_integer<16, -4>{
5.5}),
cnl::elastic_scaled_integer<16, 0>{5.0}));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -4>{5.5}), 88));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, 0>{5.0}), 5));
static_assert(
identical(
cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag,
cnl::elastic_scaled_integer<16, -1>>(cnl::elastic_scaled_integer<16, -4>{
5.25}),
cnl::elastic_scaled_integer<16, -1>{5.0}));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -4>{5.25}), 84));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -1>{5.0}), 10));
// Negative
static_assert(
identical(
cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag,
cnl::elastic_scaled_integer<16, 0>>(cnl::elastic_scaled_integer<16, -4>{
-5.25}),
cnl::elastic_scaled_integer<16, 0>{-5.0}));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -4>{-5.25}), -84));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, 0>{-5.0}), -5));
static_assert(
identical(
cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag,
cnl::elastic_scaled_integer<16, 0>>(cnl::elastic_scaled_integer<16, -4>{
-5.5}),
cnl::elastic_scaled_integer<16, 0>{-5.0}));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -4>{-5.5}), -88));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, 0>{-5.0}), -5));
static_assert(
identical(
cnl::convert<
cnl::native_rounding_tag, cnl::_impl::native_tag,
cnl::elastic_scaled_integer<16, -1>>(cnl::elastic_scaled_integer<16, -4>{
-5.25}),
cnl::elastic_scaled_integer<16, -1>{-5.0}));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -4>{-5.25}), -84));
static_assert(identical(cnl::unwrap(cnl::elastic_scaled_integer<16, -1>{-5.0}), -10));
}
namespace elastic_scaled_integer_implicit_conversions {
using q4_4 = cnl::elastic_scaled_integer<8, -4>;
using q4_1 = cnl::elastic_scaled_integer<5, -1>;
static_assert(
identical(q4_1{0.0}, static_cast<q4_1>(q4_4{0.25})),
"conversion 1 (elastic_scaled_integer)");
static_assert(
identical(q4_1{0.0}, static_cast<q4_1>(q4_4{-0.25})),
"conversion 2 (elastic_scaled_integer)");
static_assert(
identical(q4_1{-0.5}, static_cast<q4_1>(q4_4{-0.75})),
"conversion 3 (elastic_scaled_integer)");
static_assert(
identical(q4_1{0.5}, static_cast<q4_1>(q4_4{0.75})),
"conversion 4 (elastic_scaled_integer)");
}
namespace elastic_scaled_integer_multiply {
using q4_20 = cnl::elastic_scaled_integer<24, -20>;
using q4_4 = cnl::elastic_scaled_integer<8, -4>;
using q4_1 = cnl::elastic_scaled_integer<5, -1>;
static constexpr auto expected1 = q4_1{0.0};
static constexpr q4_1 result1 = q4_4{0.5} * q4_4{0.5};
static_assert(
identical(expected1, result1), "test 1 multiply and round (elastic_scaled_integer)");
static constexpr auto expected2 = q4_1{0.0};
static constexpr q4_1 result2 = q4_4{-0.5} * q4_4{0.5};
static_assert(
identical(expected2, result2), "test 2 multiply and round (elastic_scaled_integer)");
static constexpr auto expected3 = q4_1{-0.5};
static constexpr q4_1 result3 = q4_4{-3.0} * q4_4{0.25};
static_assert(
identical(expected3, result3), "test 3 multiply and round (elastic_scaled_integer)");
static constexpr auto expected4 = q4_1{0.5};
static constexpr q4_1 result4 = q4_4{3.0} * q4_4{0.25};
static_assert(
identical(expected4, result4), "test 4 multiply and round (elastic_scaled_integer)");
static constexpr auto expected5 = q4_20{1.0};
static constexpr q4_20 result5 = q4_20{2.0} * q4_20{0.5};
static_assert(
identical(expected5, result5), "test 5 multiply and round (elastic_scaled_integer)");
}
namespace elastic_scaled_integer_divide {
using q4_4 = cnl::elastic_scaled_integer<8, -4>;
using q4_1 = cnl::elastic_scaled_integer<5, -1>;
static constexpr auto expected1 = q4_1{1.0};
static constexpr q4_1 result1 = cnl::quotient(q4_4{0.5}, q4_4{0.5});
static_assert(
identical(expected1, result1), "test 1 divide and round (elastic_scaled_integer)");
static constexpr auto expected2 = q4_1{-1.0};
static constexpr q4_1 result2 = cnl::quotient(q4_4{-0.5}, q4_4{0.5});
static_assert(
identical(expected2, result2), "test 2 divide and round (elastic_scaled_integer)");
static constexpr auto expected3 = q4_1{0.0};
static constexpr q4_1 result3 = cnl::quotient(q4_4{0.5}, q4_4{2.0});
static_assert(
identical(expected3, result3), "test 3 divide and round (elastic_scaled_integer)");
static constexpr auto expected4 = q4_1{0.0};
static constexpr q4_1 result4 = cnl::quotient(q4_4{0.5}, q4_4{1.5});
static_assert(
identical(expected4, result4), "test 4 divide and round (elastic_scaled_integer)");
static constexpr auto expected5 = q4_1{0.0};
static constexpr q4_1 result5 = cnl::quotient(q4_4{-0.5}, q4_4{1.5});
static_assert(
identical(expected5, result5), "test 5 divide and round (elastic_scaled_integer)");
}
}
|
//
// Copyright (c) 2013-2021 Winlin
//
// SPDX-License-Identifier: MIT
//
#include <srs_app_config.hpp>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
// file operations.
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef __linux__
#include <linux/version.h>
#include <sys/utsname.h>
#endif
#include <vector>
#include <algorithm>
using namespace std;
#include <srs_kernel_error.hpp>
#include <srs_kernel_log.hpp>
#include <srs_protocol_utility.hpp>
#include <srs_core_autofree.hpp>
#include <srs_app_source.hpp>
#include <srs_kernel_file.hpp>
#include <srs_app_utility.hpp>
#include <srs_core_performance.hpp>
#include <srs_protocol_amf0.hpp>
#include <srs_app_statistic.hpp>
#include <srs_protocol_json.hpp>
#include <srs_app_http_hooks.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_rtmp_stack.hpp>
using namespace srs_internal;
// @global the version to identify the core.
const char* _srs_version = "XCORE-" RTMP_SIG_SRS_SERVER;
// when user config an invalid value, macros to perfer true or false.
#define SRS_CONF_PERFER_FALSE(conf_arg) conf_arg == "on"
#define SRS_CONF_PERFER_TRUE(conf_arg) conf_arg != "off"
// default config file.
#define SRS_CONF_DEFAULT_COFNIG_FILE SRS_DEFAULT_CONFIG
// '\n'
#define SRS_LF (char)SRS_CONSTS_LF
// '\r'
#define SRS_CR (char)SRS_CONSTS_CR
/**
* dumps the ingest/transcode-engine in @param dir to amf0 object @param engine.
* @param dir the transcode or ingest config directive.
* @param engine the amf0 object to dumps to.
*/
srs_error_t srs_config_dumps_engine(SrsConfDirective* dir, SrsJsonObject* engine);
/**
* whether the ch is common space.
*/
bool is_common_space(char ch)
{
return (ch == ' ' || ch == '\t' || ch == SRS_CR || ch == SRS_LF);
}
namespace srs_internal
{
SrsConfigBuffer::SrsConfigBuffer()
{
line = 1;
pos = last = start = NULL;
end = start;
}
SrsConfigBuffer::~SrsConfigBuffer()
{
srs_freepa(start);
}
// LCOV_EXCL_START
srs_error_t SrsConfigBuffer::fullfill(const char* filename)
{
srs_error_t err = srs_success;
SrsFileReader reader;
// open file reader.
if ((err = reader.open(filename)) != srs_success) {
return srs_error_wrap(err, "open file=%s", filename);
}
// read all.
int filesize = (int)reader.filesize();
// create buffer
srs_freepa(start);
pos = last = start = new char[filesize];
end = start + filesize;
// read total content from file.
ssize_t nread = 0;
if ((err = reader.read(start, filesize, &nread)) != srs_success) {
return srs_error_wrap(err, "read %d only %d bytes", filesize, (int)nread);
}
return err;
}
// LCOV_EXCL_STOP
bool SrsConfigBuffer::empty()
{
return pos >= end;
}
};
bool srs_directive_equals_self(SrsConfDirective* a, SrsConfDirective* b)
{
// both NULL, equal.
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
if (a->name != b->name) {
return false;
}
if (a->args.size() != b->args.size()) {
return false;
}
for (int i = 0; i < (int)a->args.size(); i++) {
if (a->args.at(i) != b->args.at(i)) {
return false;
}
}
if (a->directives.size() != b->directives.size()) {
return false;
}
return true;
}
bool srs_directive_equals(SrsConfDirective* a, SrsConfDirective* b)
{
// both NULL, equal.
if (!a && !b) {
return true;
}
if (!srs_directive_equals_self(a, b)) {
return false;
}
for (int i = 0; i < (int)a->directives.size(); i++) {
SrsConfDirective* a0 = a->at(i);
SrsConfDirective* b0 = b->at(i);
if (!srs_directive_equals(a0, b0)) {
return false;
}
}
return true;
}
bool srs_directive_equals(SrsConfDirective* a, SrsConfDirective* b, string except)
{
// both NULL, equal.
if (!a && !b) {
return true;
}
if (!srs_directive_equals_self(a, b)) {
return false;
}
for (int i = 0; i < (int)a->directives.size(); i++) {
SrsConfDirective* a0 = a->at(i);
SrsConfDirective* b0 = b->at(i);
// donot compare the except child directive.
if (a0->name == except) {
continue;
}
if (!srs_directive_equals(a0, b0, except)) {
return false;
}
}
return true;
}
void set_config_directive(SrsConfDirective* parent, string dir, string value)
{
SrsConfDirective* d = parent->get_or_create(dir);
d->name = dir;
d->args.clear();
d->args.push_back(value);
}
bool srs_config_hls_is_on_error_ignore(string strategy)
{
return strategy == "ignore";
}
bool srs_config_hls_is_on_error_continue(string strategy)
{
return strategy == "continue";
}
bool srs_config_ingest_is_file(string type)
{
return type == "file";
}
bool srs_config_ingest_is_stream(string type)
{
return type == "stream";
}
bool srs_config_dvr_is_plan_segment(string plan)
{
return plan == "segment";
}
bool srs_config_dvr_is_plan_session(string plan)
{
return plan == "session";
}
bool srs_stream_caster_is_udp(string caster)
{
return caster == "mpegts_over_udp";
}
bool srs_stream_caster_is_flv(string caster)
{
return caster == "flv";
}
bool srs_config_apply_filter(SrsConfDirective* dvr_apply, SrsRequest* req)
{
static bool DEFAULT = true;
if (!dvr_apply || dvr_apply->args.empty()) {
return DEFAULT;
}
vector<string>& args = dvr_apply->args;
if (args.size() == 1 && dvr_apply->arg0() == "all") {
return true;
}
string id = req->app + "/" + req->stream;
if (std::find(args.begin(), args.end(), id) != args.end()) {
return true;
}
return false;
}
string srs_config_bool2switch(string sbool)
{
return sbool == "true"? "on":"off";
}
srs_error_t srs_config_transform_vhost(SrsConfDirective* root)
{
srs_error_t err = srs_success;
for (int i = 0; i < (int)root->directives.size(); i++) {
SrsConfDirective* dir = root->directives.at(i);
// SRS2.0, rename global http_stream to http_server.
// SRS1:
// http_stream {}
// SRS2+:
// http_server {}
if (dir->name == "http_stream") {
dir->name = "http_server";
continue;
}
// SRS4.0, removed the support of configs:
// rtc_server { perf_stat; queue_length; }
if (dir->name == "rtc_server") {
std::vector<SrsConfDirective*>::iterator it;
for (it = dir->directives.begin(); it != dir->directives.end();) {
SrsConfDirective* conf = *it;
if (conf->name == "perf_stat" || conf->name == "queue_length") {
dir->directives.erase(it);
srs_freep(conf);
continue;
}
++it;
}
}
if (!dir->is_vhost()) {
continue;
}
// for each directive of vhost.
std::vector<SrsConfDirective*>::iterator it;
for (it = dir->directives.begin(); it != dir->directives.end();) {
SrsConfDirective* conf = *it;
string n = conf->name;
// SRS2.0, rename vhost http to http_static
// SRS1:
// vhost { http {} }
// SRS2+:
// vhost { http_static {} }
if (n == "http") {
conf->name = "http_static";
srs_warn("transform: vhost.http => vhost.http_static for %s", dir->name.c_str());
++it;
continue;
}
// SRS3.0, ignore hstrs, always on.
// SRS1/2:
// vhost { http_remux { hstrs; } }
if (n == "http_remux") {
SrsConfDirective* hstrs = conf->get("hstrs");
conf->remove(hstrs);
srs_freep(hstrs);
}
// SRS3.0, change the refer style
// SRS1/2:
// vhost { refer; refer_play; refer_publish; }
// SRS3+:
// vhost { refer { enabled; all; play; publish; } }
if ((n == "refer" && conf->directives.empty()) || n == "refer_play" || n == "refer_publish") {
// remove the old one first, for name duplicated.
it = dir->directives.erase(it);
SrsConfDirective* refer = dir->get_or_create("refer");
refer->get_or_create("enabled", "on");
if (n == "refer") {
SrsConfDirective* all = refer->get_or_create("all");
all->args = conf->args;
srs_warn("transform: vhost.refer to vhost.refer.all for %s", dir->name.c_str());
} else if (n == "refer_play") {
SrsConfDirective* play = refer->get_or_create("play");
play->args = conf->args;
srs_warn("transform: vhost.refer_play to vhost.refer.play for %s", dir->name.c_str());
} else if (n == "refer_publish") {
SrsConfDirective* publish = refer->get_or_create("publish");
publish->args = conf->args;
srs_warn("transform: vhost.refer_publish to vhost.refer.publish for %s", dir->name.c_str());
}
// remove the old directive.
srs_freep(conf);
continue;
}
// SRS3.0, change the mr style
// SRS2:
// vhost { mr { enabled; latency; } }
// SRS3+:
// vhost { publish { mr; mr_latency; } }
if (n == "mr") {
it = dir->directives.erase(it);
SrsConfDirective* publish = dir->get_or_create("publish");
SrsConfDirective* enabled = conf->get("enabled");
if (enabled) {
SrsConfDirective* mr = publish->get_or_create("mr");
mr->args = enabled->args;
srs_warn("transform: vhost.mr.enabled to vhost.publish.mr for %s", dir->name.c_str());
}
SrsConfDirective* latency = conf->get("latency");
if (latency) {
SrsConfDirective* mr_latency = publish->get_or_create("mr_latency");
mr_latency->args = latency->args;
srs_warn("transform: vhost.mr.latency to vhost.publish.mr_latency for %s", dir->name.c_str());
}
srs_freep(conf);
continue;
}
// SRS3.0, change the publish_1stpkt_timeout
// SRS2:
// vhost { publish_1stpkt_timeout; }
// SRS3+:
// vhost { publish { firstpkt_timeout; } }
if (n == "publish_1stpkt_timeout") {
it = dir->directives.erase(it);
SrsConfDirective* publish = dir->get_or_create("publish");
SrsConfDirective* firstpkt_timeout = publish->get_or_create("firstpkt_timeout");
firstpkt_timeout->args = conf->args;
srs_warn("transform: vhost.publish_1stpkt_timeout to vhost.publish.firstpkt_timeout for %s", dir->name.c_str());
srs_freep(conf);
continue;
}
// SRS3.0, change the publish_normal_timeout
// SRS2:
// vhost { publish_normal_timeout; }
// SRS3+:
// vhost { publish { normal_timeout; } }
if (n == "publish_normal_timeout") {
it = dir->directives.erase(it);
SrsConfDirective* publish = dir->get_or_create("publish");
SrsConfDirective* normal_timeout = publish->get_or_create("normal_timeout");
normal_timeout->args = conf->args;
srs_warn("transform: vhost.publish_normal_timeout to vhost.publish.normal_timeout for %s", dir->name.c_str());
srs_freep(conf);
continue;
}
// SRS3.0, change the bellow like a shadow:
// time_jitter, mix_correct, atc, atc_auto, mw_latency, gop_cache, queue_length
// SRS1/2:
// vhost { shadow; }
// SRS3+:
// vhost { play { shadow; } }
if (n == "time_jitter" || n == "mix_correct" || n == "atc" || n == "atc_auto"
|| n == "mw_latency" || n == "gop_cache" || n == "queue_length" || n == "send_min_interval"
|| n == "reduce_sequence_header") {
it = dir->directives.erase(it);
SrsConfDirective* play = dir->get_or_create("play");
SrsConfDirective* shadow = play->get_or_create(conf->name);
shadow->args = conf->args;
srs_warn("transform: vhost.%s to vhost.play.%s of %s", n.c_str(), n.c_str(), dir->name.c_str());
srs_freep(conf);
continue;
}
// SRS3.0, change the forward.
// SRS1/2:
// vhost { forward target; }
// SRS3+:
// vhost { forward { enabled; destination target; } }
if (n == "forward" && conf->directives.empty() && !conf->args.empty()) {
conf->get_or_create("enabled")->set_arg0("on");
SrsConfDirective* destination = conf->get_or_create("destination");
destination->args = conf->args;
conf->args.clear();
srs_warn("transform: vhost.forward to vhost.forward.destination for %s", dir->name.c_str());
++it;
continue;
}
// SRS3.0, change the bellow like a shadow:
// mode, origin, token_traverse, vhost, debug_srs_upnode
// SRS1/2:
// vhost { shadow; }
// SRS3+:
// vhost { cluster { shadow; } }
if (n == "mode" || n == "origin" || n == "token_traverse" || n == "vhost" || n == "debug_srs_upnode") {
it = dir->directives.erase(it);
SrsConfDirective* cluster = dir->get_or_create("cluster");
SrsConfDirective* shadow = cluster->get_or_create(conf->name);
shadow->args = conf->args;
srs_warn("transform: vhost.%s to vhost.cluster.%s of %s", n.c_str(), n.c_str(), dir->name.c_str());
srs_freep(conf);
continue;
}
// SRS4.0, move nack/twcc to rtc:
// vhost { nack {enabled; no_copy;} twcc {enabled} }
// as:
// vhost { rtc { nack on; nack_no_copy on; twcc on; } }
if (n == "nack" || n == "twcc") {
it = dir->directives.erase(it);
SrsConfDirective* rtc = dir->get_or_create("rtc");
if (n == "nack") {
if (conf->get("enabled")) {
rtc->get_or_create("nack")->args = conf->get("enabled")->args;
}
if (conf->get("no_copy")) {
rtc->get_or_create("nack_no_copy")->args = conf->get("no_copy")->args;
}
} else if (n == "twcc") {
if (conf->get("enabled")) {
rtc->get_or_create("twcc")->args = conf->get("enabled")->args;
}
}
srs_warn("transform: vhost.%s to vhost.rtc.%s of %s", n.c_str(), n.c_str(), dir->name.c_str());
srs_freep(conf);
continue;
}
// SRS3.0, change the forward.
// SRS1/2:
// vhost { rtc { aac; } }
// SRS3+:
// vhost { rtc { rtmp_to_rtc; } }
if (n == "rtc") {
SrsConfDirective* aac = conf->get("aac");
if (aac) {
string v = aac->arg0() == "transcode" ? "on" : "off";
conf->get_or_create("rtmp_to_rtc")->set_arg0(v);
conf->remove(aac); srs_freep(aac);
srs_warn("transform: vhost.rtc.aac to vhost.rtc.rtmp_to_rtc %s", v.c_str());
}
SrsConfDirective* bframe = conf->get("bframe");
if (bframe) {
string v = bframe->arg0() == "keep" ? "on" : "off";
conf->get_or_create("keep_bframe")->set_arg0(v);
conf->remove(bframe); srs_freep(bframe);
srs_warn("transform: vhost.rtc.bframe to vhost.rtc.keep_bframe %s", v.c_str());
}
++it;
continue;
}
++it;
}
}
return err;
}
// LCOV_EXCL_START
srs_error_t srs_config_dumps_engine(SrsConfDirective* dir, SrsJsonObject* engine)
{
srs_error_t err = srs_success;
SrsConfDirective* conf = NULL;
engine->set("id", dir->dumps_arg0_to_str());
engine->set("enabled", SrsJsonAny::boolean(_srs_config->get_engine_enabled(dir)));
if ((conf = dir->get("iformat")) != NULL) {
engine->set("iformat", conf->dumps_arg0_to_str());
}
if ((conf = dir->get("vfilter")) != NULL) {
SrsJsonObject* vfilter = SrsJsonAny::object();
engine->set("vfilter", vfilter);
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* sdir = conf->directives.at(i);
vfilter->set(sdir->name, sdir->dumps_arg0_to_str());
}
}
if ((conf = dir->get("vcodec")) != NULL) {
engine->set("vcodec", conf->dumps_arg0_to_str());
}
if ((conf = dir->get("vbitrate")) != NULL) {
engine->set("vbitrate", conf->dumps_arg0_to_integer());
}
if ((conf = dir->get("vfps")) != NULL) {
engine->set("vfps", conf->dumps_arg0_to_number());
}
if ((conf = dir->get("vwidth")) != NULL) {
engine->set("vwidth", conf->dumps_arg0_to_integer());
}
if ((conf = dir->get("vheight")) != NULL) {
engine->set("vheight", conf->dumps_arg0_to_integer());
}
if ((conf = dir->get("vthreads")) != NULL) {
engine->set("vthreads", conf->dumps_arg0_to_integer());
}
if ((conf = dir->get("vprofile")) != NULL) {
engine->set("vprofile", conf->dumps_arg0_to_str());
}
if ((conf = dir->get("vpreset")) != NULL) {
engine->set("vpreset", conf->dumps_arg0_to_str());
}
if ((conf = dir->get("vparams")) != NULL) {
SrsJsonObject* vparams = SrsJsonAny::object();
engine->set("vparams", vparams);
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* sdir = conf->directives.at(i);
vparams->set(sdir->name, sdir->dumps_arg0_to_str());
}
}
if ((conf = dir->get("acodec")) != NULL) {
engine->set("acodec", conf->dumps_arg0_to_str());
}
if ((conf = dir->get("abitrate")) != NULL) {
engine->set("abitrate", conf->dumps_arg0_to_integer());
}
if ((conf = dir->get("asample_rate")) != NULL) {
engine->set("asample_rate", conf->dumps_arg0_to_integer());
}
if ((conf = dir->get("achannels")) != NULL) {
engine->set("achannels", conf->dumps_arg0_to_integer());
}
if ((conf = dir->get("aparams")) != NULL) {
SrsJsonObject* aparams = SrsJsonAny::object();
engine->set("aparams", aparams);
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* sdir = conf->directives.at(i);
aparams->set(sdir->name, sdir->dumps_arg0_to_str());
}
}
if ((conf = dir->get("oformat")) != NULL) {
engine->set("oformat", conf->dumps_arg0_to_str());
}
if ((conf = dir->get("output")) != NULL) {
engine->set("output", conf->dumps_arg0_to_str());
}
return err;
}
// LCOV_EXCL_STOP
SrsConfDirective::SrsConfDirective()
{
conf_line = 0;
}
SrsConfDirective::~SrsConfDirective()
{
std::vector<SrsConfDirective*>::iterator it;
for (it = directives.begin(); it != directives.end(); ++it) {
SrsConfDirective* directive = *it;
srs_freep(directive);
}
directives.clear();
}
SrsConfDirective* SrsConfDirective::copy()
{
return copy("");
}
SrsConfDirective* SrsConfDirective::copy(string except)
{
SrsConfDirective* cp = new SrsConfDirective();
cp->conf_line = conf_line;
cp->name = name;
cp->args = args;
for (int i = 0; i < (int)directives.size(); i++) {
SrsConfDirective* directive = directives.at(i);
if (!except.empty() && directive->name == except) {
continue;
}
cp->directives.push_back(directive->copy(except));
}
return cp;
}
string SrsConfDirective::arg0()
{
if (args.size() > 0) {
return args.at(0);
}
return "";
}
string SrsConfDirective::arg1()
{
if (args.size() > 1) {
return args.at(1);
}
return "";
}
string SrsConfDirective::arg2()
{
if (args.size() > 2) {
return args.at(2);
}
return "";
}
string SrsConfDirective::arg3()
{
if (args.size() > 3) {
return args.at(3);
}
return "";
}
SrsConfDirective* SrsConfDirective::at(int index)
{
srs_assert(index < (int)directives.size());
return directives.at(index);
}
SrsConfDirective* SrsConfDirective::get(string _name)
{
std::vector<SrsConfDirective*>::iterator it;
for (it = directives.begin(); it != directives.end(); ++it) {
SrsConfDirective* directive = *it;
if (directive->name == _name) {
return directive;
}
}
return NULL;
}
SrsConfDirective* SrsConfDirective::get(string _name, string _arg0)
{
std::vector<SrsConfDirective*>::iterator it;
for (it = directives.begin(); it != directives.end(); ++it) {
SrsConfDirective* directive = *it;
if (directive->name == _name && directive->arg0() == _arg0) {
return directive;
}
}
return NULL;
}
SrsConfDirective* SrsConfDirective::get_or_create(string n)
{
SrsConfDirective* conf = get(n);
if (!conf) {
conf = new SrsConfDirective();
conf->name = n;
directives.push_back(conf);
}
return conf;
}
SrsConfDirective* SrsConfDirective::get_or_create(string n, string a0)
{
SrsConfDirective* conf = get(n, a0);
if (!conf) {
conf = new SrsConfDirective();
conf->name = n;
conf->args.push_back(a0);
directives.push_back(conf);
}
return conf;
}
SrsConfDirective* SrsConfDirective::get_or_create(string n, string a0, string a1)
{
SrsConfDirective* conf = get(n, a0);
if (!conf) {
conf = new SrsConfDirective();
conf->name = n;
conf->args.push_back(a0);
conf->args.push_back(a1);
directives.push_back(conf);
}
return conf;
}
SrsConfDirective* SrsConfDirective::set_arg0(string a0)
{
if (arg0() == a0) {
return this;
}
// update a0.
if (!args.empty()) {
args.erase(args.begin());
}
args.insert(args.begin(), a0);
return this;
}
void SrsConfDirective::remove(SrsConfDirective* v)
{
std::vector<SrsConfDirective*>::iterator it;
if ((it = std::find(directives.begin(), directives.end(), v)) != directives.end()) {
directives.erase(it);
}
}
bool SrsConfDirective::is_vhost()
{
return name == "vhost";
}
bool SrsConfDirective::is_stream_caster()
{
return name == "stream_caster";
}
srs_error_t SrsConfDirective::parse(SrsConfigBuffer* buffer)
{
return parse_conf(buffer, parse_file);
}
srs_error_t SrsConfDirective::persistence(SrsFileWriter* writer, int level)
{
srs_error_t err = srs_success;
static char SPACE = SRS_CONSTS_SP;
static char SEMICOLON = SRS_CONSTS_SE;
static char LF = SRS_CONSTS_LF;
static char LB = SRS_CONSTS_LB;
static char RB = SRS_CONSTS_RB;
static const char* INDENT = " ";
// for level0 directive, only contains sub directives.
if (level > 0) {
// indent by (level - 1) * 4 space.
for (int i = 0; i < level - 1; i++) {
if ((err = writer->write((char*)INDENT, 4, NULL)) != srs_success) {
return srs_error_wrap(err, "write indent");
}
}
// directive name.
if ((err = writer->write((char*)name.c_str(), (int)name.length(), NULL)) != srs_success) {
return srs_error_wrap(err, "write name");
}
if (!args.empty() && (err = writer->write((char*)&SPACE, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write name space");
}
// directive args.
for (int i = 0; i < (int)args.size(); i++) {
std::string& arg = args.at(i);
if ((err = writer->write((char*)arg.c_str(), (int)arg.length(), NULL)) != srs_success) {
return srs_error_wrap(err, "write arg");
}
if (i < (int)args.size() - 1 && (err = writer->write((char*)&SPACE, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write arg space");
}
}
// native directive, without sub directives.
if (directives.empty()) {
if ((err = writer->write((char*)&SEMICOLON, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write arg semicolon");
}
}
}
// persistence all sub directives.
if (level > 0) {
if (!directives.empty()) {
if ((err = writer->write((char*)&SPACE, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write sub-dir space");
}
if ((err = writer->write((char*)&LB, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write sub-dir left-brace");
}
}
if ((err = writer->write((char*)&LF, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write sub-dir linefeed");
}
}
for (int i = 0; i < (int)directives.size(); i++) {
SrsConfDirective* dir = directives.at(i);
if ((err = dir->persistence(writer, level + 1)) != srs_success) {
return srs_error_wrap(err, "sub-dir %s", dir->name.c_str());
}
}
if (level > 0 && !directives.empty()) {
// indent by (level - 1) * 4 space.
for (int i = 0; i < level - 1; i++) {
if ((err = writer->write((char*)INDENT, 4, NULL)) != srs_success) {
return srs_error_wrap(err, "write sub-dir indent");
}
}
if ((err = writer->write((char*)&RB, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write sub-dir right-brace");
}
if ((err = writer->write((char*)&LF, 1, NULL)) != srs_success) {
return srs_error_wrap(err, "write sub-dir linefeed");
}
}
return err;
}
// LCOV_EXCL_START
SrsJsonArray* SrsConfDirective::dumps_args()
{
SrsJsonArray* arr = SrsJsonAny::array();
for (int i = 0; i < (int)args.size(); i++) {
string arg = args.at(i);
arr->append(SrsJsonAny::str(arg.c_str()));
}
return arr;
}
SrsJsonAny* SrsConfDirective::dumps_arg0_to_str()
{
return SrsJsonAny::str(arg0().c_str());
}
SrsJsonAny* SrsConfDirective::dumps_arg0_to_integer()
{
return SrsJsonAny::integer(::atoll(arg0().c_str()));
}
SrsJsonAny* SrsConfDirective::dumps_arg0_to_number()
{
return SrsJsonAny::number(::atof(arg0().c_str()));
}
SrsJsonAny* SrsConfDirective::dumps_arg0_to_boolean()
{
return SrsJsonAny::boolean(arg0() == "on");
}
// LCOV_EXCL_STOP
// see: ngx_conf_parse
srs_error_t SrsConfDirective::parse_conf(SrsConfigBuffer* buffer, SrsDirectiveType type)
{
srs_error_t err = srs_success;
while (true) {
std::vector<string> args;
int line_start = 0;
err = read_token(buffer, args, line_start);
/**
* ret maybe:
* ERROR_SYSTEM_CONFIG_INVALID error.
* ERROR_SYSTEM_CONFIG_DIRECTIVE directive terminated by ';' found
* ERROR_SYSTEM_CONFIG_BLOCK_START token terminated by '{' found
* ERROR_SYSTEM_CONFIG_BLOCK_END the '}' found
* ERROR_SYSTEM_CONFIG_EOF the config file is done
*/
if (srs_error_code(err) == ERROR_SYSTEM_CONFIG_INVALID) {
return err;
}
if (srs_error_code(err) == ERROR_SYSTEM_CONFIG_BLOCK_END) {
if (type != parse_block) {
return srs_error_wrap(err, "line %d: unexpected \"}\"", buffer->line);
}
srs_freep(err);
return srs_success;
}
if (srs_error_code(err) == ERROR_SYSTEM_CONFIG_EOF) {
if (type == parse_block) {
return srs_error_wrap(err, "line %d: unexpected end of file, expecting \"}\"", conf_line);
}
srs_freep(err);
return srs_success;
}
if (args.empty()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "line %d: empty directive", conf_line);
}
// build directive tree.
SrsConfDirective* directive = new SrsConfDirective();
directive->conf_line = line_start;
directive->name = args[0];
args.erase(args.begin());
directive->args.swap(args);
directives.push_back(directive);
if (srs_error_code(err) == ERROR_SYSTEM_CONFIG_BLOCK_START) {
srs_freep(err);
if ((err = directive->parse_conf(buffer, parse_block)) != srs_success) {
return srs_error_wrap(err, "parse dir");
}
}
srs_freep(err);
}
return err;
}
// see: ngx_conf_read_token
srs_error_t SrsConfDirective::read_token(SrsConfigBuffer* buffer, vector<string>& args, int& line_start)
{
srs_error_t err = srs_success;
char* pstart = buffer->pos;
bool sharp_comment = false;
bool d_quoted = false;
bool s_quoted = false;
bool need_space = false;
bool last_space = true;
while (true) {
if (buffer->empty()) {
if (!args.empty() || !last_space) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID,
"line %d: unexpected end of file, expecting ; or \"}\"",
buffer->line);
}
srs_trace("config parse complete");
return srs_error_new(ERROR_SYSTEM_CONFIG_EOF, "EOF");
}
char ch = *buffer->pos++;
if (ch == SRS_LF) {
buffer->line++;
sharp_comment = false;
}
if (sharp_comment) {
continue;
}
if (need_space) {
if (is_common_space(ch)) {
last_space = true;
need_space = false;
continue;
}
if (ch == ';') {
return srs_error_new(ERROR_SYSTEM_CONFIG_DIRECTIVE, "dir");
}
if (ch == '{') {
return srs_error_new(ERROR_SYSTEM_CONFIG_BLOCK_START, "block");
}
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "line %d: unexpected '%c'", buffer->line, ch);
}
// last charecter is space.
if (last_space) {
if (is_common_space(ch)) {
continue;
}
pstart = buffer->pos - 1;
switch (ch) {
case ';':
if (args.size() == 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "line %d: unexpected ';'", buffer->line);
}
return srs_error_new(ERROR_SYSTEM_CONFIG_DIRECTIVE, "dir");
case '{':
if (args.size() == 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "line %d: unexpected '{'", buffer->line);
}
return srs_error_new(ERROR_SYSTEM_CONFIG_BLOCK_START, "block");
case '}':
if (args.size() != 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "line %d: unexpected '}'", buffer->line);
}
return srs_error_new(ERROR_SYSTEM_CONFIG_BLOCK_END, "block");
case '#':
sharp_comment = 1;
continue;
case '"':
pstart++;
d_quoted = true;
last_space = 0;
continue;
case '\'':
pstart++;
s_quoted = true;
last_space = 0;
continue;
default:
last_space = 0;
continue;
}
} else {
// last charecter is not space
if (line_start == 0) {
line_start = buffer->line;
}
bool found = false;
if (d_quoted) {
if (ch == '"') {
d_quoted = false;
need_space = true;
found = true;
}
} else if (s_quoted) {
if (ch == '\'') {
s_quoted = false;
need_space = true;
found = true;
}
} else if (is_common_space(ch) || ch == ';' || ch == '{') {
last_space = true;
found = 1;
}
if (found) {
int len = (int)(buffer->pos - pstart);
char* aword = new char[len];
memcpy(aword, pstart, len);
aword[len - 1] = 0;
string word_str = aword;
if (!word_str.empty()) {
args.push_back(word_str);
}
srs_freepa(aword);
if (ch == ';') {
return srs_error_new(ERROR_SYSTEM_CONFIG_DIRECTIVE, "dir");
}
if (ch == '{') {
return srs_error_new(ERROR_SYSTEM_CONFIG_BLOCK_START, "block");
}
}
}
}
return err;
}
SrsConfig::SrsConfig()
{
dolphin = false;
show_help = false;
show_version = false;
test_conf = false;
show_signature = false;
root = new SrsConfDirective();
root->conf_line = 0;
root->name = "root";
}
SrsConfig::~SrsConfig()
{
srs_freep(root);
}
bool SrsConfig::is_dolphin()
{
return dolphin;
}
void SrsConfig::subscribe(ISrsReloadHandler* handler)
{
std::vector<ISrsReloadHandler*>::iterator it;
it = std::find(subscribes.begin(), subscribes.end(), handler);
if (it != subscribes.end()) {
return;
}
subscribes.push_back(handler);
}
void SrsConfig::unsubscribe(ISrsReloadHandler* handler)
{
std::vector<ISrsReloadHandler*>::iterator it;
it = std::find(subscribes.begin(), subscribes.end(), handler);
if (it == subscribes.end()) {
return;
}
subscribes.erase(it);
}
// LCOV_EXCL_START
srs_error_t SrsConfig::reload()
{
srs_error_t err = srs_success;
SrsConfig conf;
if ((err = conf.parse_file(config_file.c_str())) != srs_success) {
return srs_error_wrap(err, "parse file");
}
srs_info("config reloader parse file success.");
// transform config to compatible with previous style of config.
if ((err = srs_config_transform_vhost(conf.root)) != srs_success) {
return srs_error_wrap(err, "transform config");
}
if ((err = conf.check_config()) != srs_success) {
return srs_error_wrap(err, "check config");
}
if ((err = reload_conf(&conf)) != srs_success) {
return srs_error_wrap(err, "reload config");
}
return err;
}
// LCOV_EXCL_STOP
srs_error_t SrsConfig::reload_vhost(SrsConfDirective* old_root)
{
srs_error_t err = srs_success;
// merge config.
std::vector<ISrsReloadHandler*>::iterator it;
// following directly support reload.
// origin, token_traverse, vhost, debug_srs_upnode
// state graph
// old_vhost new_vhost
// DISABLED => ENABLED
// ENABLED => DISABLED
// ENABLED => ENABLED (modified)
// collect all vhost names
std::vector<std::string> vhosts;
for (int i = 0; i < (int)root->directives.size(); i++) {
SrsConfDirective* vhost = root->at(i);
if (vhost->name != "vhost") {
continue;
}
vhosts.push_back(vhost->arg0());
}
for (int i = 0; i < (int)old_root->directives.size(); i++) {
SrsConfDirective* vhost = old_root->at(i);
if (vhost->name != "vhost") {
continue;
}
if (root->get("vhost", vhost->arg0())) {
continue;
}
vhosts.push_back(vhost->arg0());
}
// process each vhost
for (int i = 0; i < (int)vhosts.size(); i++) {
std::string vhost = vhosts.at(i);
SrsConfDirective* old_vhost = old_root->get("vhost", vhost);
SrsConfDirective* new_vhost = root->get("vhost", vhost);
// DISABLED => ENABLED
if (!get_vhost_enabled(old_vhost) && get_vhost_enabled(new_vhost)) {
if ((err = do_reload_vhost_added(vhost)) != srs_success) {
return srs_error_wrap(err, "reload vhost added");
}
continue;
}
// ENABLED => DISABLED
if (get_vhost_enabled(old_vhost) && !get_vhost_enabled(new_vhost)) {
if ((err = do_reload_vhost_removed(vhost)) != srs_success) {
return srs_error_wrap(err, "reload vhost removed");
}
continue;
}
// cluster.mode, never supports reload.
// first, for the origin and edge role change is too complex.
// second, the vhosts in origin device group normally are all origin,
// they never change to edge sometimes.
// third, the origin or upnode device can always be restart,
// edge will retry and the users connected to edge are ok.
// it's ok to add or remove edge/origin vhost.
if (get_vhost_is_edge(old_vhost) != get_vhost_is_edge(new_vhost)) {
return srs_error_new(ERROR_RTMP_EDGE_RELOAD, "vhost mode changed");
}
// the auto reload configs:
// publish.parse_sps
// ENABLED => ENABLED (modified)
if (get_vhost_enabled(new_vhost) && get_vhost_enabled(old_vhost)) {
srs_trace("vhost %s maybe modified, reload its detail.", vhost.c_str());
// chunk_size, only one per vhost.
if (!srs_directive_equals(new_vhost->get("chunk_size"), old_vhost->get("chunk_size"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_chunk_size(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes chunk_size failed", vhost.c_str());
}
}
srs_trace("vhost %s reload chunk_size success.", vhost.c_str());
}
// tcp_nodelay, only one per vhost
if (!srs_directive_equals(new_vhost->get("tcp_nodelay"), old_vhost->get("tcp_nodelay"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_tcp_nodelay(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes tcp_nodelay failed", vhost.c_str());
}
}
srs_trace("vhost %s reload tcp_nodelay success.", vhost.c_str());
}
// min_latency, only one per vhost
if (!srs_directive_equals(new_vhost->get("min_latency"), old_vhost->get("min_latency"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_realtime(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes min_latency failed", vhost.c_str());
}
}
srs_trace("vhost %s reload min_latency success.", vhost.c_str());
}
// play, only one per vhost
if (!srs_directive_equals(new_vhost->get("play"), old_vhost->get("play"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_play(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes play failed", vhost.c_str());
}
}
srs_trace("vhost %s reload play success.", vhost.c_str());
}
// forward, only one per vhost
if (!srs_directive_equals(new_vhost->get("forward"), old_vhost->get("forward"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_forward(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes forward failed", vhost.c_str());
}
}
srs_trace("vhost %s reload forward success.", vhost.c_str());
}
// To reload DASH.
if (!srs_directive_equals(new_vhost->get("dash"), old_vhost->get("dash"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_dash(vhost)) != srs_success) {
return srs_error_wrap(err, "Reload vhost %s dash failed", vhost.c_str());
}
}
srs_trace("Reload vhost %s dash ok.", vhost.c_str());
}
// hls, only one per vhost
// @remark, the hls_on_error directly support reload.
if (!srs_directive_equals(new_vhost->get("hls"), old_vhost->get("hls"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_hls(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes hls failed", vhost.c_str());
}
}
srs_trace("vhost %s reload hls success.", vhost.c_str());
}
// hds reload
if (!srs_directive_equals(new_vhost->get("hds"), old_vhost->get("hds"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_hds(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes hds failed", vhost.c_str());
}
}
srs_trace("vhost %s reload hds success.", vhost.c_str());
}
// dvr, only one per vhost, except the dvr_apply
if (!srs_directive_equals(new_vhost->get("dvr"), old_vhost->get("dvr"), "dvr_apply")) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_dvr(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes dvr failed", vhost.c_str());
}
}
srs_trace("vhost %s reload dvr success.", vhost.c_str());
}
// exec, only one per vhost
if (!srs_directive_equals(new_vhost->get("exec"), old_vhost->get("exec"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_exec(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes exec failed", vhost.c_str());
}
}
srs_trace("vhost %s reload exec success.", vhost.c_str());
}
// publish, only one per vhost
if (!srs_directive_equals(new_vhost->get("publish"), old_vhost->get("publish"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_publish(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes publish failed", vhost.c_str());
}
}
srs_trace("vhost %s reload publish success.", vhost.c_str());
}
// http_static, only one per vhost.
if (!srs_directive_equals(new_vhost->get("http_static"), old_vhost->get("http_static"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_http_updated()) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes http_static failed", vhost.c_str());
}
}
srs_trace("vhost %s reload http_static success.", vhost.c_str());
}
// http_remux, only one per vhost.
if (!srs_directive_equals(new_vhost->get("http_remux"), old_vhost->get("http_remux"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_http_remux_updated(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes http_remux failed", vhost.c_str());
}
}
srs_trace("vhost %s reload http_remux success.", vhost.c_str());
}
// transcode, many per vhost.
if ((err = reload_transcode(new_vhost, old_vhost)) != srs_success) {
return srs_error_wrap(err, "reload transcode");
}
// ingest, many per vhost.
if ((err = reload_ingest(new_vhost, old_vhost)) != srs_success) {
return srs_error_wrap(err, "reload ingest");
}
continue;
}
srs_trace("ignore reload vhost, enabled old: %d, new: %d",
get_vhost_enabled(old_vhost), get_vhost_enabled(new_vhost));
}
return err;
}
srs_error_t SrsConfig::reload_conf(SrsConfig* conf)
{
srs_error_t err = srs_success;
SrsConfDirective* old_root = root;
SrsAutoFree(SrsConfDirective, old_root);
root = conf->root;
conf->root = NULL;
// never support reload:
// daemon
//
// always support reload without additional code:
// chunk_size, ff_log_dir,
// bandcheck, http_hooks, heartbeat,
// security
// merge config: listen
if (!srs_directive_equals(root->get("listen"), old_root->get("listen"))) {
if ((err = do_reload_listen()) != srs_success) {
return srs_error_wrap(err, "listen");
}
}
// merge config: pid
if (!srs_directive_equals(root->get("pid"), old_root->get("pid"))) {
if ((err = do_reload_pid()) != srs_success) {
return srs_error_wrap(err, "pid");;
}
}
// merge config: srs_log_tank
if (!srs_directive_equals(root->get("srs_log_tank"), old_root->get("srs_log_tank"))) {
if ((err = do_reload_srs_log_tank()) != srs_success) {
return srs_error_wrap(err, "log tank");;
}
}
// merge config: srs_log_level
if (!srs_directive_equals(root->get("srs_log_level"), old_root->get("srs_log_level"))) {
if ((err = do_reload_srs_log_level()) != srs_success) {
return srs_error_wrap(err, "log level");;
}
}
// merge config: srs_log_file
if (!srs_directive_equals(root->get("srs_log_file"), old_root->get("srs_log_file"))) {
if ((err = do_reload_srs_log_file()) != srs_success) {
return srs_error_wrap(err, "log file");;
}
}
// merge config: max_connections
if (!srs_directive_equals(root->get("max_connections"), old_root->get("max_connections"))) {
if ((err = do_reload_max_connections()) != srs_success) {
return srs_error_wrap(err, "max connections");;
}
}
// merge config: utc_time
if (!srs_directive_equals(root->get("utc_time"), old_root->get("utc_time"))) {
if ((err = do_reload_utc_time()) != srs_success) {
return srs_error_wrap(err, "utc time");;
}
}
// merge config: pithy_print_ms
if (!srs_directive_equals(root->get("pithy_print_ms"), old_root->get("pithy_print_ms"))) {
if ((err = do_reload_pithy_print_ms()) != srs_success) {
return srs_error_wrap(err, "pithy print ms");;
}
}
// merge config: http_api
if ((err = reload_http_api(old_root)) != srs_success) {
return srs_error_wrap(err, "http api");;
}
// merge config: http_stream
if ((err = reload_http_stream(old_root)) != srs_success) {
return srs_error_wrap(err, "http steram");;
}
// Merge config: rtc_server
if ((err = reload_rtc_server(old_root)) != srs_success) {
return srs_error_wrap(err, "http steram");;
}
// TODO: FIXME: support reload stream_caster.
// merge config: vhost
if ((err = reload_vhost(old_root)) != srs_success) {
return srs_error_wrap(err, "vhost");;
}
return err;
}
srs_error_t SrsConfig::reload_http_api(SrsConfDirective* old_root)
{
srs_error_t err = srs_success;
// merge config.
std::vector<ISrsReloadHandler*>::iterator it;
// state graph
// old_http_api new_http_api
// DISABLED => ENABLED
// ENABLED => DISABLED
// ENABLED => ENABLED (modified)
SrsConfDirective* new_http_api = root->get("http_api");
SrsConfDirective* old_http_api = old_root->get("http_api");
// DISABLED => ENABLED
if (!get_http_api_enabled(old_http_api) && get_http_api_enabled(new_http_api)) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_api_enabled()) != srs_success) {
return srs_error_wrap(err, "http api off=>on");
}
}
srs_trace("reload off=>on http_api success.");
return err;
}
// ENABLED => DISABLED
if (get_http_api_enabled(old_http_api) && !get_http_api_enabled(new_http_api)) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_api_disabled()) != srs_success) {
return srs_error_wrap(err, "http api on=>off");
}
}
srs_trace("reload http_api on=>off success.");
return err;
}
// ENABLED => ENABLED (modified)
if (get_http_api_enabled(old_http_api) && get_http_api_enabled(new_http_api)
&& !srs_directive_equals(old_http_api, new_http_api)
) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_api_enabled()) != srs_success) {
return srs_error_wrap(err, "http api enabled");
}
}
srs_trace("reload http api enabled success.");
if (!srs_directive_equals(old_http_api->get("crossdomain"), new_http_api->get("crossdomain"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_api_crossdomain()) != srs_success) {
return srs_error_wrap(err, "http api crossdomain");
}
}
}
srs_trace("reload http api crossdomain success.");
if (!srs_directive_equals(old_http_api->get("raw_api"), new_http_api->get("raw_api"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_api_raw_api()) != srs_success) {
return srs_error_wrap(err, "http api raw_api");
}
}
}
srs_trace("reload http api raw_api success.");
return err;
}
srs_trace("reload http_api success, nothing changed.");
return err;
}
srs_error_t SrsConfig::reload_http_stream(SrsConfDirective* old_root)
{
srs_error_t err = srs_success;
// merge config.
std::vector<ISrsReloadHandler*>::iterator it;
// state graph
// old_http_stream new_http_stream
// DISABLED => ENABLED
// ENABLED => DISABLED
// ENABLED => ENABLED (modified)
SrsConfDirective* new_http_stream = root->get("http_server");
SrsConfDirective* old_http_stream = old_root->get("http_server");
// DISABLED => ENABLED
if (!get_http_stream_enabled(old_http_stream) && get_http_stream_enabled(new_http_stream)) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_stream_enabled()) != srs_success) {
return srs_error_wrap(err, "http stream off=>on");
}
}
srs_trace("reload http stream off=>on success.");
return err;
}
// ENABLED => DISABLED
if (get_http_stream_enabled(old_http_stream) && !get_http_stream_enabled(new_http_stream)) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_stream_disabled()) != srs_success) {
return srs_error_wrap(err, "http stream on=>off");
}
}
srs_trace("reload http stream on=>off success.");
return err;
}
// ENABLED => ENABLED (modified)
if (get_http_stream_enabled(old_http_stream) && get_http_stream_enabled(new_http_stream)
&& !srs_directive_equals(old_http_stream, new_http_stream)
) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_stream_updated()) != srs_success) {
return srs_error_wrap(err, "http stream enabled");
}
}
srs_trace("reload http stream enabled success.");
if (!srs_directive_equals(old_http_stream->get("crossdomain"), new_http_stream->get("crossdomain"))) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_http_stream_crossdomain()) != srs_success) {
return srs_error_wrap(err, "http stream crossdomain");
}
}
}
srs_trace("reload http stream crossdomain success.");
return err;
}
srs_trace("reload http stream success, nothing changed.");
return err;
}
srs_error_t SrsConfig::reload_rtc_server(SrsConfDirective* old_root)
{
srs_error_t err = srs_success;
// merge config.
std::vector<ISrsReloadHandler*>::iterator it;
// state graph
// old_rtc_server new_rtc_server
// ENABLED => ENABLED (modified)
SrsConfDirective* new_rtc_server = root->get("rtc_server");
SrsConfDirective* old_rtc_server = old_root->get("rtc_server");
// TODO: FIXME: Support disable or enable reloading.
// ENABLED => ENABLED (modified)
if (get_rtc_server_enabled(old_rtc_server) && get_rtc_server_enabled(new_rtc_server)
&& !srs_directive_equals(old_rtc_server, new_rtc_server)
) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_rtc_server()) != srs_success) {
return srs_error_wrap(err, "rtc server enabled");
}
}
srs_trace("reload rtc server success.");
return err;
}
srs_trace("reload rtc server success, nothing changed.");
return err;
}
srs_error_t SrsConfig::reload_transcode(SrsConfDirective* new_vhost, SrsConfDirective* old_vhost)
{
srs_error_t err = srs_success;
std::vector<SrsConfDirective*> old_transcoders;
for (int i = 0; i < (int)old_vhost->directives.size(); i++) {
SrsConfDirective* conf = old_vhost->at(i);
if (conf->name == "transcode") {
old_transcoders.push_back(conf);
}
}
std::vector<SrsConfDirective*> new_transcoders;
for (int i = 0; i < (int)new_vhost->directives.size(); i++) {
SrsConfDirective* conf = new_vhost->at(i);
if (conf->name == "transcode") {
new_transcoders.push_back(conf);
}
}
std::vector<ISrsReloadHandler*>::iterator it;
std::string vhost = new_vhost->arg0();
// to be simple:
// whatever, once tiny changed of transcode,
// restart all ffmpeg of vhost.
bool changed = false;
// discovery the removed ffmpeg.
for (int i = 0; !changed && i < (int)old_transcoders.size(); i++) {
SrsConfDirective* old_transcoder = old_transcoders.at(i);
std::string transcoder_id = old_transcoder->arg0();
// if transcoder exists in new vhost, not removed, ignore.
if (new_vhost->get("transcode", transcoder_id)) {
continue;
}
changed = true;
}
// discovery the added ffmpeg.
for (int i = 0; !changed && i < (int)new_transcoders.size(); i++) {
SrsConfDirective* new_transcoder = new_transcoders.at(i);
std::string transcoder_id = new_transcoder->arg0();
// if transcoder exists in old vhost, not added, ignore.
if (old_vhost->get("transcode", transcoder_id)) {
continue;
}
changed = true;
}
// for updated transcoders, restart them.
for (int i = 0; !changed && i < (int)new_transcoders.size(); i++) {
SrsConfDirective* new_transcoder = new_transcoders.at(i);
std::string transcoder_id = new_transcoder->arg0();
SrsConfDirective* old_transcoder = old_vhost->get("transcode", transcoder_id);
srs_assert(old_transcoder);
if (srs_directive_equals(new_transcoder, old_transcoder)) {
continue;
}
changed = true;
}
// transcode, many per vhost
if (changed) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_transcode(vhost)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes transcode failed", vhost.c_str());
}
}
srs_trace("vhost %s reload transcode success.", vhost.c_str());
}
return err;
}
srs_error_t SrsConfig::reload_ingest(SrsConfDirective* new_vhost, SrsConfDirective* old_vhost)
{
srs_error_t err = srs_success;
std::vector<SrsConfDirective*> old_ingesters;
for (int i = 0; i < (int)old_vhost->directives.size(); i++) {
SrsConfDirective* conf = old_vhost->at(i);
if (conf->name == "ingest") {
old_ingesters.push_back(conf);
}
}
std::vector<SrsConfDirective*> new_ingesters;
for (int i = 0; i < (int)new_vhost->directives.size(); i++) {
SrsConfDirective* conf = new_vhost->at(i);
if (conf->name == "ingest") {
new_ingesters.push_back(conf);
}
}
std::vector<ISrsReloadHandler*>::iterator it;
std::string vhost = new_vhost->arg0();
// for removed ingesters, stop them.
for (int i = 0; i < (int)old_ingesters.size(); i++) {
SrsConfDirective* old_ingester = old_ingesters.at(i);
std::string ingest_id = old_ingester->arg0();
SrsConfDirective* new_ingester = new_vhost->get("ingest", ingest_id);
// ENABLED => DISABLED
if (get_ingest_enabled(old_ingester) && !get_ingest_enabled(new_ingester)) {
// notice handler ingester removed.
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_ingest_removed(vhost, ingest_id)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes ingest=%s removed failed", vhost.c_str(), ingest_id.c_str());
}
}
srs_trace("vhost %s reload ingest=%s removed success.", vhost.c_str(), ingest_id.c_str());
}
}
// for added ingesters, start them.
for (int i = 0; i < (int)new_ingesters.size(); i++) {
SrsConfDirective* new_ingester = new_ingesters.at(i);
std::string ingest_id = new_ingester->arg0();
SrsConfDirective* old_ingester = old_vhost->get("ingest", ingest_id);
// DISABLED => ENABLED
if (!get_ingest_enabled(old_ingester) && get_ingest_enabled(new_ingester)) {
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_ingest_added(vhost, ingest_id)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes ingest=%s added failed", vhost.c_str(), ingest_id.c_str());
}
}
srs_trace("vhost %s reload ingest=%s added success.", vhost.c_str(), ingest_id.c_str());
}
}
// for updated ingesters, restart them.
for (int i = 0; i < (int)new_ingesters.size(); i++) {
SrsConfDirective* new_ingester = new_ingesters.at(i);
std::string ingest_id = new_ingester->arg0();
SrsConfDirective* old_ingester = old_vhost->get("ingest", ingest_id);
// ENABLED => ENABLED
if (get_ingest_enabled(old_ingester) && get_ingest_enabled(new_ingester)) {
if (srs_directive_equals(new_ingester, old_ingester)) {
continue;
}
// notice handler ingester removed.
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_ingest_updated(vhost, ingest_id)) != srs_success) {
return srs_error_wrap(err, "vhost %s notify subscribes ingest=%s updated failed", vhost.c_str(), ingest_id.c_str());
}
}
srs_trace("vhost %s reload ingest=%s updated success.", vhost.c_str(), ingest_id.c_str());
}
}
srs_trace("ingest nothing changed for vhost=%s", vhost.c_str());
return err;
}
// see: ngx_get_options
// LCOV_EXCL_START
srs_error_t SrsConfig::parse_options(int argc, char** argv)
{
srs_error_t err = srs_success;
// argv
for (int i = 0; i < argc; i++) {
_argv.append(argv[i]);
if (i < argc - 1) {
_argv.append(" ");
}
}
// Show help if has any argv
show_help = argc > 1;
for (int i = 1; i < argc; i++) {
if ((err = parse_argv(i, argv)) != srs_success) {
return srs_error_wrap(err, "parse argv");
}
}
if (show_help) {
print_help(argv);
exit(0);
}
if (show_version) {
fprintf(stderr, "%s\n", RTMP_SIG_SRS_VERSION);
exit(0);
}
if (show_signature) {
fprintf(stderr, "%s\n", RTMP_SIG_SRS_SERVER);
exit(0);
}
// first hello message.
srs_trace(_srs_version);
// Try config files as bellow:
// User specified config(not empty), like user/docker.conf
// If user specified *docker.conf, try *srs.conf, like user/srs.conf
// Try the default srs config, defined as SRS_CONF_DEFAULT_COFNIG_FILE, like conf/srs.conf
// Try config for FHS, like /etc/srs/srs.conf @see https://github.com/ossrs/srs/pull/2711
if (true) {
vector<string> try_config_files;
if (!config_file.empty()) {
try_config_files.push_back(config_file);
}
if (srs_string_ends_with(config_file, "docker.conf")) {
try_config_files.push_back(srs_string_replace(config_file, "docker.conf", "srs.conf"));
}
try_config_files.push_back(SRS_CONF_DEFAULT_COFNIG_FILE);
try_config_files.push_back("/etc/srs/srs.conf");
// Match the first exists file.
string exists_config_file;
for (int i = 0; i < (int) try_config_files.size(); i++) {
string try_config_file = try_config_files.at(i);
if (srs_path_exists(try_config_file)) {
exists_config_file = try_config_file;
break;
}
}
if (exists_config_file.empty()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "no config file at %s", srs_join_vector_string(try_config_files, ", ").c_str());
}
if (config_file != exists_config_file) {
srs_warn("user config %s does not exists, use %s instead", config_file.c_str(), exists_config_file.c_str());
config_file = exists_config_file;
}
}
// Parse the matched config file.
err = parse_file(config_file.c_str());
if (test_conf) {
// the parse_file never check the config,
// we check it when user requires check config file.
if (err == srs_success && (err = srs_config_transform_vhost(root)) == srs_success) {
if (err == srs_success && (err = check_config()) == srs_success) {
srs_trace("config file is ok");
exit(0);
}
}
srs_error("invalid config, %s", srs_error_desc(err).c_str());
int ret = srs_error_code(err);
srs_freep(err);
exit(ret);
}
// transform config to compatible with previous style of config.
if ((err = srs_config_transform_vhost(root)) != srs_success) {
return srs_error_wrap(err, "transform");
}
////////////////////////////////////////////////////////////////////////
// check log name and level
////////////////////////////////////////////////////////////////////////
if (true) {
std::string log_filename = this->get_log_file();
if (get_log_tank_file() && log_filename.empty()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "no log file");
}
if (get_log_tank_file()) {
srs_trace("you can check log by: tail -n 30 -f %s", log_filename.c_str());
srs_trace("please check SRS by: ./etc/init.d/srs status");
} else {
srs_trace("write log to console");
}
}
return err;
}
srs_error_t SrsConfig::initialize_cwd()
{
// cwd
char cwd[256];
getcwd(cwd, sizeof(cwd));
_cwd = cwd;
return srs_success;
}
srs_error_t SrsConfig::persistence()
{
srs_error_t err = srs_success;
// write to a tmp file, then mv to the config.
std::string path = config_file + ".tmp";
// open the tmp file for persistence
SrsFileWriter fw;
if ((err = fw.open(path)) != srs_success) {
return srs_error_wrap(err, "open file");
}
// do persistence to writer.
if ((err = do_persistence(&fw)) != srs_success) {
::unlink(path.c_str());
return srs_error_wrap(err, "persistence");
}
// rename the config file.
if (::rename(path.c_str(), config_file.c_str()) < 0) {
::unlink(path.c_str());
return srs_error_new(ERROR_SYSTEM_CONFIG_PERSISTENCE, "rename %s=>%s", path.c_str(), config_file.c_str());
}
return err;
}
srs_error_t SrsConfig::do_persistence(SrsFileWriter* fw)
{
srs_error_t err = srs_success;
// persistence root directive to writer.
if ((err = root->persistence(fw, 0)) != srs_success) {
return srs_error_wrap(err, "root persistence");
}
return err;
}
srs_error_t SrsConfig::raw_to_json(SrsJsonObject* obj)
{
srs_error_t err = srs_success;
SrsJsonObject* sobj = SrsJsonAny::object();
obj->set("http_api", sobj);
sobj->set("enabled", SrsJsonAny::boolean(get_http_api_enabled()));
sobj->set("listen", SrsJsonAny::str(get_http_api_listen().c_str()));
sobj->set("crossdomain", SrsJsonAny::boolean(get_http_api_crossdomain()));
SrsJsonObject* ssobj = SrsJsonAny::object();
sobj->set("raw_api", ssobj);
ssobj->set("enabled", SrsJsonAny::boolean(get_raw_api()));
ssobj->set("allow_reload", SrsJsonAny::boolean(get_raw_api_allow_reload()));
ssobj->set("allow_query", SrsJsonAny::boolean(get_raw_api_allow_query()));
ssobj->set("allow_update", SrsJsonAny::boolean(get_raw_api_allow_update()));
return err;
}
srs_error_t SrsConfig::do_reload_listen()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_listen()) != srs_success) {
return srs_error_wrap(err, "notify subscribes reload listen failed");
}
}
srs_trace("reload listen success.");
return err;
}
srs_error_t SrsConfig::do_reload_pid()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_pid()) != srs_success) {
return srs_error_wrap(err, "notify subscribes reload pid failed");
}
}
srs_trace("reload pid success.");
return err;
}
srs_error_t SrsConfig::do_reload_srs_log_tank()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_log_tank()) != srs_success) {
return srs_error_wrap(err, "notify subscribes reload srs_log_tank failed");
}
}
srs_trace("reload srs_log_tank success.");
return err;
}
srs_error_t SrsConfig::do_reload_srs_log_level()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_log_level()) != srs_success) {
return srs_error_wrap(err, "notify subscribes reload srs_log_level failed");
}
}
srs_trace("reload srs_log_level success.");
return err;
}
srs_error_t SrsConfig::do_reload_srs_log_file()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_log_file()) != srs_success) {
return srs_error_wrap(err, "notify subscribes reload srs_log_file failed");
}
}
srs_trace("reload srs_log_file success.");
return err;
}
srs_error_t SrsConfig::do_reload_max_connections()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_max_conns()) != srs_success) {
return srs_error_wrap(err, "notify subscribes reload max_connections failed");
}
}
srs_trace("reload max_connections success.");
return err;
}
srs_error_t SrsConfig::do_reload_utc_time()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_utc_time()) != srs_success) {
return srs_error_wrap(err, "utc_time");
}
}
srs_trace("reload utc_time success.");
return err;
}
srs_error_t SrsConfig::do_reload_pithy_print_ms()
{
srs_error_t err = srs_success;
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_pithy_print()) != srs_success) {
return srs_error_wrap(err, "notify subscribes pithy_print_ms failed");
}
}
srs_trace("reload pithy_print_ms success.");
return err;
}
srs_error_t SrsConfig::do_reload_vhost_added(string vhost)
{
srs_error_t err = srs_success;
srs_trace("vhost %s added, reload it.", vhost.c_str());
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_added(vhost)) != srs_success) {
return srs_error_wrap(err, "notify subscribes added vhost %s failed", vhost.c_str());
}
}
srs_trace("reload new vhost %s success.", vhost.c_str());
return err;
}
srs_error_t SrsConfig::do_reload_vhost_removed(string vhost)
{
srs_error_t err = srs_success;
srs_trace("vhost %s removed, reload it.", vhost.c_str());
vector<ISrsReloadHandler*>::iterator it;
for (it = subscribes.begin(); it != subscribes.end(); ++it) {
ISrsReloadHandler* subscribe = *it;
if ((err = subscribe->on_reload_vhost_removed(vhost)) != srs_success) {
return srs_error_wrap(err, "notify subscribes removed vhost %s failed", vhost.c_str());
}
}
srs_trace("reload removed vhost %s success.", vhost.c_str());
return err;
}
string SrsConfig::config()
{
return config_file;
}
// LCOV_EXCL_START
srs_error_t SrsConfig::parse_argv(int& i, char** argv)
{
srs_error_t err = srs_success;
char* p = argv[i];
if (*p++ != '-') {
show_help = true;
return err;
}
while (*p) {
switch (*p++) {
case '?':
case 'h':
show_help = true;
break;
case 't':
show_help = false;
test_conf = true;
break;
case 'p':
dolphin = true;
if (*p) {
dolphin_rtmp_port = p;
continue;
}
if (argv[++i]) {
dolphin_rtmp_port = argv[i];
continue;
}
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "-p requires params");
case 'x':
dolphin = true;
if (*p) {
dolphin_http_port = p;
continue;
}
if (argv[++i]) {
dolphin_http_port = argv[i];
continue;
}
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "-x requires params");
case 'v':
case 'V':
show_help = false;
show_version = true;
break;
case 'g':
case 'G':
show_help = false;
show_signature = true;
break;
case 'c':
show_help = false;
if (*p) {
config_file = p;
continue;
}
if (argv[++i]) {
config_file = argv[i];
continue;
}
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "-c requires params");
default:
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "invalid option: \"%c\", read help: %s -h",
*(p - 1), argv[0]);
}
}
return err;
}
void SrsConfig::print_help(char** argv)
{
printf(
"%s, %s, %s, created by %s\n\n"
"Usage: %s <-h?vVgG>|<[-t] -c filename>\n"
"Options:\n"
" -?, -h : Show this help and exit 0.\n"
" -v, -V : Show version and exit 0.\n"
" -g, -G : Show server signature and exit 0.\n"
" -t : Test configuration file, exit with error code(0 for success).\n"
" -c filename : Use config file to start server.\n"
"For example:\n"
" %s -v\n"
" %s -t -c %s\n"
" %s -c %s\n",
RTMP_SIG_SRS_SERVER, RTMP_SIG_SRS_URL, RTMP_SIG_SRS_LICENSE,
RTMP_SIG_SRS_AUTHORS,
argv[0], argv[0], argv[0], SRS_CONF_DEFAULT_COFNIG_FILE,
argv[0], SRS_CONF_DEFAULT_COFNIG_FILE);
}
srs_error_t SrsConfig::parse_file(const char* filename)
{
srs_error_t err = srs_success;
config_file = filename;
if (config_file.empty()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "empty config");
}
SrsConfigBuffer buffer;
if ((err = buffer.fullfill(config_file.c_str())) != srs_success) {
return srs_error_wrap(err, "buffer fullfil");
}
if ((err = parse_buffer(&buffer)) != srs_success) {
return srs_error_wrap(err, "parse buffer");
}
return err;
}
// LCOV_EXCL_STOP
srs_error_t SrsConfig::check_config()
{
srs_error_t err = srs_success;
if ((err = check_normal_config()) != srs_success) {
return srs_error_wrap(err, "check normal");
}
if ((err = check_number_connections()) != srs_success) {
return srs_error_wrap(err, "check connections");
}
// If use the full.conf, fail.
if (is_full_config()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID,
"never use full.conf(%s)", config_file.c_str());
}
return err;
}
srs_error_t SrsConfig::check_normal_config()
{
srs_error_t err = srs_success;
srs_trace("srs checking config...");
////////////////////////////////////////////////////////////////////////
// check empty
////////////////////////////////////////////////////////////////////////
if (root->directives.size() == 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "conf is empty");
}
////////////////////////////////////////////////////////////////////////
// check root directives.
////////////////////////////////////////////////////////////////////////
for (int i = 0; i < (int)root->directives.size(); i++) {
SrsConfDirective* conf = root->at(i);
std::string n = conf->name;
if (n != "listen" && n != "pid" && n != "chunk_size" && n != "ff_log_dir"
&& n != "srs_log_tank" && n != "srs_log_level" && n != "srs_log_file"
&& n != "max_connections" && n != "daemon" && n != "heartbeat"
&& n != "http_api" && n != "stats" && n != "vhost" && n != "pithy_print_ms"
&& n != "http_server" && n != "stream_caster" && n != "rtc_server" && n != "srt_server"
&& n != "utc_time" && n != "work_dir" && n != "asprocess"
&& n != "ff_log_level" && n != "grace_final_wait" && n != "force_grace_quit"
&& n != "grace_start_wait" && n != "empty_ip_ok" && n != "disable_daemon_for_docker"
&& n != "inotify_auto_reload" && n != "auto_reload_for_docker" && n != "tcmalloc_release_rate"
&& n != "query_latest_version"
&& n != "circuit_breaker" && n != "is_full" && n != "in_docker"
) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal directive %s", n.c_str());
}
}
if (true) {
SrsConfDirective* conf = root->get("http_api");
for (int i = 0; conf && i < (int)conf->directives.size(); i++) {
SrsConfDirective* obj = conf->at(i);
string n = obj->name;
if (n != "enabled" && n != "listen" && n != "crossdomain" && n != "raw_api" && n != "https") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal http_api.%s", n.c_str());
}
if (n == "raw_api") {
for (int j = 0; j < (int)obj->directives.size(); j++) {
string m = obj->at(j)->name;
if (m != "enabled" && m != "allow_reload" && m != "allow_query" && m != "allow_update") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal http_api.raw_api.%s", m.c_str());
}
}
}
}
}
if (true) {
SrsConfDirective* conf = root->get("http_server");
for (int i = 0; conf && i < (int)conf->directives.size(); i++) {
string n = conf->at(i)->name;
if (n != "enabled" && n != "listen" && n != "dir" && n != "crossdomain" && n != "https") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal http_stream.%s", n.c_str());
}
}
}
if (true) {
SrsConfDirective* conf = root->get("srt_server");
for (int i = 0; conf && i < (int)conf->directives.size(); i++) {
string n = conf->at(i)->name;
if (n != "enabled" && n != "listen" && n != "maxbw"
&& n != "mss" && n != "latency" && n != "recvlatency"
&& n != "peerlatency" && n != "tlpkdrop" && n != "connect_timeout"
&& n != "sendbuf" && n != "recvbuf" && n != "payloadsize"
&& n != "default_app" && n != "mix_correct" && n != "sei_filter") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal srt_stream.%s", n.c_str());
}
}
}
if (true) {
SrsConfDirective* conf = get_heartbeart();
for (int i = 0; conf && i < (int)conf->directives.size(); i++) {
string n = conf->at(i)->name;
if (n != "enabled" && n != "interval" && n != "url"
&& n != "device_id" && n != "summaries") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal heartbeat.%s", n.c_str());
}
}
}
if (true) {
SrsConfDirective* conf = get_stats();
for (int i = 0; conf && i < (int)conf->directives.size(); i++) {
string n = conf->at(i)->name;
if (n != "enabled" && n != "network" && n != "disk") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal stats.%s", n.c_str());
}
}
}
if (true) {
SrsConfDirective* conf = root->get("rtc_server");
for (int i = 0; conf && i < (int)conf->directives.size(); i++) {
string n = conf->at(i)->name;
if (n != "enabled" && n != "listen" && n != "dir" && n != "candidate" && n != "ecdsa"
&& n != "encrypt" && n != "reuseport" && n != "merge_nalus" && n != "black_hole"
&& n != "ip_family" && n != "api_as_candidates") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal rtc_server.%s", n.c_str());
}
}
}
////////////////////////////////////////////////////////////////////////
// check listen for rtmp.
////////////////////////////////////////////////////////////////////////
if (true) {
vector<string> listens = get_listens();
if (listens.size() <= 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "listen requires params");
}
for (int i = 0; i < (int)listens.size(); i++) {
int port; string ip;
srs_parse_endpoint(listens[i], ip, port);
// check ip
if (!srs_check_ip_addr_valid(ip)) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "listen.ip=%s is invalid", ip.c_str());
}
// check port
if (port <= 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "listen.port=%d is invalid", port);
}
}
}
////////////////////////////////////////////////////////////////////////
// check heartbeat
////////////////////////////////////////////////////////////////////////
if (get_heartbeat_interval() <= 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "invalid heartbeat.interval=%" PRId64,
get_heartbeat_interval());
}
////////////////////////////////////////////////////////////////////////
// check stats
////////////////////////////////////////////////////////////////////////
if (get_stats_network() < 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "invalid stats.network=%d", get_stats_network());
}
if (true) {
vector<SrsIPAddress*> ips = srs_get_local_ips();
int index = get_stats_network();
if (index >= (int)ips.size()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "invalid stats.network=%d of %d",
index, (int)ips.size());
}
SrsIPAddress* addr = ips.at(index);
srs_warn("stats network use index=%d, ip=%s, ifname=%s", index, addr->ip.c_str(), addr->ifname.c_str());
}
if (true) {
SrsConfDirective* conf = get_stats_disk_device();
if (conf == NULL || (int)conf->args.size() <= 0) {
srs_warn("stats disk not configed, disk iops disabled.");
} else {
string disks;
for (int i = 0; i < (int)conf->args.size(); i++) {
disks += conf->args.at(i);
disks += " ";
}
srs_warn("stats disk list: %s", disks.c_str());
}
}
////////////////////////////////////////////////////////////////////////
// check http api
////////////////////////////////////////////////////////////////////////
if (get_http_api_listen().empty()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "http_api.listen requires params");
}
////////////////////////////////////////////////////////////////////////
// check http stream
////////////////////////////////////////////////////////////////////////
if (get_http_stream_listen().empty()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "http_stream.listen requires params");
}
////////////////////////////////////////////////////////////////////////
// check log name and level
////////////////////////////////////////////////////////////////////////
if (true) {
std::string log_filename = this->get_log_file();
if (get_log_tank_file() && log_filename.empty()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "log file is empty");
}
if (get_log_tank_file()) {
srs_trace("you can check log by: tail -n 30 -f %s", log_filename.c_str());
srs_trace("please check SRS by: ./etc/init.d/srs status");
} else {
srs_trace("write log to console");
}
}
////////////////////////////////////////////////////////////////////////
// check features
////////////////////////////////////////////////////////////////////////
vector<SrsConfDirective*> stream_casters = get_stream_casters();
for (int n = 0; n < (int)stream_casters.size(); n++) {
SrsConfDirective* stream_caster = stream_casters[n];
for (int i = 0; stream_caster && i < (int)stream_caster->directives.size(); i++) {
SrsConfDirective* conf = stream_caster->at(i);
string n = conf->name;
if (n != "enabled" && n != "caster" && n != "output"
&& n != "listen" && n != "tcp_enable" && n != "rtp_port_min" && n != "rtp_port_max"
&& n != "rtp_idle_timeout" && n != "sip"
&& n != "audio_enable" && n != "wait_keyframe" && n != "jitterbuffer_enable"
&& n != "host" && n != "auto_create_channel") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal stream_caster.%s", n.c_str());
}
if (n == "sip") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "listen" && m != "ack_timeout" && m != "keepalive_timeout"
&& m != "host" && m != "serial" && m != "realm" && m != "auto_play" && m != "invite_port_fixed"
&& m != "query_catalog_interval") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal stream_caster.%s", m.c_str());
}
}
}
}
}
////////////////////////////////////////////////////////////////////////
// check vhosts.
////////////////////////////////////////////////////////////////////////
vector<SrsConfDirective*> vhosts;
get_vhosts(vhosts);
for (int n = 0; n < (int)vhosts.size(); n++) {
SrsConfDirective* vhost = vhosts[n];
for (int i = 0; vhost && i < (int)vhost->directives.size(); i++) {
SrsConfDirective* conf = vhost->at(i);
string n = conf->name;
if (n != "enabled" && n != "chunk_size" && n != "min_latency" && n != "tcp_nodelay"
&& n != "dvr" && n != "ingest" && n != "hls" && n != "http_hooks"
&& n != "refer" && n != "forward" && n != "transcode" && n != "bandcheck"
&& n != "play" && n != "publish" && n != "cluster"
&& n != "security" && n != "http_remux" && n != "dash"
&& n != "http_static" && n != "hds" && n != "exec"
&& n != "in_ack_size" && n != "out_ack_size" && n != "rtc") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.%s", n.c_str());
}
// for each sub directives of vhost.
if (n == "dvr") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "dvr_apply" && m != "dvr_path" && m != "dvr_plan"
&& m != "dvr_duration" && m != "dvr_wait_keyframe" && m != "time_jitter") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.dvr.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "refer") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "all" && m != "publish" && m != "play") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.refer.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "exec") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "publish") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.exec.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "play") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "time_jitter" && m != "mix_correct" && m != "atc" && m != "atc_auto" && m != "mw_latency"
&& m != "gop_cache" && m != "queue_length" && m != "send_min_interval" && m != "reduce_sequence_header"
&& m != "mw_msgs") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.play.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "cluster") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "mode" && m != "origin" && m != "token_traverse" && m != "vhost" && m != "debug_srs_upnode" && m != "coworkers"
&& m != "origin_cluster") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.cluster.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "publish") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "mr" && m != "mr_latency" && m != "firstpkt_timeout" && m != "normal_timeout" && m != "parse_sps") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.publish.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "ingest") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "input" && m != "ffmpeg" && m != "engine") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.ingest.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "http_static") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "mount" && m != "dir") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.http_static.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "http_remux") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "mount" && m != "fast_cache") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.http_remux.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "dash") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "dash_fragment" && m != "dash_update_period" && m != "dash_timeshift" && m != "dash_path"
&& m != "dash_mpd_file") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.dash.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "hls") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "hls_entry_prefix" && m != "hls_path" && m != "hls_fragment" && m != "hls_window" && m != "hls_on_error"
&& m != "hls_storage" && m != "hls_mount" && m != "hls_td_ratio" && m != "hls_aof_ratio" && m != "hls_acodec" && m != "hls_vcodec"
&& m != "hls_m3u8_file" && m != "hls_ts_file" && m != "hls_ts_floor" && m != "hls_cleanup" && m != "hls_nb_notify"
&& m != "hls_wait_keyframe" && m != "hls_dispose" && m != "hls_keys" && m != "hls_fragments_per_key" && m != "hls_key_file"
&& m != "hls_key_file_path" && m != "hls_key_url" && m != "hls_dts_directly") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.hls.%s of %s", m.c_str(), vhost->arg0().c_str());
}
// TODO: FIXME: remove it in future.
if (m == "hls_storage" || m == "hls_mount") {
srs_warn("HLS RAM is removed in SRS3+, read https://github.com/ossrs/srs/issues/513.");
}
}
} else if (n == "http_hooks") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "on_connect" && m != "on_close" && m != "on_publish"
&& m != "on_unpublish" && m != "on_play" && m != "on_stop"
&& m != "on_dvr" && m != "on_hls" && m != "on_hls_notify") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.http_hooks.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "forward") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "destination") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.forward.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "security") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
SrsConfDirective* security = conf->at(j);
string m = security->name.c_str();
if (m != "enabled" && m != "deny" && m != "allow") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.security.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "transcode") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
SrsConfDirective* trans = conf->at(j);
string m = trans->name.c_str();
if (m != "enabled" && m != "ffmpeg" && m != "engine") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.transcode.%s of %s", m.c_str(), vhost->arg0().c_str());
}
if (m == "engine") {
for (int k = 0; k < (int)trans->directives.size(); k++) {
string e = trans->at(k)->name;
if (e != "enabled" && e != "vfilter" && e != "vcodec"
&& e != "vbitrate" && e != "vfps" && e != "vwidth" && e != "vheight"
&& e != "vthreads" && e != "vprofile" && e != "vpreset" && e != "vparams"
&& e != "acodec" && e != "abitrate" && e != "asample_rate" && e != "achannels"
&& e != "aparams" && e != "output" && e != "perfile"
&& e != "iformat" && e != "oformat") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.transcode.engine.%s of %s", e.c_str(), vhost->arg0().c_str());
}
}
}
}
} else if (n == "bandcheck") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "key" && m != "interval" && m != "limit_kbps") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.bandcheck.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
} else if (n == "rtc") {
for (int j = 0; j < (int)conf->directives.size(); j++) {
string m = conf->at(j)->name;
if (m != "enabled" && m != "nack" && m != "twcc" && m != "nack_no_copy"
&& m != "bframe" && m != "aac" && m != "stun_timeout" && m != "stun_strict_check"
&& m != "dtls_role" && m != "dtls_version" && m != "drop_for_pt" && m != "rtc_to_rtmp"
&& m != "pli_for_rtmp" && m != "rtmp_to_rtc" && m != "keep_bframe") {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "illegal vhost.rtc.%s of %s", m.c_str(), vhost->arg0().c_str());
}
}
}
}
}
// check ingest id unique.
for (int i = 0; i < (int)vhosts.size(); i++) {
SrsConfDirective* vhost = vhosts[i];
std::vector<std::string> ids;
for (int j = 0; j < (int)vhost->directives.size(); j++) {
SrsConfDirective* conf = vhost->at(j);
if (conf->name != "ingest") {
continue;
}
std::string id = conf->arg0();
for (int k = 0; k < (int)ids.size(); k++) {
if (id == ids.at(k)) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "ingest id=%s exists for %s",
id.c_str(), vhost->arg0().c_str());
}
}
ids.push_back(id);
}
}
////////////////////////////////////////////////////////////////////////
// check chunk size
////////////////////////////////////////////////////////////////////////
if (get_global_chunk_size() < SRS_CONSTS_RTMP_MIN_CHUNK_SIZE
|| get_global_chunk_size() > SRS_CONSTS_RTMP_MAX_CHUNK_SIZE) {
srs_warn("chunk_size=%s should be in [%d, %d]", get_global_chunk_size(),
SRS_CONSTS_RTMP_MIN_CHUNK_SIZE, SRS_CONSTS_RTMP_MAX_CHUNK_SIZE);
}
for (int i = 0; i < (int)vhosts.size(); i++) {
SrsConfDirective* vhost = vhosts[i];
if (get_chunk_size(vhost->arg0()) < SRS_CONSTS_RTMP_MIN_CHUNK_SIZE
|| get_chunk_size(vhost->arg0()) > SRS_CONSTS_RTMP_MAX_CHUNK_SIZE) {
srs_warn("chunk_size=%s of %s should be in [%d, %d]", get_global_chunk_size(), vhost->arg0().c_str(),
SRS_CONSTS_RTMP_MIN_CHUNK_SIZE, SRS_CONSTS_RTMP_MAX_CHUNK_SIZE);
}
}
// asprocess conflict with daemon
if (get_asprocess() && get_daemon()) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "daemon conflicts with asprocess");
}
return err;
}
// LCOV_EXCL_START
srs_error_t SrsConfig::check_number_connections()
{
srs_error_t err = srs_success;
////////////////////////////////////////////////////////////////////////
// check max connections
////////////////////////////////////////////////////////////////////////
if (get_max_connections() <= 0) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "max_connections=%d is invalid", get_max_connections());
}
// check max connections of system limits
if (true) {
int nb_consumed_fds = (int)get_listens().size();
if (!get_http_api_listen().empty()) {
nb_consumed_fds++;
}
if (!get_http_stream_listen().empty()) {
nb_consumed_fds++;
}
if (get_log_tank_file()) {
nb_consumed_fds++;
}
// 0, 1, 2 for stdin, stdout and stderr.
nb_consumed_fds += 3;
int nb_connections = get_max_connections();
int nb_total = nb_connections + nb_consumed_fds;
int max_open_files = (int)sysconf(_SC_OPEN_MAX);
int nb_canbe = max_open_files - nb_consumed_fds - 1;
// for each play connections, we open a pipe(2fds) to convert SrsConsumver to io,
if (nb_total >= max_open_files) {
srs_error("invalid max_connections=%d, required=%d, system limit to %d, "
"total=%d(max_connections=%d, nb_consumed_fds=%d). "
"you can change max_connections from %d to %d, or "
"you can login as root and set the limit: ulimit -HSn %d",
nb_connections, nb_total + 100, max_open_files,
nb_total, nb_connections, nb_consumed_fds,
nb_connections, nb_canbe, nb_total + 100);
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "%d exceed max open files=%d",
nb_total, max_open_files);
}
}
return err;
}
// LCOV_EXCL_STOP
srs_error_t SrsConfig::parse_buffer(SrsConfigBuffer* buffer)
{
srs_error_t err = srs_success;
// We use a new root to parse buffer, to allow parse multiple times.
srs_freep(root);
root = new SrsConfDirective();
// Parse root tree from buffer.
if ((err = root->parse(buffer)) != srs_success) {
return srs_error_wrap(err, "root parse");
}
// mock by dolphin mode.
// for the dolphin will start srs with specified params.
if (dolphin) {
// for RTMP.
set_config_directive(root, "listen", dolphin_rtmp_port);
// for HTTP
set_config_directive(root, "http_server", "");
SrsConfDirective* http_server = root->get("http_server");
set_config_directive(http_server, "enabled", "on");
set_config_directive(http_server, "listen", dolphin_http_port);
// others.
set_config_directive(root, "daemon", "off");
set_config_directive(root, "srs_log_tank", "console");
}
return err;
}
string SrsConfig::cwd()
{
return _cwd;
}
string SrsConfig::argv()
{
return _argv;
}
bool SrsConfig::get_daemon()
{
SrsConfDirective* conf = root->get("daemon");
if (!conf || conf->arg0().empty()) {
return true;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_in_docker()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("in_docker");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::is_full_config()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("is_full");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_root()
{
return root;
}
int SrsConfig::get_max_connections()
{
static int DEFAULT = 1000;
SrsConfDirective* conf = root->get("max_connections");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
vector<string> SrsConfig::get_listens()
{
std::vector<string> ports;
SrsConfDirective* conf = root->get("listen");
if (!conf) {
return ports;
}
for (int i = 0; i < (int)conf->args.size(); i++) {
ports.push_back(conf->args.at(i));
}
return ports;
}
string SrsConfig::get_pid_file()
{
static string DEFAULT = "./objs/srs.pid";
SrsConfDirective* conf = root->get("pid");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
srs_utime_t SrsConfig::get_pithy_print()
{
static srs_utime_t DEFAULT = 10 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = root->get("pithy_print_ms");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_MILLISECONDS);
}
bool SrsConfig::get_utc_time()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("utc_time");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_work_dir() {
static string DEFAULT = "./";
SrsConfDirective* conf = root->get("work_dir");
if( !conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_asprocess()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("asprocess");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::whether_query_latest_version()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("query_latest_version");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::empty_ip_ok()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("empty_ip_ok");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
srs_utime_t SrsConfig::get_grace_start_wait()
{
static srs_utime_t DEFAULT = 2300 * SRS_UTIME_MILLISECONDS;
SrsConfDirective* conf = root->get("grace_start_wait");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atol(conf->arg0().c_str()) * SRS_UTIME_MILLISECONDS);
}
srs_utime_t SrsConfig::get_grace_final_wait()
{
static srs_utime_t DEFAULT = 3200 * SRS_UTIME_MILLISECONDS;
SrsConfDirective* conf = root->get("grace_final_wait");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atol(conf->arg0().c_str()) * SRS_UTIME_MILLISECONDS);
}
bool SrsConfig::is_force_grace_quit()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("force_grace_quit");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::disable_daemon_for_docker()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("disable_daemon_for_docker");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::inotify_auto_reload()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("inotify_auto_reload");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::auto_reload_for_docker()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("auto_reload_for_docker");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
// TODO: FIXME: Support reload.
double SrsConfig::tcmalloc_release_rate()
{
static double DEFAULT = SRS_PERF_TCMALLOC_RELEASE_RATE;
SrsConfDirective* conf = root->get("tcmalloc_release_rate");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
double trr = ::atof(conf->arg0().c_str());
trr = srs_min(10, trr);
trr = srs_max(0, trr);
return trr;
}
bool SrsConfig::get_circuit_breaker()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("circuit_breaker");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
int SrsConfig::get_high_threshold()
{
static int DEFAULT = 90;
SrsConfDirective* conf = root->get("circuit_breaker");
if (!conf) {
return DEFAULT;
}
conf = conf->get("high_threshold");
if (!conf) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_high_pulse()
{
static int DEFAULT = 2;
SrsConfDirective* conf = root->get("circuit_breaker");
if (!conf) {
return DEFAULT;
}
conf = conf->get("high_pulse");
if (!conf) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_critical_threshold()
{
static int DEFAULT = 95;
SrsConfDirective* conf = root->get("circuit_breaker");
if (!conf) {
return DEFAULT;
}
conf = conf->get("critical_threshold");
if (!conf) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_critical_pulse()
{
static int DEFAULT = 1;
SrsConfDirective* conf = root->get("circuit_breaker");
if (!conf) {
return DEFAULT;
}
conf = conf->get("critical_pulse");
if (!conf) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_dying_threshold()
{
static int DEFAULT = 99;
SrsConfDirective* conf = root->get("circuit_breaker");
if (!conf) {
return DEFAULT;
}
conf = conf->get("dying_threshold");
if (!conf) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_dying_pulse()
{
static int DEFAULT = 5;
SrsConfDirective* conf = root->get("circuit_breaker");
if (!conf) {
return DEFAULT;
}
conf = conf->get("dying_pulse");
if (!conf) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
vector<SrsConfDirective*> SrsConfig::get_stream_casters()
{
srs_assert(root);
std::vector<SrsConfDirective*> stream_casters;
for (int i = 0; i < (int)root->directives.size(); i++) {
SrsConfDirective* conf = root->at(i);
if (!conf->is_stream_caster()) {
continue;
}
stream_casters.push_back(conf);
}
return stream_casters;
}
bool SrsConfig::get_stream_caster_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_stream_caster_engine(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("caster");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_stream_caster_output(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("output");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
int SrsConfig::get_stream_caster_listen(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("listen");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_stream_caster_tcp_enable(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("tcp_enable");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
int SrsConfig::get_stream_caster_rtp_port_min(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("rtp_port_min");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_stream_caster_rtp_port_max(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("rtp_port_max");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_rtc_server_enabled()
{
SrsConfDirective* conf = root->get("rtc_server");
return get_rtc_server_enabled(conf);
}
bool SrsConfig::get_rtc_server_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
int SrsConfig::get_rtc_server_listen()
{
static int DEFAULT = 8000;
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("listen");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
std::string SrsConfig::get_rtc_server_candidates()
{
static string DEFAULT = "*";
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("candidate");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
string eip = srs_getenv(conf->arg0());
if (!eip.empty()) {
return eip;
}
// If configed as ENV, but no ENV set, use default value.
if (srs_string_starts_with(conf->arg0(), "$")) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_api_as_candidates()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("api_as_candidates");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
std::string SrsConfig::get_rtc_server_ip_family()
{
static string DEFAULT = "ipv4";
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("ip_family");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_rtc_server_ecdsa()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("ecdsa");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_rtc_server_encrypt()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("encrypt");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
int SrsConfig::get_rtc_server_reuseport()
{
int v = get_rtc_server_reuseport2();
#if !defined(SO_REUSEPORT)
if (v > 1) {
srs_warn("REUSEPORT not supported, reset to 1");
v = 1;
}
#endif
return v;
}
int SrsConfig::get_rtc_server_reuseport2()
{
static int DEFAULT = 1;
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("reuseport");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_rtc_server_merge_nalus()
{
static int DEFAULT = false;
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("merge_nalus");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_rtc_server_black_hole()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("black_hole");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
std::string SrsConfig::get_rtc_server_black_hole_addr()
{
static string DEFAULT = "";
SrsConfDirective* conf = root->get("rtc_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("black_hole");
if (!conf) {
return DEFAULT;
}
conf = conf->get("addr");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
SrsConfDirective* SrsConfig::get_rtc(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
return conf? conf->get("rtc") : NULL;
}
bool SrsConfig::get_rtc_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::get_rtc_keep_bframe(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("keep_bframe");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::get_rtc_from_rtmp(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("rtmp_to_rtc");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_rtc_stun_timeout(string vhost)
{
static srs_utime_t DEFAULT = 30 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("stun_timeout");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
bool SrsConfig::get_rtc_stun_strict_check(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("stun_strict_check");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
std::string SrsConfig::get_rtc_dtls_role(string vhost)
{
static std::string DEFAULT = "passive";
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dtls_role");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
std::string SrsConfig::get_rtc_dtls_version(string vhost)
{
static std::string DEFAULT = "auto";
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dtls_version");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
int SrsConfig::get_rtc_drop_for_pt(string vhost)
{
static int DEFAULT = 0;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("drop_for_pt");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_rtc_to_rtmp(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("rtc_to_rtmp");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_rtc_pli_for_rtmp(string vhost)
{
static srs_utime_t DEFAULT = 6 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("pli_for_rtmp");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
srs_utime_t v = (srs_utime_t)(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
if (v < 500 * SRS_UTIME_MILLISECONDS || v > 30 * SRS_UTIME_SECONDS) {
srs_warn("Reset pli %dms to %dms", srsu2msi(v), srsu2msi(DEFAULT));
return DEFAULT;
}
return v;
}
bool SrsConfig::get_rtc_nack_enabled(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("nack");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_rtc_nack_no_copy(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("nack_no_copy");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_rtc_twcc_enabled(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_rtc(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("twcc");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_vhost(string vhost, bool try_default_vhost)
{
srs_assert(root);
for (int i = 0; i < (int)root->directives.size(); i++) {
SrsConfDirective* conf = root->at(i);
if (!conf->is_vhost()) {
continue;
}
if (conf->arg0() == vhost) {
return conf;
}
}
if (try_default_vhost && vhost != SRS_CONSTS_RTMP_DEFAULT_VHOST) {
return get_vhost(SRS_CONSTS_RTMP_DEFAULT_VHOST);
}
return NULL;
}
void SrsConfig::get_vhosts(vector<SrsConfDirective*>& vhosts)
{
srs_assert(root);
for (int i = 0; i < (int)root->directives.size(); i++) {
SrsConfDirective* conf = root->at(i);
if (!conf->is_vhost()) {
continue;
}
vhosts.push_back(conf);
}
}
bool SrsConfig::get_vhost_enabled(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
return get_vhost_enabled(conf);
}
bool SrsConfig::get_vhost_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = true;
// false for NULL vhost.
if (!conf) {
return false;
}
// perfer true for exists one.
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_gop_cache(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return SRS_PERF_GOP_CACHE;
}
conf = conf->get("play");
if (!conf) {
return SRS_PERF_GOP_CACHE;
}
conf = conf->get("gop_cache");
if (!conf || conf->arg0().empty()) {
return SRS_PERF_GOP_CACHE;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_debug_srs_upnode(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("cluster");
if (!conf) {
return DEFAULT;
}
conf = conf->get("debug_srs_upnode");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_atc(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("atc");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::get_atc_auto(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("atc_auto");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
int SrsConfig::get_time_jitter(string vhost)
{
static string DEFAULT = "full";
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return srs_time_jitter_string2int(DEFAULT);
}
conf = conf->get("play");
if (!conf) {
return srs_time_jitter_string2int(DEFAULT);
}
conf = conf->get("time_jitter");
if (!conf || conf->arg0().empty()) {
return srs_time_jitter_string2int(DEFAULT);
}
return srs_time_jitter_string2int(conf->arg0());
}
bool SrsConfig::get_mix_correct(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mix_correct");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_queue_length(string vhost)
{
static srs_utime_t DEFAULT = SRS_PERF_PLAY_QUEUE;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("queue_length");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return srs_utime_t(::atoi(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
bool SrsConfig::get_refer_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("refer");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_refer_all(string vhost)
{
static SrsConfDirective* DEFAULT = NULL;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("refer");
if (!conf) {
return DEFAULT;
}
return conf->get("all");
}
SrsConfDirective* SrsConfig::get_refer_play(string vhost)
{
static SrsConfDirective* DEFAULT = NULL;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("refer");
if (!conf) {
return DEFAULT;
}
return conf->get("play");
}
SrsConfDirective* SrsConfig::get_refer_publish(string vhost)
{
static SrsConfDirective* DEFAULT = NULL;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("refer");
if (!conf) {
return DEFAULT;
}
return conf->get("publish");
}
int SrsConfig::get_in_ack_size(string vhost)
{
static int DEFAULT = 0;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("in_ack_size");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_out_ack_size(string vhost)
{
static int DEFAULT = 2500000;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("out_ack_size");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_chunk_size(string vhost)
{
if (vhost.empty()) {
return get_global_chunk_size();
}
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
// vhost does not specify the chunk size,
// use the global instead.
return get_global_chunk_size();
}
conf = conf->get("chunk_size");
if (!conf || conf->arg0().empty()) {
// vhost does not specify the chunk size,
// use the global instead.
return get_global_chunk_size();
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_parse_sps(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("publish");
if (!conf) {
return DEFAULT;
}
conf = conf->get("parse_sps");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_mr_enabled(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return SRS_PERF_MR_ENABLED;
}
conf = conf->get("publish");
if (!conf) {
return SRS_PERF_MR_ENABLED;
}
conf = conf->get("mr");
if (!conf || conf->arg0().empty()) {
return SRS_PERF_MR_ENABLED;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_mr_sleep(string vhost)
{
static srs_utime_t DEFAULT = SRS_PERF_MR_SLEEP;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("publish");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mr_latency");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_MILLISECONDS);
}
srs_utime_t SrsConfig::get_mw_sleep(string vhost, bool is_rtc)
{
static srs_utime_t SYS_DEFAULT = SRS_PERF_MW_SLEEP;
static srs_utime_t RTC_DEFAULT = 0;
srs_utime_t DEFAULT = is_rtc? RTC_DEFAULT : SYS_DEFAULT;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mw_latency");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
int v = ::atoi(conf->arg0().c_str());
if (is_rtc && v > 0) {
srs_warn("For RTC, we ignore mw_latency");
return 0;
}
return (srs_utime_t)(v * SRS_UTIME_MILLISECONDS);
}
int SrsConfig::get_mw_msgs(string vhost, bool is_realtime, bool is_rtc)
{
int DEFAULT = SRS_PERF_MW_MIN_MSGS;
if (is_rtc) {
DEFAULT = SRS_PERF_MW_MIN_MSGS_FOR_RTC;
}
if (is_realtime) {
DEFAULT = SRS_PERF_MW_MIN_MSGS_REALTIME;
}
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mw_msgs");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
int v = ::atoi(conf->arg0().c_str());
if (v > SRS_PERF_MW_MSGS) {
srs_warn("reset mw_msgs %d to max %d", v, SRS_PERF_MW_MSGS);
v = SRS_PERF_MW_MSGS;
}
return v;
}
bool SrsConfig::get_realtime_enabled(string vhost, bool is_rtc)
{
static bool SYS_DEFAULT = SRS_PERF_MIN_LATENCY_ENABLED;
static bool RTC_DEFAULT = true;
bool DEFAULT = is_rtc? RTC_DEFAULT : SYS_DEFAULT;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("min_latency");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
if (is_rtc) {
return SRS_CONF_PERFER_TRUE(conf->arg0());
} else {
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
}
bool SrsConfig::get_tcp_nodelay(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("tcp_nodelay");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_send_min_interval(string vhost)
{
static srs_utime_t DEFAULT = 0;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("send_min_interval");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return srs_utime_t(::atof(conf->arg0().c_str()) * SRS_UTIME_MILLISECONDS);
}
bool SrsConfig::get_reduce_sequence_header(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("play");
if (!conf) {
return DEFAULT;
}
conf = conf->get("reduce_sequence_header");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_publish_1stpkt_timeout(string vhost)
{
// when no msg recevied for publisher, use larger timeout.
static srs_utime_t DEFAULT = 20 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("publish");
if (!conf) {
return DEFAULT;
}
conf = conf->get("firstpkt_timeout");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_MILLISECONDS);
}
srs_utime_t SrsConfig::get_publish_normal_timeout(string vhost)
{
// the timeout for publish recv.
// we must use more smaller timeout, for the recv never know the status
// of underlayer socket.
static srs_utime_t DEFAULT = 5 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("publish");
if (!conf) {
return DEFAULT;
}
conf = conf->get("normal_timeout");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_MILLISECONDS);
}
int SrsConfig::get_global_chunk_size()
{
SrsConfDirective* conf = root->get("chunk_size");
if (!conf || conf->arg0().empty()) {
return SRS_CONSTS_RTMP_SRS_CHUNK_SIZE;
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_forward_enabled(string vhost) {
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_forward_enabled(conf);
}
bool SrsConfig::get_forward_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("forward");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_forwards(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
conf = conf->get("forward");
if (!conf) {
return NULL;
}
return conf->get("destination");
}
SrsConfDirective* SrsConfig::get_vhost_http_hooks(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
return conf->get("http_hooks");
}
bool SrsConfig::get_vhost_http_hooks_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_vhost_http_hooks_enabled(conf);
}
bool SrsConfig::get_vhost_http_hooks_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("http_hooks");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_vhost_on_connect(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_connect");
}
SrsConfDirective* SrsConfig::get_vhost_on_close(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_close");
}
SrsConfDirective* SrsConfig::get_vhost_on_publish(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_publish");
}
SrsConfDirective* SrsConfig::get_vhost_on_unpublish(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_unpublish");
}
SrsConfDirective* SrsConfig::get_vhost_on_play(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_play");
}
SrsConfDirective* SrsConfig::get_vhost_on_stop(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_stop");
}
SrsConfDirective* SrsConfig::get_vhost_on_dvr(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_dvr");
}
SrsConfDirective* SrsConfig::get_vhost_on_hls(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_hls");
}
SrsConfDirective* SrsConfig::get_vhost_on_hls_notify(string vhost)
{
SrsConfDirective* conf = get_vhost_http_hooks(vhost);
if (!conf) {
return NULL;
}
return conf->get("on_hls_notify");
}
bool SrsConfig::get_bw_check_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("bandcheck");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_bw_check_key(string vhost)
{
static string DEFAULT = "";
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("bandcheck");
if (!conf) {
return DEFAULT;
}
conf = conf->get("key");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
srs_utime_t SrsConfig::get_bw_check_interval(string vhost)
{
static int64_t DEFAULT = 30 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("bandcheck");
if (!conf) {
return DEFAULT;
}
conf = conf->get("interval");
if (!conf) {
return DEFAULT;
}
return (srs_utime_t)(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
int SrsConfig::get_bw_check_limit_kbps(string vhost)
{
static int DEFAULT = 1000;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("bandcheck");
if (!conf) {
return DEFAULT;
}
conf = conf->get("limit_kbps");
if (!conf) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_vhost_is_edge(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
return get_vhost_is_edge(conf);
}
bool SrsConfig::get_vhost_is_edge(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost;
if (!conf) {
return DEFAULT;
}
conf = conf->get("cluster");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mode");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return "remote" == conf->arg0();
}
SrsConfDirective* SrsConfig::get_vhost_edge_origin(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
conf = conf->get("cluster");
if (!conf) {
return NULL;
}
return conf->get("origin");
}
bool SrsConfig::get_vhost_edge_token_traverse(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("cluster");
if (!conf) {
return DEFAULT;
}
conf = conf->get("token_traverse");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_vhost_edge_transform_vhost(string vhost)
{
static string DEFAULT = "[vhost]";
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("cluster");
if (!conf) {
return DEFAULT;
}
conf = conf->get("vhost");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_vhost_origin_cluster(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
return get_vhost_origin_cluster(conf);
}
bool SrsConfig::get_vhost_origin_cluster(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost;
if (!conf) {
return DEFAULT;
}
conf = conf->get("cluster");
if (!conf) {
return DEFAULT;
}
conf = conf->get("origin_cluster");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
vector<string> SrsConfig::get_vhost_coworkers(string vhost)
{
vector<string> coworkers;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return coworkers;
}
conf = conf->get("cluster");
if (!conf) {
return coworkers;
}
conf = conf->get("coworkers");
for (int i = 0; i < (int)conf->args.size(); i++) {
coworkers.push_back(conf->args.at(i));
}
return coworkers;
}
bool SrsConfig::get_security_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_security_enabled(conf);
}
bool SrsConfig::get_security_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("security");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_security_rules(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
return conf->get("security");
}
SrsConfDirective* SrsConfig::get_transcode(string vhost, string scope)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
conf = conf->get("transcode");
if (!conf || conf->arg0() != scope) {
return NULL;
}
return conf;
}
bool SrsConfig::get_transcode_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_transcode_ffmpeg(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("ffmpeg");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
vector<SrsConfDirective*> SrsConfig::get_transcode_engines(SrsConfDirective* conf)
{
vector<SrsConfDirective*> engines;
if (!conf) {
return engines;
}
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* engine = conf->directives[i];
if (engine->name == "engine") {
engines.push_back(engine);
}
}
return engines;
}
bool SrsConfig::get_engine_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string srs_prefix_underscores_ifno(string name)
{
if (srs_string_starts_with(name, "-")) {
return name;
} else {
return "-" + name;
}
}
vector<string> SrsConfig::get_engine_perfile(SrsConfDirective* conf)
{
vector<string> perfile;
if (!conf) {
return perfile;
}
conf = conf->get("perfile");
if (!conf) {
return perfile;
}
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* option = conf->directives[i];
if (!option) {
continue;
}
perfile.push_back(srs_prefix_underscores_ifno(option->name));
if (!option->arg0().empty()) {
perfile.push_back(option->arg0());
}
}
return perfile;
}
string SrsConfig::get_engine_iformat(SrsConfDirective* conf)
{
static string DEFAULT = "flv";
if (!conf) {
return DEFAULT;
}
conf = conf->get("iformat");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
vector<string> SrsConfig::get_engine_vfilter(SrsConfDirective* conf)
{
vector<string> vfilter;
if (!conf) {
return vfilter;
}
conf = conf->get("vfilter");
if (!conf) {
return vfilter;
}
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* filter = conf->directives[i];
if (!filter) {
continue;
}
vfilter.push_back(srs_prefix_underscores_ifno(filter->name));
if (!filter->arg0().empty()) {
vfilter.push_back(filter->arg0());
}
}
return vfilter;
}
string SrsConfig::get_engine_vcodec(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("vcodec");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
int SrsConfig::get_engine_vbitrate(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("vbitrate");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
double SrsConfig::get_engine_vfps(SrsConfDirective* conf)
{
static double DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("vfps");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atof(conf->arg0().c_str());
}
int SrsConfig::get_engine_vwidth(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("vwidth");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_engine_vheight(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("vheight");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_engine_vthreads(SrsConfDirective* conf)
{
static int DEFAULT = 1;
if (!conf) {
return DEFAULT;
}
conf = conf->get("vthreads");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
string SrsConfig::get_engine_vprofile(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("vprofile");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_engine_vpreset(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("vpreset");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
vector<string> SrsConfig::get_engine_vparams(SrsConfDirective* conf)
{
vector<string> vparams;
if (!conf) {
return vparams;
}
conf = conf->get("vparams");
if (!conf) {
return vparams;
}
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* filter = conf->directives[i];
if (!filter) {
continue;
}
vparams.push_back(srs_prefix_underscores_ifno(filter->name));
if (!filter->arg0().empty()) {
vparams.push_back(filter->arg0());
}
}
return vparams;
}
string SrsConfig::get_engine_acodec(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("acodec");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
int SrsConfig::get_engine_abitrate(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("abitrate");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_engine_asample_rate(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("asample_rate");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
int SrsConfig::get_engine_achannels(SrsConfDirective* conf)
{
static int DEFAULT = 0;
if (!conf) {
return DEFAULT;
}
conf = conf->get("achannels");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
vector<string> SrsConfig::get_engine_aparams(SrsConfDirective* conf)
{
vector<string> aparams;
if (!conf) {
return aparams;
}
conf = conf->get("aparams");
if (!conf) {
return aparams;
}
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* filter = conf->directives[i];
if (!filter) {
continue;
}
aparams.push_back(srs_prefix_underscores_ifno(filter->name));
if (!filter->arg0().empty()) {
aparams.push_back(filter->arg0());
}
}
return aparams;
}
string SrsConfig::get_engine_oformat(SrsConfDirective* conf)
{
static string DEFAULT = "flv";
if (!conf) {
return DEFAULT;
}
conf = conf->get("oformat");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_engine_output(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("output");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
SrsConfDirective* SrsConfig::get_exec(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
return conf->get("exec");
}
bool SrsConfig::get_exec_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_exec_enabled(conf);
}
bool SrsConfig::get_exec_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("exec");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
vector<SrsConfDirective*> SrsConfig::get_exec_publishs(string vhost)
{
vector<SrsConfDirective*> eps;
SrsConfDirective* conf = get_exec(vhost);
if (!conf) {
return eps;
}
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* ep = conf->at(i);
if (ep->name == "publish") {
eps.push_back(ep);
}
}
return eps;
}
vector<SrsConfDirective*> SrsConfig::get_ingesters(string vhost)
{
vector<SrsConfDirective*> integers;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return integers;
}
for (int i = 0; i < (int)conf->directives.size(); i++) {
SrsConfDirective* ingester = conf->directives[i];
if (ingester->name == "ingest") {
integers.push_back(ingester);
}
}
return integers;
}
SrsConfDirective* SrsConfig::get_ingest_by_id(string vhost, string ingest_id)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
return conf->get("ingest", ingest_id);
}
bool SrsConfig::get_ingest_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_ingest_ffmpeg(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("ffmpeg");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_ingest_input_type(SrsConfDirective* conf)
{
static string DEFAULT = "file";
if (!conf) {
return DEFAULT;
}
conf = conf->get("input");
if (!conf) {
return DEFAULT;
}
conf = conf->get("type");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_ingest_input_url(SrsConfDirective* conf)
{
static string DEFAULT = "";
if (!conf) {
return DEFAULT;
}
conf = conf->get("input");
if (!conf) {
return DEFAULT;
}
conf = conf->get("url");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
extern bool _srs_in_docker;
bool SrsConfig::get_log_tank_file()
{
static bool DEFAULT = true;
if (_srs_in_docker) {
DEFAULT = false;
}
SrsConfDirective* conf = root->get("srs_log_tank");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0() != "console";
}
string SrsConfig::get_log_level()
{
static string DEFAULT = "trace";
SrsConfDirective* conf = root->get("srs_log_level");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_log_file()
{
static string DEFAULT = "./objs/srs.log";
SrsConfDirective* conf = root->get("srs_log_file");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_ff_log_enabled()
{
string log = get_ff_log_dir();
return log != SRS_CONSTS_NULL_FILE;
}
string SrsConfig::get_ff_log_dir()
{
static string DEFAULT = "./objs";
SrsConfDirective* conf = root->get("ff_log_dir");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_ff_log_level()
{
static string DEFAULT = "info";
SrsConfDirective* conf = root->get("ff_log_level");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
SrsConfDirective* SrsConfig::get_dash(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
return conf? conf->get("dash") : NULL;
}
bool SrsConfig::get_dash_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_dash_enabled(conf);
}
bool SrsConfig::get_dash_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("dash");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_dash_fragment(string vhost)
{
static int DEFAULT = 30 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_dash(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dash_fragment");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
srs_utime_t SrsConfig::get_dash_update_period(string vhost)
{
static srs_utime_t DEFAULT = 150 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_dash(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dash_update_period");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
srs_utime_t SrsConfig::get_dash_timeshift(string vhost)
{
static srs_utime_t DEFAULT = 300 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_dash(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dash_timeshift");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
string SrsConfig::get_dash_path(string vhost)
{
static string DEFAULT = "./objs/nginx/html";
SrsConfDirective* conf = get_dash(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dash_path");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_dash_mpd_file(string vhost)
{
static string DEFAULT = "[app]/[stream].mpd";
SrsConfDirective* conf = get_dash(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dash_mpd_file");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
SrsConfDirective* SrsConfig::get_hls(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
return conf? conf->get("hls") : NULL;
}
bool SrsConfig::get_hls_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_hls_enabled(conf);
}
bool SrsConfig::get_hls_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("hls");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_hls_entry_prefix(string vhost)
{
static string DEFAULT = "";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_entry_prefix");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_hls_path(string vhost)
{
static string DEFAULT = "./objs/nginx/html";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_path");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_hls_m3u8_file(string vhost)
{
static string DEFAULT = "[app]/[stream].m3u8";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_m3u8_file");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_hls_ts_file(string vhost)
{
static string DEFAULT = "[app]/[stream]-[seq].ts";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_ts_file");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_hls_ts_floor(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_ts_floor");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_hls_fragment(string vhost)
{
static srs_utime_t DEFAULT = 10 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_fragment");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return srs_utime_t(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
double SrsConfig::get_hls_td_ratio(string vhost)
{
static double DEFAULT = 1.5;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_td_ratio");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atof(conf->arg0().c_str());
}
double SrsConfig::get_hls_aof_ratio(string vhost)
{
static double DEFAULT = 2.0;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_aof_ratio");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atof(conf->arg0().c_str());
}
srs_utime_t SrsConfig::get_hls_window(string vhost)
{
static srs_utime_t DEFAULT = (60 * SRS_UTIME_SECONDS);
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_window");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return srs_utime_t(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
string SrsConfig::get_hls_on_error(string vhost)
{
// try to ignore the error.
static string DEFAULT = "continue";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_on_error");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_hls_acodec(string vhost)
{
static string DEFAULT = "aac";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_acodec");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_hls_vcodec(string vhost)
{
static string DEFAULT = "h264";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_vcodec");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
int SrsConfig::get_vhost_hls_nb_notify(string vhost)
{
static int DEFAULT = 64;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_nb_notify");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
bool SrsConfig::get_vhost_hls_dts_directly(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_dts_directly");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_hls_cleanup(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_cleanup");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
srs_utime_t SrsConfig::get_hls_dispose(string vhost)
{
static srs_utime_t DEFAULT = 0;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_dispose");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
bool SrsConfig::get_hls_wait_keyframe(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_wait_keyframe");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_hls_keys(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_keys");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
int SrsConfig::get_hls_fragments_per_key(string vhost)
{
static int DEFAULT = 5;
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_fragments_per_key");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
string SrsConfig::get_hls_key_file(string vhost)
{
static string DEFAULT = "[app]/[stream]-[seq].key";
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_key_file");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_hls_key_file_path(std::string vhost)
{
//put the key in ts path defaultly.
static string DEFAULT = get_hls_path(vhost);
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_key_file_path");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_hls_key_url(std::string vhost)
{
//put the key in ts path defaultly.
static string DEFAULT = get_hls_path(vhost);
SrsConfDirective* conf = get_hls(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hls_key_url");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
SrsConfDirective *SrsConfig::get_hds(const string &vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
return conf->get("hds");
}
bool SrsConfig::get_hds_enabled(const string &vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_hds_enabled(conf);
}
bool SrsConfig::get_hds_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("hds");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_hds_path(const string &vhost)
{
static string DEFAULT = "./objs/nginx/html";
SrsConfDirective* conf = get_hds(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hds_path");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
srs_utime_t SrsConfig::get_hds_fragment(const string &vhost)
{
static srs_utime_t DEFAULT = (10 * SRS_UTIME_SECONDS);
SrsConfDirective* conf = get_hds(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hds_fragment");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return srs_utime_t(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
srs_utime_t SrsConfig::get_hds_window(const string &vhost)
{
static srs_utime_t DEFAULT = (60 * SRS_UTIME_SECONDS);
SrsConfDirective* conf = get_hds(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("hds_window");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return srs_utime_t(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
SrsConfDirective* SrsConfig::get_dvr(string vhost)
{
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return NULL;
}
return conf->get("dvr");
}
bool SrsConfig::get_dvr_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_dvr_enabled(conf);
}
bool SrsConfig::get_dvr_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("dvr");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_dvr_apply(string vhost)
{
SrsConfDirective* conf = get_dvr(vhost);
if (!conf) {
return NULL;
}
conf = conf->get("dvr_apply");
if (!conf || conf->arg0().empty()) {
return NULL;
}
return conf;
}
string SrsConfig::get_dvr_path(string vhost)
{
static string DEFAULT = "./objs/nginx/html/[app]/[stream].[timestamp].flv";
SrsConfDirective* conf = get_dvr(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dvr_path");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_dvr_plan(string vhost)
{
static string DEFAULT = "session";
SrsConfDirective* conf = get_dvr(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dvr_plan");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
srs_utime_t SrsConfig::get_dvr_duration(string vhost)
{
static srs_utime_t DEFAULT = 30 * SRS_UTIME_SECONDS;
SrsConfDirective* conf = get_dvr(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dvr_duration");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
bool SrsConfig::get_dvr_wait_keyframe(string vhost)
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_dvr(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("dvr_wait_keyframe");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
int SrsConfig::get_dvr_time_jitter(string vhost)
{
static string DEFAULT = "full";
SrsConfDirective* conf = get_dvr(vhost);
if (!conf) {
return srs_time_jitter_string2int(DEFAULT);
}
conf = conf->get("time_jitter");
if (!conf || conf->arg0().empty()) {
return srs_time_jitter_string2int(DEFAULT);
}
return srs_time_jitter_string2int(conf->arg0());
}
bool SrsConfig::get_http_api_enabled()
{
SrsConfDirective* conf = root->get("http_api");
return get_http_api_enabled(conf);
}
bool SrsConfig::get_http_api_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_http_api_listen()
{
static string DEFAULT = "1985";
SrsConfDirective* conf = root->get("http_api");
if (!conf) {
return DEFAULT;
}
conf = conf->get("listen");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_http_api_crossdomain()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("http_api");
if (!conf) {
return DEFAULT;
}
conf = conf->get("crossdomain");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_raw_api()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("http_api");
if (!conf) {
return DEFAULT;
}
conf = conf->get("raw_api");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::get_raw_api_allow_reload()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("http_api");
if (!conf) {
return DEFAULT;
}
conf = conf->get("raw_api");
if (!conf) {
return DEFAULT;
}
conf = conf->get("allow_reload");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
bool SrsConfig::get_raw_api_allow_query()
{
// Disable RAW API query, @see https://github.com/ossrs/srs/issues/2653#issuecomment-939389178
return false;
}
bool SrsConfig::get_raw_api_allow_update()
{
// Disable RAW API update, @see https://github.com/ossrs/srs/issues/2653#issuecomment-939389178
return false;
}
SrsConfDirective* SrsConfig::get_https_api()
{
SrsConfDirective* conf = root->get("http_api");
if (!conf) {
return NULL;
}
return conf->get("https");
}
bool SrsConfig::get_https_api_enabled()
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_https_api();
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_https_api_listen()
{
static string DEFAULT = "1990";
SrsConfDirective* conf = get_https_api();
if (!conf) {
return DEFAULT;
}
conf = conf->get("listen");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_https_api_ssl_key()
{
static string DEFAULT = "./conf/server.key";
SrsConfDirective* conf = get_https_api();
if (!conf) {
return DEFAULT;
}
conf = conf->get("key");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_https_api_ssl_cert()
{
static string DEFAULT = "./conf/server.crt";
SrsConfDirective* conf = get_https_api();
if (!conf) {
return DEFAULT;
}
conf = conf->get("cert");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_srt_enabled()
{
static bool DEFAULT = false;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
unsigned short SrsConfig::get_srt_listen_port()
{
static unsigned short DEFAULT = 10080;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("listen");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (unsigned short)atoi(conf->arg0().c_str());
}
bool SrsConfig::get_srt_mix_correct() {
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mix_correct");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
int SrsConfig::get_srto_maxbw() {
static int64_t DEFAULT = -1;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("maxbw");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
int SrsConfig::get_srto_mss() {
static int DEFAULT = 1500;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mms");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
int SrsConfig::get_srto_latency() {
static int DEFAULT = 120;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("latency");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
int SrsConfig::get_srto_recv_latency() {
static int DEFAULT = 120;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("recvlatency");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
int SrsConfig::get_srto_peer_latency() {
static int DEFAULT = 0;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("peerlatency");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
bool SrsConfig::get_srt_sei_filter() {
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("sei_filter");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
bool SrsConfig::get_srto_tlpkdrop() {
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("tlpkdrop");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
int SrsConfig::get_srto_conntimeout() {
static int DEFAULT = 3000;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("connect_timeout");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
int SrsConfig::get_srto_sendbuf() {
static int64_t DEFAULT = 8192 * (1500-28);
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("sendbuf");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
int SrsConfig::get_srto_recvbuf() {
static int64_t DEFAULT = 8192 * (1500-28);
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("recvbuf");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
int SrsConfig::get_srto_payloadsize() {
static int DEFAULT = 1316;
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("payloadsize");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return atoi(conf->arg0().c_str());
}
string SrsConfig::get_default_app_name() {
static string DEFAULT = "live";
SrsConfDirective* conf = root->get("srt_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("default_app");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_http_stream_enabled()
{
SrsConfDirective* conf = root->get("http_server");
return get_http_stream_enabled(conf);
}
bool SrsConfig::get_http_stream_enabled(SrsConfDirective* conf)
{
static bool DEFAULT = false;
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_http_stream_listen()
{
static string DEFAULT = "8080";
SrsConfDirective* conf = root->get("http_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("listen");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_http_stream_dir()
{
static string DEFAULT = "./objs/nginx/html";
SrsConfDirective* conf = root->get("http_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("dir");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_http_stream_crossdomain()
{
static bool DEFAULT = true;
SrsConfDirective* conf = root->get("http_server");
if (!conf) {
return DEFAULT;
}
conf = conf->get("crossdomain");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_https_stream()
{
SrsConfDirective* conf = root->get("http_server");
if (!conf) {
return NULL;
}
return conf->get("https");
}
bool SrsConfig::get_https_stream_enabled()
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_https_stream();
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_https_stream_listen()
{
static string DEFAULT = "8088";
SrsConfDirective* conf = get_https_stream();
if (!conf) {
return DEFAULT;
}
conf = conf->get("listen");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_https_stream_ssl_key()
{
static string DEFAULT = "./conf/server.key";
SrsConfDirective* conf = get_https_stream();
if (!conf) {
return DEFAULT;
}
conf = conf->get("key");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_https_stream_ssl_cert()
{
static string DEFAULT = "./conf/server.crt";
SrsConfDirective* conf = get_https_stream();
if (!conf) {
return DEFAULT;
}
conf = conf->get("cert");
if (!conf) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_vhost_http_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("http_static");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
string SrsConfig::get_vhost_http_mount(string vhost)
{
static string DEFAULT = "[vhost]/";
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("http_static");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mount");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_vhost_http_dir(string vhost)
{
static string DEFAULT = "./objs/nginx/html";
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("http_static");
if (!conf) {
return DEFAULT;
}
conf = conf->get("dir");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_vhost_http_remux_enabled(string vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
return get_vhost_http_remux_enabled(conf);
}
bool SrsConfig::get_vhost_http_remux_enabled(SrsConfDirective* vhost)
{
static bool DEFAULT = false;
SrsConfDirective* conf = vhost->get("http_remux");
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_vhost_http_remux_fast_cache(string vhost)
{
static srs_utime_t DEFAULT = 0;
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("http_remux");
if (!conf) {
return DEFAULT;
}
conf = conf->get("fast_cache");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return srs_utime_t(::atof(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
string SrsConfig::get_vhost_http_remux_mount(string vhost)
{
static string DEFAULT = "[vhost]/[app]/[stream].flv";
SrsConfDirective* conf = get_vhost(vhost);
if (!conf) {
return DEFAULT;
}
conf = conf->get("http_remux");
if (!conf) {
return DEFAULT;
}
conf = conf->get("mount");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
SrsConfDirective* SrsConfig::get_heartbeart()
{
return root->get("heartbeat");
}
bool SrsConfig::get_heartbeat_enabled()
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_heartbeart();
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
srs_utime_t SrsConfig::get_heartbeat_interval()
{
static srs_utime_t DEFAULT = (srs_utime_t)(10 * SRS_UTIME_SECONDS);
SrsConfDirective* conf = get_heartbeart();
if (!conf) {
return DEFAULT;
}
conf = conf->get("interval");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return (srs_utime_t)(::atoi(conf->arg0().c_str()) * SRS_UTIME_SECONDS);
}
string SrsConfig::get_heartbeat_url()
{
static string DEFAULT = "http://" SRS_CONSTS_LOCALHOST ":8085/api/v1/servers";
SrsConfDirective* conf = get_heartbeart();
if (!conf) {
return DEFAULT;
}
conf = conf->get("url");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
string SrsConfig::get_heartbeat_device_id()
{
static string DEFAULT = "";
SrsConfDirective* conf = get_heartbeart();
if (!conf) {
return DEFAULT;
}
conf = conf->get("device_id");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return conf->arg0();
}
bool SrsConfig::get_heartbeat_summaries()
{
static bool DEFAULT = false;
SrsConfDirective* conf = get_heartbeart();
if (!conf) {
return DEFAULT;
}
conf = conf->get("summaries");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_FALSE(conf->arg0());
}
SrsConfDirective* SrsConfig::get_stats()
{
return root->get("stats");
}
bool SrsConfig::get_stats_enabled()
{
static bool DEFAULT = true;
SrsConfDirective* conf = get_stats();
if (!conf) {
return DEFAULT;
}
conf = conf->get("enabled");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return SRS_CONF_PERFER_TRUE(conf->arg0());
}
int SrsConfig::get_stats_network()
{
static int DEFAULT = 0;
SrsConfDirective* conf = get_stats();
if (!conf) {
return DEFAULT;
}
conf = conf->get("network");
if (!conf || conf->arg0().empty()) {
return DEFAULT;
}
return ::atoi(conf->arg0().c_str());
}
SrsConfDirective* SrsConfig::get_stats_disk_device()
{
SrsConfDirective* conf = get_stats();
if (!conf) {
return NULL;
}
conf = conf->get("disk");
if (!conf || conf->args.size() == 0) {
return NULL;
}
return conf;
}
|
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include <utility>
#include <vector>
#include "../../../include/fpdfapi/fpdf_module.h"
#include "../../../include/fpdfapi/fpdf_page.h"
#include "../../../include/fpdfapi/fpdf_parser.h"
#include "../../../include/fxcrt/fx_safe_types.h"
#include "../fpdf_page/pageint.h"
FX_BOOL IsSignatureDict(const CPDF_Dictionary* pDict)
{
CPDF_Object* pType = pDict->GetElementValue(FX_BSTRC("Type"));
if (!pType) {
pType = pDict->GetElementValue(FX_BSTRC("FT"));
if (!pType) {
return FALSE;
}
}
if (pType->GetString() == FX_BSTRC("Sig")) {
return TRUE;
}
return FALSE;
}
static int _CompareFileSize(const void* p1, const void* p2)
{
FX_FILESIZE ret = (*(FX_FILESIZE*)p1) - (*(FX_FILESIZE*)p2);
if (ret > 0) {
return 1;
}
if (ret < 0) {
return -1;
}
return 0;
}
CPDF_Parser::CPDF_Parser()
{
m_pDocument = NULL;
m_pTrailer = NULL;
m_pEncryptDict = NULL;
m_pSecurityHandler = NULL;
m_pLinearized = NULL;
m_dwFirstPageNo = 0;
m_dwXrefStartObjNum = 0;
m_bOwnFileRead = TRUE;
m_FileVersion = 0;
m_bForceUseSecurityHandler = FALSE;
}
CPDF_Parser::~CPDF_Parser()
{
CloseParser(FALSE);
}
FX_DWORD CPDF_Parser::GetLastObjNum()
{
FX_DWORD dwSize = m_CrossRef.GetSize();
return dwSize ? dwSize - 1 : 0;
}
void CPDF_Parser::SetEncryptDictionary(CPDF_Dictionary* pDict)
{
m_pEncryptDict = pDict;
}
void CPDF_Parser::CloseParser(FX_BOOL bReParse)
{
m_bVersionUpdated = FALSE;
if (!bReParse) {
delete m_pDocument;
m_pDocument = NULL;
}
if (m_pTrailer) {
m_pTrailer->Release();
m_pTrailer = NULL;
}
ReleaseEncryptHandler();
SetEncryptDictionary(NULL);
if (m_bOwnFileRead && m_Syntax.m_pFileAccess) {
m_Syntax.m_pFileAccess->Release();
m_Syntax.m_pFileAccess = NULL;
}
FX_POSITION pos = m_ObjectStreamMap.GetStartPosition();
while (pos) {
void* objnum;
CPDF_StreamAcc* pStream;
m_ObjectStreamMap.GetNextAssoc(pos, objnum, (void*&)pStream);
delete pStream;
}
m_ObjectStreamMap.RemoveAll();
m_SortedOffset.RemoveAll();
m_CrossRef.RemoveAll();
m_V5Type.RemoveAll();
m_ObjVersion.RemoveAll();
int32_t iLen = m_Trailers.GetSize();
for (int32_t i = 0; i < iLen; ++i) {
if (CPDF_Dictionary* trailer = m_Trailers.GetAt(i))
trailer->Release();
}
m_Trailers.RemoveAll();
if (m_pLinearized) {
m_pLinearized->Release();
m_pLinearized = NULL;
}
}
static int32_t GetHeaderOffset(IFX_FileRead* pFile)
{
FX_DWORD tag = FXDWORD_FROM_LSBFIRST(0x46445025);
uint8_t buf[4];
int32_t offset = 0;
while (1) {
if (!pFile->ReadBlock(buf, offset, 4)) {
return -1;
}
if (*(FX_DWORD*)buf == tag) {
return offset;
}
offset ++;
if (offset > 1024) {
return -1;
}
}
return -1;
}
FX_DWORD CPDF_Parser::StartParse(const FX_CHAR* filename, FX_BOOL bReParse)
{
IFX_FileRead* pFileAccess = FX_CreateFileRead(filename);
if (!pFileAccess) {
return PDFPARSE_ERROR_FILE;
}
return StartParse(pFileAccess, bReParse);
}
FX_DWORD CPDF_Parser::StartParse(const FX_WCHAR* filename, FX_BOOL bReParse)
{
IFX_FileRead* pFileAccess = FX_CreateFileRead(filename);
if (!pFileAccess) {
return PDFPARSE_ERROR_FILE;
}
return StartParse(pFileAccess, bReParse);
}
CPDF_SecurityHandler* FPDF_CreateStandardSecurityHandler();
CPDF_SecurityHandler* FPDF_CreatePubKeyHandler(void*);
FX_DWORD CPDF_Parser::StartParse(IFX_FileRead* pFileAccess, FX_BOOL bReParse, FX_BOOL bOwnFileRead)
{
CloseParser(bReParse);
m_bXRefStream = FALSE;
m_LastXRefOffset = 0;
m_bOwnFileRead = bOwnFileRead;
int32_t offset = GetHeaderOffset(pFileAccess);
if (offset == -1) {
if (bOwnFileRead && pFileAccess) {
pFileAccess->Release();
}
return PDFPARSE_ERROR_FORMAT;
}
m_Syntax.InitParser(pFileAccess, offset);
uint8_t ch;
if (!m_Syntax.GetCharAt(5, ch)) {
return PDFPARSE_ERROR_FORMAT;
}
if (ch >= '0' && ch <= '9') {
m_FileVersion = (ch - '0') * 10;
}
if (!m_Syntax.GetCharAt(7, ch)) {
return PDFPARSE_ERROR_FORMAT;
}
if (ch >= '0' && ch <= '9') {
m_FileVersion += ch - '0';
}
if (m_Syntax.m_FileLen < m_Syntax.m_HeaderOffset + 9) {
return PDFPARSE_ERROR_FORMAT;
}
m_Syntax.RestorePos(m_Syntax.m_FileLen - m_Syntax.m_HeaderOffset - 9);
if (!bReParse) {
m_pDocument = new CPDF_Document(this);
}
FX_BOOL bXRefRebuilt = FALSE;
if (m_Syntax.SearchWord(FX_BSTRC("startxref"), TRUE, FALSE, 4096)) {
FX_FILESIZE startxref_offset = m_Syntax.SavePos();
void* pResult = FXSYS_bsearch(&startxref_offset, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(startxref_offset);
}
m_Syntax.GetKeyword();
FX_BOOL bNumber;
CFX_ByteString xrefpos_str = m_Syntax.GetNextWord(bNumber);
if (!bNumber) {
return PDFPARSE_ERROR_FORMAT;
}
m_LastXRefOffset = (FX_FILESIZE)FXSYS_atoi64(xrefpos_str);
if (!LoadAllCrossRefV4(m_LastXRefOffset) && !LoadAllCrossRefV5(m_LastXRefOffset)) {
if (!RebuildCrossRef()) {
return PDFPARSE_ERROR_FORMAT;
}
bXRefRebuilt = TRUE;
m_LastXRefOffset = 0;
}
} else {
if (!RebuildCrossRef()) {
return PDFPARSE_ERROR_FORMAT;
}
bXRefRebuilt = TRUE;
}
FX_DWORD dwRet = SetEncryptHandler();
if (dwRet != PDFPARSE_ERROR_SUCCESS) {
return dwRet;
}
m_pDocument->LoadDoc();
if (m_pDocument->GetRoot() == NULL || m_pDocument->GetPageCount() == 0) {
if (bXRefRebuilt) {
return PDFPARSE_ERROR_FORMAT;
}
ReleaseEncryptHandler();
if (!RebuildCrossRef()) {
return PDFPARSE_ERROR_FORMAT;
}
dwRet = SetEncryptHandler();
if (dwRet != PDFPARSE_ERROR_SUCCESS) {
return dwRet;
}
m_pDocument->LoadDoc();
if (m_pDocument->GetRoot() == NULL) {
return PDFPARSE_ERROR_FORMAT;
}
}
FXSYS_qsort(m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
FX_DWORD RootObjNum = GetRootObjNum();
if (RootObjNum == 0) {
ReleaseEncryptHandler();
RebuildCrossRef();
RootObjNum = GetRootObjNum();
if (RootObjNum == 0) {
return PDFPARSE_ERROR_FORMAT;
}
dwRet = SetEncryptHandler();
if (dwRet != PDFPARSE_ERROR_SUCCESS) {
return dwRet;
}
}
if (m_pSecurityHandler && !m_pSecurityHandler->IsMetadataEncrypted()) {
CPDF_Reference* pMetadata = (CPDF_Reference*)m_pDocument->GetRoot()->GetElement(FX_BSTRC("Metadata"));
if (pMetadata && pMetadata->GetType() == PDFOBJ_REFERENCE) {
m_Syntax.m_MetadataObjnum = pMetadata->GetRefObjNum();
}
}
return PDFPARSE_ERROR_SUCCESS;
}
FX_DWORD CPDF_Parser::SetEncryptHandler()
{
ReleaseEncryptHandler();
SetEncryptDictionary(NULL);
if (m_pTrailer == NULL) {
return PDFPARSE_ERROR_FORMAT;
}
CPDF_Object* pEncryptObj = m_pTrailer->GetElement(FX_BSTRC("Encrypt"));
if (pEncryptObj) {
if (pEncryptObj->GetType() == PDFOBJ_DICTIONARY) {
SetEncryptDictionary((CPDF_Dictionary*)pEncryptObj);
} else if (pEncryptObj->GetType() == PDFOBJ_REFERENCE) {
pEncryptObj = m_pDocument->GetIndirectObject(((CPDF_Reference*)pEncryptObj)->GetRefObjNum());
if (pEncryptObj) {
SetEncryptDictionary(pEncryptObj->GetDict());
}
}
}
if (m_bForceUseSecurityHandler) {
FX_DWORD err = PDFPARSE_ERROR_HANDLER;
if (m_pSecurityHandler == NULL) {
return PDFPARSE_ERROR_HANDLER;
}
if (!m_pSecurityHandler->OnInit(this, m_pEncryptDict)) {
return err;
}
CPDF_CryptoHandler* pCryptoHandler = m_pSecurityHandler->CreateCryptoHandler();
if (!pCryptoHandler->Init(m_pEncryptDict, m_pSecurityHandler)) {
delete pCryptoHandler;
pCryptoHandler = NULL;
return PDFPARSE_ERROR_HANDLER;
}
m_Syntax.SetEncrypt(pCryptoHandler);
} else if (m_pEncryptDict) {
CFX_ByteString filter = m_pEncryptDict->GetString(FX_BSTRC("Filter"));
CPDF_SecurityHandler* pSecurityHandler = NULL;
FX_DWORD err = PDFPARSE_ERROR_HANDLER;
if (filter == FX_BSTRC("Standard")) {
pSecurityHandler = FPDF_CreateStandardSecurityHandler();
err = PDFPARSE_ERROR_PASSWORD;
}
if (pSecurityHandler == NULL) {
return PDFPARSE_ERROR_HANDLER;
}
if (!pSecurityHandler->OnInit(this, m_pEncryptDict)) {
delete pSecurityHandler;
pSecurityHandler = NULL;
return err;
}
m_pSecurityHandler = pSecurityHandler;
CPDF_CryptoHandler* pCryptoHandler = pSecurityHandler->CreateCryptoHandler();
if (!pCryptoHandler->Init(m_pEncryptDict, m_pSecurityHandler)) {
delete pCryptoHandler;
pCryptoHandler = NULL;
return PDFPARSE_ERROR_HANDLER;
}
m_Syntax.SetEncrypt(pCryptoHandler);
}
return PDFPARSE_ERROR_SUCCESS;
}
void CPDF_Parser::ReleaseEncryptHandler()
{
delete m_Syntax.m_pCryptoHandler;
m_Syntax.m_pCryptoHandler = NULL;
if (!m_bForceUseSecurityHandler) {
delete m_pSecurityHandler;
m_pSecurityHandler = NULL;
}
}
FX_FILESIZE CPDF_Parser::GetObjectOffset(FX_DWORD objnum)
{
if (objnum >= (FX_DWORD)m_CrossRef.GetSize()) {
return 0;
}
if (m_V5Type[objnum] == 1) {
return m_CrossRef[objnum];
}
if (m_V5Type[objnum] == 2) {
return m_CrossRef[(int32_t)m_CrossRef[objnum]];
}
return 0;
}
static int32_t GetDirectInteger(CPDF_Dictionary* pDict, const CFX_ByteStringC& key)
{
CPDF_Object* pObj = pDict->GetElement(key);
if (pObj == NULL) {
return 0;
}
if (pObj->GetType() == PDFOBJ_NUMBER) {
return ((CPDF_Number*)pObj)->GetInteger();
}
return 0;
}
static FX_BOOL CheckDirectType(CPDF_Dictionary* pDict, const CFX_ByteStringC& key, int32_t iType)
{
CPDF_Object* pObj = pDict->GetElement(key);
if (!pObj) {
return TRUE;
}
return pObj->GetType() == iType;
}
FX_BOOL CPDF_Parser::LoadAllCrossRefV4(FX_FILESIZE xrefpos)
{
if (!LoadCrossRefV4(xrefpos, 0, TRUE, FALSE)) {
return FALSE;
}
m_pTrailer = LoadTrailerV4();
if (m_pTrailer == NULL) {
return FALSE;
}
int32_t xrefsize = GetDirectInteger(m_pTrailer, FX_BSTRC("Size"));
if (xrefsize <= 0 || xrefsize > (1 << 20)) {
return FALSE;
}
m_CrossRef.SetSize(xrefsize);
m_V5Type.SetSize(xrefsize);
CFX_FileSizeArray CrossRefList, XRefStreamList;
CrossRefList.Add(xrefpos);
XRefStreamList.Add(GetDirectInteger(m_pTrailer, FX_BSTRC("XRefStm")));
if (!CheckDirectType(m_pTrailer, FX_BSTRC("Prev"), PDFOBJ_NUMBER)) {
return FALSE;
}
FX_FILESIZE newxrefpos = GetDirectInteger(m_pTrailer, FX_BSTRC("Prev"));
if (newxrefpos == xrefpos) {
return FALSE;
}
xrefpos = newxrefpos;
while (xrefpos) {
CrossRefList.InsertAt(0, xrefpos);
LoadCrossRefV4(xrefpos, 0, TRUE, FALSE);
CPDF_Dictionary* pDict = LoadTrailerV4();
if (pDict == NULL) {
return FALSE;
}
if (!CheckDirectType(pDict, FX_BSTRC("Prev"), PDFOBJ_NUMBER)) {
pDict->Release();
return FALSE;
}
newxrefpos = GetDirectInteger(pDict, FX_BSTRC("Prev"));
if (newxrefpos == xrefpos) {
pDict->Release();
return FALSE;
}
xrefpos = newxrefpos;
XRefStreamList.InsertAt(0, pDict->GetInteger(FX_BSTRC("XRefStm")));
m_Trailers.Add(pDict);
}
for (int32_t i = 0; i < CrossRefList.GetSize(); i ++)
if (!LoadCrossRefV4(CrossRefList[i], XRefStreamList[i], FALSE, i == 0)) {
return FALSE;
}
return TRUE;
}
FX_BOOL CPDF_Parser::LoadLinearizedAllCrossRefV4(FX_FILESIZE xrefpos, FX_DWORD dwObjCount)
{
if (!LoadLinearizedCrossRefV4(xrefpos, dwObjCount)) {
return FALSE;
}
m_pTrailer = LoadTrailerV4();
if (m_pTrailer == NULL) {
return FALSE;
}
int32_t xrefsize = GetDirectInteger(m_pTrailer, FX_BSTRC("Size"));
if (xrefsize == 0) {
return FALSE;
}
CFX_FileSizeArray CrossRefList, XRefStreamList;
CrossRefList.Add(xrefpos);
XRefStreamList.Add(GetDirectInteger(m_pTrailer, FX_BSTRC("XRefStm")));
xrefpos = GetDirectInteger(m_pTrailer, FX_BSTRC("Prev"));
while (xrefpos) {
CrossRefList.InsertAt(0, xrefpos);
LoadCrossRefV4(xrefpos, 0, TRUE, FALSE);
CPDF_Dictionary* pDict = LoadTrailerV4();
if (pDict == NULL) {
return FALSE;
}
xrefpos = GetDirectInteger(pDict, FX_BSTRC("Prev"));
XRefStreamList.InsertAt(0, pDict->GetInteger(FX_BSTRC("XRefStm")));
m_Trailers.Add(pDict);
}
for (int32_t i = 1; i < CrossRefList.GetSize(); i ++)
if (!LoadCrossRefV4(CrossRefList[i], XRefStreamList[i], FALSE, i == 0)) {
return FALSE;
}
return TRUE;
}
FX_BOOL CPDF_Parser::LoadLinearizedCrossRefV4(FX_FILESIZE pos, FX_DWORD dwObjCount)
{
FX_FILESIZE dwStartPos = pos - m_Syntax.m_HeaderOffset;
m_Syntax.RestorePos(dwStartPos);
void* pResult = FXSYS_bsearch(&pos, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(pos);
}
FX_DWORD start_objnum = 0;
FX_DWORD count = dwObjCount;
FX_FILESIZE SavedPos = m_Syntax.SavePos();
int32_t recordsize = 20;
char* pBuf = FX_Alloc(char, 1024 * recordsize + 1);
pBuf[1024 * recordsize] = '\0';
int32_t nBlocks = count / 1024 + 1;
for (int32_t block = 0; block < nBlocks; block ++) {
int32_t block_size = block == nBlocks - 1 ? count % 1024 : 1024;
FX_DWORD dwReadSize = block_size * recordsize;
if ((FX_FILESIZE)(dwStartPos + dwReadSize) > m_Syntax.m_FileLen) {
FX_Free(pBuf);
return FALSE;
}
if (!m_Syntax.ReadBlock((uint8_t*)pBuf, dwReadSize)) {
FX_Free(pBuf);
return FALSE;
}
for (int32_t i = 0; i < block_size; i ++) {
FX_DWORD objnum = start_objnum + block * 1024 + i;
char* pEntry = pBuf + i * recordsize;
if (pEntry[17] == 'f') {
m_CrossRef.SetAtGrow(objnum, 0);
m_V5Type.SetAtGrow(objnum, 0);
} else {
int32_t offset = FXSYS_atoi(pEntry);
if (offset == 0) {
for (int32_t c = 0; c < 10; c ++) {
if (pEntry[c] < '0' || pEntry[c] > '9') {
FX_Free(pBuf);
return FALSE;
}
}
}
m_CrossRef.SetAtGrow(objnum, offset);
int32_t version = FXSYS_atoi(pEntry + 11);
if (version >= 1) {
m_bVersionUpdated = TRUE;
}
m_ObjVersion.SetAtGrow(objnum, version);
if (m_CrossRef[objnum] < m_Syntax.m_FileLen) {
void* pResult = FXSYS_bsearch(&m_CrossRef[objnum], m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(m_CrossRef[objnum]);
}
}
m_V5Type.SetAtGrow(objnum, 1);
}
}
}
FX_Free(pBuf);
m_Syntax.RestorePos(SavedPos + count * recordsize);
return TRUE;
}
FX_BOOL CPDF_Parser::LoadCrossRefV4(FX_FILESIZE pos, FX_FILESIZE streampos, FX_BOOL bSkip, FX_BOOL bFirst)
{
m_Syntax.RestorePos(pos);
if (m_Syntax.GetKeyword() != FX_BSTRC("xref")) {
return FALSE;
}
void* pResult = FXSYS_bsearch(&pos, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(pos);
}
if (streampos) {
void* pResult = FXSYS_bsearch(&streampos, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(streampos);
}
}
while (1) {
FX_FILESIZE SavedPos = m_Syntax.SavePos();
FX_BOOL bIsNumber;
CFX_ByteString word = m_Syntax.GetNextWord(bIsNumber);
if (word.IsEmpty()) {
return FALSE;
}
if (!bIsNumber) {
m_Syntax.RestorePos(SavedPos);
break;
}
FX_DWORD start_objnum = FXSYS_atoi(word);
if (start_objnum >= (1 << 20)) {
return FALSE;
}
FX_DWORD count = m_Syntax.GetDirectNum();
m_Syntax.ToNextWord();
SavedPos = m_Syntax.SavePos();
FX_BOOL bFirstItem = FALSE;
int32_t recordsize = 20;
if (bFirst) {
bFirstItem = TRUE;
}
m_dwXrefStartObjNum = start_objnum;
if (!bSkip) {
char* pBuf = FX_Alloc(char, 1024 * recordsize + 1);
pBuf[1024 * recordsize] = '\0';
int32_t nBlocks = count / 1024 + 1;
FX_BOOL bFirstBlock = TRUE;
for (int32_t block = 0; block < nBlocks; block ++) {
int32_t block_size = block == nBlocks - 1 ? count % 1024 : 1024;
m_Syntax.ReadBlock((uint8_t*)pBuf, block_size * recordsize);
for (int32_t i = 0; i < block_size; i ++) {
FX_DWORD objnum = start_objnum + block * 1024 + i;
char* pEntry = pBuf + i * recordsize;
if (pEntry[17] == 'f') {
if (bFirstItem) {
objnum = 0;
bFirstItem = FALSE;
}
if (bFirstBlock) {
FX_FILESIZE offset = (FX_FILESIZE)FXSYS_atoi64(pEntry);
int32_t version = FXSYS_atoi(pEntry + 11);
if (offset == 0 && version == 65535 && start_objnum != 0) {
start_objnum--;
objnum = 0;
}
}
m_CrossRef.SetAtGrow(objnum, 0);
m_V5Type.SetAtGrow(objnum, 0);
} else {
FX_FILESIZE offset = (FX_FILESIZE)FXSYS_atoi64(pEntry);
if (offset == 0) {
for (int32_t c = 0; c < 10; c ++) {
if (pEntry[c] < '0' || pEntry[c] > '9') {
FX_Free(pBuf);
return FALSE;
}
}
}
m_CrossRef.SetAtGrow(objnum, offset);
int32_t version = FXSYS_atoi(pEntry + 11);
if (version >= 1) {
m_bVersionUpdated = TRUE;
}
m_ObjVersion.SetAtGrow(objnum, version);
if (m_CrossRef[objnum] < m_Syntax.m_FileLen) {
void* pResult = FXSYS_bsearch(&m_CrossRef[objnum], m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(m_CrossRef[objnum]);
}
}
m_V5Type.SetAtGrow(objnum, 1);
}
if (bFirstBlock) {
bFirstBlock = FALSE;
}
}
}
FX_Free(pBuf);
}
m_Syntax.RestorePos(SavedPos + count * recordsize);
}
if (streampos)
if (!LoadCrossRefV5(streampos, streampos, FALSE)) {
return FALSE;
}
return TRUE;
}
FX_BOOL CPDF_Parser::LoadAllCrossRefV5(FX_FILESIZE xrefpos)
{
if (!LoadCrossRefV5(xrefpos, xrefpos, TRUE)) {
return FALSE;
}
while (xrefpos)
if (!LoadCrossRefV5(xrefpos, xrefpos, FALSE)) {
return FALSE;
}
m_ObjectStreamMap.InitHashTable(101, FALSE);
m_bXRefStream = TRUE;
return TRUE;
}
FX_BOOL CPDF_Parser::RebuildCrossRef()
{
m_CrossRef.RemoveAll();
m_V5Type.RemoveAll();
m_SortedOffset.RemoveAll();
m_ObjVersion.RemoveAll();
if (m_pTrailer) {
m_pTrailer->Release();
m_pTrailer = NULL;
}
int32_t status = 0;
int32_t inside_index = 0;
FX_DWORD objnum = 0, gennum = 0;
int32_t depth = 0;
uint8_t* buffer = FX_Alloc(uint8_t, 4096);
FX_FILESIZE pos = m_Syntax.m_HeaderOffset;
FX_FILESIZE start_pos = 0, start_pos1 = 0;
FX_FILESIZE last_obj = -1, last_xref = -1, last_trailer = -1;
while (pos < m_Syntax.m_FileLen) {
FX_BOOL bOverFlow = FALSE;
FX_DWORD size = (FX_DWORD)(m_Syntax.m_FileLen - pos);
if (size > 4096) {
size = 4096;
}
if (!m_Syntax.m_pFileAccess->ReadBlock(buffer, pos, size)) {
break;
}
for (FX_DWORD i = 0; i < size; i ++) {
uint8_t byte = buffer[i];
switch (status) {
case 0:
if (PDF_CharType[byte] == 'W') {
status = 1;
}
if (byte <= '9' && byte >= '0') {
--i;
status = 1;
}
if (byte == '%') {
inside_index = 0;
status = 9;
}
if (byte == '(') {
status = 10;
depth = 1;
}
if (byte == '<') {
inside_index = 1;
status = 11;
}
if (byte == '\\') {
status = 13;
}
if (byte == 't') {
status = 7;
inside_index = 1;
}
break;
case 1:
if (PDF_CharType[byte] == 'W') {
break;
} else if (byte <= '9' && byte >= '0') {
start_pos = pos + i;
status = 2;
objnum = byte - '0';
} else if (byte == 't') {
status = 7;
inside_index = 1;
} else if (byte == 'x') {
status = 8;
inside_index = 1;
} else {
--i;
status = 0;
}
break;
case 2:
if (byte <= '9' && byte >= '0') {
objnum = objnum * 10 + byte - '0';
break;
} else if (PDF_CharType[byte] == 'W') {
status = 3;
} else {
--i;
status = 14;
inside_index = 0;
}
break;
case 3:
if (byte <= '9' && byte >= '0') {
start_pos1 = pos + i;
status = 4;
gennum = byte - '0';
} else if (PDF_CharType[byte] == 'W') {
break;
} else if (byte == 't') {
status = 7;
inside_index = 1;
} else {
--i;
status = 0;
}
break;
case 4:
if (byte <= '9' && byte >= '0') {
gennum = gennum * 10 + byte - '0';
break;
} else if (PDF_CharType[byte] == 'W') {
status = 5;
} else {
--i;
status = 0;
}
break;
case 5:
if (byte == 'o') {
status = 6;
inside_index = 1;
} else if (PDF_CharType[byte] == 'W') {
break;
} else if (byte <= '9' && byte >= '0') {
objnum = gennum;
gennum = byte - '0';
start_pos = start_pos1;
start_pos1 = pos + i;
status = 4;
} else if (byte == 't') {
status = 7;
inside_index = 1;
} else {
--i;
status = 0;
}
break;
case 6:
switch (inside_index) {
case 1:
if (byte != 'b') {
--i;
status = 0;
} else {
inside_index ++;
}
break;
case 2:
if (byte != 'j') {
--i;
status = 0;
} else {
inside_index ++;
}
break;
case 3:
if (PDF_CharType[byte] == 'W' || PDF_CharType[byte] == 'D') {
if (objnum > 0x1000000) {
status = 0;
break;
}
FX_FILESIZE obj_pos = start_pos - m_Syntax.m_HeaderOffset;
last_obj = start_pos;
void* pResult = FXSYS_bsearch(&obj_pos, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(obj_pos);
}
FX_FILESIZE obj_end = 0;
CPDF_Object *pObject = ParseIndirectObjectAtByStrict(m_pDocument, obj_pos, objnum, NULL, &obj_end);
if (pObject) {
int iType = pObject->GetType();
if (iType == PDFOBJ_STREAM) {
CPDF_Stream* pStream = (CPDF_Stream*)pObject;
CPDF_Dictionary* pDict = pStream->GetDict();
if (pDict) {
if (pDict->KeyExist(FX_BSTRC("Type"))) {
CFX_ByteString bsValue = pDict->GetString(FX_BSTRC("Type"));
if (bsValue == FX_BSTRC("XRef") && pDict->KeyExist(FX_BSTRC("Size"))) {
CPDF_Object* pRoot = pDict->GetElement(FX_BSTRC("Root"));
if (pRoot && pRoot->GetDict() && pRoot->GetDict()->GetElement(FX_BSTRC("Pages"))) {
if (m_pTrailer) {
m_pTrailer->Release();
}
m_pTrailer = (CPDF_Dictionary*)pDict->Clone();
}
}
}
}
}
}
FX_FILESIZE offset = 0;
m_Syntax.RestorePos(obj_pos);
offset = m_Syntax.FindTag(FX_BSTRC("obj"), 0);
if (offset == -1) {
offset = 0;
} else {
offset += 3;
}
FX_FILESIZE nLen = obj_end - obj_pos - offset;
if ((FX_DWORD)nLen > size - i) {
pos = obj_end + m_Syntax.m_HeaderOffset;
bOverFlow = TRUE;
} else {
i += (FX_DWORD)nLen;
}
if (m_CrossRef.GetSize() > (int32_t)objnum && m_CrossRef[objnum]) {
if (pObject) {
FX_DWORD oldgen = m_ObjVersion.GetAt(objnum);
m_CrossRef[objnum] = obj_pos;
m_ObjVersion.SetAt(objnum, (int16_t)gennum);
if (oldgen != gennum) {
m_bVersionUpdated = TRUE;
}
}
} else {
m_CrossRef.SetAtGrow(objnum, obj_pos);
m_V5Type.SetAtGrow(objnum, 1);
m_ObjVersion.SetAtGrow(objnum, (int16_t)gennum);
}
if (pObject) {
pObject->Release();
}
}
--i;
status = 0;
break;
}
break;
case 7:
if (inside_index == 7) {
if (PDF_CharType[byte] == 'W' || PDF_CharType[byte] == 'D') {
last_trailer = pos + i - 7;
m_Syntax.RestorePos(pos + i - m_Syntax.m_HeaderOffset);
CPDF_Object* pObj = m_Syntax.GetObject(m_pDocument, 0, 0, 0);
if (pObj) {
if (pObj->GetType() != PDFOBJ_DICTIONARY && pObj->GetType() != PDFOBJ_STREAM) {
pObj->Release();
} else {
CPDF_Dictionary* pTrailer = NULL;
if (pObj->GetType() == PDFOBJ_STREAM) {
pTrailer = ((CPDF_Stream*)pObj)->GetDict();
} else {
pTrailer = (CPDF_Dictionary*)pObj;
}
if (pTrailer) {
if (m_pTrailer) {
CPDF_Object* pRoot = pTrailer->GetElement(FX_BSTRC("Root"));
if (pRoot == NULL || (pRoot->GetType() == PDFOBJ_REFERENCE &&
(FX_DWORD)m_CrossRef.GetSize() > ((CPDF_Reference*)pRoot)->GetRefObjNum() &&
m_CrossRef.GetAt(((CPDF_Reference*)pRoot)->GetRefObjNum()) != 0)) {
FX_POSITION pos = pTrailer->GetStartPos();
while (pos) {
CFX_ByteString key;
CPDF_Object* pObj = pTrailer->GetNextElement(pos, key);
m_pTrailer->SetAt(key, pObj->Clone(), m_pDocument);
}
pObj->Release();
} else {
pObj->Release();
}
} else {
if (pObj->GetType() == PDFOBJ_STREAM) {
m_pTrailer = (CPDF_Dictionary*)pTrailer->Clone();
pObj->Release();
} else {
m_pTrailer = pTrailer;
}
FX_FILESIZE dwSavePos = m_Syntax.SavePos();
CFX_ByteString strWord = m_Syntax.GetKeyword();
if (!strWord.Compare(FX_BSTRC("startxref"))) {
FX_BOOL bNumber = FALSE;
CFX_ByteString bsOffset = m_Syntax.GetNextWord(bNumber);
if (bNumber) {
m_LastXRefOffset = FXSYS_atoi(bsOffset);
}
}
m_Syntax.RestorePos(dwSavePos);
}
} else {
pObj->Release();
}
}
}
}
--i;
status = 0;
} else if (byte == "trailer"[inside_index]) {
inside_index ++;
} else {
--i;
status = 0;
}
break;
case 8:
if (inside_index == 4) {
last_xref = pos + i - 4;
status = 1;
} else if (byte == "xref"[inside_index]) {
inside_index ++;
} else {
--i;
status = 0;
}
break;
case 9:
if (byte == '\r' || byte == '\n') {
status = 0;
}
break;
case 10:
if (byte == ')') {
if (depth > 0) {
depth--;
}
} else if (byte == '(') {
depth++;
}
if (!depth) {
status = 0;
}
break;
case 11:
if (byte == '<' && inside_index == 1) {
status = 12;
} else if (byte == '>') {
status = 0;
}
inside_index = 0;
break;
case 12:
--i;
status = 0;
break;
case 13:
if (PDF_CharType[byte] == 'D' || PDF_CharType[byte] == 'W') {
--i;
status = 0;
}
break;
case 14:
if (PDF_CharType[byte] == 'W') {
status = 0;
} else if (byte == '%' || byte == '(' || byte == '<' || byte == '\\') {
status = 0;
--i;
} else if (inside_index == 6) {
status = 0;
--i;
} else if (byte == "endobj"[inside_index]) {
inside_index++;
}
break;
}
if (bOverFlow) {
size = 0;
break;
}
}
pos += size;
}
if (last_xref != -1 && last_xref > last_obj) {
last_trailer = last_xref;
} else if (last_trailer == -1 || last_xref < last_obj) {
last_trailer = m_Syntax.m_FileLen;
}
FX_FILESIZE offset = last_trailer - m_Syntax.m_HeaderOffset;
void* pResult = FXSYS_bsearch(&offset, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(offset);
}
FX_Free(buffer);
return TRUE;
}
static FX_DWORD _GetVarInt(const uint8_t* p, int32_t n)
{
FX_DWORD result = 0;
for (int32_t i = 0; i < n; i ++) {
result = result * 256 + p[i];
}
return result;
}
FX_BOOL CPDF_Parser::LoadCrossRefV5(FX_FILESIZE pos, FX_FILESIZE& prev, FX_BOOL bMainXRef)
{
CPDF_Stream* pStream = (CPDF_Stream*)ParseIndirectObjectAt(m_pDocument, pos, 0, NULL);
if (!pStream) {
return FALSE;
}
if (m_pDocument) {
CPDF_Dictionary * pDict = m_pDocument->GetRoot();
if (!pDict || pDict->GetObjNum() != pStream->m_ObjNum) {
m_pDocument->InsertIndirectObject(pStream->m_ObjNum, pStream);
} else {
if (pStream->GetType() == PDFOBJ_STREAM) {
pStream->Release();
}
return FALSE;
}
}
if (pStream->GetType() != PDFOBJ_STREAM) {
return FALSE;
}
prev = pStream->GetDict()->GetInteger(FX_BSTRC("Prev"));
int32_t size = pStream->GetDict()->GetInteger(FX_BSTRC("Size"));
if (size < 0) {
pStream->Release();
return FALSE;
}
if (bMainXRef) {
m_pTrailer = (CPDF_Dictionary*)pStream->GetDict()->Clone();
m_CrossRef.SetSize(size);
if (m_V5Type.SetSize(size)) {
FXSYS_memset(m_V5Type.GetData(), 0, size);
}
} else {
m_Trailers.Add((CPDF_Dictionary*)pStream->GetDict()->Clone());
}
std::vector<std::pair<int32_t, int32_t> > arrIndex;
CPDF_Array* pArray = pStream->GetDict()->GetArray(FX_BSTRC("Index"));
if (pArray) {
FX_DWORD nPairSize = pArray->GetCount() / 2;
for (FX_DWORD i = 0; i < nPairSize; i++) {
CPDF_Object* pStartNumObj = pArray->GetElement(i * 2);
CPDF_Object* pCountObj = pArray->GetElement(i * 2 + 1);
if (pStartNumObj && pStartNumObj->GetType() == PDFOBJ_NUMBER
&& pCountObj && pCountObj->GetType() == PDFOBJ_NUMBER) {
int nStartNum = pStartNumObj->GetInteger();
int nCount = pCountObj->GetInteger();
if (nStartNum >= 0 && nCount > 0) {
arrIndex.push_back(std::make_pair(nStartNum, nCount));
}
}
}
}
if (arrIndex.size() == 0) {
arrIndex.push_back(std::make_pair(0, size));
}
pArray = pStream->GetDict()->GetArray(FX_BSTRC("W"));
if (pArray == NULL) {
pStream->Release();
return FALSE;
}
CFX_DWordArray WidthArray;
FX_SAFE_DWORD dwAccWidth = 0;
for (FX_DWORD i = 0; i < pArray->GetCount(); i ++) {
WidthArray.Add(pArray->GetInteger(i));
dwAccWidth += WidthArray[i];
}
if (!dwAccWidth.IsValid() || WidthArray.GetSize() < 3) {
pStream->Release();
return FALSE;
}
FX_DWORD totalWidth = dwAccWidth.ValueOrDie();
CPDF_StreamAcc acc;
acc.LoadAllData(pStream);
const uint8_t* pData = acc.GetData();
FX_DWORD dwTotalSize = acc.GetSize();
FX_DWORD segindex = 0;
for (FX_DWORD i = 0; i < arrIndex.size(); i ++) {
int32_t startnum = arrIndex[i].first;
if (startnum < 0) {
continue;
}
m_dwXrefStartObjNum = pdfium::base::checked_cast<FX_DWORD, int32_t> (startnum);
FX_DWORD count = pdfium::base::checked_cast<FX_DWORD, int32_t> (arrIndex[i].second);
FX_SAFE_DWORD dwCaculatedSize = segindex;
dwCaculatedSize += count;
dwCaculatedSize *= totalWidth;
if (!dwCaculatedSize.IsValid() || dwCaculatedSize.ValueOrDie() > dwTotalSize) {
continue;
}
const uint8_t* segstart = pData + segindex * totalWidth;
FX_SAFE_DWORD dwMaxObjNum = startnum;
dwMaxObjNum += count;
FX_DWORD dwV5Size = pdfium::base::checked_cast<FX_DWORD, int32_t> (m_V5Type.GetSize());
if (!dwMaxObjNum.IsValid() || dwMaxObjNum.ValueOrDie() > dwV5Size) {
continue;
}
for (FX_DWORD j = 0; j < count; j ++) {
int32_t type = 1;
const uint8_t* entrystart = segstart + j * totalWidth;
if (WidthArray[0]) {
type = _GetVarInt(entrystart, WidthArray[0]);
}
if (m_V5Type[startnum + j] == 255) {
FX_FILESIZE offset = _GetVarInt(entrystart + WidthArray[0], WidthArray[1]);
m_CrossRef[startnum + j] = offset;
void* pResult = FXSYS_bsearch(&offset, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(offset);
}
continue;
}
if (m_V5Type[startnum + j]) {
continue;
}
m_V5Type[startnum + j] = type;
if (type == 0) {
m_CrossRef[startnum + j] = 0;
} else {
FX_FILESIZE offset = _GetVarInt(entrystart + WidthArray[0], WidthArray[1]);
m_CrossRef[startnum + j] = offset;
if (type == 1) {
void* pResult = FXSYS_bsearch(&offset, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_SortedOffset.Add(offset);
}
} else {
if (offset < 0 || offset >= m_V5Type.GetSize()) {
pStream->Release();
return FALSE;
}
m_V5Type[offset] = 255;
}
}
}
segindex += count;
}
pStream->Release();
return TRUE;
}
CPDF_Array* CPDF_Parser::GetIDArray()
{
CPDF_Object* pID = m_pTrailer ? m_pTrailer->GetElement(FX_BSTRC("ID")) : NULL;
if (pID == NULL) {
return NULL;
}
if (pID->GetType() == PDFOBJ_REFERENCE) {
pID = ParseIndirectObject(NULL, ((CPDF_Reference*)pID)->GetRefObjNum());
m_pTrailer->SetAt(FX_BSTRC("ID"), pID);
}
if (pID == NULL || pID->GetType() != PDFOBJ_ARRAY) {
return NULL;
}
return (CPDF_Array*)pID;
}
FX_DWORD CPDF_Parser::GetRootObjNum()
{
CPDF_Object* pRef = m_pTrailer ? m_pTrailer->GetElement(FX_BSTRC("Root")) : NULL;
if (pRef == NULL || pRef->GetType() != PDFOBJ_REFERENCE) {
return 0;
}
return ((CPDF_Reference*) pRef)->GetRefObjNum();
}
FX_DWORD CPDF_Parser::GetInfoObjNum()
{
CPDF_Object* pRef = m_pTrailer ? m_pTrailer->GetElement(FX_BSTRC("Info")) : NULL;
if (pRef == NULL || pRef->GetType() != PDFOBJ_REFERENCE) {
return 0;
}
return ((CPDF_Reference*) pRef)->GetRefObjNum();
}
FX_BOOL CPDF_Parser::IsFormStream(FX_DWORD objnum, FX_BOOL& bForm)
{
bForm = FALSE;
if (objnum >= (FX_DWORD)m_CrossRef.GetSize()) {
return TRUE;
}
if (m_V5Type[objnum] == 0) {
return TRUE;
}
if (m_V5Type[objnum] == 2) {
return TRUE;
}
FX_FILESIZE pos = m_CrossRef[objnum];
void* pResult = FXSYS_bsearch(&pos, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
return TRUE;
}
if ((FX_FILESIZE*)pResult - (FX_FILESIZE*)m_SortedOffset.GetData() == m_SortedOffset.GetSize() - 1) {
return FALSE;
}
FX_FILESIZE size = ((FX_FILESIZE*)pResult)[1] - pos;
FX_FILESIZE SavedPos = m_Syntax.SavePos();
m_Syntax.RestorePos(pos);
bForm = m_Syntax.SearchMultiWord(FX_BSTRC("/Form\0stream"), TRUE, size) == 0;
m_Syntax.RestorePos(SavedPos);
return TRUE;
}
CPDF_Object* CPDF_Parser::ParseIndirectObject(CPDF_IndirectObjects* pObjList, FX_DWORD objnum, PARSE_CONTEXT* pContext)
{
if (objnum >= (FX_DWORD)m_CrossRef.GetSize()) {
return NULL;
}
if (m_V5Type[objnum] == 1 || m_V5Type[objnum] == 255) {
FX_FILESIZE pos = m_CrossRef[objnum];
if (pos <= 0) {
return NULL;
}
return ParseIndirectObjectAt(pObjList, pos, objnum, pContext);
}
if (m_V5Type[objnum] == 2) {
CPDF_StreamAcc* pObjStream = GetObjectStream((FX_DWORD)m_CrossRef[objnum]);
if (pObjStream == NULL) {
return NULL;
}
int32_t n = pObjStream->GetDict()->GetInteger(FX_BSTRC("N"));
int32_t offset = pObjStream->GetDict()->GetInteger(FX_BSTRC("First"));
CPDF_SyntaxParser syntax;
CFX_SmartPointer<IFX_FileStream> file(FX_CreateMemoryStream((uint8_t*)pObjStream->GetData(), (size_t)pObjStream->GetSize(), FALSE));
syntax.InitParser(file.Get(), 0);
CPDF_Object* pRet = NULL;
while (n) {
FX_DWORD thisnum = syntax.GetDirectNum();
FX_DWORD thisoff = syntax.GetDirectNum();
if (thisnum == objnum) {
syntax.RestorePos(offset + thisoff);
pRet = syntax.GetObject(pObjList, 0, 0, pContext);
break;
}
n --;
}
return pRet;
}
return NULL;
}
CPDF_StreamAcc* CPDF_Parser::GetObjectStream(FX_DWORD objnum)
{
CPDF_StreamAcc* pStreamAcc = NULL;
if (m_ObjectStreamMap.Lookup((void*)(uintptr_t)objnum, (void*&)pStreamAcc)) {
return pStreamAcc;
}
const CPDF_Stream* pStream = m_pDocument ? (CPDF_Stream*)m_pDocument->GetIndirectObject(objnum) : NULL;
if (pStream == NULL || pStream->GetType() != PDFOBJ_STREAM) {
return NULL;
}
pStreamAcc = new CPDF_StreamAcc;
pStreamAcc->LoadAllData(pStream);
m_ObjectStreamMap.SetAt((void*)(uintptr_t)objnum, pStreamAcc);
return pStreamAcc;
}
FX_FILESIZE CPDF_Parser::GetObjectSize(FX_DWORD objnum)
{
if (objnum >= (FX_DWORD)m_CrossRef.GetSize()) {
return 0;
}
if (m_V5Type[objnum] == 2) {
objnum = (FX_DWORD)m_CrossRef[objnum];
}
if (m_V5Type[objnum] == 1 || m_V5Type[objnum] == 255) {
FX_FILESIZE offset = m_CrossRef[objnum];
if (offset == 0) {
return 0;
}
void* pResult = FXSYS_bsearch(&offset, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
return 0;
}
if ((FX_FILESIZE*)pResult - (FX_FILESIZE*)m_SortedOffset.GetData() == m_SortedOffset.GetSize() - 1) {
return 0;
}
return ((FX_FILESIZE*)pResult)[1] - offset;
}
return 0;
}
void CPDF_Parser::GetIndirectBinary(FX_DWORD objnum, uint8_t*& pBuffer, FX_DWORD& size)
{
pBuffer = NULL;
size = 0;
if (objnum >= (FX_DWORD)m_CrossRef.GetSize()) {
return;
}
if (m_V5Type[objnum] == 2) {
CPDF_StreamAcc* pObjStream = GetObjectStream((FX_DWORD)m_CrossRef[objnum]);
if (pObjStream == NULL) {
return;
}
int32_t n = pObjStream->GetDict()->GetInteger(FX_BSTRC("N"));
int32_t offset = pObjStream->GetDict()->GetInteger(FX_BSTRC("First"));
CPDF_SyntaxParser syntax;
const uint8_t* pData = pObjStream->GetData();
FX_DWORD totalsize = pObjStream->GetSize();
CFX_SmartPointer<IFX_FileStream> file(FX_CreateMemoryStream((uint8_t*)pData, (size_t)totalsize, FALSE));
syntax.InitParser(file.Get(), 0);
while (n) {
FX_DWORD thisnum = syntax.GetDirectNum();
FX_DWORD thisoff = syntax.GetDirectNum();
if (thisnum == objnum) {
if (n == 1) {
size = totalsize - (thisoff + offset);
} else {
syntax.GetDirectNum(); // Skip nextnum.
FX_DWORD nextoff = syntax.GetDirectNum();
size = nextoff - thisoff;
}
pBuffer = FX_Alloc(uint8_t, size);
FXSYS_memcpy(pBuffer, pData + thisoff + offset, size);
return;
}
n --;
}
return;
}
if (m_V5Type[objnum] == 1) {
FX_FILESIZE pos = m_CrossRef[objnum];
if (pos == 0) {
return;
}
FX_FILESIZE SavedPos = m_Syntax.SavePos();
m_Syntax.RestorePos(pos);
FX_BOOL bIsNumber;
CFX_ByteString word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
m_Syntax.RestorePos(SavedPos);
return;
}
FX_DWORD parser_objnum = FXSYS_atoi(word);
if (parser_objnum && parser_objnum != objnum) {
m_Syntax.RestorePos(SavedPos);
return;
}
word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
m_Syntax.RestorePos(SavedPos);
return;
}
if (m_Syntax.GetKeyword() != FX_BSTRC("obj")) {
m_Syntax.RestorePos(SavedPos);
return;
}
void* pResult = FXSYS_bsearch(&pos, m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
m_Syntax.RestorePos(SavedPos);
return;
}
FX_FILESIZE nextoff = ((FX_FILESIZE*)pResult)[1];
FX_BOOL bNextOffValid = FALSE;
if (nextoff != pos) {
m_Syntax.RestorePos(nextoff);
word = m_Syntax.GetNextWord(bIsNumber);
if (word == FX_BSTRC("xref")) {
bNextOffValid = TRUE;
} else if (bIsNumber) {
word = m_Syntax.GetNextWord(bIsNumber);
if (bIsNumber && m_Syntax.GetKeyword() == FX_BSTRC("obj")) {
bNextOffValid = TRUE;
}
}
}
if (!bNextOffValid) {
m_Syntax.RestorePos(pos);
while (1) {
if (m_Syntax.GetKeyword() == FX_BSTRC("endobj")) {
break;
}
if (m_Syntax.SavePos() == m_Syntax.m_FileLen) {
break;
}
}
nextoff = m_Syntax.SavePos();
}
size = (FX_DWORD)(nextoff - pos);
pBuffer = FX_Alloc(uint8_t, size);
m_Syntax.RestorePos(pos);
m_Syntax.ReadBlock(pBuffer, size);
m_Syntax.RestorePos(SavedPos);
}
}
CPDF_Object* CPDF_Parser::ParseIndirectObjectAt(CPDF_IndirectObjects* pObjList, FX_FILESIZE pos, FX_DWORD objnum,
PARSE_CONTEXT* pContext)
{
FX_FILESIZE SavedPos = m_Syntax.SavePos();
m_Syntax.RestorePos(pos);
FX_BOOL bIsNumber;
CFX_ByteString word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
FX_FILESIZE objOffset = m_Syntax.SavePos();
objOffset -= word.GetLength();
FX_DWORD parser_objnum = FXSYS_atoi(word);
if (objnum && parser_objnum != objnum) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
FX_DWORD parser_gennum = FXSYS_atoi(word);
if (m_Syntax.GetKeyword() != FX_BSTRC("obj")) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
CPDF_Object* pObj = m_Syntax.GetObject(pObjList, objnum, parser_gennum, pContext);
m_Syntax.SavePos();
CFX_ByteString bsWord = m_Syntax.GetKeyword();
if (bsWord == FX_BSTRC("endobj")) {
m_Syntax.SavePos();
}
m_Syntax.RestorePos(SavedPos);
if (pObj) {
if (!objnum) {
pObj->m_ObjNum = parser_objnum;
}
pObj->m_GenNum = parser_gennum;
}
return pObj;
}
CPDF_Object* CPDF_Parser::ParseIndirectObjectAtByStrict(CPDF_IndirectObjects* pObjList, FX_FILESIZE pos, FX_DWORD objnum,
struct PARSE_CONTEXT* pContext, FX_FILESIZE *pResultPos)
{
FX_FILESIZE SavedPos = m_Syntax.SavePos();
m_Syntax.RestorePos(pos);
FX_BOOL bIsNumber;
CFX_ByteString word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
FX_DWORD parser_objnum = FXSYS_atoi(word);
if (objnum && parser_objnum != objnum) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
FX_DWORD gennum = FXSYS_atoi(word);
if (m_Syntax.GetKeyword() != FX_BSTRC("obj")) {
m_Syntax.RestorePos(SavedPos);
return NULL;
}
CPDF_Object* pObj = m_Syntax.GetObjectByStrict(pObjList, objnum, gennum, pContext);
if (pResultPos) {
*pResultPos = m_Syntax.m_Pos;
}
m_Syntax.RestorePos(SavedPos);
return pObj;
}
CPDF_Dictionary* CPDF_Parser::LoadTrailerV4()
{
if (m_Syntax.GetKeyword() != FX_BSTRC("trailer")) {
return NULL;
}
CPDF_Object* pObj = m_Syntax.GetObject(m_pDocument, 0, 0, 0);
if (pObj == NULL || pObj->GetType() != PDFOBJ_DICTIONARY) {
if (pObj) {
pObj->Release();
}
return NULL;
}
return (CPDF_Dictionary*)pObj;
}
FX_DWORD CPDF_Parser::GetPermissions(FX_BOOL bCheckRevision)
{
if (m_pSecurityHandler == NULL) {
return (FX_DWORD) - 1;
}
FX_DWORD dwPermission = m_pSecurityHandler->GetPermissions();
if (m_pEncryptDict && m_pEncryptDict->GetString(FX_BSTRC("Filter")) == FX_BSTRC("Standard")) {
dwPermission &= 0xFFFFFFFC;
dwPermission |= 0xFFFFF0C0;
if(bCheckRevision && m_pEncryptDict->GetInteger(FX_BSTRC("R")) == 2) {
dwPermission &= 0xFFFFF0FF;
}
}
return dwPermission;
}
FX_BOOL CPDF_Parser::IsOwner()
{
return m_pSecurityHandler == NULL ? TRUE : m_pSecurityHandler->IsOwner();
}
void CPDF_Parser::SetSecurityHandler(CPDF_SecurityHandler* pSecurityHandler, FX_BOOL bForced)
{
ASSERT(m_pSecurityHandler == NULL);
if (!m_bForceUseSecurityHandler) {
delete m_pSecurityHandler;
m_pSecurityHandler = NULL;
}
m_bForceUseSecurityHandler = bForced;
m_pSecurityHandler = pSecurityHandler;
if (m_bForceUseSecurityHandler) {
return;
}
m_Syntax.m_pCryptoHandler = pSecurityHandler->CreateCryptoHandler();
m_Syntax.m_pCryptoHandler->Init(NULL, pSecurityHandler);
}
FX_BOOL CPDF_Parser::IsLinearizedFile(IFX_FileRead* pFileAccess, FX_DWORD offset)
{
m_Syntax.InitParser(pFileAccess, offset);
m_Syntax.RestorePos(m_Syntax.m_HeaderOffset + 9);
FX_FILESIZE SavedPos = m_Syntax.SavePos();
FX_BOOL bIsNumber;
CFX_ByteString word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
return FALSE;
}
FX_DWORD objnum = FXSYS_atoi(word);
word = m_Syntax.GetNextWord(bIsNumber);
if (!bIsNumber) {
return FALSE;
}
FX_DWORD gennum = FXSYS_atoi(word);
if (m_Syntax.GetKeyword() != FX_BSTRC("obj")) {
m_Syntax.RestorePos(SavedPos);
return FALSE;
}
m_pLinearized = m_Syntax.GetObject(NULL, objnum, gennum, 0);
if (!m_pLinearized) {
return FALSE;
}
if (m_pLinearized->GetDict() && m_pLinearized->GetDict()->GetElement(FX_BSTRC("Linearized"))) {
m_Syntax.GetNextWord(bIsNumber);
CPDF_Object *pLen = m_pLinearized->GetDict()->GetElement(FX_BSTRC("L"));
if (!pLen) {
m_pLinearized->Release();
m_pLinearized = NULL;
return FALSE;
}
if (pLen->GetInteger() != (int)pFileAccess->GetSize()) {
return FALSE;
}
CPDF_Object *pNo = m_pLinearized->GetDict()->GetElement(FX_BSTRC("P"));
if (pNo && pNo->GetType() == PDFOBJ_NUMBER) {
m_dwFirstPageNo = pNo->GetInteger();
}
CPDF_Object *pTable = m_pLinearized->GetDict()->GetElement(FX_BSTRC("T"));
if (pTable && pTable->GetType() == PDFOBJ_NUMBER) {
m_LastXRefOffset = pTable->GetInteger();
}
return TRUE;
}
m_pLinearized->Release();
m_pLinearized = NULL;
return FALSE;
}
FX_DWORD CPDF_Parser::StartAsynParse(IFX_FileRead* pFileAccess, FX_BOOL bReParse, FX_BOOL bOwnFileRead)
{
CloseParser(bReParse);
m_bXRefStream = FALSE;
m_LastXRefOffset = 0;
m_bOwnFileRead = bOwnFileRead;
int32_t offset = GetHeaderOffset(pFileAccess);
if (offset == -1) {
return PDFPARSE_ERROR_FORMAT;
}
if (!IsLinearizedFile(pFileAccess, offset)) {
m_Syntax.m_pFileAccess = NULL;
return StartParse(pFileAccess, bReParse, bOwnFileRead);
}
if (!bReParse) {
m_pDocument = new CPDF_Document(this);
}
FX_FILESIZE dwFirstXRefOffset = m_Syntax.SavePos();
FX_BOOL bXRefRebuilt = FALSE;
FX_BOOL bLoadV4 = FALSE;
if (!(bLoadV4 = LoadCrossRefV4(dwFirstXRefOffset, 0, FALSE, FALSE)) && !LoadCrossRefV5(dwFirstXRefOffset, dwFirstXRefOffset, TRUE)) {
if (!RebuildCrossRef()) {
return PDFPARSE_ERROR_FORMAT;
}
bXRefRebuilt = TRUE;
m_LastXRefOffset = 0;
}
if (bLoadV4) {
m_pTrailer = LoadTrailerV4();
if (m_pTrailer == NULL) {
return FALSE;
}
int32_t xrefsize = GetDirectInteger(m_pTrailer, FX_BSTRC("Size"));
if (xrefsize > 0) {
m_CrossRef.SetSize(xrefsize);
m_V5Type.SetSize(xrefsize);
}
}
FX_DWORD dwRet = SetEncryptHandler();
if (dwRet != PDFPARSE_ERROR_SUCCESS) {
return dwRet;
}
m_pDocument->LoadAsynDoc(m_pLinearized->GetDict());
if (m_pDocument->GetRoot() == NULL || m_pDocument->GetPageCount() == 0) {
if (bXRefRebuilt) {
return PDFPARSE_ERROR_FORMAT;
}
ReleaseEncryptHandler();
if (!RebuildCrossRef()) {
return PDFPARSE_ERROR_FORMAT;
}
dwRet = SetEncryptHandler();
if (dwRet != PDFPARSE_ERROR_SUCCESS) {
return dwRet;
}
m_pDocument->LoadAsynDoc(m_pLinearized->GetDict());
if (m_pDocument->GetRoot() == NULL) {
return PDFPARSE_ERROR_FORMAT;
}
}
FXSYS_qsort(m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
FX_DWORD RootObjNum = GetRootObjNum();
if (RootObjNum == 0) {
ReleaseEncryptHandler();
RebuildCrossRef();
RootObjNum = GetRootObjNum();
if (RootObjNum == 0) {
return PDFPARSE_ERROR_FORMAT;
}
dwRet = SetEncryptHandler();
if (dwRet != PDFPARSE_ERROR_SUCCESS) {
return dwRet;
}
}
if (m_pSecurityHandler && m_pSecurityHandler->IsMetadataEncrypted()) {
CPDF_Object* pMetadata = m_pDocument->GetRoot()->GetElement(FX_BSTRC("Metadata"));
if (pMetadata && pMetadata->GetType() == PDFOBJ_REFERENCE) {
m_Syntax.m_MetadataObjnum = ((CPDF_Reference*) pMetadata)->GetRefObjNum();
}
}
return PDFPARSE_ERROR_SUCCESS;
}
FX_BOOL CPDF_Parser::LoadLinearizedAllCrossRefV5(FX_FILESIZE xrefpos)
{
if (!LoadCrossRefV5(xrefpos, xrefpos, FALSE)) {
return FALSE;
}
while (xrefpos)
if (!LoadCrossRefV5(xrefpos, xrefpos, FALSE)) {
return FALSE;
}
m_ObjectStreamMap.InitHashTable(101, FALSE);
m_bXRefStream = TRUE;
return TRUE;
}
FX_DWORD CPDF_Parser::LoadLinearizedMainXRefTable()
{
FX_DWORD dwSaveMetadataObjnum = m_Syntax.m_MetadataObjnum;
m_Syntax.m_MetadataObjnum = 0;
if (m_pTrailer) {
m_pTrailer->Release();
m_pTrailer = NULL;
}
m_Syntax.RestorePos(m_LastXRefOffset - m_Syntax.m_HeaderOffset);
uint8_t ch = 0;
FX_DWORD dwCount = 0;
m_Syntax.GetNextChar(ch);
int32_t type = PDF_CharType[ch];
while (type == 'W') {
++dwCount;
if (m_Syntax.m_FileLen >= (FX_FILESIZE)(m_Syntax.SavePos() + m_Syntax.m_HeaderOffset)) {
break;
}
m_Syntax.GetNextChar(ch);
type = PDF_CharType[ch];
}
m_LastXRefOffset += dwCount;
FX_POSITION pos = m_ObjectStreamMap.GetStartPosition();
while (pos) {
void* objnum;
CPDF_StreamAcc* pStream;
m_ObjectStreamMap.GetNextAssoc(pos, objnum, (void*&)pStream);
delete pStream;
}
m_ObjectStreamMap.RemoveAll();
if (!LoadLinearizedAllCrossRefV4(m_LastXRefOffset, m_dwXrefStartObjNum) && !LoadLinearizedAllCrossRefV5(m_LastXRefOffset)) {
m_LastXRefOffset = 0;
m_Syntax.m_MetadataObjnum = dwSaveMetadataObjnum;
return PDFPARSE_ERROR_FORMAT;
}
FXSYS_qsort(m_SortedOffset.GetData(), m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
m_Syntax.m_MetadataObjnum = dwSaveMetadataObjnum;
return PDFPARSE_ERROR_SUCCESS;
}
// static
int CPDF_SyntaxParser::s_CurrentRecursionDepth = 0;
CPDF_SyntaxParser::CPDF_SyntaxParser()
{
m_pFileAccess = NULL;
m_pCryptoHandler = NULL;
m_pFileBuf = NULL;
m_BufSize = CPDF_ModuleMgr::kFileBufSize;
m_pFileBuf = NULL;
m_MetadataObjnum = 0;
m_dwWordPos = 0;
m_bFileStream = FALSE;
}
CPDF_SyntaxParser::~CPDF_SyntaxParser()
{
if (m_pFileBuf) {
FX_Free(m_pFileBuf);
}
}
FX_BOOL CPDF_SyntaxParser::GetCharAt(FX_FILESIZE pos, uint8_t& ch)
{
FX_FILESIZE save_pos = m_Pos;
m_Pos = pos;
FX_BOOL ret = GetNextChar(ch);
m_Pos = save_pos;
return ret;
}
FX_BOOL CPDF_SyntaxParser::GetNextChar(uint8_t& ch)
{
FX_FILESIZE pos = m_Pos + m_HeaderOffset;
if (pos >= m_FileLen) {
return FALSE;
}
if (m_BufOffset >= pos || (FX_FILESIZE)(m_BufOffset + m_BufSize) <= pos) {
FX_FILESIZE read_pos = pos;
FX_DWORD read_size = m_BufSize;
if ((FX_FILESIZE)read_size > m_FileLen) {
read_size = (FX_DWORD)m_FileLen;
}
if ((FX_FILESIZE)(read_pos + read_size) > m_FileLen) {
if (m_FileLen < (FX_FILESIZE)read_size) {
read_pos = 0;
read_size = (FX_DWORD)m_FileLen;
} else {
read_pos = m_FileLen - read_size;
}
}
if (!m_pFileAccess->ReadBlock(m_pFileBuf, read_pos, read_size)) {
return FALSE;
}
m_BufOffset = read_pos;
}
ch = m_pFileBuf[pos - m_BufOffset];
m_Pos ++;
return TRUE;
}
FX_BOOL CPDF_SyntaxParser::GetCharAtBackward(FX_FILESIZE pos, uint8_t& ch)
{
pos += m_HeaderOffset;
if (pos >= m_FileLen) {
return FALSE;
}
if (m_BufOffset >= pos || (FX_FILESIZE)(m_BufOffset + m_BufSize) <= pos) {
FX_FILESIZE read_pos;
if (pos < (FX_FILESIZE)m_BufSize) {
read_pos = 0;
} else {
read_pos = pos - m_BufSize + 1;
}
FX_DWORD read_size = m_BufSize;
if ((FX_FILESIZE)(read_pos + read_size) > m_FileLen) {
if (m_FileLen < (FX_FILESIZE)read_size) {
read_pos = 0;
read_size = (FX_DWORD)m_FileLen;
} else {
read_pos = m_FileLen - read_size;
}
}
if (!m_pFileAccess->ReadBlock(m_pFileBuf, read_pos, read_size)) {
return FALSE;
}
m_BufOffset = read_pos;
}
ch = m_pFileBuf[pos - m_BufOffset];
return TRUE;
}
FX_BOOL CPDF_SyntaxParser::ReadBlock(uint8_t* pBuf, FX_DWORD size)
{
if (!m_pFileAccess->ReadBlock(pBuf, m_Pos + m_HeaderOffset, size)) {
return FALSE;
}
m_Pos += size;
return TRUE;
}
#define MAX_WORD_BUFFER 256
void CPDF_SyntaxParser::GetNextWord()
{
m_WordSize = 0;
m_bIsNumber = TRUE;
uint8_t ch;
if (!GetNextChar(ch)) {
return;
}
uint8_t type = PDF_CharType[ch];
while (1) {
while (type == 'W') {
if (!GetNextChar(ch)) {
return;
}
type = PDF_CharType[ch];
}
if (ch != '%') {
break;
}
while (1) {
if (!GetNextChar(ch)) {
return;
}
if (ch == '\r' || ch == '\n') {
break;
}
}
type = PDF_CharType[ch];
}
if (type == 'D') {
m_bIsNumber = FALSE;
m_WordBuffer[m_WordSize++] = ch;
if (ch == '/') {
while (1) {
if (!GetNextChar(ch)) {
return;
}
type = PDF_CharType[ch];
if (type != 'R' && type != 'N') {
m_Pos --;
return;
}
if (m_WordSize < MAX_WORD_BUFFER) {
m_WordBuffer[m_WordSize++] = ch;
}
}
} else if (ch == '<') {
if (!GetNextChar(ch)) {
return;
}
if (ch == '<') {
m_WordBuffer[m_WordSize++] = ch;
} else {
m_Pos --;
}
} else if (ch == '>') {
if (!GetNextChar(ch)) {
return;
}
if (ch == '>') {
m_WordBuffer[m_WordSize++] = ch;
} else {
m_Pos --;
}
}
return;
}
while (1) {
if (m_WordSize < MAX_WORD_BUFFER) {
m_WordBuffer[m_WordSize++] = ch;
}
if (type != 'N') {
m_bIsNumber = FALSE;
}
if (!GetNextChar(ch)) {
return;
}
type = PDF_CharType[ch];
if (type == 'D' || type == 'W') {
m_Pos --;
break;
}
}
}
CFX_ByteString CPDF_SyntaxParser::ReadString()
{
uint8_t ch;
if (!GetNextChar(ch)) {
return CFX_ByteString();
}
CFX_ByteTextBuf buf;
int32_t parlevel = 0;
int32_t status = 0, iEscCode = 0;
while (1) {
switch (status) {
case 0:
if (ch == ')') {
if (parlevel == 0) {
return buf.GetByteString();
}
parlevel --;
buf.AppendChar(')');
} else if (ch == '(') {
parlevel ++;
buf.AppendChar('(');
} else if (ch == '\\') {
status = 1;
} else {
buf.AppendChar(ch);
}
break;
case 1:
if (ch >= '0' && ch <= '7') {
iEscCode = ch - '0';
status = 2;
break;
}
if (ch == 'n') {
buf.AppendChar('\n');
} else if (ch == 'r') {
buf.AppendChar('\r');
} else if (ch == 't') {
buf.AppendChar('\t');
} else if (ch == 'b') {
buf.AppendChar('\b');
} else if (ch == 'f') {
buf.AppendChar('\f');
} else if (ch == '\r') {
status = 4;
break;
} else if (ch == '\n') {
} else {
buf.AppendChar(ch);
}
status = 0;
break;
case 2:
if (ch >= '0' && ch <= '7') {
iEscCode = iEscCode * 8 + ch - '0';
status = 3;
} else {
buf.AppendChar(iEscCode);
status = 0;
continue;
}
break;
case 3:
if (ch >= '0' && ch <= '7') {
iEscCode = iEscCode * 8 + ch - '0';
buf.AppendChar(iEscCode);
status = 0;
} else {
buf.AppendChar(iEscCode);
status = 0;
continue;
}
break;
case 4:
status = 0;
if (ch != '\n') {
continue;
}
break;
}
if (!GetNextChar(ch)) {
break;
}
}
GetNextChar(ch);
return buf.GetByteString();
}
CFX_ByteString CPDF_SyntaxParser::ReadHexString()
{
uint8_t ch;
if (!GetNextChar(ch)) {
return CFX_ByteString();
}
CFX_BinaryBuf buf;
FX_BOOL bFirst = TRUE;
uint8_t code = 0;
while (1) {
if (ch == '>') {
break;
}
if (ch >= '0' && ch <= '9') {
if (bFirst) {
code = (ch - '0') * 16;
} else {
code += ch - '0';
buf.AppendByte((uint8_t)code);
}
bFirst = !bFirst;
} else if (ch >= 'A' && ch <= 'F') {
if (bFirst) {
code = (ch - 'A' + 10) * 16;
} else {
code += ch - 'A' + 10;
buf.AppendByte((uint8_t)code);
}
bFirst = !bFirst;
} else if (ch >= 'a' && ch <= 'f') {
if (bFirst) {
code = (ch - 'a' + 10) * 16;
} else {
code += ch - 'a' + 10;
buf.AppendByte((uint8_t)code);
}
bFirst = !bFirst;
}
if (!GetNextChar(ch)) {
break;
}
}
if (!bFirst) {
buf.AppendByte((uint8_t)code);
}
return buf.GetByteString();
}
void CPDF_SyntaxParser::ToNextLine()
{
uint8_t ch;
while (1) {
if (!GetNextChar(ch)) {
return;
}
if (ch == '\n') {
return;
}
if (ch == '\r') {
GetNextChar(ch);
if (ch == '\n') {
return;
} else {
m_Pos --;
return;
}
}
}
}
void CPDF_SyntaxParser::ToNextWord()
{
uint8_t ch;
if (!GetNextChar(ch)) {
return;
}
uint8_t type = PDF_CharType[ch];
while (1) {
while (type == 'W') {
m_dwWordPos = m_Pos;
if (!GetNextChar(ch)) {
return;
}
type = PDF_CharType[ch];
}
if (ch != '%') {
break;
}
while (1) {
if (!GetNextChar(ch)) {
return;
}
if (ch == '\r' || ch == '\n') {
break;
}
}
type = PDF_CharType[ch];
}
m_Pos --;
}
CFX_ByteString CPDF_SyntaxParser::GetNextWord(FX_BOOL& bIsNumber)
{
GetNextWord();
bIsNumber = m_bIsNumber;
return CFX_ByteString((const FX_CHAR*)m_WordBuffer, m_WordSize);
}
CFX_ByteString CPDF_SyntaxParser::GetKeyword()
{
GetNextWord();
return CFX_ByteString((const FX_CHAR*)m_WordBuffer, m_WordSize);
}
CPDF_Object* CPDF_SyntaxParser::GetObject(CPDF_IndirectObjects* pObjList, FX_DWORD objnum, FX_DWORD gennum, PARSE_CONTEXT* pContext, FX_BOOL bDecrypt)
{
CFX_AutoRestorer<int> restorer(&s_CurrentRecursionDepth);
if (++s_CurrentRecursionDepth > kParserMaxRecursionDepth) {
return NULL;
}
FX_FILESIZE SavedPos = m_Pos;
FX_BOOL bTypeOnly = pContext && (pContext->m_Flags & PDFPARSE_TYPEONLY);
FX_BOOL bIsNumber;
CFX_ByteString word = GetNextWord(bIsNumber);
if (word.GetLength() == 0) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_INVALID;
}
return NULL;
}
if (bIsNumber) {
FX_FILESIZE SavedPos = m_Pos;
CFX_ByteString nextword = GetNextWord(bIsNumber);
if (bIsNumber) {
CFX_ByteString nextword2 = GetNextWord(bIsNumber);
if (nextword2 == FX_BSTRC("R")) {
FX_DWORD objnum = FXSYS_atoi(word);
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_REFERENCE;
}
return new CPDF_Reference(pObjList, objnum);
} else {
m_Pos = SavedPos;
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NUMBER;
}
return CPDF_Number::Create(word);
}
} else {
m_Pos = SavedPos;
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NUMBER;
}
return CPDF_Number::Create(word);
}
}
if (word == FX_BSTRC("true") || word == FX_BSTRC("false")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_BOOLEAN;
}
return CPDF_Boolean::Create(word == FX_BSTRC("true"));
}
if (word == FX_BSTRC("null")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NULL;
}
return CPDF_Null::Create();
}
if (word == FX_BSTRC("(")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_STRING;
}
CFX_ByteString str = ReadString();
if (m_pCryptoHandler && bDecrypt) {
m_pCryptoHandler->Decrypt(objnum, gennum, str);
}
return CPDF_String::Create(str, FALSE);
}
if (word == FX_BSTRC("<")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_STRING;
}
CFX_ByteString str = ReadHexString();
if (m_pCryptoHandler && bDecrypt) {
m_pCryptoHandler->Decrypt(objnum, gennum, str);
}
return CPDF_String::Create(str, TRUE);
}
if (word == FX_BSTRC("[")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_ARRAY;
}
CPDF_Array* pArray = CPDF_Array::Create();
while (1) {
CPDF_Object* pObj = GetObject(pObjList, objnum, gennum);
if (pObj == NULL) {
return pArray;
}
pArray->Add(pObj);
}
}
if (word[0] == '/') {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NAME;
}
return CPDF_Name::Create(
PDF_NameDecode(CFX_ByteStringC(m_WordBuffer + 1, m_WordSize - 1)));
}
if (word == FX_BSTRC("<<")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_DICTIONARY;
}
if (pContext) {
pContext->m_DictStart = SavedPos;
}
CPDF_Dictionary* pDict = CPDF_Dictionary::Create();
int32_t nKeys = 0;
FX_FILESIZE dwSignValuePos = 0;
while (1) {
FX_BOOL bIsNumber;
CFX_ByteString key = GetNextWord(bIsNumber);
if (key.IsEmpty()) {
if (pDict)
pDict->Release();
return NULL;
}
FX_FILESIZE SavedPos = m_Pos - key.GetLength();
if (key == FX_BSTRC(">>")) {
break;
}
if (key == FX_BSTRC("endobj")) {
m_Pos = SavedPos;
break;
}
if (key[0] != '/') {
continue;
}
nKeys ++;
key = PDF_NameDecode(key);
if (key == FX_BSTRC("/Contents")) {
dwSignValuePos = m_Pos;
}
CPDF_Object* pObj = GetObject(pObjList, objnum, gennum);
if (pObj == NULL) {
continue;
}
if (key.GetLength() >= 1) {
if (nKeys < 32) {
pDict->SetAt(CFX_ByteStringC(key.c_str() + 1, key.GetLength() - 1), pObj);
} else {
pDict->AddValue(CFX_ByteStringC(key.c_str() + 1, key.GetLength() - 1), pObj);
}
}
}
if (IsSignatureDict(pDict)) {
FX_FILESIZE dwSavePos = m_Pos;
m_Pos = dwSignValuePos;
CPDF_Object* pObj = GetObject(pObjList, objnum, gennum, NULL, FALSE);
pDict->SetAt(FX_BSTRC("Contents"), pObj);
m_Pos = dwSavePos;
}
if (pContext) {
pContext->m_DictEnd = m_Pos;
if (pContext->m_Flags & PDFPARSE_NOSTREAM) {
return pDict;
}
}
FX_FILESIZE SavedPos = m_Pos;
FX_BOOL bIsNumber;
CFX_ByteString nextword = GetNextWord(bIsNumber);
if (nextword == FX_BSTRC("stream")) {
CPDF_Stream* pStream = ReadStream(pDict, pContext, objnum, gennum);
if (pStream) {
return pStream;
}
if (pDict)
pDict->Release();
return NULL;
} else {
m_Pos = SavedPos;
return pDict;
}
}
if (word == FX_BSTRC(">>")) {
m_Pos = SavedPos;
return NULL;
}
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_INVALID;
}
return NULL;
}
CPDF_Object* CPDF_SyntaxParser::GetObjectByStrict(CPDF_IndirectObjects* pObjList, FX_DWORD objnum, FX_DWORD gennum, struct PARSE_CONTEXT* pContext)
{
CFX_AutoRestorer<int> restorer(&s_CurrentRecursionDepth);
if (++s_CurrentRecursionDepth > kParserMaxRecursionDepth) {
return NULL;
}
FX_FILESIZE SavedPos = m_Pos;
FX_BOOL bTypeOnly = pContext && (pContext->m_Flags & PDFPARSE_TYPEONLY);
FX_BOOL bIsNumber;
CFX_ByteString word = GetNextWord(bIsNumber);
if (word.GetLength() == 0) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_INVALID;
}
return NULL;
}
if (bIsNumber) {
FX_FILESIZE SavedPos = m_Pos;
CFX_ByteString nextword = GetNextWord(bIsNumber);
if (bIsNumber) {
CFX_ByteString nextword2 = GetNextWord(bIsNumber);
if (nextword2 == FX_BSTRC("R")) {
FX_DWORD objnum = FXSYS_atoi(word);
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_REFERENCE;
}
return new CPDF_Reference(pObjList, objnum);
} else {
m_Pos = SavedPos;
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NUMBER;
}
return CPDF_Number::Create(word);
}
} else {
m_Pos = SavedPos;
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NUMBER;
}
return CPDF_Number::Create(word);
}
}
if (word == FX_BSTRC("true") || word == FX_BSTRC("false")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_BOOLEAN;
}
return CPDF_Boolean::Create(word == FX_BSTRC("true"));
}
if (word == FX_BSTRC("null")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NULL;
}
return CPDF_Null::Create();
}
if (word == FX_BSTRC("(")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_STRING;
}
CFX_ByteString str = ReadString();
if (m_pCryptoHandler) {
m_pCryptoHandler->Decrypt(objnum, gennum, str);
}
return CPDF_String::Create(str, FALSE);
}
if (word == FX_BSTRC("<")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_STRING;
}
CFX_ByteString str = ReadHexString();
if (m_pCryptoHandler) {
m_pCryptoHandler->Decrypt(objnum, gennum, str);
}
return CPDF_String::Create(str, TRUE);
}
if (word == FX_BSTRC("[")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_ARRAY;
}
CPDF_Array* pArray = CPDF_Array::Create();
while (1) {
CPDF_Object* pObj = GetObject(pObjList, objnum, gennum);
if (pObj == NULL) {
if (m_WordBuffer[0] == ']') {
return pArray;
}
if (pArray) {
pArray->Release();
}
return NULL;
}
pArray->Add(pObj);
}
}
if (word[0] == '/') {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_NAME;
}
return CPDF_Name::Create(PDF_NameDecode(CFX_ByteStringC(m_WordBuffer + 1, m_WordSize - 1)));
}
if (word == FX_BSTRC("<<")) {
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_DICTIONARY;
}
if (pContext) {
pContext->m_DictStart = SavedPos;
}
CPDF_Dictionary* pDict = CPDF_Dictionary::Create();
while (1) {
FX_BOOL bIsNumber;
FX_FILESIZE SavedPos = m_Pos;
CFX_ByteString key = GetNextWord(bIsNumber);
if (key.IsEmpty()) {
if (pDict) {
pDict->Release();
}
return NULL;
}
if (key == FX_BSTRC(">>")) {
break;
}
if (key == FX_BSTRC("endobj")) {
m_Pos = SavedPos;
break;
}
if (key[0] != '/') {
continue;
}
key = PDF_NameDecode(key);
CPDF_Object* pObj = GetObject(pObjList, objnum, gennum);
if (pObj == NULL) {
if (pDict) {
pDict->Release();
}
uint8_t ch;
while (1) {
if (!GetNextChar(ch)) {
break;
}
if (ch == 0x0A || ch == 0x0D) {
break;
}
}
return NULL;
}
if (key.GetLength() > 1) {
pDict->AddValue(CFX_ByteStringC(key.c_str() + 1, key.GetLength() - 1), pObj);
}
}
if (pContext) {
pContext->m_DictEnd = m_Pos;
if (pContext->m_Flags & PDFPARSE_NOSTREAM) {
return pDict;
}
}
FX_FILESIZE SavedPos = m_Pos;
FX_BOOL bIsNumber;
CFX_ByteString nextword = GetNextWord(bIsNumber);
if (nextword == FX_BSTRC("stream")) {
CPDF_Stream* pStream = ReadStream(pDict, pContext, objnum, gennum);
if (pStream) {
return pStream;
}
if (pDict) {
pDict->Release();
}
return NULL;
} else {
m_Pos = SavedPos;
return pDict;
}
}
if (word == FX_BSTRC(">>")) {
m_Pos = SavedPos;
return NULL;
}
if (bTypeOnly) {
return (CPDF_Object*)PDFOBJ_INVALID;
}
return NULL;
}
CPDF_Stream* CPDF_SyntaxParser::ReadStream(CPDF_Dictionary* pDict, PARSE_CONTEXT* pContext,
FX_DWORD objnum, FX_DWORD gennum)
{
CPDF_Object* pLenObj = pDict->GetElement(FX_BSTRC("Length"));
FX_FILESIZE len = 0;
if (pLenObj && ((pLenObj->GetType() != PDFOBJ_REFERENCE) ||
((((CPDF_Reference*)pLenObj)->GetObjList() != NULL) &&
((CPDF_Reference*)pLenObj)->GetRefObjNum() != objnum))) {
len = pLenObj->GetInteger();
}
ToNextLine();
FX_FILESIZE StreamStartPos = m_Pos;
if (pContext) {
pContext->m_DataStart = m_Pos;
}
CPDF_CryptoHandler* pCryptoHandler = objnum == (FX_DWORD)m_MetadataObjnum ? NULL : m_pCryptoHandler;
if (pCryptoHandler == NULL) {
pdfium::base::CheckedNumeric<FX_FILESIZE> pos = m_Pos;
pos += len;
if (pos.IsValid() && pos.ValueOrDie() < m_FileLen) {
m_Pos = pos.ValueOrDie();
}
GetNextWord();
if (m_WordSize < 9 || FXSYS_memcmp(m_WordBuffer, "endstream", 9)) {
m_Pos = StreamStartPos;
FX_FILESIZE offset = FindTag(FX_BSTRC("endstream"), 0);
if (offset >= 0) {
FX_FILESIZE curPos = m_Pos;
m_Pos = StreamStartPos;
FX_FILESIZE endobjOffset = FindTag(FX_BSTRC("endobj"), 0);
if (endobjOffset < offset && endobjOffset >= 0) {
offset = endobjOffset;
} else {
m_Pos = curPos;
}
uint8_t byte1, byte2;
GetCharAt(StreamStartPos + offset - 1, byte1);
GetCharAt(StreamStartPos + offset - 2, byte2);
if (byte1 == 0x0a && byte2 == 0x0d) {
len -= 2;
} else if (byte1 == 0x0a || byte1 == 0x0d) {
len --;
}
len = (FX_DWORD)offset;
pDict->SetAtInteger(FX_BSTRC("Length"), len);
} else {
m_Pos = StreamStartPos;
if (FindTag(FX_BSTRC("endobj"), 0) < 0) {
return NULL;
}
}
}
m_Pos = StreamStartPos;
}
CPDF_Stream* pStream;
uint8_t* pData = FX_Alloc(uint8_t, len);
ReadBlock(pData, len);
if (pCryptoHandler) {
CFX_BinaryBuf dest_buf;
dest_buf.EstimateSize(pCryptoHandler->DecryptGetSize(len));
void* context = pCryptoHandler->DecryptStart(objnum, gennum);
pCryptoHandler->DecryptStream(context, pData, len, dest_buf);
pCryptoHandler->DecryptFinish(context, dest_buf);
FX_Free(pData);
pData = dest_buf.GetBuffer();
len = dest_buf.GetSize();
dest_buf.DetachBuffer();
}
pStream = new CPDF_Stream(pData, len, pDict);
if (pContext) {
pContext->m_DataEnd = pContext->m_DataStart + len;
}
StreamStartPos = m_Pos;
GetNextWord();
if (m_WordSize == 6 && 0 == FXSYS_memcmp(m_WordBuffer, "endobj", 6)) {
m_Pos = StreamStartPos;
}
return pStream;
}
void CPDF_SyntaxParser::InitParser(IFX_FileRead* pFileAccess, FX_DWORD HeaderOffset)
{
if (m_pFileBuf) {
FX_Free(m_pFileBuf);
m_pFileBuf = NULL;
}
m_pFileBuf = FX_Alloc(uint8_t, m_BufSize);
m_HeaderOffset = HeaderOffset;
m_FileLen = pFileAccess->GetSize();
m_Pos = 0;
m_pFileAccess = pFileAccess;
m_BufOffset = 0;
pFileAccess->ReadBlock(m_pFileBuf, 0, (size_t)((FX_FILESIZE)m_BufSize > m_FileLen ? m_FileLen : m_BufSize));
}
int32_t CPDF_SyntaxParser::GetDirectNum()
{
GetNextWord();
if (!m_bIsNumber) {
return 0;
}
m_WordBuffer[m_WordSize] = 0;
return FXSYS_atoi((const FX_CHAR*)m_WordBuffer);
}
FX_BOOL CPDF_SyntaxParser::IsWholeWord(FX_FILESIZE startpos, FX_FILESIZE limit, const uint8_t* tag, FX_DWORD taglen)
{
uint8_t type = PDF_CharType[tag[0]];
FX_BOOL bCheckLeft = type != 'D' && type != 'W';
type = PDF_CharType[tag[taglen - 1]];
FX_BOOL bCheckRight = type != 'D' && type != 'W';
uint8_t ch;
if (bCheckRight && startpos + (int32_t)taglen <= limit && GetCharAt(startpos + (int32_t)taglen, ch)) {
uint8_t type = PDF_CharType[ch];
if (type == 'N' || type == 'R') {
return FALSE;
}
}
if (bCheckLeft && startpos > 0 && GetCharAt(startpos - 1, ch)) {
uint8_t type = PDF_CharType[ch];
if (type == 'N' || type == 'R') {
return FALSE;
}
}
return TRUE;
}
FX_BOOL CPDF_SyntaxParser::SearchWord(const CFX_ByteStringC& tag, FX_BOOL bWholeWord, FX_BOOL bForward, FX_FILESIZE limit)
{
int32_t taglen = tag.GetLength();
if (taglen == 0) {
return FALSE;
}
FX_FILESIZE pos = m_Pos;
int32_t offset = 0;
if (!bForward) {
offset = taglen - 1;
}
const uint8_t* tag_data = tag.GetPtr();
uint8_t byte;
while (1) {
if (bForward) {
if (limit) {
if (pos >= m_Pos + limit) {
return FALSE;
}
}
if (!GetCharAt(pos, byte)) {
return FALSE;
}
} else {
if (limit) {
if (pos <= m_Pos - limit) {
return FALSE;
}
}
if (!GetCharAtBackward(pos, byte)) {
return FALSE;
}
}
if (byte == tag_data[offset]) {
if (bForward) {
offset ++;
if (offset < taglen) {
pos ++;
continue;
}
} else {
offset --;
if (offset >= 0) {
pos --;
continue;
}
}
FX_FILESIZE startpos = bForward ? pos - taglen + 1 : pos;
if (!bWholeWord || IsWholeWord(startpos, limit, tag.GetPtr(), taglen)) {
m_Pos = startpos;
return TRUE;
}
}
if (bForward) {
offset = byte == tag_data[0] ? 1 : 0;
pos ++;
} else {
offset = byte == tag_data[taglen - 1] ? taglen - 2 : taglen - 1;
pos --;
}
if (pos < 0) {
return FALSE;
}
}
return FALSE;
}
struct _SearchTagRecord {
const uint8_t* m_pTag;
FX_DWORD m_Len;
FX_DWORD m_Offset;
};
int32_t CPDF_SyntaxParser::SearchMultiWord(const CFX_ByteStringC& tags, FX_BOOL bWholeWord, FX_FILESIZE limit)
{
int32_t ntags = 1, i;
for (i = 0; i < tags.GetLength(); i ++)
if (tags[i] == 0) {
ntags ++;
}
_SearchTagRecord* pPatterns = FX_Alloc(_SearchTagRecord, ntags);
FX_DWORD start = 0, itag = 0, max_len = 0;
for (i = 0; i <= tags.GetLength(); i ++) {
if (tags[i] == 0) {
FX_DWORD len = i - start;
if (len > max_len) {
max_len = len;
}
pPatterns[itag].m_pTag = tags.GetPtr() + start;
pPatterns[itag].m_Len = len;
pPatterns[itag].m_Offset = 0;
start = i + 1;
itag ++;
}
}
FX_FILESIZE pos = m_Pos;
uint8_t byte;
GetCharAt(pos++, byte);
int32_t found = -1;
while (1) {
for (i = 0; i < ntags; i ++) {
if (pPatterns[i].m_pTag[pPatterns[i].m_Offset] == byte) {
pPatterns[i].m_Offset ++;
if (pPatterns[i].m_Offset == pPatterns[i].m_Len) {
if (!bWholeWord || IsWholeWord(pos - pPatterns[i].m_Len, limit, pPatterns[i].m_pTag, pPatterns[i].m_Len)) {
found = i;
goto end;
} else {
if (pPatterns[i].m_pTag[0] == byte) {
pPatterns[i].m_Offset = 1;
} else {
pPatterns[i].m_Offset = 0;
}
}
}
} else {
if (pPatterns[i].m_pTag[0] == byte) {
pPatterns[i].m_Offset = 1;
} else {
pPatterns[i].m_Offset = 0;
}
}
}
if (limit && pos >= m_Pos + limit) {
goto end;
}
if (!GetCharAt(pos, byte)) {
goto end;
}
pos ++;
}
end:
FX_Free(pPatterns);
return found;
}
FX_FILESIZE CPDF_SyntaxParser::FindTag(const CFX_ByteStringC& tag, FX_FILESIZE limit)
{
int32_t taglen = tag.GetLength();
int32_t match = 0;
limit += m_Pos;
FX_FILESIZE startpos = m_Pos;
while (1) {
uint8_t ch;
if (!GetNextChar(ch)) {
return -1;
}
if (ch == tag[match]) {
match ++;
if (match == taglen) {
return m_Pos - startpos - taglen;
}
} else {
match = ch == tag[0] ? 1 : 0;
}
if (limit && m_Pos == limit) {
return -1;
}
}
return -1;
}
void CPDF_SyntaxParser::GetBinary(uint8_t* buffer, FX_DWORD size)
{
FX_DWORD offset = 0;
uint8_t ch;
while (1) {
if (!GetNextChar(ch)) {
return;
}
buffer[offset++] = ch;
if (offset == size) {
break;
}
}
}
class CPDF_DataAvail final : public IPDF_DataAvail
{
public:
CPDF_DataAvail(IFX_FileAvail* pFileAvail, IFX_FileRead* pFileRead);
~CPDF_DataAvail();
virtual FX_BOOL IsDocAvail(IFX_DownloadHints* pHints) override;
virtual void SetDocument(CPDF_Document* pDoc) override;
virtual FX_BOOL IsPageAvail(int iPage, IFX_DownloadHints* pHints) override;
virtual int32_t IsFormAvail(IFX_DownloadHints *pHints) override;
virtual int32_t IsLinearizedPDF() override;
virtual FX_BOOL IsLinearized() override
{
return m_bLinearized;
}
virtual void GetLinearizedMainXRefInfo(FX_FILESIZE *pPos, FX_DWORD *pSize) override;
protected:
static const int kMaxDataAvailRecursionDepth = 64;
static int s_CurrentDataAvailRecursionDepth;
FX_DWORD GetObjectSize(FX_DWORD objnum, FX_FILESIZE& offset);
FX_BOOL IsObjectsAvail(CFX_PtrArray& obj_array, FX_BOOL bParsePage, IFX_DownloadHints* pHints, CFX_PtrArray &ret_array);
FX_BOOL CheckDocStatus(IFX_DownloadHints *pHints);
FX_BOOL CheckHeader(IFX_DownloadHints* pHints);
FX_BOOL CheckFirstPage(IFX_DownloadHints *pHints);
FX_BOOL CheckEnd(IFX_DownloadHints *pHints);
FX_BOOL CheckCrossRef(IFX_DownloadHints* pHints);
FX_BOOL CheckCrossRefItem(IFX_DownloadHints *pHints);
FX_BOOL CheckTrailer(IFX_DownloadHints* pHints);
FX_BOOL CheckRoot(IFX_DownloadHints* pHints);
FX_BOOL CheckInfo(IFX_DownloadHints* pHints);
FX_BOOL CheckPages(IFX_DownloadHints* pHints);
FX_BOOL CheckPage(IFX_DownloadHints* pHints);
FX_BOOL CheckResources(IFX_DownloadHints* pHints);
FX_BOOL CheckAnnots(IFX_DownloadHints* pHints);
FX_BOOL CheckAcroForm(IFX_DownloadHints* pHints);
FX_BOOL CheckAcroFormSubObject(IFX_DownloadHints* pHints);
FX_BOOL CheckTrailerAppend(IFX_DownloadHints* pHints);
FX_BOOL CheckPageStatus(IFX_DownloadHints* pHints);
FX_BOOL CheckAllCrossRefStream(IFX_DownloadHints *pHints);
int32_t CheckCrossRefStream(IFX_DownloadHints *pHints, FX_FILESIZE &xref_offset);
FX_BOOL IsLinearizedFile(uint8_t* pData, FX_DWORD dwLen);
void SetStartOffset(FX_FILESIZE dwOffset);
FX_BOOL GetNextToken(CFX_ByteString &token);
FX_BOOL GetNextChar(uint8_t &ch);
CPDF_Object * ParseIndirectObjectAt(FX_FILESIZE pos, FX_DWORD objnum);
CPDF_Object * GetObject(FX_DWORD objnum, IFX_DownloadHints* pHints, FX_BOOL *pExistInFile);
FX_BOOL GetPageKids(CPDF_Parser *pParser, CPDF_Object *pPages);
FX_BOOL PreparePageItem();
FX_BOOL LoadPages(IFX_DownloadHints* pHints);
FX_BOOL LoadAllXref(IFX_DownloadHints* pHints);
FX_BOOL LoadAllFile(IFX_DownloadHints* pHints);
FX_BOOL CheckLinearizedData(IFX_DownloadHints* pHints);
FX_BOOL CheckFileResources(IFX_DownloadHints* pHints);
FX_BOOL CheckPageAnnots(int iPage, IFX_DownloadHints* pHints);
FX_BOOL CheckLinearizedFirstPage(int iPage, IFX_DownloadHints* pHints);
FX_BOOL HaveResourceAncestor(CPDF_Dictionary *pDict);
FX_BOOL CheckPage(int32_t iPage, IFX_DownloadHints* pHints);
FX_BOOL LoadDocPages(IFX_DownloadHints* pHints);
FX_BOOL LoadDocPage(int32_t iPage, IFX_DownloadHints* pHints);
FX_BOOL CheckPageNode(CPDF_PageNode &pageNodes, int32_t iPage, int32_t &iCount, IFX_DownloadHints* pHints);
FX_BOOL CheckUnkownPageNode(FX_DWORD dwPageNo, CPDF_PageNode *pPageNode, IFX_DownloadHints* pHints);
FX_BOOL CheckArrayPageNode(FX_DWORD dwPageNo, CPDF_PageNode *pPageNode, IFX_DownloadHints* pHints);
FX_BOOL CheckPageCount(IFX_DownloadHints* pHints);
FX_BOOL IsFirstCheck(int iPage);
void ResetFirstCheck(int iPage);
CPDF_Parser m_parser;
CPDF_SyntaxParser m_syntaxParser;
CPDF_Object *m_pRoot;
FX_DWORD m_dwRootObjNum;
FX_DWORD m_dwInfoObjNum;
CPDF_Object *m_pLinearized;
CPDF_Object *m_pTrailer;
FX_BOOL m_bDocAvail;
FX_FILESIZE m_dwHeaderOffset;
FX_FILESIZE m_dwLastXRefOffset;
FX_FILESIZE m_dwXRefOffset;
FX_FILESIZE m_dwTrailerOffset;
FX_FILESIZE m_dwCurrentOffset;
PDF_DATAAVAIL_STATUS m_docStatus;
FX_FILESIZE m_dwFileLen;
CPDF_Document* m_pDocument;
CPDF_SortObjNumArray m_objnum_array;
CFX_PtrArray m_objs_array;
FX_FILESIZE m_Pos;
FX_FILESIZE m_bufferOffset;
FX_DWORD m_bufferSize;
CFX_ByteString m_WordBuf;
uint8_t m_WordBuffer[257];
FX_DWORD m_WordSize;
uint8_t m_bufferData[512];
CFX_FileSizeArray m_CrossOffset;
CFX_DWordArray m_XRefStreamList;
CFX_DWordArray m_PageObjList;
FX_DWORD m_PagesObjNum;
FX_BOOL m_bLinearized;
FX_DWORD m_dwFirstPageNo;
FX_BOOL m_bLinearedDataOK;
FX_BOOL m_bMainXRefLoadTried;
FX_BOOL m_bMainXRefLoadedOK;
FX_BOOL m_bPagesTreeLoad;
FX_BOOL m_bPagesLoad;
CPDF_Parser * m_pCurrentParser;
FX_FILESIZE m_dwCurrentXRefSteam;
FX_BOOL m_bAnnotsLoad;
FX_BOOL m_bHaveAcroForm;
FX_DWORD m_dwAcroFormObjNum;
FX_BOOL m_bAcroFormLoad;
CPDF_Object * m_pAcroForm;
CFX_PtrArray m_arrayAcroforms;
CPDF_Dictionary * m_pPageDict;
CPDF_Object * m_pPageResource;
FX_BOOL m_bNeedDownLoadResource;
FX_BOOL m_bPageLoadedOK;
FX_BOOL m_bLinearizedFormParamLoad;
CFX_PtrArray m_PagesArray;
FX_DWORD m_dwEncryptObjNum;
FX_FILESIZE m_dwPrevXRefOffset;
FX_BOOL m_bTotalLoadPageTree;
FX_BOOL m_bCurPageDictLoadOK;
CPDF_PageNode m_pageNodes;
CFX_CMapDWordToDWord * m_pageMapCheckState;
CFX_CMapDWordToDWord * m_pagesLoadState;
};
IPDF_DataAvail::IPDF_DataAvail(IFX_FileAvail* pFileAvail, IFX_FileRead* pFileRead) :
m_pFileAvail(pFileAvail),
m_pFileRead(pFileRead) {
}
// static
IPDF_DataAvail* IPDF_DataAvail::Create(IFX_FileAvail* pFileAvail, IFX_FileRead* pFileRead)
{
return new CPDF_DataAvail(pFileAvail, pFileRead);
}
// static
int CPDF_DataAvail::s_CurrentDataAvailRecursionDepth = 0;
CPDF_DataAvail::CPDF_DataAvail(IFX_FileAvail* pFileAvail, IFX_FileRead* pFileRead)
: IPDF_DataAvail(pFileAvail, pFileRead)
{
m_Pos = 0;
m_dwFileLen = 0;
if (m_pFileRead) {
m_dwFileLen = (FX_DWORD)m_pFileRead->GetSize();
}
m_dwCurrentOffset = 0;
m_WordSize = 0;
m_dwXRefOffset = 0;
m_bufferOffset = 0;
m_dwFirstPageNo = 0;
m_bufferSize = 0;
m_PagesObjNum = 0;
m_dwCurrentXRefSteam = 0;
m_dwAcroFormObjNum = 0;
m_dwInfoObjNum = 0;
m_pDocument = 0;
m_dwEncryptObjNum = 0;
m_dwPrevXRefOffset = 0;
m_dwLastXRefOffset = 0;
m_bDocAvail = FALSE;
m_bMainXRefLoadTried = FALSE;
m_bDocAvail = FALSE;
m_bLinearized = FALSE;
m_bPagesLoad = FALSE;
m_bPagesTreeLoad = FALSE;
m_bMainXRefLoadedOK = FALSE;
m_bAnnotsLoad = FALSE;
m_bHaveAcroForm = FALSE;
m_bAcroFormLoad = FALSE;
m_bPageLoadedOK = FALSE;
m_bNeedDownLoadResource = FALSE;
m_bLinearizedFormParamLoad = FALSE;
m_pLinearized = NULL;
m_pRoot = NULL;
m_pTrailer = NULL;
m_pCurrentParser = NULL;
m_pAcroForm = NULL;
m_pPageDict = NULL;
m_pPageResource = NULL;
m_pageMapCheckState = NULL;
m_docStatus = PDF_DATAAVAIL_HEADER;
m_parser.m_bOwnFileRead = FALSE;
m_bTotalLoadPageTree = FALSE;
m_bCurPageDictLoadOK = FALSE;
m_bLinearedDataOK = FALSE;
m_pagesLoadState = NULL;
}
CPDF_DataAvail::~CPDF_DataAvail()
{
if (m_pLinearized) {
m_pLinearized->Release();
}
if (m_pRoot) {
m_pRoot->Release();
}
if (m_pTrailer) {
m_pTrailer->Release();
}
delete m_pageMapCheckState;
delete m_pagesLoadState;
int32_t i = 0;
int32_t iSize = m_arrayAcroforms.GetSize();
for (i = 0; i < iSize; ++i) {
((CPDF_Object *)m_arrayAcroforms.GetAt(i))->Release();
}
}
void CPDF_DataAvail::SetDocument(CPDF_Document* pDoc)
{
m_pDocument = pDoc;
}
FX_DWORD CPDF_DataAvail::GetObjectSize(FX_DWORD objnum, FX_FILESIZE& offset)
{
CPDF_Parser *pParser = (CPDF_Parser *)(m_pDocument->GetParser());
if (pParser == NULL) {
return 0;
}
if (objnum >= (FX_DWORD)pParser->m_CrossRef.GetSize()) {
return 0;
}
if (pParser->m_V5Type[objnum] == 2) {
objnum = (FX_DWORD)pParser->m_CrossRef[objnum];
}
if (pParser->m_V5Type[objnum] == 1 || pParser->m_V5Type[objnum] == 255) {
offset = pParser->m_CrossRef[objnum];
if (offset == 0) {
return 0;
}
void* pResult = FXSYS_bsearch(&offset, pParser->m_SortedOffset.GetData(), pParser->m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
if (pResult == NULL) {
return 0;
}
if ((FX_FILESIZE*)pResult - (FX_FILESIZE*)pParser->m_SortedOffset.GetData() == pParser->m_SortedOffset.GetSize() - 1) {
return 0;
}
return (FX_DWORD)(((FX_FILESIZE*)pResult)[1] - offset);
}
return 0;
}
FX_BOOL CPDF_DataAvail::IsObjectsAvail(CFX_PtrArray& obj_array, FX_BOOL bParsePage, IFX_DownloadHints* pHints, CFX_PtrArray &ret_array)
{
if (!obj_array.GetSize()) {
return TRUE;
}
FX_DWORD count = 0;
CFX_PtrArray new_obj_array;
int32_t i = 0;
for (i = 0; i < obj_array.GetSize(); i++) {
CPDF_Object *pObj = (CPDF_Object *)obj_array[i];
if (!pObj) {
continue;
}
int32_t type = pObj->GetType();
switch (type) {
case PDFOBJ_ARRAY: {
CPDF_Array *pArray = pObj->GetArray();
for (FX_DWORD k = 0; k < pArray->GetCount(); k++) {
new_obj_array.Add(pArray->GetElement(k));
}
}
break;
case PDFOBJ_STREAM:
pObj = pObj->GetDict();
case PDFOBJ_DICTIONARY: {
CPDF_Dictionary *pDict = pObj->GetDict();
if (pDict && pDict->GetString("Type") == "Page" && !bParsePage) {
continue;
}
FX_POSITION pos = pDict->GetStartPos();
while (pos) {
CPDF_Object *value;
CFX_ByteString key;
value = pDict->GetNextElement(pos, key);
if (key != "Parent") {
new_obj_array.Add(value);
}
}
}
break;
case PDFOBJ_REFERENCE: {
CPDF_Reference *pRef = (CPDF_Reference*)pObj;
FX_DWORD dwNum = pRef->GetRefObjNum();
FX_FILESIZE offset;
FX_DWORD original_size = GetObjectSize(dwNum, offset);
pdfium::base::CheckedNumeric<FX_DWORD> size = original_size;
if (size.ValueOrDefault(0) == 0 || offset < 0 || offset >= m_dwFileLen) {
break;
}
size += offset;
size += 512;
if (!size.IsValid()) {
break;
}
if (size.ValueOrDie() > m_dwFileLen) {
size = m_dwFileLen - offset;
} else {
size = original_size + 512;
}
if (!size.IsValid()) {
break;
}
if (!m_pFileAvail->IsDataAvail(offset, size.ValueOrDie())) {
pHints->AddSegment(offset, size.ValueOrDie());
ret_array.Add(pObj);
count++;
} else if (!m_objnum_array.Find(dwNum)) {
m_objnum_array.AddObjNum(dwNum);
CPDF_Object *pReferred = m_pDocument->GetIndirectObject(pRef->GetRefObjNum(), NULL);
if (pReferred) {
new_obj_array.Add(pReferred);
}
}
}
break;
}
}
if (count > 0) {
int32_t iSize = new_obj_array.GetSize();
for (i = 0; i < iSize; ++i) {
CPDF_Object *pObj = (CPDF_Object *)new_obj_array[i];
int32_t type = pObj->GetType();
if (type == PDFOBJ_REFERENCE) {
CPDF_Reference *pRef = (CPDF_Reference *)pObj;
FX_DWORD dwNum = pRef->GetRefObjNum();
if (!m_objnum_array.Find(dwNum)) {
ret_array.Add(pObj);
}
} else {
ret_array.Add(pObj);
}
}
return FALSE;
}
obj_array.RemoveAll();
obj_array.Append(new_obj_array);
return IsObjectsAvail(obj_array, FALSE, pHints, ret_array);
}
FX_BOOL CPDF_DataAvail::IsDocAvail(IFX_DownloadHints* pHints)
{
if (!m_dwFileLen && m_pFileRead) {
m_dwFileLen = (FX_DWORD)m_pFileRead->GetSize();
if (!m_dwFileLen) {
return TRUE;
}
}
while (!m_bDocAvail) {
if (!CheckDocStatus(pHints)) {
return FALSE;
}
}
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckAcroFormSubObject(IFX_DownloadHints* pHints)
{
if (!m_objs_array.GetSize()) {
m_objs_array.RemoveAll();
m_objnum_array.RemoveAll();
CFX_PtrArray obj_array;
obj_array.Append(m_arrayAcroforms);
FX_BOOL bRet = IsObjectsAvail(obj_array, FALSE, pHints, m_objs_array);
if (bRet) {
m_objs_array.RemoveAll();
}
return bRet;
} else {
CFX_PtrArray new_objs_array;
FX_BOOL bRet = IsObjectsAvail(m_objs_array, FALSE, pHints, new_objs_array);
if (bRet) {
int32_t iSize = m_arrayAcroforms.GetSize();
for (int32_t i = 0; i < iSize; ++i) {
((CPDF_Object *)m_arrayAcroforms.GetAt(i))->Release();
}
m_arrayAcroforms.RemoveAll();
} else {
m_objs_array.RemoveAll();
m_objs_array.Append(new_objs_array);
}
return bRet;
}
}
FX_BOOL CPDF_DataAvail::CheckAcroForm(IFX_DownloadHints* pHints)
{
FX_BOOL bExist = FALSE;
m_pAcroForm = GetObject(m_dwAcroFormObjNum, pHints, &bExist);
if (!bExist) {
m_docStatus = PDF_DATAAVAIL_PAGETREE;
return TRUE;
}
if (!m_pAcroForm) {
if (m_docStatus == PDF_DATAAVAIL_ERROR) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
return FALSE;
}
m_arrayAcroforms.Add(m_pAcroForm);
m_docStatus = PDF_DATAAVAIL_PAGETREE;
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckDocStatus(IFX_DownloadHints *pHints)
{
switch (m_docStatus) {
case PDF_DATAAVAIL_HEADER:
return CheckHeader(pHints);
case PDF_DATAAVAIL_FIRSTPAGE:
case PDF_DATAAVAIL_FIRSTPAGE_PREPARE:
return CheckFirstPage(pHints);
case PDF_DATAAVAIL_END:
return CheckEnd(pHints);
case PDF_DATAAVAIL_CROSSREF:
return CheckCrossRef(pHints);
case PDF_DATAAVAIL_CROSSREF_ITEM:
return CheckCrossRefItem(pHints);
case PDF_DATAAVAIL_CROSSREF_STREAM:
return CheckAllCrossRefStream(pHints);
case PDF_DATAAVAIL_TRAILER:
return CheckTrailer(pHints);
case PDF_DATAAVAIL_TRAILER_APPEND:
return CheckTrailerAppend(pHints);
case PDF_DATAAVAIL_LOADALLCRSOSSREF:
return LoadAllXref(pHints);
case PDF_DATAAVAIL_LOADALLFILE:
return LoadAllFile(pHints);
case PDF_DATAAVAIL_ROOT:
return CheckRoot(pHints);
case PDF_DATAAVAIL_INFO:
return CheckInfo(pHints);
case PDF_DATAAVAIL_ACROFORM:
return CheckAcroForm(pHints);
case PDF_DATAAVAIL_PAGETREE:
if (m_bTotalLoadPageTree) {
return CheckPages(pHints);
} else {
return LoadDocPages(pHints);
}
case PDF_DATAAVAIL_PAGE:
if (m_bTotalLoadPageTree) {
return CheckPage(pHints);
} else {
m_docStatus = PDF_DATAAVAIL_PAGE_LATERLOAD;
return TRUE;
}
case PDF_DATAAVAIL_ERROR:
return LoadAllFile(pHints);
case PDF_DATAAVAIL_PAGE_LATERLOAD:
m_docStatus = PDF_DATAAVAIL_PAGE;
default:
m_bDocAvail = TRUE;
return TRUE;
}
}
FX_BOOL CPDF_DataAvail::CheckPageStatus(IFX_DownloadHints* pHints)
{
switch (m_docStatus) {
case PDF_DATAAVAIL_PAGETREE:
return CheckPages(pHints);
case PDF_DATAAVAIL_PAGE:
return CheckPage(pHints);
case PDF_DATAAVAIL_ERROR:
return LoadAllFile(pHints);
default:
m_bPagesTreeLoad = TRUE;
m_bPagesLoad = TRUE;
return TRUE;
}
}
FX_BOOL CPDF_DataAvail::LoadAllFile(IFX_DownloadHints* pHints)
{
if (m_pFileAvail->IsDataAvail(0, (FX_DWORD)m_dwFileLen)) {
m_docStatus = PDF_DATAAVAIL_DONE;
return TRUE;
}
pHints->AddSegment(0, (FX_DWORD)m_dwFileLen);
return FALSE;
}
FX_BOOL CPDF_DataAvail::LoadAllXref(IFX_DownloadHints* pHints)
{
m_parser.m_Syntax.InitParser(m_pFileRead, (FX_DWORD)m_dwHeaderOffset);
m_parser.m_bOwnFileRead = FALSE;
if (!m_parser.LoadAllCrossRefV4(m_dwLastXRefOffset) && !m_parser.LoadAllCrossRefV5(m_dwLastXRefOffset)) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return FALSE;
}
FXSYS_qsort(m_parser.m_SortedOffset.GetData(), m_parser.m_SortedOffset.GetSize(), sizeof(FX_FILESIZE), _CompareFileSize);
m_dwRootObjNum = m_parser.GetRootObjNum();
m_dwInfoObjNum = m_parser.GetInfoObjNum();
m_pCurrentParser = &m_parser;
m_docStatus = PDF_DATAAVAIL_ROOT;
return TRUE;
}
CPDF_Object* CPDF_DataAvail::GetObject(FX_DWORD objnum, IFX_DownloadHints* pHints, FX_BOOL *pExistInFile)
{
CPDF_Object *pRet = NULL;
FX_DWORD original_size = 0;
FX_FILESIZE offset = 0;
CPDF_Parser *pParser = NULL;
if (pExistInFile) {
*pExistInFile = TRUE;
}
if (m_pDocument == NULL) {
original_size = (FX_DWORD)m_parser.GetObjectSize(objnum);
offset = m_parser.GetObjectOffset(objnum);
pParser = &m_parser;
} else {
original_size = GetObjectSize(objnum, offset);
pParser = (CPDF_Parser *)(m_pDocument->GetParser());
}
pdfium::base::CheckedNumeric<FX_DWORD> size = original_size;
if (size.ValueOrDefault(0) == 0 || offset < 0 || offset >= m_dwFileLen) {
if (pExistInFile)
*pExistInFile = FALSE;
return NULL;
}
size += offset;
size += 512;
if (!size.IsValid()) {
return NULL;
}
if (size.ValueOrDie() > m_dwFileLen) {
size = m_dwFileLen - offset;
} else {
size = original_size + 512;
}
if (!size.IsValid()) {
return NULL;
}
if (!m_pFileAvail->IsDataAvail(offset, size.ValueOrDie())) {
pHints->AddSegment(offset, size.ValueOrDie());
return NULL;
}
if (pParser) {
pRet = pParser->ParseIndirectObject(NULL, objnum, NULL);
}
if (!pRet && pExistInFile) {
*pExistInFile = FALSE;
}
return pRet;
}
FX_BOOL CPDF_DataAvail::CheckInfo(IFX_DownloadHints* pHints)
{
FX_BOOL bExist = FALSE;
CPDF_Object *pInfo = GetObject(m_dwInfoObjNum, pHints, &bExist);
if (!bExist) {
if (m_bHaveAcroForm) {
m_docStatus = PDF_DATAAVAIL_ACROFORM;
} else {
m_docStatus = PDF_DATAAVAIL_PAGETREE;
}
return TRUE;
}
if (!pInfo) {
if (m_docStatus == PDF_DATAAVAIL_ERROR) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
if (m_Pos == m_dwFileLen) {
m_docStatus = PDF_DATAAVAIL_ERROR;
}
return FALSE;
}
if (pInfo) {
pInfo->Release();
}
if (m_bHaveAcroForm) {
m_docStatus = PDF_DATAAVAIL_ACROFORM;
} else {
m_docStatus = PDF_DATAAVAIL_PAGETREE;
}
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckRoot(IFX_DownloadHints* pHints)
{
FX_BOOL bExist = FALSE;
m_pRoot = GetObject(m_dwRootObjNum, pHints, &bExist);
if (!bExist) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
if (!m_pRoot) {
if (m_docStatus == PDF_DATAAVAIL_ERROR) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
return FALSE;
}
CPDF_Dictionary* pDict = m_pRoot->GetDict();
if (!pDict) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
CPDF_Reference* pRef = (CPDF_Reference*)pDict->GetElement(FX_BSTRC("Pages"));
if (pRef == NULL || pRef->GetType() != PDFOBJ_REFERENCE) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
m_PagesObjNum = pRef->GetRefObjNum();
CPDF_Reference* pAcroFormRef = (CPDF_Reference*)m_pRoot->GetDict()->GetElement(FX_BSTRC("AcroForm"));
if (pAcroFormRef && pAcroFormRef->GetType() == PDFOBJ_REFERENCE) {
m_bHaveAcroForm = TRUE;
m_dwAcroFormObjNum = pAcroFormRef->GetRefObjNum();
}
if (m_dwInfoObjNum) {
m_docStatus = PDF_DATAAVAIL_INFO;
} else {
if (m_bHaveAcroForm) {
m_docStatus = PDF_DATAAVAIL_ACROFORM;
} else {
m_docStatus = PDF_DATAAVAIL_PAGETREE;
}
}
return TRUE;
}
FX_BOOL CPDF_DataAvail::PreparePageItem()
{
CPDF_Dictionary *pRoot = m_pDocument->GetRoot();
CPDF_Reference* pRef = pRoot ? (CPDF_Reference*)pRoot->GetElement(FX_BSTRC("Pages")) : NULL;
if (pRef == NULL || pRef->GetType() != PDFOBJ_REFERENCE) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
m_PagesObjNum = pRef->GetRefObjNum();
m_pCurrentParser = (CPDF_Parser *)m_pDocument->GetParser();
m_docStatus = PDF_DATAAVAIL_PAGETREE;
return TRUE;
}
FX_BOOL CPDF_DataAvail::IsFirstCheck(int iPage)
{
if (NULL == m_pageMapCheckState) {
m_pageMapCheckState = new CFX_CMapDWordToDWord();
}
FX_DWORD dwValue = 0;
if (!m_pageMapCheckState->Lookup(iPage, dwValue)) {
m_pageMapCheckState->SetAt(iPage, 1);
return TRUE;
}
if (dwValue != 0) {
return FALSE;
}
m_pageMapCheckState->SetAt(iPage, 1);
return TRUE;
}
void CPDF_DataAvail::ResetFirstCheck(int iPage)
{
if (NULL == m_pageMapCheckState) {
m_pageMapCheckState = new CFX_CMapDWordToDWord();
}
FX_DWORD dwValue = 1;
if (!m_pageMapCheckState->Lookup(iPage, dwValue)) {
return;
}
m_pageMapCheckState->SetAt(iPage, 0);
}
FX_BOOL CPDF_DataAvail::CheckPage(IFX_DownloadHints* pHints)
{
FX_DWORD iPageObjs = m_PageObjList.GetSize();
CFX_DWordArray UnavailObjList;
for (FX_DWORD i = 0; i < iPageObjs; ++i) {
FX_DWORD dwPageObjNum = m_PageObjList.GetAt(i);
FX_BOOL bExist = FALSE;
CPDF_Object *pObj = GetObject(dwPageObjNum, pHints, &bExist);
if (!pObj) {
if (bExist) {
UnavailObjList.Add(dwPageObjNum);
}
continue;
}
if (pObj->GetType() == PDFOBJ_ARRAY) {
CPDF_Array *pArray = pObj->GetArray();
if (pArray) {
int32_t iSize = pArray->GetCount();
CPDF_Object *pItem = NULL;
for (int32_t j = 0; j < iSize; ++j) {
pItem = pArray->GetElement(j);
if (pItem && pItem->GetType() == PDFOBJ_REFERENCE) {
UnavailObjList.Add(((CPDF_Reference *)pItem)->GetRefObjNum());
}
}
}
}
if (pObj->GetType() != PDFOBJ_DICTIONARY) {
pObj->Release();
continue;
}
CFX_ByteString type = pObj->GetDict()->GetString(FX_BSTRC("Type"));
if (type == FX_BSTRC("Pages")) {
m_PagesArray.Add(pObj);
continue;
}
pObj->Release();
}
m_PageObjList.RemoveAll();
if (UnavailObjList.GetSize()) {
m_PageObjList.Append(UnavailObjList);
return FALSE;
}
FX_DWORD iPages = m_PagesArray.GetSize();
for (FX_DWORD i = 0; i < iPages; i++) {
CPDF_Object *pPages = (CPDF_Object *)m_PagesArray.GetAt(i);
if (!pPages) {
continue;
}
if (!GetPageKids(m_pCurrentParser, pPages)) {
pPages->Release();
while (++i < iPages) {
pPages = (CPDF_Object *)m_PagesArray.GetAt(i);
pPages->Release();
}
m_PagesArray.RemoveAll();
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
pPages->Release();
}
m_PagesArray.RemoveAll();
if (!m_PageObjList.GetSize()) {
m_docStatus = PDF_DATAAVAIL_DONE;
}
return TRUE;
}
FX_BOOL CPDF_DataAvail::GetPageKids(CPDF_Parser *pParser, CPDF_Object *pPages)
{
if (!pParser) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
CPDF_Dictionary* pDict = pPages->GetDict();
CPDF_Object *pKids = pDict ? pDict->GetElement(FX_BSTRC("Kids")) : NULL;
if (!pKids) {
return TRUE;
}
switch (pKids->GetType()) {
case PDFOBJ_REFERENCE: {
CPDF_Reference *pKid = (CPDF_Reference *)pKids;
m_PageObjList.Add(pKid->GetRefObjNum());
}
break;
case PDFOBJ_ARRAY: {
CPDF_Array *pKidsArray = (CPDF_Array *)pKids;
for (FX_DWORD i = 0; i < pKidsArray->GetCount(); ++i) {
CPDF_Object *pKid = (CPDF_Object *)pKidsArray->GetElement(i);
if (pKid && pKid->GetType() == PDFOBJ_REFERENCE) {
m_PageObjList.Add(((CPDF_Reference *)pKid)->GetRefObjNum());
}
}
}
break;
default:
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckPages(IFX_DownloadHints* pHints)
{
FX_BOOL bExist = FALSE;
CPDF_Object *pPages = GetObject(m_PagesObjNum, pHints, &bExist);
if (!bExist) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
if (!pPages) {
if (m_docStatus == PDF_DATAAVAIL_ERROR) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
return FALSE;
}
if (!GetPageKids(m_pCurrentParser, pPages)) {
pPages->Release();
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
pPages->Release();
m_docStatus = PDF_DATAAVAIL_PAGE;
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckHeader(IFX_DownloadHints* pHints)
{
FX_DWORD req_size = 1024;
if ((FX_FILESIZE)req_size > m_dwFileLen) {
req_size = (FX_DWORD)m_dwFileLen;
}
if (m_pFileAvail->IsDataAvail(0, req_size)) {
uint8_t buffer[1024];
m_pFileRead->ReadBlock(buffer, 0, req_size);
if (IsLinearizedFile(buffer, req_size)) {
m_docStatus = PDF_DATAAVAIL_FIRSTPAGE;
} else {
if (m_docStatus == PDF_DATAAVAIL_ERROR) {
return FALSE;
}
m_docStatus = PDF_DATAAVAIL_END;
}
return TRUE;
}
pHints->AddSegment(0, req_size);
return FALSE;
}
FX_BOOL CPDF_DataAvail::CheckFirstPage(IFX_DownloadHints *pHints)
{
CPDF_Dictionary* pDict = m_pLinearized->GetDict();
CPDF_Object *pEndOffSet = pDict ? pDict->GetElement(FX_BSTRC("E")) : NULL;
if (!pEndOffSet) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
CPDF_Object *pXRefOffset = pDict ? pDict->GetElement(FX_BSTRC("T")) : NULL;
if (!pXRefOffset) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
CPDF_Object *pFileLen = pDict ? pDict->GetElement(FX_BSTRC("L")) : NULL;
if (!pFileLen) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
FX_BOOL bNeedDownLoad = FALSE;
if (pEndOffSet->GetType() == PDFOBJ_NUMBER) {
FX_DWORD dwEnd = pEndOffSet->GetInteger();
dwEnd += 512;
if ((FX_FILESIZE)dwEnd > m_dwFileLen) {
dwEnd = (FX_DWORD)m_dwFileLen;
}
int32_t iStartPos = (int32_t)(m_dwFileLen > 1024 ? 1024 : m_dwFileLen);
int32_t iSize = dwEnd > 1024 ? dwEnd - 1024 : 0;
if (!m_pFileAvail->IsDataAvail(iStartPos, iSize)) {
pHints->AddSegment(iStartPos, iSize);
bNeedDownLoad = TRUE;
}
}
m_dwLastXRefOffset = 0;
FX_FILESIZE dwFileLen = 0;
if (pXRefOffset->GetType() == PDFOBJ_NUMBER) {
m_dwLastXRefOffset = pXRefOffset->GetInteger();
}
if (pFileLen->GetType() == PDFOBJ_NUMBER) {
dwFileLen = pFileLen->GetInteger();
}
if (!m_pFileAvail->IsDataAvail(m_dwLastXRefOffset, (FX_DWORD)(dwFileLen - m_dwLastXRefOffset))) {
if (m_docStatus == PDF_DATAAVAIL_FIRSTPAGE) {
FX_DWORD dwSize = (FX_DWORD)(dwFileLen - m_dwLastXRefOffset);
FX_FILESIZE offset = m_dwLastXRefOffset;
if (dwSize < 512 && dwFileLen > 512) {
dwSize = 512;
offset = dwFileLen - 512;
}
pHints->AddSegment(offset, dwSize);
}
} else {
m_docStatus = PDF_DATAAVAIL_FIRSTPAGE_PREPARE;
}
if (!bNeedDownLoad && m_docStatus == PDF_DATAAVAIL_FIRSTPAGE_PREPARE) {
m_docStatus = PDF_DATAAVAIL_DONE;
return TRUE;
}
m_docStatus = PDF_DATAAVAIL_FIRSTPAGE_PREPARE;
return FALSE;
}
CPDF_Object * CPDF_DataAvail::ParseIndirectObjectAt(FX_FILESIZE pos, FX_DWORD objnum)
{
FX_FILESIZE SavedPos = m_syntaxParser.SavePos();
m_syntaxParser.RestorePos(pos);
FX_BOOL bIsNumber;
CFX_ByteString word = m_syntaxParser.GetNextWord(bIsNumber);
if (!bIsNumber) {
return NULL;
}
FX_DWORD parser_objnum = FXSYS_atoi(word);
if (objnum && parser_objnum != objnum) {
return NULL;
}
word = m_syntaxParser.GetNextWord(bIsNumber);
if (!bIsNumber) {
return NULL;
}
FX_DWORD gennum = FXSYS_atoi(word);
if (m_syntaxParser.GetKeyword() != FX_BSTRC("obj")) {
m_syntaxParser.RestorePos(SavedPos);
return NULL;
}
CPDF_Object* pObj = m_syntaxParser.GetObject(NULL, objnum, gennum, 0);
m_syntaxParser.RestorePos(SavedPos);
return pObj;
}
int32_t CPDF_DataAvail::IsLinearizedPDF()
{
FX_DWORD req_size = 1024;
if (!m_pFileAvail->IsDataAvail(0, req_size)) {
return PDF_UNKNOW_LINEARIZED;
}
if (!m_pFileRead) {
return PDF_NOT_LINEARIZED;
}
FX_FILESIZE dwSize = m_pFileRead->GetSize();
if (dwSize < (FX_FILESIZE)req_size) {
return PDF_UNKNOW_LINEARIZED;
}
uint8_t buffer[1024];
m_pFileRead->ReadBlock(buffer, 0, req_size);
if (IsLinearizedFile(buffer, req_size)) {
return PDF_IS_LINEARIZED;
}
return PDF_NOT_LINEARIZED;
}
FX_BOOL CPDF_DataAvail::IsLinearizedFile(uint8_t* pData, FX_DWORD dwLen)
{
CFX_SmartPointer<IFX_FileStream> file(FX_CreateMemoryStream(pData, (size_t)dwLen, FALSE));
int32_t offset = GetHeaderOffset(file.Get());
if (offset == -1) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
m_dwHeaderOffset = offset;
m_syntaxParser.InitParser(file.Get(), offset);
m_syntaxParser.RestorePos(m_syntaxParser.m_HeaderOffset + 9);
FX_BOOL bNumber = FALSE;
CFX_ByteString wordObjNum = m_syntaxParser.GetNextWord(bNumber);
if (!bNumber) {
return FALSE;
}
FX_DWORD objnum = FXSYS_atoi(wordObjNum);
if (m_pLinearized) {
m_pLinearized->Release();
m_pLinearized = NULL;
}
m_pLinearized = ParseIndirectObjectAt(m_syntaxParser.m_HeaderOffset + 9, objnum);
if (!m_pLinearized) {
return FALSE;
}
if (m_pLinearized->GetDict() && m_pLinearized->GetDict()->GetElement(FX_BSTRC("Linearized"))) {
CPDF_Object *pLen = m_pLinearized->GetDict()->GetElement(FX_BSTRC("L"));
if (!pLen) {
return FALSE;
}
if ((FX_FILESIZE)pLen->GetInteger() != m_pFileRead->GetSize()) {
return FALSE;
}
m_bLinearized = TRUE;
CPDF_Object *pNo = m_pLinearized->GetDict()->GetElement(FX_BSTRC("P"));
if (pNo && pNo->GetType() == PDFOBJ_NUMBER) {
m_dwFirstPageNo = pNo->GetInteger();
}
return TRUE;
}
return FALSE;
}
FX_BOOL CPDF_DataAvail::CheckEnd(IFX_DownloadHints* pHints)
{
FX_DWORD req_pos = (FX_DWORD)(m_dwFileLen > 1024 ? m_dwFileLen - 1024 : 0);
FX_DWORD dwSize = (FX_DWORD)(m_dwFileLen - req_pos);
if (m_pFileAvail->IsDataAvail(req_pos, dwSize)) {
uint8_t buffer[1024];
m_pFileRead->ReadBlock(buffer, req_pos, dwSize);
CFX_SmartPointer<IFX_FileStream> file(FX_CreateMemoryStream(buffer, (size_t)dwSize, FALSE));
m_syntaxParser.InitParser(file.Get(), 0);
m_syntaxParser.RestorePos(dwSize - 1);
if (m_syntaxParser.SearchWord(FX_BSTRC("startxref"), TRUE, FALSE, dwSize)) {
FX_BOOL bNumber;
m_syntaxParser.GetNextWord(bNumber);
CFX_ByteString xrefpos_str = m_syntaxParser.GetNextWord(bNumber);
if (!bNumber) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
m_dwXRefOffset = (FX_FILESIZE)FXSYS_atoi64(xrefpos_str);
if (!m_dwXRefOffset || m_dwXRefOffset > m_dwFileLen) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
m_dwLastXRefOffset = m_dwXRefOffset;
SetStartOffset(m_dwXRefOffset);
m_docStatus = PDF_DATAAVAIL_CROSSREF;
return TRUE;
} else {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
}
pHints->AddSegment(req_pos, dwSize);
return FALSE;
}
int32_t CPDF_DataAvail::CheckCrossRefStream(IFX_DownloadHints* pHints, FX_FILESIZE &xref_offset)
{
xref_offset = 0;
FX_DWORD req_size = (FX_DWORD)(m_Pos + 512 > m_dwFileLen ? m_dwFileLen - m_Pos : 512);
if (m_pFileAvail->IsDataAvail(m_Pos, req_size)) {
int32_t iSize = (int32_t)(m_Pos + req_size - m_dwCurrentXRefSteam);
CFX_BinaryBuf buf(iSize);
uint8_t* pBuf = buf.GetBuffer();
m_pFileRead->ReadBlock(pBuf, m_dwCurrentXRefSteam, iSize);
CFX_SmartPointer<IFX_FileStream> file(FX_CreateMemoryStream(pBuf, (size_t)iSize, FALSE));
m_parser.m_Syntax.InitParser(file.Get(), 0);
FX_BOOL bNumber = FALSE;
CFX_ByteString objnum = m_parser.m_Syntax.GetNextWord(bNumber);
if (!bNumber) {
return -1;
}
FX_DWORD objNum = FXSYS_atoi(objnum);
CPDF_Object *pObj = m_parser.ParseIndirectObjectAt(NULL, 0, objNum, NULL);
if (!pObj) {
m_Pos += m_parser.m_Syntax.SavePos();
return 0;
}
CPDF_Dictionary* pDict = pObj->GetDict();
CPDF_Object *pName = pDict ? pDict->GetElement(FX_BSTRC("Type")) : NULL;
if (pName && pName->GetType() == PDFOBJ_NAME) {
if (pName->GetString() == FX_BSTRC("XRef")) {
m_Pos += m_parser.m_Syntax.SavePos();
xref_offset = pObj->GetDict()->GetInteger(FX_BSTRC("Prev"));
pObj->Release();
return 1;
} else {
pObj->Release();
return -1;
}
}
pObj->Release();
return -1;
}
pHints->AddSegment(m_Pos, req_size);
return 0;
}
inline void CPDF_DataAvail::SetStartOffset(FX_FILESIZE dwOffset)
{
m_Pos = dwOffset;
}
#define MAX_WORD_BUFFER 256
FX_BOOL CPDF_DataAvail::GetNextToken(CFX_ByteString &token)
{
m_WordSize = 0;
uint8_t ch;
if (!GetNextChar(ch)) {
return FALSE;
}
uint8_t type = PDF_CharType[ch];
while (1) {
while (type == 'W') {
if (!GetNextChar(ch)) {
return FALSE;
}
type = PDF_CharType[ch];
}
if (ch != '%') {
break;
}
while (1) {
if (!GetNextChar(ch)) {
return FALSE;
}
if (ch == '\r' || ch == '\n') {
break;
}
}
type = PDF_CharType[ch];
}
if (type == 'D') {
m_WordBuffer[m_WordSize++] = ch;
if (ch == '/') {
while (1) {
if (!GetNextChar(ch)) {
return FALSE;
}
type = PDF_CharType[ch];
if (type != 'R' && type != 'N') {
m_Pos --;
CFX_ByteString ret(m_WordBuffer, m_WordSize);
token = ret;
return TRUE;
}
if (m_WordSize < MAX_WORD_BUFFER) {
m_WordBuffer[m_WordSize++] = ch;
}
}
} else if (ch == '<') {
if (!GetNextChar(ch)) {
return FALSE;
}
if (ch == '<') {
m_WordBuffer[m_WordSize++] = ch;
} else {
m_Pos --;
}
} else if (ch == '>') {
if (!GetNextChar(ch)) {
return FALSE;
}
if (ch == '>') {
m_WordBuffer[m_WordSize++] = ch;
} else {
m_Pos --;
}
}
CFX_ByteString ret(m_WordBuffer, m_WordSize);
token = ret;
return TRUE;
}
while (1) {
if (m_WordSize < MAX_WORD_BUFFER) {
m_WordBuffer[m_WordSize++] = ch;
}
if (!GetNextChar(ch)) {
return FALSE;
}
type = PDF_CharType[ch];
if (type == 'D' || type == 'W') {
m_Pos --;
break;
}
}
CFX_ByteString ret(m_WordBuffer, m_WordSize);
token = ret;
return TRUE;
}
FX_BOOL CPDF_DataAvail::GetNextChar(uint8_t &ch)
{
FX_FILESIZE pos = m_Pos;
if (pos >= m_dwFileLen) {
return FALSE;
}
if (m_bufferOffset >= pos || (FX_FILESIZE)(m_bufferOffset + m_bufferSize) <= pos) {
FX_FILESIZE read_pos = pos;
FX_DWORD read_size = 512;
if ((FX_FILESIZE)read_size > m_dwFileLen) {
read_size = (FX_DWORD)m_dwFileLen;
}
if ((FX_FILESIZE)(read_pos + read_size) > m_dwFileLen) {
read_pos = m_dwFileLen - read_size;
}
if (!m_pFileRead->ReadBlock(m_bufferData, read_pos, read_size)) {
return FALSE;
}
m_bufferOffset = read_pos;
m_bufferSize = read_size;
}
ch = m_bufferData[pos - m_bufferOffset];
m_Pos ++;
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckCrossRefItem(IFX_DownloadHints *pHints)
{
int32_t iSize = 0;
CFX_ByteString token;
while (1) {
if (!GetNextToken(token)) {
iSize = (int32_t)(m_Pos + 512 > m_dwFileLen ? m_dwFileLen - m_Pos : 512);
pHints->AddSegment(m_Pos, iSize);
return FALSE;
}
if (token == "trailer") {
m_dwTrailerOffset = m_Pos;
m_docStatus = PDF_DATAAVAIL_TRAILER;
return TRUE;
}
}
}
FX_BOOL CPDF_DataAvail::CheckAllCrossRefStream(IFX_DownloadHints *pHints)
{
FX_FILESIZE xref_offset = 0;
int32_t nRet = CheckCrossRefStream(pHints, xref_offset);
if (nRet == 1) {
if (!xref_offset) {
m_docStatus = PDF_DATAAVAIL_LOADALLCRSOSSREF;
} else {
m_dwCurrentXRefSteam = xref_offset;
m_Pos = xref_offset;
}
return TRUE;
} else if (nRet == -1) {
m_docStatus = PDF_DATAAVAIL_ERROR;
}
return FALSE;
}
FX_BOOL CPDF_DataAvail::CheckCrossRef(IFX_DownloadHints* pHints)
{
int32_t iSize = 0;
CFX_ByteString token;
if (!GetNextToken(token)) {
iSize = (int32_t)(m_Pos + 512 > m_dwFileLen ? m_dwFileLen - m_Pos : 512);
pHints->AddSegment(m_Pos, iSize);
return FALSE;
}
if (token == "xref") {
m_CrossOffset.InsertAt(0, m_dwXRefOffset);
while (1) {
if (!GetNextToken(token)) {
iSize = (int32_t)(m_Pos + 512 > m_dwFileLen ? m_dwFileLen - m_Pos : 512);
pHints->AddSegment(m_Pos, iSize);
m_docStatus = PDF_DATAAVAIL_CROSSREF_ITEM;
return FALSE;
}
if (token == "trailer") {
m_dwTrailerOffset = m_Pos;
m_docStatus = PDF_DATAAVAIL_TRAILER;
return TRUE;
}
}
} else {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
return TRUE;
}
return FALSE;
}
FX_BOOL CPDF_DataAvail::CheckTrailerAppend(IFX_DownloadHints* pHints)
{
if (m_Pos < m_dwFileLen) {
FX_FILESIZE dwAppendPos = m_Pos + m_syntaxParser.SavePos();
int32_t iSize = (int32_t)(dwAppendPos + 512 > m_dwFileLen ? m_dwFileLen - dwAppendPos : 512);
if (!m_pFileAvail->IsDataAvail(dwAppendPos, iSize)) {
pHints->AddSegment(dwAppendPos, iSize);
return FALSE;
}
}
if (m_dwPrevXRefOffset) {
SetStartOffset(m_dwPrevXRefOffset);
m_docStatus = PDF_DATAAVAIL_CROSSREF;
} else {
m_docStatus = PDF_DATAAVAIL_LOADALLCRSOSSREF;
}
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckTrailer(IFX_DownloadHints* pHints)
{
int32_t iTrailerSize = (int32_t)(m_Pos + 512 > m_dwFileLen ? m_dwFileLen - m_Pos : 512);
if (m_pFileAvail->IsDataAvail(m_Pos, iTrailerSize)) {
int32_t iSize = (int32_t)(m_Pos + iTrailerSize - m_dwTrailerOffset);
CFX_BinaryBuf buf(iSize);
uint8_t* pBuf = buf.GetBuffer();
if (!pBuf) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
if (!m_pFileRead->ReadBlock(pBuf, m_dwTrailerOffset, iSize)) {
return FALSE;
}
CFX_SmartPointer<IFX_FileStream> file(FX_CreateMemoryStream(pBuf, (size_t)iSize, FALSE));
m_syntaxParser.InitParser(file.Get(), 0);
CPDF_Object *pTrailer = m_syntaxParser.GetObject(NULL, 0, 0, 0);
if (!pTrailer) {
m_Pos += m_syntaxParser.SavePos();
pHints->AddSegment(m_Pos, iTrailerSize);
return FALSE;
}
if (pTrailer->GetType() != PDFOBJ_DICTIONARY) {
return FALSE;
}
CPDF_Dictionary *pTrailerDict = pTrailer->GetDict();
if (pTrailerDict) {
CPDF_Object *pEncrypt = pTrailerDict->GetElement("Encrypt");
if (pEncrypt && pEncrypt->GetType() == PDFOBJ_REFERENCE) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
pTrailer->Release();
return TRUE;
}
}
FX_DWORD xrefpos = GetDirectInteger(pTrailer->GetDict(), FX_BSTRC("Prev"));
if (xrefpos) {
m_dwPrevXRefOffset = GetDirectInteger(pTrailer->GetDict(), FX_BSTRC("XRefStm"));
pTrailer->Release();
if (m_dwPrevXRefOffset) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
} else {
m_dwPrevXRefOffset = xrefpos;
if (m_dwPrevXRefOffset >= m_dwFileLen) {
m_docStatus = PDF_DATAAVAIL_LOADALLFILE;
} else {
SetStartOffset(m_dwPrevXRefOffset);
m_docStatus = PDF_DATAAVAIL_TRAILER_APPEND;
}
}
return TRUE;
} else {
m_dwPrevXRefOffset = 0;
m_docStatus = PDF_DATAAVAIL_TRAILER_APPEND;
pTrailer->Release();
}
return TRUE;
}
pHints->AddSegment(m_Pos, iTrailerSize);
return FALSE;
}
FX_BOOL CPDF_DataAvail::CheckPage(int32_t iPage, IFX_DownloadHints* pHints)
{
while (TRUE) {
switch (m_docStatus) {
case PDF_DATAAVAIL_PAGETREE:
if (!LoadDocPages(pHints)) {
return FALSE;
}
break;
case PDF_DATAAVAIL_PAGE:
if (!LoadDocPage(iPage, pHints)) {
return FALSE;
}
break;
case PDF_DATAAVAIL_ERROR:
return LoadAllFile(pHints);
default:
m_bPagesTreeLoad = TRUE;
m_bPagesLoad = TRUE;
m_bCurPageDictLoadOK = TRUE;
m_docStatus = PDF_DATAAVAIL_PAGE;
return TRUE;
}
}
}
FX_BOOL CPDF_DataAvail::CheckArrayPageNode(FX_DWORD dwPageNo, CPDF_PageNode *pPageNode, IFX_DownloadHints* pHints)
{
FX_BOOL bExist = FALSE;
CPDF_Object *pPages = GetObject(dwPageNo, pHints, &bExist);
if (!bExist) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
if (!pPages) {
if (m_docStatus == PDF_DATAAVAIL_ERROR) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
return FALSE;
}
if (pPages->GetType() != PDFOBJ_ARRAY) {
pPages->Release();
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
pPageNode->m_type = PDF_PAGENODE_PAGES;
CPDF_Array* pArray = (CPDF_Array*)pPages;
for (FX_DWORD i = 0; i < pArray->GetCount(); ++i) {
CPDF_Object *pKid = (CPDF_Object *)pArray->GetElement(i);
if (!pKid || pKid->GetType() != PDFOBJ_REFERENCE) {
continue;
}
CPDF_PageNode *pNode = new CPDF_PageNode();
pPageNode->m_childNode.Add(pNode);
pNode->m_dwPageNo = ((CPDF_Reference*)pKid)->GetRefObjNum();
}
pPages->Release();
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckUnkownPageNode(FX_DWORD dwPageNo, CPDF_PageNode *pPageNode, IFX_DownloadHints* pHints)
{
FX_BOOL bExist = FALSE;
CPDF_Object *pPage = GetObject(dwPageNo, pHints, &bExist);
if (!bExist) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
if (!pPage) {
if (m_docStatus == PDF_DATAAVAIL_ERROR) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
return FALSE;
}
if (pPage->GetType() == PDFOBJ_ARRAY) {
pPageNode->m_dwPageNo = dwPageNo;
pPageNode->m_type = PDF_PAGENODE_ARRAY;
pPage->Release();
return TRUE;
}
if (pPage->GetType() != PDFOBJ_DICTIONARY) {
pPage->Release();
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
pPageNode->m_dwPageNo = dwPageNo;
CPDF_Dictionary* pDict = pPage->GetDict();
CFX_ByteString type = pDict ? pDict->GetString(FX_BSTRC("Type")) : CFX_ByteString();
if (type == FX_BSTRC("Pages")) {
pPageNode->m_type = PDF_PAGENODE_PAGES;
CPDF_Object *pKids = pDict->GetElement(FX_BSTRC("Kids"));
if (!pKids) {
m_docStatus = PDF_DATAAVAIL_PAGE;
return TRUE;
}
switch (pKids->GetType()) {
case PDFOBJ_REFERENCE: {
CPDF_Reference *pKid = (CPDF_Reference *)pKids;
CPDF_PageNode *pNode = new CPDF_PageNode();
pPageNode->m_childNode.Add(pNode);
pNode->m_dwPageNo = pKid->GetRefObjNum();
}
break;
case PDFOBJ_ARRAY: {
CPDF_Array *pKidsArray = (CPDF_Array *)pKids;
for (FX_DWORD i = 0; i < pKidsArray->GetCount(); ++i) {
CPDF_Object *pKid = (CPDF_Object *)pKidsArray->GetElement(i);
if (!pKid || pKid->GetType() != PDFOBJ_REFERENCE) {
continue;
}
CPDF_PageNode *pNode = new CPDF_PageNode();
pPageNode->m_childNode.Add(pNode);
pNode->m_dwPageNo = ((CPDF_Reference*)pKid)->GetRefObjNum();
}
}
break;
default:
break;
}
} else if (type == FX_BSTRC("Page")) {
pPageNode->m_type = PDF_PAGENODE_PAGE;
} else {
pPage->Release();
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
pPage->Release();
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckPageNode(CPDF_PageNode &pageNodes, int32_t iPage, int32_t &iCount, IFX_DownloadHints* pHints)
{
int32_t iSize = pageNodes.m_childNode.GetSize();
if (iSize <= 0 || iPage >= iSize) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
for (int32_t i = 0; i < iSize; ++i) {
CPDF_PageNode *pNode = (CPDF_PageNode*)pageNodes.m_childNode.GetAt(i);
if (!pNode) {
continue;
}
switch (pNode->m_type) {
case PDF_PAGENODE_UNKOWN:
if (!CheckUnkownPageNode(pNode->m_dwPageNo, pNode, pHints)) {
return FALSE;
}
--i;
break;
case PDF_PAGENODE_PAGE:
iCount++;
if (iPage == iCount && m_pDocument) {
m_pDocument->m_PageList.SetAt(iPage, pNode->m_dwPageNo);
}
break;
case PDF_PAGENODE_PAGES:
if (!CheckPageNode(*pNode, iPage, iCount, pHints)) {
return FALSE;
}
break;
case PDF_PAGENODE_ARRAY:
if (!CheckArrayPageNode(pNode->m_dwPageNo, pNode, pHints)) {
return FALSE;
}
--i;
break;
}
if (iPage == iCount) {
m_docStatus = PDF_DATAAVAIL_DONE;
return TRUE;
}
}
return TRUE;
}
FX_BOOL CPDF_DataAvail::LoadDocPage(int32_t iPage, IFX_DownloadHints* pHints)
{
if (m_pDocument->GetPageCount() <= iPage || m_pDocument->m_PageList.GetAt(iPage)) {
m_docStatus = PDF_DATAAVAIL_DONE;
return TRUE;
}
if (m_pageNodes.m_type == PDF_PAGENODE_PAGE) {
if (iPage == 0) {
m_docStatus = PDF_DATAAVAIL_DONE;
return TRUE;
}
m_docStatus = PDF_DATAAVAIL_ERROR;
return TRUE;
}
int32_t iCount = -1;
return CheckPageNode(m_pageNodes, iPage, iCount, pHints);
}
FX_BOOL CPDF_DataAvail::CheckPageCount(IFX_DownloadHints* pHints)
{
FX_BOOL bExist = FALSE;
CPDF_Object *pPages = GetObject(m_PagesObjNum, pHints, &bExist);
if (!bExist) {
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
if (!pPages) {
return FALSE;
}
CPDF_Dictionary* pPagesDict = pPages->GetDict();
if (!pPagesDict) {
pPages->Release();
m_docStatus = PDF_DATAAVAIL_ERROR;
return FALSE;
}
if (!pPagesDict->KeyExist(FX_BSTRC("Kids"))) {
pPages->Release();
return TRUE;
}
int count = pPagesDict->GetInteger(FX_BSTRC("Count"));
if (count > 0) {
pPages->Release();
return TRUE;
}
pPages->Release();
return FALSE;
}
FX_BOOL CPDF_DataAvail::LoadDocPages(IFX_DownloadHints* pHints)
{
if (!CheckUnkownPageNode(m_PagesObjNum, &m_pageNodes, pHints)) {
return FALSE;
}
if (CheckPageCount(pHints)) {
m_docStatus = PDF_DATAAVAIL_PAGE;
return TRUE;
} else {
m_bTotalLoadPageTree = TRUE;
}
return FALSE;
}
FX_BOOL CPDF_DataAvail::LoadPages(IFX_DownloadHints* pHints)
{
while (!m_bPagesTreeLoad) {
if (!CheckPageStatus(pHints)) {
return FALSE;
}
}
if (m_bPagesLoad) {
return TRUE;
}
m_pDocument->LoadPages();
return FALSE;
}
FX_BOOL CPDF_DataAvail::CheckLinearizedData(IFX_DownloadHints* pHints)
{
if (m_bLinearedDataOK) {
return TRUE;
}
if (!m_bMainXRefLoadTried) {
FX_SAFE_DWORD data_size = m_dwFileLen;
data_size -= m_dwLastXRefOffset;
if (!data_size.IsValid()) {
return FALSE;
}
if (!m_pFileAvail->IsDataAvail(m_dwLastXRefOffset, data_size.ValueOrDie())) {
pHints->AddSegment(m_dwLastXRefOffset, data_size.ValueOrDie());
return FALSE;
}
FX_DWORD dwRet = ((CPDF_Parser *)m_pDocument->GetParser())->LoadLinearizedMainXRefTable();
m_bMainXRefLoadTried = TRUE;
if (dwRet != PDFPARSE_ERROR_SUCCESS) {
return FALSE;
}
if (!PreparePageItem()) {
return FALSE;
}
m_bMainXRefLoadedOK = TRUE;
m_bLinearedDataOK = TRUE;
}
return m_bLinearedDataOK;
}
FX_BOOL CPDF_DataAvail::CheckPageAnnots(int32_t iPage, IFX_DownloadHints* pHints)
{
if (!m_objs_array.GetSize()) {
m_objs_array.RemoveAll();
m_objnum_array.RemoveAll();
CPDF_Dictionary *pPageDict = m_pDocument->GetPage(iPage);
if (!pPageDict) {
return TRUE;
}
CPDF_Object *pAnnots = pPageDict->GetElement(FX_BSTRC("Annots"));
if (!pAnnots) {
return TRUE;
}
CFX_PtrArray obj_array;
obj_array.Add(pAnnots);
FX_BOOL bRet = IsObjectsAvail(obj_array, FALSE, pHints, m_objs_array);
if (bRet) {
m_objs_array.RemoveAll();
}
return bRet;
} else {
CFX_PtrArray new_objs_array;
FX_BOOL bRet = IsObjectsAvail(m_objs_array, FALSE, pHints, new_objs_array);
m_objs_array.RemoveAll();
if (!bRet) {
m_objs_array.Append(new_objs_array);
}
return bRet;
}
}
FX_BOOL CPDF_DataAvail::CheckLinearizedFirstPage(int32_t iPage, IFX_DownloadHints* pHints)
{
if (!m_bAnnotsLoad) {
if (!CheckPageAnnots(iPage, pHints)) {
return FALSE;
}
m_bAnnotsLoad = TRUE;
}
if (m_bAnnotsLoad)
if (!CheckLinearizedData(pHints)) {
return FALSE;
}
m_bPageLoadedOK = FALSE;
return TRUE;
}
FX_BOOL CPDF_DataAvail::HaveResourceAncestor(CPDF_Dictionary *pDict)
{
CFX_AutoRestorer<int> restorer(&s_CurrentDataAvailRecursionDepth);
if (++s_CurrentDataAvailRecursionDepth > kMaxDataAvailRecursionDepth) {
return FALSE;
}
CPDF_Object *pParent = pDict->GetElement("Parent");
if (!pParent) {
return FALSE;
}
CPDF_Dictionary *pParentDict = pParent->GetDict();
if (!pParentDict) {
return FALSE;
}
CPDF_Object *pRet = pParentDict->GetElement("Resources");
if (pRet) {
m_pPageResource = pRet;
return TRUE;
}
return HaveResourceAncestor(pParentDict);
}
FX_BOOL CPDF_DataAvail::IsPageAvail(int32_t iPage, IFX_DownloadHints* pHints)
{
if (!m_pDocument) {
return FALSE;
}
if (IsFirstCheck(iPage)) {
m_bCurPageDictLoadOK = FALSE;
m_bPageLoadedOK = FALSE;
m_bAnnotsLoad = FALSE;
m_bNeedDownLoadResource = FALSE;
m_objs_array.RemoveAll();
m_objnum_array.RemoveAll();
}
if (m_pagesLoadState == NULL) {
m_pagesLoadState = new CFX_CMapDWordToDWord();
}
FX_DWORD dwPageLoad = 0;
if (m_pagesLoadState->Lookup(iPage, dwPageLoad) && dwPageLoad != 0) {
return TRUE;
}
if (m_bLinearized) {
if ((FX_DWORD)iPage == m_dwFirstPageNo) {
m_pagesLoadState->SetAt(iPage, TRUE);
return TRUE;
}
if (!CheckLinearizedData(pHints)) {
return FALSE;
}
if (m_bMainXRefLoadedOK) {
if (m_bTotalLoadPageTree) {
if (!LoadPages(pHints)) {
return FALSE;
}
} else {
if (!m_bCurPageDictLoadOK && !CheckPage(iPage, pHints)) {
return FALSE;
}
}
} else {
if (!LoadAllFile(pHints)) {
return FALSE;
}
((CPDF_Parser *)m_pDocument->GetParser())->RebuildCrossRef();
ResetFirstCheck(iPage);
return TRUE;
}
} else {
if (!m_bTotalLoadPageTree) {
if (!m_bCurPageDictLoadOK && !CheckPage(iPage, pHints)) {
return FALSE;
}
}
}
if (m_bHaveAcroForm && !m_bAcroFormLoad) {
if (!CheckAcroFormSubObject(pHints)) {
return FALSE;
}
m_bAcroFormLoad = TRUE;
}
if (!m_bPageLoadedOK) {
if (!m_objs_array.GetSize()) {
m_objs_array.RemoveAll();
m_objnum_array.RemoveAll();
m_pPageDict = m_pDocument->GetPage(iPage);
if (!m_pPageDict) {
ResetFirstCheck(iPage);
return TRUE;
}
CFX_PtrArray obj_array;
obj_array.Add(m_pPageDict);
FX_BOOL bRet = IsObjectsAvail(obj_array, TRUE, pHints, m_objs_array);
if (bRet) {
m_objs_array.RemoveAll();
m_bPageLoadedOK = TRUE;
} else {
return bRet;
}
} else {
CFX_PtrArray new_objs_array;
FX_BOOL bRet = IsObjectsAvail(m_objs_array, FALSE, pHints, new_objs_array);
m_objs_array.RemoveAll();
if (bRet) {
m_bPageLoadedOK = TRUE;
} else {
m_objs_array.Append(new_objs_array);
return bRet;
}
}
}
if (m_bPageLoadedOK) {
if (!m_bAnnotsLoad) {
if (!CheckPageAnnots(iPage, pHints)) {
return FALSE;
}
m_bAnnotsLoad = TRUE;
}
}
if (m_pPageDict && !m_bNeedDownLoadResource) {
m_pPageResource = m_pPageDict->GetElement("Resources");
if (!m_pPageResource) {
m_bNeedDownLoadResource = HaveResourceAncestor(m_pPageDict);
} else {
m_bNeedDownLoadResource = TRUE;
}
}
if (m_bNeedDownLoadResource) {
FX_BOOL bRet = CheckResources(pHints);
if (!bRet) {
return FALSE;
}
m_bNeedDownLoadResource = FALSE;
}
m_bPageLoadedOK = FALSE;
m_bAnnotsLoad = FALSE;
m_bCurPageDictLoadOK = FALSE;
ResetFirstCheck(iPage);
m_pagesLoadState->SetAt(iPage, TRUE);
return TRUE;
}
FX_BOOL CPDF_DataAvail::CheckResources(IFX_DownloadHints* pHints)
{
if (!m_objs_array.GetSize()) {
m_objs_array.RemoveAll();
CFX_PtrArray obj_array;
obj_array.Add(m_pPageResource);
FX_BOOL bRet = IsObjectsAvail(obj_array, TRUE, pHints, m_objs_array);
if (bRet) {
m_objs_array.RemoveAll();
}
return bRet;
} else {
CFX_PtrArray new_objs_array;
FX_BOOL bRet = IsObjectsAvail(m_objs_array, FALSE, pHints, new_objs_array);
m_objs_array.RemoveAll();
if (!bRet) {
m_objs_array.Append(new_objs_array);
}
return bRet;
}
}
void CPDF_DataAvail::GetLinearizedMainXRefInfo(FX_FILESIZE *pPos, FX_DWORD *pSize)
{
if (pPos) {
*pPos = m_dwLastXRefOffset;
}
if (pSize) {
*pSize = (FX_DWORD)(m_dwFileLen - m_dwLastXRefOffset);
}
}
int32_t CPDF_DataAvail::IsFormAvail(IFX_DownloadHints *pHints)
{
if (!m_pDocument) {
return PDFFORM_AVAIL;
}
if (!m_bLinearizedFormParamLoad) {
CPDF_Dictionary *pRoot = m_pDocument->GetRoot();
if (!pRoot) {
return PDFFORM_AVAIL;
}
CPDF_Object *pAcroForm = pRoot->GetElement(FX_BSTRC("AcroForm"));
if (!pAcroForm) {
return PDFFORM_NOTEXIST;
}
if (!CheckLinearizedData(pHints)) {
return PDFFORM_NOTAVAIL;
}
if (!m_objs_array.GetSize()) {
m_objs_array.Add(pAcroForm->GetDict());
}
m_bLinearizedFormParamLoad = TRUE;
}
CFX_PtrArray new_objs_array;
FX_BOOL bRet = IsObjectsAvail(m_objs_array, FALSE, pHints, new_objs_array);
m_objs_array.RemoveAll();
if (!bRet) {
m_objs_array.Append(new_objs_array);
return PDFFORM_NOTAVAIL;
}
return PDFFORM_AVAIL;
}
void CPDF_SortObjNumArray::AddObjNum(FX_DWORD dwObjNum)
{
int32_t iNext = 0;
if (BinarySearch(dwObjNum, iNext)) {
return;
}
m_number_array.InsertAt(iNext, dwObjNum);
}
FX_BOOL CPDF_SortObjNumArray::Find(FX_DWORD dwObjNum)
{
int32_t iNext = 0;
return BinarySearch(dwObjNum, iNext);
}
FX_BOOL CPDF_SortObjNumArray::BinarySearch(FX_DWORD value, int32_t &iNext)
{
int32_t iLen = m_number_array.GetSize();
int32_t iLow = 0;
int32_t iHigh = iLen - 1;
int32_t iMid = 0;
while (iLow <= iHigh) {
iMid = (iLow + iHigh) / 2;
if (m_number_array.GetAt(iMid) == value) {
iNext = iMid;
return TRUE;
} else if (m_number_array.GetAt(iMid) > value) {
iHigh = iMid - 1;
} else if (m_number_array.GetAt(iMid) < value) {
iLow = iMid + 1;
}
}
iNext = iLow;
return FALSE;
}
CPDF_PageNode::~CPDF_PageNode()
{
int32_t iSize = m_childNode.GetSize();
for (int32_t i = 0; i < iSize; ++i) {
CPDF_PageNode* pNode = (CPDF_PageNode*)m_childNode[i];
delete pNode;
}
m_childNode.RemoveAll();
}
|
/*
***********************************************************************************************************************
*
* Copyright (c) 2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* 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.
*
**********************************************************************************************************************/
#include "ddTransferManager.h"
#include "protocols/ddTransferServer.h"
#include "messageChannel.h"
namespace DevDriver
{
namespace TransferProtocol
{
// ============================================================================================================
TransferManager::TransferManager(const AllocCb& allocCb)
: m_pMessageChannel(nullptr)
, m_pSessionManager(nullptr)
, m_pTransferServer(nullptr)
, m_allocCb(allocCb)
, m_rng()
, m_mutex()
, m_registeredServerBlocks(allocCb)
, m_idleBlocks(allocCb)
{}
// ============================================================================================================
TransferManager::~TransferManager()
{
Destroy();
}
// ============================================================================================================
Result TransferManager::Init(IMsgChannel* pMsgChannel, SessionManager* pSessionManager)
{
DD_ASSERT(pMsgChannel != nullptr);
DD_ASSERT(pSessionManager != nullptr);
m_pMessageChannel = pMsgChannel;
m_pSessionManager = pSessionManager;
m_pTransferServer = DD_NEW(TransferServer, m_allocCb)(m_pMessageChannel, this);
if (m_pTransferServer != nullptr)
{
m_pSessionManager->RegisterProtocolServer(m_pTransferServer);
}
return (m_pTransferServer != nullptr) ? Result::Success : Result::Error;
}
// ============================================================================================================
void TransferManager::Destroy()
{
if (m_pTransferServer != nullptr)
{
m_pSessionManager->UnregisterProtocolServer(m_pTransferServer);
DD_DELETE(m_pTransferServer, m_allocCb);
m_pTransferServer = nullptr;
}
}
// ============================================================================================================
SharedPointer<ServerBlock> TransferManager::OpenServerBlock()
{
Platform::LockGuard<Platform::Mutex> lock(m_mutex);
BlockId newBlockId = kInvalidBlockId;
do
{
newBlockId = m_rng.Generate();
} while ((newBlockId == kInvalidBlockId) && m_registeredServerBlocks.Contains(newBlockId));
// Attempt to allocate a new server block
SharedPointer<ServerBlock> pBlock = SharedPointer<ServerBlock>::Create(m_allocCb,
m_allocCb,
newBlockId);
if (!pBlock.IsNull())
{
m_registeredServerBlocks.Create(newBlockId, pBlock);
}
return pBlock;
}
// ============================================================================================================
SharedPointer<ServerBlock> TransferManager::GetServerBlock(BlockId serverBlockId)
{
SharedPointer<ServerBlock> pBlock = SharedPointer<ServerBlock>();
Platform::LockGuard<Platform::Mutex> lock(m_mutex);
const auto blockIter = m_registeredServerBlocks.Find(serverBlockId);
if (blockIter != m_registeredServerBlocks.End())
{
pBlock = blockIter->value;
}
return pBlock;
}
// ============================================================================================================
void TransferManager::CloseServerBlock(SharedPointer<ServerBlock>& pBlock)
{
if (!pBlock.IsNull())
{
Platform::LockGuard<Platform::Mutex> lock(m_mutex);
m_registeredServerBlocks.Erase(pBlock->GetBlockId());
// Clear the external shared pointer to the block.
pBlock.Clear();
}
}
// ============================================================================================================
PullBlock* TransferManager::OpenPullBlock(ClientId clientId, BlockId blockId)
{
PullBlock* pBlock = DD_NEW(PullBlock, m_allocCb)(m_pMessageChannel, blockId);
if (pBlock != nullptr)
{
// Connect to the remote client and request a transfer.
Result result = pBlock->m_transferClient.Connect(clientId);
if (result == Result::Success)
{
result = pBlock->m_transferClient.RequestPullTransfer(blockId, &pBlock->m_blockDataSize);
}
// If we fail the transfer or connection, destroy the block.
if (result != Result::Success)
{
pBlock->m_transferClient.Disconnect();
DD_DELETE(pBlock, m_allocCb);
pBlock = nullptr;
}
}
return pBlock;
}
// ============================================================================================================
void TransferManager::ClosePullBlock(PullBlock** ppBlock)
{
DD_ASSERT(ppBlock != nullptr);
TransferProtocol::TransferClient& transferClient = (*ppBlock)->m_transferClient;
if (transferClient.IsTransferInProgress())
{
// Attempt to abort the transfer if there's currently one in progress.
const Result result = transferClient.AbortPullTransfer();
DD_UNUSED(result);
}
transferClient.Disconnect();
DD_DELETE((*ppBlock), m_allocCb);
*ppBlock = nullptr;
}
// ============================================================================================================
PushBlock* TransferManager::OpenPushBlock(ClientId clientId, BlockId blockId, size_t blockSize)
{
PushBlock* pBlock = DD_NEW(PushBlock, m_allocCb)(m_pMessageChannel, blockId);
if (pBlock != nullptr)
{
// Connect to the remote client and request a transfer.
Result result = pBlock->m_transferClient.Connect(clientId);
if (result == Result::Success)
{
result = pBlock->m_transferClient.RequestPushTransfer(blockId, blockSize);
}
// If we fail the transfer or connection, destroy the block.
if (result != Result::Success)
{
pBlock->m_transferClient.Disconnect();
DD_DELETE(pBlock, m_allocCb);
pBlock = nullptr;
}
}
return pBlock;
}
// ============================================================================================================
void TransferManager::ClosePushBlock(PushBlock** ppBlock)
{
DD_ASSERT(ppBlock != nullptr);
TransferProtocol::TransferClient& transferClient = (*ppBlock)->m_transferClient;
if (transferClient.IsTransferInProgress())
{
// Attempt to abort the transfer if there's currently one in progress.
const Result result = transferClient.ClosePushTransfer(true);
DD_ASSERT(result == Result::Aborted);
DD_UNUSED(result);
}
transferClient.Disconnect();
DD_DELETE((*ppBlock), m_allocCb);
*ppBlock = nullptr;
}
// ============================================================================================================
void ServerBlock::Write(const void* pSrcBuffer, size_t numBytes)
{
// Writes can only be performed on blocks that are not closed.
DD_ASSERT(m_isClosed == false);
if (numBytes > 0)
{
// Calculate how many bytes we have available.
const size_t blockCapacityInBytes = (m_chunks.Size() * kTransferChunkSizeInBytes);
const size_t bytesAvailable = (blockCapacityInBytes - m_blockDataSize);
// Allocate more chunks if necessary.
if (bytesAvailable < numBytes)
{
const size_t additionalBytesRequired = (numBytes - bytesAvailable);
const size_t numChunksRequired =
(Platform::Pow2Align(additionalBytesRequired, kTransferChunkSizeInBytes) / kTransferChunkSizeInBytes);
m_chunks.Resize(m_chunks.Size() + numChunksRequired);
}
// Copy the new data into the block
uint8* pData = (reinterpret_cast<uint8*>(m_chunks.Data()) + m_blockDataSize);
memcpy(pData, pSrcBuffer, numBytes);
m_crc32 = CRC32(pData, numBytes, m_crc32);
m_blockDataSize += numBytes;
}
}
// ============================================================================================================
void ServerBlock::Close()
{
DD_ASSERT(m_isClosed == false);
m_isClosed = true;
}
// ============================================================================================================
void ServerBlock::Reset()
{
m_isClosed = false;
m_blockDataSize = 0;
m_crc32 = 0;
}
// ============================================================================================================
void ServerBlock::Reserve(size_t bytes)
{
if (!m_isClosed)
{
m_chunks.Reserve(Platform::Pow2Align(bytes, kTransferChunkSizeInBytes) / kTransferChunkSizeInBytes);
}
}
// ============================================================================================================
void ServerBlock::BeginTransfer()
{
Platform::LockGuard<Platform::Mutex> lockGuard(m_pendingTransfersMutex);
// Increment the number of pending transfers.
++m_numPendingTransfers;
// Reset the event if this is the first transfer that's starting on this block.
if (m_numPendingTransfers == 1)
{
m_transfersCompletedEvent.Clear();
}
}
// ============================================================================================================
void ServerBlock::EndTransfer()
{
Platform::LockGuard<Platform::Mutex> lockGuard(m_pendingTransfersMutex);
// We should always have pending transfers when end is called.
DD_ASSERT(m_numPendingTransfers > 0);
// Decrement the number of pending transfers.
--m_numPendingTransfers;
// Signal the event if this was the last transfer that was pending on this block.
if (m_numPendingTransfers == 0)
{
m_transfersCompletedEvent.Signal();
}
}
// ============================================================================================================
bool ServerBlock::HasPendingTransfers()
{
Platform::LockGuard<Platform::Mutex> lockGuard(m_pendingTransfersMutex);
return (m_numPendingTransfers > 0);
}
// ============================================================================================================
uint32 ServerBlock::QueryNumPendingTransfers()
{
Platform::LockGuard<Platform::Mutex> lockGuard(m_pendingTransfersMutex);
return m_numPendingTransfers;
}
// ============================================================================================================
Result ServerBlock::WaitForPendingTransfers(uint32 timeoutInMs)
{
return m_transfersCompletedEvent.Wait(timeoutInMs);
}
// ============================================================================================================
Result PullBlock::Read(uint8* pDstBuffer, size_t bufferSize, size_t* pBytesRead)
{
return m_transferClient.ReadPullTransferData(pDstBuffer, bufferSize, pBytesRead);
}
// ============================================================================================================
Result PushBlock::Write(const uint8* pSrcBuffer, size_t bufferSize)
{
return m_transferClient.WritePushTransferData(pSrcBuffer, bufferSize);
}
// ============================================================================================================
Result PushBlock::Finalize()
{
return m_transferClient.ClosePushTransfer(false);
}
// ============================================================================================================
Result PushBlock::Discard()
{
return m_transferClient.ClosePushTransfer(true);
}
} // TransferProtocol
} // DevDriver
|
//-----------------------------------------------------------------------------
// File: DXUtil.cpp
//
// Desc: Shortcut macros and functions for using DX objects
//
//
// Copyright (c) 1997-2001 Microsoft Corporation. All rights reserved
//-----------------------------------------------------------------------------
#define STRICT
#define _CRT_SECURE_NO_DEPRECATE
#pragma warning(disable : 4996)
#include <windows.h>
#include <mmsystem.h>
#include <tchar.h>
#include <stdio.h>
#include <stdarg.h>
#include "DXUtil.h"
//-----------------------------------------------------------------------------
// Name: DXUtil_GetDXSDKMediaPath()
// Desc: Returns the DirectX SDK media path
//-----------------------------------------------------------------------------
const TCHAR* DXUtil_GetDXSDKMediaPath()
{
static TCHAR strNull[2] = _T("");
static TCHAR strPath[MAX_PATH];
DWORD dwType;
DWORD dwSize = MAX_PATH;
HKEY hKey;
// Open the appropriate registry key
LONG lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
_T("Software\\Microsoft\\DirectX SDK"),
0, KEY_READ, &hKey );
if( ERROR_SUCCESS != lResult )
return strNull;
lResult = RegQueryValueEx( hKey, _T("DX81SDK Samples Path"), NULL,
&dwType, (BYTE*)strPath, &dwSize );
RegCloseKey( hKey );
if( ERROR_SUCCESS != lResult )
return strNull;
_tcscat( strPath, _T("\\Media\\") );
return strPath;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_FindMediaFile()
// Desc: Returns a valid path to a DXSDK media file
//-----------------------------------------------------------------------------
HRESULT DXUtil_FindMediaFile( TCHAR* strPath, TCHAR* strFilename )
{
HANDLE file;
TCHAR strFullPath[1024];
TCHAR *strShortName;
DWORD cchPath;
if( NULL==strFilename || NULL==strPath )
return E_INVALIDARG;
// Build full path name from strFileName (strShortName will be just the leaf filename)
cchPath = GetFullPathName(strFilename, sizeof(strFullPath)/sizeof(TCHAR), strFullPath, &strShortName);
if ((cchPath == 0) || (sizeof(strFullPath)/sizeof(TCHAR) <= cchPath))
return E_FAIL;
// first try to find the filename given a full path
file = CreateFile( strFullPath, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
if( INVALID_HANDLE_VALUE != file )
{
_tcscpy( strPath, strFullPath );
CloseHandle( file );
return S_OK;
}
// next try to find the filename in the current working directory (path stripped)
file = CreateFile( strShortName, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
if( INVALID_HANDLE_VALUE != file )
{
_tcscpy( strPath, strShortName );
CloseHandle( file );
return S_OK;
}
// last, check if the file exists in the media directory
_stprintf( strPath, _T("%s%s"), DXUtil_GetDXSDKMediaPath(), strShortName );
file = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
if( INVALID_HANDLE_VALUE != file )
{
CloseHandle( file );
return S_OK;
}
// On failure, just return the file as the path
_tcscpy( strPath, strFilename );
return E_FAIL;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadStringRegKey()
// Desc: Helper function to read a registry key string
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadStringRegKey( HKEY hKey, TCHAR* strRegName, TCHAR* strValue,
DWORD dwLength, TCHAR* strDefault )
{
DWORD dwType;
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(BYTE*)strValue, &dwLength ) )
{
_tcscpy( strValue, strDefault );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteStringRegKey()
// Desc: Helper function to write a registry key string
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteStringRegKey( HKEY hKey, TCHAR* strRegName,
TCHAR* strValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_SZ,
(BYTE*)strValue,
(_tcslen(strValue)+1)*sizeof(TCHAR) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadIntRegKey()
// Desc: Helper function to read a registry key int
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD* pdwValue,
DWORD dwDefault )
{
DWORD dwType;
DWORD dwLength = sizeof(DWORD);
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(BYTE*)pdwValue, &dwLength ) )
{
*pdwValue = dwDefault;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteIntRegKey()
// Desc: Helper function to write a registry key int
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD dwValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_DWORD,
(BYTE*)&dwValue, sizeof(DWORD) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadBoolRegKey()
// Desc: Helper function to read a registry key BOOL
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL* pbValue,
BOOL bDefault )
{
DWORD dwType;
DWORD dwLength = sizeof(BOOL);
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(BYTE*)pbValue, &dwLength ) )
{
*pbValue = bDefault;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteBoolRegKey()
// Desc: Helper function to write a registry key BOOL
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL bValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_DWORD,
(BYTE*)&bValue, sizeof(BOOL) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ReadGuidRegKey()
// Desc: Helper function to read a registry key guid
//-----------------------------------------------------------------------------
HRESULT DXUtil_ReadGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID* pGuidValue,
GUID& guidDefault )
{
DWORD dwType;
DWORD dwLength = sizeof(GUID);
if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType,
(LPBYTE) pGuidValue, &dwLength ) )
{
*pGuidValue = guidDefault;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_WriteGuidRegKey()
// Desc: Helper function to write a registry key guid
//-----------------------------------------------------------------------------
HRESULT DXUtil_WriteGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID guidValue )
{
if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_BINARY,
(BYTE*)&guidValue, sizeof(GUID) ) )
return E_FAIL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_Timer()
// Desc: Performs timer opertations. Use the following commands:
// TIMER_RESET - to reset the timer
// TIMER_START - to start the timer
// TIMER_STOP - to stop (or pause) the timer
// TIMER_ADVANCE - to advance the timer by 0.1 seconds
// TIMER_GETABSOLUTETIME - to get the absolute system time
// TIMER_GETAPPTIME - to get the current time
// TIMER_GETELAPSEDTIME - to get the time that elapsed between
// TIMER_GETELAPSEDTIME calls
//-----------------------------------------------------------------------------
FLOAT __stdcall DXUtil_Timer( TIMER_COMMAND command )
{
static BOOL m_bTimerInitialized = FALSE;
static BOOL m_bUsingQPF = FALSE;
static BOOL m_bTimerStopped = TRUE;
static LONGLONG m_llQPFTicksPerSec = 0;
// Initialize the timer
if( FALSE == m_bTimerInitialized )
{
m_bTimerInitialized = TRUE;
// Use QueryPerformanceFrequency() to get frequency of timer. If QPF is
// not supported, we will timeGetTime() which returns milliseconds.
LARGE_INTEGER qwTicksPerSec;
m_bUsingQPF = QueryPerformanceFrequency( &qwTicksPerSec );
if( m_bUsingQPF )
m_llQPFTicksPerSec = qwTicksPerSec.QuadPart;
}
if( m_bUsingQPF )
{
static LONGLONG m_llStopTime = 0;
static LONGLONG m_llLastElapsedTime = 0;
static LONGLONG m_llBaseTime = 0;
double fTime;
double fElapsedTime;
LARGE_INTEGER qwTime;
// Get either the current time or the stop time, depending
// on whether we're stopped and what command was sent
if( m_llStopTime != 0 && command != TIMER_START && command != TIMER_GETABSOLUTETIME)
qwTime.QuadPart = m_llStopTime;
else
QueryPerformanceCounter( &qwTime );
// Return the elapsed time
if( command == TIMER_GETELAPSEDTIME )
{
fElapsedTime = (double) ( qwTime.QuadPart - m_llLastElapsedTime ) / (double) m_llQPFTicksPerSec;
m_llLastElapsedTime = qwTime.QuadPart;
return (FLOAT) fElapsedTime;
}
// Return the current time
if( command == TIMER_GETAPPTIME )
{
double fAppTime = (double) ( qwTime.QuadPart - m_llBaseTime ) / (double) m_llQPFTicksPerSec;
return (FLOAT) fAppTime;
}
// Reset the timer
if( command == TIMER_RESET )
{
m_llBaseTime = qwTime.QuadPart;
m_llLastElapsedTime = qwTime.QuadPart;
m_llStopTime = 0;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Start the timer
if( command == TIMER_START )
{
if( m_bTimerStopped )
m_llBaseTime += qwTime.QuadPart - m_llStopTime;
m_llStopTime = 0;
m_llLastElapsedTime = qwTime.QuadPart;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Stop the timer
if( command == TIMER_STOP )
{
m_llStopTime = qwTime.QuadPart;
m_llLastElapsedTime = qwTime.QuadPart;
m_bTimerStopped = TRUE;
return 0.0f;
}
// Advance the timer by 1/10th second
if( command == TIMER_ADVANCE )
{
m_llStopTime += m_llQPFTicksPerSec/10;
return 0.0f;
}
if( command == TIMER_GETABSOLUTETIME )
{
fTime = qwTime.QuadPart / (double) m_llQPFTicksPerSec;
return (FLOAT) fTime;
}
return -1.0f; // Invalid command specified
}
else
{
// Get the time using timeGetTime()
static double m_fLastElapsedTime = 0.0;
static double m_fBaseTime = 0.0;
static double m_fStopTime = 0.0;
double fTime;
double fElapsedTime;
// Get either the current time or the stop time, depending
// on whether we're stopped and what command was sent
if( m_fStopTime != 0.0 && command != TIMER_START && command != TIMER_GETABSOLUTETIME)
fTime = m_fStopTime;
else
fTime = timeGetTime() * 0.001;
// Return the elapsed time
if( command == TIMER_GETELAPSEDTIME )
{
fElapsedTime = (double) (fTime - m_fLastElapsedTime);
m_fLastElapsedTime = fTime;
return (FLOAT) fElapsedTime;
}
// Return the current time
if( command == TIMER_GETAPPTIME )
{
return (FLOAT) (fTime - m_fBaseTime);
}
// Reset the timer
if( command == TIMER_RESET )
{
m_fBaseTime = fTime;
m_fLastElapsedTime = fTime;
m_fStopTime = 0;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Start the timer
if( command == TIMER_START )
{
if( m_bTimerStopped )
m_fBaseTime += fTime - m_fStopTime;
m_fStopTime = 0.0f;
m_fLastElapsedTime = fTime;
m_bTimerStopped = FALSE;
return 0.0f;
}
// Stop the timer
if( command == TIMER_STOP )
{
m_fStopTime = fTime;
m_fLastElapsedTime = fTime;
m_bTimerStopped = TRUE;
return 0.0f;
}
// Advance the timer by 1/10th second
if( command == TIMER_ADVANCE )
{
m_fStopTime += 0.1f;
return 0.0f;
}
if( command == TIMER_GETABSOLUTETIME )
{
return (FLOAT) fTime;
}
return -1.0f; // Invalid command specified
}
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertAnsiStringToWide()
// Desc: This is a UNICODE conversion utility to convert a CHAR string into a
// WCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertAnsiStringToWide( WCHAR* wstrDestination, const CHAR* strSource,
int cchDestChar )
{
if( wstrDestination==NULL || strSource==NULL )
return;
if( cchDestChar == -1 )
cchDestChar = strlen(strSource)+1;
MultiByteToWideChar( CP_ACP, 0, strSource, -1,
wstrDestination, cchDestChar-1 );
wstrDestination[cchDestChar-1] = 0;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertWideStringToAnsi()
// Desc: This is a UNICODE conversion utility to convert a WCHAR string into a
// CHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertWideStringToAnsi( CHAR* strDestination, const WCHAR* wstrSource,
int cchDestChar )
{
if( strDestination==NULL || wstrSource==NULL )
return;
if( cchDestChar == -1 )
cchDestChar = wcslen(wstrSource)+1;
WideCharToMultiByte( CP_ACP, 0, wstrSource, -1, strDestination,
cchDestChar-1, NULL, NULL );
strDestination[cchDestChar-1] = 0;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertGenericStringToAnsi()
// Desc: This is a UNICODE conversion utility to convert a TCHAR string into a
// CHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertGenericStringToAnsi( CHAR* strDestination, const TCHAR* tstrSource,
int cchDestChar )
{
if( strDestination==NULL || tstrSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
DXUtil_ConvertWideStringToAnsi( strDestination, tstrSource, cchDestChar );
#else
if( cchDestChar == -1 )
{
strcpy( strDestination, tstrSource );
}
else
{
strncpy( strDestination, tstrSource, cchDestChar );
strDestination[cchDestChar-1] = '\0';
}
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertGenericStringToWide()
// Desc: This is a UNICODE conversion utility to convert a TCHAR string into a
// WCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertGenericStringToWide( WCHAR* wstrDestination, const TCHAR* tstrSource,
int cchDestChar )
{
if( wstrDestination==NULL || tstrSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
if( cchDestChar == -1 )
{
wcscpy( wstrDestination, tstrSource );
}
else
{
wcsncpy( wstrDestination, tstrSource, cchDestChar );
wstrDestination[cchDestChar-1] = L'\0';
}
#else
DXUtil_ConvertAnsiStringToWide( wstrDestination, tstrSource, cchDestChar );
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertAnsiStringToGeneric()
// Desc: This is a UNICODE conversion utility to convert a CHAR string into a
// TCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertAnsiStringToGeneric( TCHAR* tstrDestination, const CHAR* strSource,
int cchDestChar )
{
if( tstrDestination==NULL || strSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
DXUtil_ConvertAnsiStringToWide( tstrDestination, strSource, cchDestChar );
#else
if( cchDestChar == -1 )
{
strcpy( tstrDestination, strSource );
}
else
{
strncpy( tstrDestination, strSource, cchDestChar );
tstrDestination[cchDestChar-1] = '\0';
}
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertAnsiStringToGeneric()
// Desc: This is a UNICODE conversion utility to convert a WCHAR string into a
// TCHAR string. cchDestChar defaults -1 which means it
// assumes strDest is large enough to store strSource
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertWideStringToGeneric( TCHAR* tstrDestination, const WCHAR* wstrSource,
int cchDestChar )
{
if( tstrDestination==NULL || wstrSource==NULL || cchDestChar == 0 )
return;
#ifdef _UNICODE
if( cchDestChar == -1 )
{
wcscpy( tstrDestination, wstrSource );
}
else
{
wcsncpy( tstrDestination, wstrSource, cchDestChar );
tstrDestination[cchDestChar-1] = L'\0';
}
#else
DXUtil_ConvertWideStringToAnsi( tstrDestination, wstrSource, cchDestChar );
#endif
}
//-----------------------------------------------------------------------------
// Name: _DbgOut()
// Desc: Outputs a message to the debug stream
//-----------------------------------------------------------------------------
HRESULT _DbgOut( TCHAR* strFile, DWORD dwLine, HRESULT hr, TCHAR* strMsg )
{
TCHAR buffer[256];
wsprintf( buffer, _T("%s(%ld): "), strFile, dwLine );
OutputDebugString( buffer );
OutputDebugString( strMsg );
if( hr )
{
wsprintf( buffer, _T("(hr=%08lx)\n"), hr );
OutputDebugString( buffer );
}
OutputDebugString( _T("\n") );
return hr;
}
//-----------------------------------------------------------------------------
// Name: DXUtil_Trace()
// Desc: Outputs to the debug stream a formatted string with a variable-
// argument list.
//-----------------------------------------------------------------------------
VOID DXUtil_Trace( TCHAR* strMsg, ... )
{
#if defined(DEBUG) | defined(_DEBUG)
TCHAR strBuffer[512];
va_list args;
va_start(args, strMsg);
_vsntprintf( strBuffer, 512, strMsg, args );
va_end(args);
OutputDebugString( strBuffer );
#else
UNREFERENCED_PARAMETER(strMsg);
#endif
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertStringToGUID()
// Desc: Converts a string to a GUID
//-----------------------------------------------------------------------------
BOOL DXUtil_ConvertStringToGUID( const TCHAR* strIn, GUID* pGuidOut )
{
UINT aiTmp[10];
if( _stscanf( strIn, TEXT("{%8X-%4X-%4X-%2X%2X-%2X%2X%2X%2X%2X%2X}"),
&pGuidOut->Data1,
&aiTmp[0], &aiTmp[1],
&aiTmp[2], &aiTmp[3],
&aiTmp[4], &aiTmp[5],
&aiTmp[6], &aiTmp[7],
&aiTmp[8], &aiTmp[9] ) != 11 )
{
ZeroMemory( pGuidOut, sizeof(GUID) );
return FALSE;
}
else
{
pGuidOut->Data2 = (USHORT) aiTmp[0];
pGuidOut->Data3 = (USHORT) aiTmp[1];
pGuidOut->Data4[0] = (BYTE) aiTmp[2];
pGuidOut->Data4[1] = (BYTE) aiTmp[3];
pGuidOut->Data4[2] = (BYTE) aiTmp[4];
pGuidOut->Data4[3] = (BYTE) aiTmp[5];
pGuidOut->Data4[4] = (BYTE) aiTmp[6];
pGuidOut->Data4[5] = (BYTE) aiTmp[7];
pGuidOut->Data4[6] = (BYTE) aiTmp[8];
pGuidOut->Data4[7] = (BYTE) aiTmp[9];
return TRUE;
}
}
//-----------------------------------------------------------------------------
// Name: DXUtil_ConvertGUIDToString()
// Desc: Converts a GUID to a string
//-----------------------------------------------------------------------------
VOID DXUtil_ConvertGUIDToString( const GUID* pGuidIn, TCHAR* strOut )
{
_stprintf( strOut, TEXT("{%0.8X-%0.4X-%0.4X-%0.2X%0.2X-%0.2X%0.2X%0.2X%0.2X%0.2X%0.2X}"),
pGuidIn->Data1, pGuidIn->Data2, pGuidIn->Data3,
pGuidIn->Data4[0], pGuidIn->Data4[1],
pGuidIn->Data4[2], pGuidIn->Data4[3],
pGuidIn->Data4[4], pGuidIn->Data4[5],
pGuidIn->Data4[6], pGuidIn->Data4[7] );
}
|
//-*****************************************************************************
//
// Copyright (c) 2009-2012,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//-*****************************************************************************
#include <Foundation.h>
using namespace boost::python;
//-*****************************************************************************
void register_isampleselector()
{
// ISampleSelector
//
scope ss =
class_<Abc::ISampleSelector>(
"ISampleSelector",
"The ISampleSelector utilize the selection of the sample index "
"for the initialized requested index or time",
init<AbcA::index_t>(
( arg( "requestedIndex" ) ),
"Create an ISampleSelector with the given requested index") )
.def( init<AbcA::chrono_t,
optional<Abc::ISampleSelector::TimeIndexType> >(
( arg( "requestedTime" ),
arg( "requestedIndexType ") ),
"Create an ISampleSelector with the given requested time and "
" the optional request index type" ) )
.def( init<>(
"Create an ISampleSelector with the requested index value of "
"0 and the requested index type of kNearIndex" ) )
.def( "getIndex",
&Abc::ISampleSelector::getIndex,
( arg( "timeSampling" ), arg( "numSamples" ) ),
"Return the requested index with the given time sampling and "
"the number of samples" )
.def( "getRequestedIndex",
&Abc::ISampleSelector::getRequestedIndex,
"Return the requested Index" )
.def( "getRequestedTime",
&Abc::ISampleSelector::getRequestedTime,
"Return the requested time" )
.def( "getRequestedTimeIndexType",
&Abc::ISampleSelector::getRequestedTimeIndexType,
"Return the requested time index type" )
;
// Implicit conversions for ISampleSelector
//
implicitly_convertible<AbcA::index_t, Abc::ISampleSelector>();
implicitly_convertible<AbcA::chrono_t, Abc::ISampleSelector>();
// TimeIndexType
//
enum_<Abc::ISampleSelector::TimeIndexType>( "TimeIndexType" )
.value( "kFloorIndex", Abc::ISampleSelector::kFloorIndex )
.value( "kCeilIndex", Abc::ISampleSelector::kCeilIndex )
.value( "kNearIndex", Abc::ISampleSelector::kNearIndex )
;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <arrow/compute/api.h>
#include <arrow/io/api.h>
#include <arrow/ipc/reader.h>
#include <arrow/ipc/util.h>
#include <arrow/record_batch.h>
#include <arrow/util/io_util.h>
#include <gtest/gtest.h>
#include <iostream>
#include "shuffle/splitter.h"
#include "tests/test_utils.h"
namespace sparkcolumnarplugin {
namespace shuffle {
class SplitterTest : public ::testing::Test {
protected:
void SetUp() {
auto f_na = field("f_na", arrow::null());
auto f_int8_a = field("f_int8_a", arrow::int8());
auto f_int8_b = field("f_int8_b", arrow::int8());
auto f_uint64 = field("f_uint64", arrow::uint64());
auto f_double = field("f_double", arrow::float64());
auto f_bool = field("f_bool", arrow::boolean());
auto f_string = field("f_string", arrow::utf8());
auto f_nullable_string = field("f_nullable_string", arrow::utf8());
auto f_decimal = field("f_decimal128", arrow::decimal(10, 2));
ARROW_ASSIGN_OR_THROW(tmp_dir_1_,
std::move(arrow::internal::TemporaryDir::Make(tmp_dir_prefix)))
ARROW_ASSIGN_OR_THROW(tmp_dir_2_,
std::move(arrow::internal::TemporaryDir::Make(tmp_dir_prefix)))
auto config_dirs =
tmp_dir_1_->path().ToString() + "," + tmp_dir_2_->path().ToString();
setenv("NATIVESQL_SPARK_LOCAL_DIRS", config_dirs.c_str(), 1);
schema_ = arrow::schema({f_na, f_int8_a, f_int8_b, f_uint64, f_double, f_bool,
f_string, f_nullable_string, f_decimal});
MakeInputBatch(input_data_1, schema_, &input_batch_1_);
MakeInputBatch(input_data_2, schema_, &input_batch_2_);
}
void TearDown() override {
if (file_ != nullptr && !file_->closed()) {
file_->Close();
}
auto& file_infos = splitter_->GetPartitionFileInfo();
std::vector<std::string> file_names;
for (const auto& file_info : file_infos) {
arrow::internal::DeleteFile(
*arrow::internal::PlatformFilename::FromString(file_info.second));
}
arrow::internal::DeleteDirTree(tmp_dir_1_->path());
arrow::internal::DeleteDirTree(tmp_dir_2_->path());
}
void CheckFileExsists(const std::string& file_name) {
ASSERT_EQ(*arrow::internal::FileExists(
*arrow::internal::PlatformFilename::FromString(file_name)),
true);
ASSERT_NE(file_name.find(tmp_dir_prefix), std::string::npos);
}
arrow::Status MakeSplitter(const std::string& name, int32_t num_partitions,
int32_t buffer_size) {
return arrow::Status::OK();
}
arrow::Result<std::shared_ptr<arrow::RecordBatch>> TakeRows(
std::shared_ptr<arrow::RecordBatch> input_batch, std::string json_idx) {
std::shared_ptr<arrow::Array> take_idx;
ASSERT_NOT_OK(
arrow::ipc::internal::json::ArrayFromJSON(arrow::int32(), json_idx, &take_idx));
auto cntx = arrow::compute::FunctionContext();
std::shared_ptr<arrow::RecordBatch> res;
ASSERT_NOT_OK(arrow::compute::Take(&cntx, *input_batch, *take_idx,
arrow::compute::TakeOptions{}, &res));
return res;
}
arrow::Result<std::shared_ptr<arrow::ipc::RecordBatchReader>> GetRecordBatchReader(
const std::string& file_name) {
if (file_ != nullptr && !file_->closed()) {
RETURN_NOT_OK(file_->Close());
}
ARROW_ASSIGN_OR_RAISE(file_, arrow::io::ReadableFile::Open(file_name))
ARROW_ASSIGN_OR_RAISE(auto file_reader,
arrow::ipc::RecordBatchStreamReader::Open(file_))
return file_reader;
}
static const std::string tmp_dir_prefix;
static const std::vector<std::string> input_data_1;
static const std::vector<std::string> input_data_2;
std::shared_ptr<arrow::internal::TemporaryDir> tmp_dir_1_;
std::shared_ptr<arrow::internal::TemporaryDir> tmp_dir_2_;
std::shared_ptr<arrow::Schema> schema_;
std::shared_ptr<Splitter> splitter_;
std::shared_ptr<arrow::RecordBatch> input_batch_1_;
std::shared_ptr<arrow::RecordBatch> input_batch_2_;
std::shared_ptr<arrow::io::ReadableFile> file_;
};
const std::string SplitterTest::tmp_dir_prefix = "columnar-shuffle-test";
const std::vector<std::string> SplitterTest::input_data_1 = {
"[null, null, null, null]",
"[1, 2, 3, null]",
"[1, -1, null, null]",
"[null, null, null, null]",
R"([-0.1234567, null, 0.1234567, null])",
"[null, true, false, null]",
R"(["alice", "bob", "alice", "bob"])",
R"(["alice", "bob", null, null])",
R"(["-1.01", "2.01", "-3.01", null])"};
const std::vector<std::string> SplitterTest::input_data_2 = {
"[null, null, null, null]",
"[null, null, null, 4]",
"[1, -1, 1, -1]",
"[1, 1, 1, 1]",
R"([0.142857, -0.142857, 0.1234567, -0.1234567])",
"[true, false, true, false]",
R"(["bob", "alice", "bob", "alice"])",
R"([null, null, null, null])",
R"([null, null, "3.01", "4.01"])"};
TEST_F(SplitterTest, TestSingleSplitter) {
int32_t buffer_size = 2;
ARROW_ASSIGN_OR_THROW(splitter_, Splitter::Make("rr", schema_, 1))
splitter_->set_buffer_size(buffer_size);
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_));
ASSERT_NOT_OK(splitter_->Split(*input_batch_2_));
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_));
ASSERT_NOT_OK(splitter_->Stop());
// verify output temporary files
const auto& file_info = splitter_->GetPartitionFileInfo();
ASSERT_EQ(file_info.size(), 1);
auto file_name = file_info[0].second;
CheckFileExsists(file_name);
std::shared_ptr<arrow::ipc::RecordBatchReader> file_reader;
ARROW_ASSIGN_OR_THROW(file_reader, GetRecordBatchReader(file_name));
// verify schema
ASSERT_EQ(*file_reader->schema(), *schema_);
std::vector<std::shared_ptr<arrow::RecordBatch>> batches;
ASSERT_NOT_OK(file_reader->ReadAll(&batches));
ASSERT_EQ(batches.size(), 6);
for (auto i = 0; i < batches.size(); ++i) {
const auto& rb = batches[i];
ASSERT_EQ(rb->num_columns(), schema_->num_fields());
ASSERT_EQ(rb->num_rows(), buffer_size);
for (auto j = 0; j < rb->num_columns(); ++j) {
ASSERT_EQ(rb->column(j)->length(), rb->num_rows());
}
if (i == batches.size() - 1) {
std::shared_ptr<arrow::RecordBatch> last_output_batch;
ARROW_ASSIGN_OR_THROW(last_output_batch, TakeRows(input_batch_1_, "[2, 3]"));
ASSERT_TRUE(rb->Equals(*last_output_batch));
}
}
}
TEST_F(SplitterTest, TestRoundRobinSplitter) {
int32_t num_partitions = 2;
int32_t buffer_size = 2;
ARROW_ASSIGN_OR_THROW(splitter_, Splitter::Make("rr", schema_, num_partitions));
splitter_->set_buffer_size(buffer_size);
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_));
ASSERT_NOT_OK(splitter_->Split(*input_batch_2_));
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_));
ASSERT_NOT_OK(splitter_->Stop());
auto file_info = splitter_->GetPartitionFileInfo();
ASSERT_EQ(file_info.size(), num_partitions);
std::vector<std::shared_ptr<arrow::RecordBatch>> output_batches;
std::shared_ptr<arrow::RecordBatch> res_batch;
ARROW_ASSIGN_OR_THROW(res_batch, TakeRows(input_batch_1_, "[0, 2]"))
output_batches.push_back(std::move(res_batch));
ARROW_ASSIGN_OR_THROW(res_batch, TakeRows(input_batch_1_, "[1, 3]"))
output_batches.push_back(std::move(res_batch));
for (const auto& info : file_info) {
// verify output temporary files
auto pid = info.first;
const auto& file_name = info.second;
CheckFileExsists(file_name);
std::shared_ptr<arrow::ipc::RecordBatchReader> file_reader;
ARROW_ASSIGN_OR_THROW(file_reader, GetRecordBatchReader(file_name));
// verify schema
ASSERT_EQ(*file_reader->schema(), *schema_);
std::vector<std::shared_ptr<arrow::RecordBatch>> batches;
ASSERT_NOT_OK(file_reader->ReadAll(&batches));
for (auto i = 0; i < batches.size(); ++i) {
const auto& rb = batches[i];
ASSERT_EQ(rb->num_columns(), schema_->num_fields());
ASSERT_EQ(rb->num_rows(), buffer_size);
for (auto j = 0; j < rb->num_columns(); ++j) {
ASSERT_EQ(rb->column(j)->length(), rb->num_rows());
}
if (i == batches.size() - 1) {
ASSERT_TRUE(rb->Equals(*output_batches[pid]));
}
}
}
}
TEST_F(SplitterTest, TestHashSplitter) {
int32_t num_partitions = 2;
int32_t buffer_size = 2;
auto f_0 = TreeExprBuilder::MakeField(schema_->field(1));
auto f_1 = TreeExprBuilder::MakeField(schema_->field(2));
auto f_2 = TreeExprBuilder::MakeField(schema_->field(3));
auto node_0 = TreeExprBuilder::MakeFunction("add", {f_0, f_1}, int8());
auto expr_0 = TreeExprBuilder::MakeExpression(node_0, field("res0", int8()));
auto expr_1 = TreeExprBuilder::MakeExpression(f_2, field("f_uint64", uint64()));
ARROW_ASSIGN_OR_THROW(splitter_,
Splitter::Make("hash", schema_, num_partitions, {expr_0, expr_1}))
splitter_->set_buffer_size(buffer_size);
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_));
ASSERT_NOT_OK(splitter_->Split(*input_batch_2_));
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_));
ASSERT_NOT_OK(splitter_->Stop());
auto file_info = splitter_->GetPartitionFileInfo();
ASSERT_EQ(file_info.size(), num_partitions);
for (auto& info : file_info) {
// verify output temporary files
auto file_name = info.second;
CheckFileExsists(file_name);
std::shared_ptr<arrow::ipc::RecordBatchReader> file_reader;
ARROW_ASSIGN_OR_THROW(file_reader, GetRecordBatchReader(file_name));
// verify schema
ASSERT_EQ(*file_reader->schema(), *schema_);
std::vector<std::shared_ptr<arrow::RecordBatch>> batches;
ASSERT_NOT_OK(file_reader->ReadAll(&batches));
for (auto i = 0; i < batches.size(); ++i) {
const auto& rb = batches[i];
ASSERT_EQ(rb->num_columns(), schema_->num_fields());
ASSERT_EQ(rb->num_rows(), buffer_size);
for (auto j = 0; j < rb->num_columns(); ++j) {
ASSERT_EQ(rb->column(j)->length(), rb->num_rows());
}
}
}
}
TEST_F(SplitterTest, TestFallbackRangeSplitter) {
int32_t num_partitions = 2;
int32_t buffer_size = 2;
std::shared_ptr<arrow::Array> pid_arr;
ASSERT_NOT_OK(arrow::ipc::internal::json::ArrayFromJSON(arrow::int32(), "[0, 1, 0, 1]",
&pid_arr));
std::shared_ptr<arrow::Schema> schema_w_pid;
std::shared_ptr<arrow::RecordBatch> input_batch_1_w_pid;
std::shared_ptr<arrow::RecordBatch> input_batch_2_w_pid;
ARROW_ASSIGN_OR_THROW(schema_w_pid,
schema_->AddField(0, arrow::field("pid", arrow::int32())));
ARROW_ASSIGN_OR_THROW(input_batch_1_w_pid,
input_batch_1_->AddColumn(0, "pid", pid_arr));
ARROW_ASSIGN_OR_THROW(input_batch_2_w_pid,
input_batch_2_->AddColumn(0, "pid", pid_arr));
ARROW_ASSIGN_OR_THROW(splitter_,
Splitter::Make("range", std::move(schema_w_pid), num_partitions))
splitter_->set_buffer_size(buffer_size);
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_w_pid));
ASSERT_NOT_OK(splitter_->Split(*input_batch_2_w_pid));
ASSERT_NOT_OK(splitter_->Split(*input_batch_1_w_pid));
ASSERT_NOT_OK(splitter_->Stop());
auto file_info = splitter_->GetPartitionFileInfo();
ASSERT_EQ(file_info.size(), num_partitions);
std::vector<std::shared_ptr<arrow::RecordBatch>> output_batches;
std::shared_ptr<arrow::RecordBatch> res_batch;
ARROW_ASSIGN_OR_THROW(res_batch, TakeRows(input_batch_1_, "[0, 2]"))
output_batches.push_back(std::move(res_batch));
ARROW_ASSIGN_OR_THROW(res_batch, TakeRows(input_batch_1_, "[1, 3]"))
output_batches.push_back(std::move(res_batch));
for (const auto& info : file_info) {
// verify output temporary files
auto pid = info.first;
const auto& file_name = info.second;
CheckFileExsists(file_name);
std::shared_ptr<arrow::ipc::RecordBatchReader> file_reader;
ARROW_ASSIGN_OR_THROW(file_reader, GetRecordBatchReader(file_name));
// verify schema
ASSERT_EQ(*schema_, *file_reader->schema());
std::vector<std::shared_ptr<arrow::RecordBatch>> batches;
ASSERT_NOT_OK(file_reader->ReadAll(&batches));
for (auto i = 0; i < batches.size(); ++i) {
const auto& rb = batches[i];
ASSERT_EQ(rb->num_columns(), schema_->num_fields());
ASSERT_EQ(rb->num_rows(), buffer_size);
for (auto j = 0; j < rb->num_columns(); ++j) {
ASSERT_EQ(rb->column(j)->length(), rb->num_rows());
}
if (i == batches.size() - 1) {
ASSERT_TRUE(rb->Equals(*output_batches[pid]));
}
}
}
}
} // namespace shuffle
} // namespace sparkcolumnarplugin
|
#ifndef _RAR_PPMMODEL_
#define _RAR_PPMMODEL_
#include "suballoc.hpp"
/****************************************************************************
* Contents: 'Carryless rangecoder' by Dmitry Subbotin *
****************************************************************************/
class RangeCoder
{
public:
void InitDecoder(Unpack *UnpackRead);
unsigned int GetChar();
int GetCurrentCount()
{
return (code-low)/(range /= SubRange.scale);
}
uint GetCurrentShiftCount(uint SHIFT)
{
return (code-low)/(range >>= SHIFT);
}
void Decode()
{
low += range*SubRange.LowCount;
range *= SubRange.HighCount-SubRange.LowCount;
}
uint low, code, range;
struct SUBRANGE
{
uint LowCount, HighCount, scale;
} SubRange;
Unpack *UnpackRead;
};
/****************************************************************************
****************************************************************************/
const int MAX_O=64; /* maximum allowed model order */
const int INT_BITS=7, PERIOD_BITS=7, TOT_BITS=INT_BITS+PERIOD_BITS,
INTERVAL=1 << INT_BITS, BIN_SCALE=1 << TOT_BITS, MAX_FREQ=124;
#ifndef STRICT_ALIGNMENT_REQUIRED
#pragma pack(1)
#endif
struct SEE2_CONTEXT
{ // SEE-contexts for PPM-contexts with masked symbols
ushort Summ;
byte Shift, Count;
void init(int InitVal)
{
Summ=InitVal << (Shift=PERIOD_BITS-4);
Count=4;
}
uint getMean()
{
uint RetVal=GET_SHORT16(Summ) >> Shift;
Summ -= RetVal;
return RetVal+(RetVal == 0);
}
void update()
{
if (Shift < PERIOD_BITS && --Count == 0)
{
Summ += Summ;
Count=3 << Shift++;
}
}
};
class ModelPPM;
struct PPM_CONTEXT;
struct STATE
{
byte Symbol;
byte Freq;
PPM_CONTEXT* Successor;
};
struct FreqData
{
ushort SummFreq;
STATE _PACK_ATTR * Stats;
};
struct PPM_CONTEXT
{
ushort NumStats;
union
{
FreqData U;
STATE OneState;
};
PPM_CONTEXT* Suffix;
inline void encodeBinSymbol(ModelPPM *Model,int symbol); // MaxOrder:
inline void encodeSymbol1(ModelPPM *Model,int symbol); // ABCD context
inline void encodeSymbol2(ModelPPM *Model,int symbol); // BCD suffix
inline void decodeBinSymbol(ModelPPM *Model); // BCDE successor
inline bool decodeSymbol1(ModelPPM *Model); // other orders:
inline bool decodeSymbol2(ModelPPM *Model); // BCD context
inline void update1(ModelPPM *Model,STATE* p); // CD suffix
inline void update2(ModelPPM *Model,STATE* p); // BCDE successor
void rescale(ModelPPM *Model);
inline PPM_CONTEXT* createChild(ModelPPM *Model,STATE* pStats,STATE& FirstState);
inline SEE2_CONTEXT* makeEscFreq2(ModelPPM *Model,int Diff);
};
#ifndef STRICT_ALIGNMENT_REQUIRED
#pragma pack()
#endif
const uint UNIT_SIZE=Max(sizeof(PPM_CONTEXT),sizeof(RAR_MEM_BLK));
const uint FIXED_UNIT_SIZE=12;
template <class T>
inline void _PPMD_SWAP(T& t1,T& t2) { T tmp=t1; t1=t2; t2=tmp; }
class ModelPPM
{
private:
friend struct PPM_CONTEXT;
SEE2_CONTEXT SEE2Cont[25][16], DummySEE2Cont;
struct PPM_CONTEXT *MinContext, *MedContext, *MaxContext;
STATE* FoundState; // found next state transition
int NumMasked, InitEsc, OrderFall, MaxOrder, RunLength, InitRL;
byte CharMask[256], NS2Indx[256], NS2BSIndx[256], HB2Flag[256];
byte EscCount, PrevSuccess, HiBitsFlag;
ushort BinSumm[128][64]; // binary SEE-contexts
RangeCoder Coder;
SubAllocator SubAlloc;
void RestartModelRare();
void StartModelRare(int MaxOrder);
inline PPM_CONTEXT* CreateSuccessors(bool Skip,STATE* p1);
inline void UpdateModel();
inline void ClearMask();
public:
ModelPPM();
void CleanUp(); // reset PPM variables after data error
bool DecodeInit(Unpack *UnpackRead,int &EscChar);
int DecodeChar();
};
#endif
|
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
* Benedikt-Alexander Mokroß <bam@icognize.de>
*
* 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 "Int32Test.hpp"
#include "oatpp-mongo/TestUtils.hpp"
#include "oatpp-mongo/bson/mapping/ObjectMapper.hpp"
#include "oatpp/core/Types.hpp"
#include "oatpp/core/macro/codegen.hpp"
namespace oatpp { namespace mongo { namespace test { namespace bson {
namespace {
#include OATPP_CODEGEN_BEGIN(DTO)
/* Complete object */
class Obj : public oatpp::DTO {
DTO_INIT(Obj, DTO)
DTO_FIELD(Int32, f1) = std::numeric_limits<v_int32>::max();
DTO_FIELD(Int32, f2) = 32;
DTO_FIELD(Int32, f3) = nullptr;
DTO_FIELD(Int32, f4) = std::numeric_limits<v_int32>::min();
};
/* No first field */
class Sub1 : public oatpp::DTO {
DTO_INIT(Sub1, DTO)
DTO_FIELD(Int32, f2);
DTO_FIELD(Int32, f3);
DTO_FIELD(Int32, f4);
};
/* No second field */
class Sub2 : public oatpp::DTO {
DTO_INIT(Sub2, DTO)
DTO_FIELD(Int32, f1);
DTO_FIELD(Int32, f3);
DTO_FIELD(Int32, f4);
};
/* No null field */
class Sub3 : public oatpp::DTO {
DTO_INIT(Sub3, DTO)
DTO_FIELD(Int32, f1);
DTO_FIELD(Int32, f2);
DTO_FIELD(Int32, f4);
};
/* No last field */
class Sub4 : public oatpp::DTO {
DTO_INIT(Sub4, DTO)
DTO_FIELD(Int32, f1);
DTO_FIELD(Int32, f2);
DTO_FIELD(Int32, f3);
};
////////////////////////////////////////
// Unsigned
/* Complete object */
class UObj : public oatpp::DTO {
DTO_INIT(UObj, DTO)
DTO_FIELD(UInt32, f1) = std::numeric_limits<v_uint32>::max();
DTO_FIELD(UInt32, f2) = std::numeric_limits<v_uint32>::max() - 32;
DTO_FIELD(UInt32, f3) = nullptr;
DTO_FIELD(UInt32, f4) = std::numeric_limits<v_uint32>::max() - 10032;
};
/* No first field */
class USub1 : public oatpp::DTO {
DTO_INIT(USub1, DTO)
DTO_FIELD(UInt32, f2);
DTO_FIELD(UInt32, f3);
DTO_FIELD(UInt32, f4);
};
/* No second field */
class USub2 : public oatpp::DTO {
DTO_INIT(USub2, DTO)
DTO_FIELD(UInt32, f1);
DTO_FIELD(UInt32, f3);
DTO_FIELD(UInt32, f4);
};
/* No null field */
class USub3 : public oatpp::DTO {
DTO_INIT(USub3, DTO)
DTO_FIELD(UInt32, f1);
DTO_FIELD(UInt32, f2);
DTO_FIELD(UInt32, f4);
};
/* No last field */
class USub4 : public oatpp::DTO {
DTO_INIT(USub4, DTO)
DTO_FIELD(UInt32, f1);
DTO_FIELD(UInt32, f2);
DTO_FIELD(UInt32, f3);
};
#include OATPP_CODEGEN_END(DTO)
}
void Int32Test::onRun() {
oatpp::mongo::bson::mapping::ObjectMapper bsonMapper;
/////////////////////////////////////////////////////
// Signed
{
auto obj = Obj::createShared();
auto bson = bsonMapper.writeToString(obj);
auto bcxx = TestUtils::writeJsonToBsonCXX(obj);
if (bson != bcxx) {
TestUtils::writeBinary(bson, "oatpp-mongo::bson (signed)");
TestUtils::writeBinary(bcxx, "bsoncxx (signed)");
}
OATPP_ASSERT(bson == bcxx);
{
OATPP_LOGI(TAG, "sub0...");
auto sub = bsonMapper.readFromString<oatpp::Object<Obj>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "sub0 - OK");
}
{
OATPP_LOGI(TAG, "sub1...");
auto sub = bsonMapper.readFromString<oatpp::Object<Sub1>>(bson);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "sub1 - OK");
}
{
OATPP_LOGI(TAG, "sub2...");
auto sub = bsonMapper.readFromString<oatpp::Object<Sub2>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "sub2 - OK");
}
{
OATPP_LOGI(TAG, "sub3...");
auto sub = bsonMapper.readFromString<oatpp::Object<Sub3>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "sub3 - OK");
}
{
OATPP_LOGI(TAG, "sub4...");
auto sub = bsonMapper.readFromString<oatpp::Object<Sub4>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_LOGI(TAG, "sub4 - OK");
}
}
/////////////////////////////////////////////////////
// Unsigned
{
auto obj = UObj::createShared();
auto bson = bsonMapper.writeToString(obj);
auto bcxx = TestUtils::writeJsonToBsonCXX(obj);
if (bson != bcxx) {
TestUtils::writeBinary(bson, "oatpp-mongo::bson (unsigned)");
TestUtils::writeBinary(bcxx, "bsoncxx (unsigned)");
}
OATPP_ASSERT(bson == bcxx);
{
OATPP_LOGI(TAG, "usub0...");
auto sub = bsonMapper.readFromString<oatpp::Object<UObj>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "usub0 - OK");
}
{
OATPP_LOGI(TAG, "usub1...");
auto sub = bsonMapper.readFromString<oatpp::Object<USub1>>(bson);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "usub1 - OK");
}
{
OATPP_LOGI(TAG, "usub2...");
auto sub = bsonMapper.readFromString<oatpp::Object<USub2>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "usub2 - OK");
}
{
OATPP_LOGI(TAG, "usub3...");
auto sub = bsonMapper.readFromString<oatpp::Object<USub3>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(sub->f4 == obj->f4);
OATPP_LOGI(TAG, "usub3 - OK");
}
{
OATPP_LOGI(TAG, "usub4...");
auto sub = bsonMapper.readFromString<oatpp::Object<USub4>>(bson);
OATPP_ASSERT(sub->f1 == obj->f1);
OATPP_ASSERT(sub->f2 == obj->f2);
OATPP_ASSERT(!sub->f3.getPtr() && !obj->f3.getPtr());
OATPP_LOGI(TAG, "usub4 - OK");
}
}
}
}}}}
|
/*
* @lc app=leetcode id=1373 lang=cpp
*
* [1373] Maximum Sum BST in Binary Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <tuple>
using namespace std;
#define LOWER_BOUND -40005
#define UPPER_BOUND 40005
#define INVALID_FLAG -50000
#define ROOT 0
#define LEFT 1
#define RIGHT 2
const pair<int, int> INVALID_PAIR = {INVALID_FLAG, -1};
const tuple<int, int, int> INVALID_TUPLE = {INVALID_FLAG, INVALID_FLAG, -1};
class Solution {
public:
tuple<int, int, int> BSTRange(TreeNode* root, int direction = ROOT){
// RESULT: MIN, MAX, SUM
if (!root)
return {UPPER_BOUND, LOWER_BOUND, 0};
if (!root->left && !root->right){
ans = max(ans, root->val);
return {root->val, root->val, root->val};
}
tuple<int,int,int> l = BSTRange(root->left, LEFT);
tuple<int,int,int> r = BSTRange(root->right, RIGHT);
if (get<0>(l) != INVALID_FLAG && get<0>(r) != INVALID_FLAG)
if (root->val > get<1>(l) && root->val < get<0>(r)){
int curSum = root->val + get<2>(l) + get<2>(r);
ans = max(curSum, ans);
if (direction == ROOT)
return {root->val, root->val, curSum};
else
return {min(root->val, get<0>(l)), max(root->val, get<1>(r)), curSum};
}
return INVALID_TUPLE;
}
int maxSumBST(TreeNode* root) {
BSTRange(root);
return ans;
}
private:
int ans = 0;
};
// @lc code=end
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "vgui_BudgetFPSPanel.H"
#include "vgui_BudgetPanel.h"
#include <vgui/ISurface.h>
#include "tier0/vprof.h"
#include "materialsystem/imaterialsystem.h"
static ConVar budget_peaks_window( "budget_peaks_window", "30", FCVAR_ARCHIVE, "number of frames to look at when figuring out peak frametimes" );
static ConVar budget_averages_window( "budget_averages_window", "30", FCVAR_ARCHIVE, "number of frames to look at when figuring out average frametimes" );
static ConVar budget_show_peaks( "budget_show_peaks", "1", FCVAR_ARCHIVE, "enable/disable peaks in the budget panel" );
static ConVar budget_show_averages( "budget_show_averages", "0", FCVAR_ARCHIVE, "enable/disable averages in the budget panel" );
CBudgetFPSPanel::CBudgetFPSPanel( vgui::Panel *pParent, const char *pPanelName ) : BaseClass( pParent, pPanelName )
{
SetProportional( false );
SetKeyBoardInputEnabled( false );
SetMouseInputEnabled( false );
SetSizeable( false );
SetVisible( true );
SetPaintBackgroundEnabled( false );
// hide the system buttons
SetTitleBarVisible( false );
}
CBudgetFPSPanel::~CBudgetFPSPanel()
{
}
#define PIXELS_BETWEEN_BARS 4
void CBudgetFPSPanel::DrawBarAtIndex( int id, float percent )
{
int panelWidth, panelHeight;
GetSize( panelWidth, panelHeight );
int nGroups = g_VProfCurrentProfile.GetNumBudgetGroups();
int top = 2 + ( id * panelHeight ) / nGroups;
int bottom = ( ( ( id + 1 ) * panelHeight ) / nGroups ) - PIXELS_BETWEEN_BARS;
int left = 0;
int right = panelWidth * percent;
int red, green, blue, alpha;
g_VProfCurrentProfile.GetBudgetGroupColor( id, red, green, blue, alpha );
// DrawFilledRect is panel relative
vgui::surface()->DrawSetColor( 0, 0, 0, alpha );
vgui::surface()->DrawFilledRect( left, top-2, right+2, bottom+2 );
vgui::surface()->DrawSetColor( 255, 255, 255, alpha );
vgui::surface()->DrawFilledRect( left, top-1, right+1, bottom+1 );
vgui::surface()->DrawSetColor( red, green, blue, alpha );
vgui::surface()->DrawFilledRect( left, top, right, bottom );
}
void CBudgetFPSPanel::DrawTickAtIndex( int id, float percent, int red, int green, int blue, int alpha )
{
if( percent > 1.0f )
{
percent = 1.0f;
}
int panelWidth, panelHeight;
GetSize( panelWidth, panelHeight );
int nGroups = g_VProfCurrentProfile.GetNumBudgetGroups();
int top = 2 + ( id * panelHeight ) / nGroups;
int bottom = ( ( ( id + 1 ) * panelHeight ) / nGroups ) - PIXELS_BETWEEN_BARS;
int right = ( int )( panelWidth * percent + 1.0f );
int left = right - 2;
// DrawFilledRect is panel relative
vgui::surface()->DrawSetColor( 0, 0, 0, alpha );
vgui::surface()->DrawFilledRect( left-2, top-2, right+2, bottom+2 );
vgui::surface()->DrawSetColor( 255, 255, 255, alpha );
vgui::surface()->DrawFilledRect( left-1, top-1, right+1, bottom+1 );
vgui::surface()->DrawSetColor( red, green, blue, alpha );
vgui::surface()->DrawFilledRect( left, top, right, bottom );
}
void CBudgetFPSPanel::DrawTimeLines( void )
{
int panelWidth, panelHeight;
GetSize( panelWidth, panelHeight );
int i;
int left, right, top, bottom;
top = 0;
bottom = panelHeight;
for( i = ( int )m_fRangeMin; i < ( int )( m_fRangeMax + 0.5f ); i++ )
{
int alpha;
if( i % 10 == 0 )
{
alpha = 150;
}
else if( i % 5 == 0 )
{
alpha = 100;
}
else
{
alpha = 50;
}
left = -0.5f + panelWidth * ( ( float )i - m_fRangeMin ) / ( m_fRangeMax - m_fRangeMin );
right = left + 1;
vgui::surface()->DrawSetColor( 0, 0, 0, alpha );
vgui::surface()->DrawFilledRect( left-1, top, right+1, bottom );
vgui::surface()->DrawSetColor( 255, 255, 255, alpha );
vgui::surface()->DrawFilledRect( left, top+1, right, bottom-1 );
}
}
void CBudgetFPSPanel::DrawInstantaneous()
{
int nGroups, nSamplesPerGroup, nSampleOffset;
const double *pBudgetGroupTimes = GetBudgetPanel()->GetBudgetGroupData( nGroups, nSamplesPerGroup, nSampleOffset );
if( !pBudgetGroupTimes )
{
return;
}
int i;
for( i = 0; i < nGroups; i++ )
{
DrawBarAtIndex( i, ( pBudgetGroupTimes[nSamplesPerGroup * i + nSampleOffset] - m_fRangeMin ) / ( m_fRangeMax - m_fRangeMin ) );
}
}
void CBudgetFPSPanel::DrawPeaks()
{
int nGroups, nSamplesPerGroup, nSampleOffset;
const double *pBudgetGroupTimes = GetBudgetPanel()->GetBudgetGroupData( nGroups, nSamplesPerGroup, nSampleOffset );
if( !pBudgetGroupTimes )
{
return;
}
int numSamples = budget_peaks_window.GetInt();
int i;
for( i = 0; i < nGroups; i++ )
{
double max = 0;
int j;
for( j = 0; j < numSamples; j++ )
{
double tmp;
int offset = ( nSampleOffset - j + VPROF_HISTORY_COUNT ) % VPROF_HISTORY_COUNT;
tmp = pBudgetGroupTimes[i * nSamplesPerGroup + offset];
if( tmp > max )
{
max = tmp;
}
}
float percent = ( max - m_fRangeMin ) / ( m_fRangeMax - m_fRangeMin );
DrawTickAtIndex( i, percent, 255, 0, 0, 255 );
}
}
void CBudgetFPSPanel::DrawAverages()
{
int nGroups, nSamplesPerGroup, nSampleOffset;
const double *pBudgetGroupTimes = GetBudgetPanel()->GetBudgetGroupData( nGroups, nSamplesPerGroup, nSampleOffset );
if( !pBudgetGroupTimes )
{
return;
}
int numSamples = budget_averages_window.GetInt();
int i;
for( i = 0; i < nGroups; i++ )
{
int red, green, blue, alpha;
g_VProfCurrentProfile.GetBudgetGroupColor( i, red, green, blue, alpha );
double sum = 0;
int j;
for( j = 0; j < numSamples; j++ )
{
int offset = ( nSampleOffset - j + VPROF_HISTORY_COUNT ) % VPROF_HISTORY_COUNT;
sum += pBudgetGroupTimes[i * nSamplesPerGroup + offset];
}
sum *= ( 1.0f / numSamples );
float percent = ( sum - m_fRangeMin ) / ( m_fRangeMax - m_fRangeMin );
DrawTickAtIndex( i, percent, red, green, blue, alpha );
}
}
void CBudgetFPSPanel::Paint( void )
{
materials->Flush();
g_VProfCurrentProfile.Pause();
int width, height;
GetSize( width, height );
DrawTimeLines();
DrawInstantaneous();
if( budget_show_peaks.GetBool() )
{
DrawPeaks();
}
if( budget_show_averages.GetBool() )
{
DrawAverages();
}
materials->Flush();
g_VProfCurrentProfile.Resume();
}
void CBudgetFPSPanel::SetRange( float fMin, float fMax )
{
m_fRangeMin = fMin;
m_fRangeMax = fMax;
}
|
#include "steamwrap.h"
vdynamic *CallbackHandler::EncodeLobbyData( LobbyDataUpdate_t *d ) {
if( !d->m_bSuccess ) return NULL;
HLValue ret;
ret.Set("lobby",d->m_ulSteamIDLobby);
if( d->m_ulSteamIDMember != d->m_ulSteamIDLobby ) ret.Set("user",d->m_ulSteamIDMember);
return ret.value;
}
vdynamic *CallbackHandler::EncodeLobbyChatUpdate( LobbyChatUpdate_t *d ) {
HLValue ret;
ret.Set("lobby",d->m_ulSteamIDLobby);
ret.Set("user",d->m_ulSteamIDUserChanged);
ret.Set("origin", d->m_ulSteamIDMakingChange);
ret.Set("flags", d->m_rgfChatMemberStateChange);
return ret.value;
}
vdynamic *CallbackHandler::EncodeLobbyChatMsg( LobbyChatMsg_t *d ) {
HLValue ret;
ret.Set("lobby",d->m_ulSteamIDLobby);
ret.Set("user",d->m_ulSteamIDUser);
ret.Set("type",d->m_eChatEntryType);
ret.Set("cid", d->m_iChatID);
return ret.value;
}
vdynamic *CallbackHandler::EncodeLobbyJoinRequest( GameLobbyJoinRequested_t *d ) {
HLValue ret;
ret.Set("lobby", d->m_steamIDLobby);
ret.Set("user", d->m_steamIDFriend);
return ret.value;
}
// --------- Lobby Search --------------------------
static void on_lobby_list( vclosure *c, LobbyMatchList_t *result, bool error ) {
vdynamic d;
d.t = &hlt_i32;
d.v.i = error ? -1 : result->m_nLobbiesMatching;
dyn_call_result(c,&d,error);
}
HL_PRIM CClosureCallResult<LobbyMatchList_t>* HL_NAME(request_lobby_list)( vclosure *closure ) {
if( !CheckInit() ) return NULL;
ASYNC_CALL(SteamMatchmaking()->RequestLobbyList(), LobbyMatchList_t, on_lobby_list);
return m_call;
}
HL_PRIM vuid HL_NAME(get_lobby_by_index)( int index ) {
return hl_of_uid(SteamMatchmaking()->GetLobbyByIndex(index));
}
HL_PRIM void HL_NAME(request_filter_string)( vbyte *key, vbyte *value, int type ) {
SteamMatchmaking()->AddRequestLobbyListStringFilter((char*)key,(char*)value,(ELobbyComparison)type);
}
HL_PRIM void HL_NAME(request_filter_numerical)( vbyte *key, int value, int type ) {
SteamMatchmaking()->AddRequestLobbyListNumericalFilter((char*)key,value,(ELobbyComparison)type);
}
HL_PRIM void HL_NAME(request_filter_near_value)( vbyte *key, int value ) {
SteamMatchmaking()->AddRequestLobbyListNearValueFilter((char*)key,value);
}
HL_PRIM void HL_NAME(request_filter_slots_available)( int slots ) {
SteamMatchmaking()->AddRequestLobbyListFilterSlotsAvailable(slots);
}
HL_PRIM void HL_NAME(request_filter_distance)( int distance ) {
SteamMatchmaking()->AddRequestLobbyListDistanceFilter((ELobbyDistanceFilter)distance);
}
HL_PRIM void HL_NAME(request_result_count)( int max ) {
SteamMatchmaking()->AddRequestLobbyListResultCountFilter(max);
}
DEFINE_PRIM(_CRESULT, request_lobby_list, _CALLB(_I32));
DEFINE_PRIM(_UID, get_lobby_by_index, _I32);
DEFINE_PRIM(_VOID, request_filter_string, _BYTES _BYTES _I32);
DEFINE_PRIM(_VOID, request_filter_numerical, _BYTES _I32 _I32);
DEFINE_PRIM(_VOID, request_filter_near_value, _BYTES _I32);
DEFINE_PRIM(_VOID, request_filter_slots_available, _I32);
DEFINE_PRIM(_VOID, request_filter_distance, _I32);
DEFINE_PRIM(_VOID, request_result_count, _I32);
// --------- Lobby Create / Manage --------------------------
static void on_lobby_created( vclosure *c, LobbyCreated_t *result, bool error ) {
vdynamic d;
hl_set_uid(&d,error ? 0 : result->m_ulSteamIDLobby);
dyn_call_result(c,&d,error);
}
HL_PRIM CClosureCallResult<LobbyCreated_t>* HL_NAME(create_lobby)( ELobbyType lobbyType, int maxMembers, vclosure *closure ) {
ASYNC_CALL(SteamMatchmaking()->CreateLobby(lobbyType,maxMembers), LobbyCreated_t, on_lobby_created);
return m_call;
}
HL_PRIM void HL_NAME(leave_lobby)( vuid uid ) {
SteamMatchmaking()->LeaveLobby(hl_to_uid(uid));
}
static void on_lobby_joined( vclosure *c, LobbyEnter_t *result, bool error ) {
vdynamic d;
d.t = &hlt_bool;
d.v.b = result->m_bLocked;
dyn_call_result(c,&d,error);
}
HL_PRIM CClosureCallResult<LobbyEnter_t>* HL_NAME(join_lobby)( vuid uid, vclosure *closure ) {
ASYNC_CALL(SteamMatchmaking()->JoinLobby(hl_to_uid(uid)), LobbyEnter_t, on_lobby_joined);
return m_call;
}
HL_PRIM int HL_NAME(get_num_lobby_members)( vuid uid ) {
return SteamMatchmaking()->GetNumLobbyMembers(hl_to_uid(uid));
}
HL_PRIM vuid HL_NAME(get_lobby_member_by_index)( vuid uid, int index ) {
return hl_of_uid(SteamMatchmaking()->GetLobbyMemberByIndex(hl_to_uid(uid),index));
}
HL_PRIM vuid HL_NAME(get_lobby_owner)( vuid uid ) {
return hl_of_uid(SteamMatchmaking()->GetLobbyOwner(hl_to_uid(uid)));
}
HL_PRIM void HL_NAME(lobby_invite_friends)( vuid uid ) {
SteamFriends()->ActivateGameOverlayInviteDialog(hl_to_uid(uid));
}
HL_PRIM bool HL_NAME(send_lobby_chat_msg)( vuid uid, vbyte *msg, int len ) {
return SteamMatchmaking()->SendLobbyChatMsg(hl_to_uid(uid),msg,len);
}
HL_PRIM vuid HL_NAME(get_lobby_chat_entry)( vuid uid, int cid, vbyte *data, int maxData, int *type, int *outLen ) {
CSteamID user;
EChatEntryType chatType;
*outLen = SteamMatchmaking()->GetLobbyChatEntry(hl_to_uid(uid), cid, &user, data, maxData, &chatType);
*type = chatType;
return hl_of_uid(user);
}
HL_PRIM bool HL_NAME(lobby_invite_user)( vuid lid, vuid fid ) {
return SteamMatchmaking()->InviteUserToLobby(hl_to_uid(lid),hl_to_uid(fid));
}
HL_PRIM int HL_NAME(get_lobby_member_limit)( vuid uid ) {
return SteamMatchmaking()->GetLobbyMemberLimit(hl_to_uid(uid));
}
HL_PRIM void HL_NAME(set_lobby_member_limit)( vuid uid, int count ) {
SteamMatchmaking()->SetLobbyMemberLimit(hl_to_uid(uid), count);
}
DEFINE_PRIM(_CRESULT, create_lobby, _I32 _I32 _CALLB(_UID));
DEFINE_PRIM(_VOID, leave_lobby, _UID);
DEFINE_PRIM(_CRESULT, join_lobby, _UID _CALLB(_BOOL));
DEFINE_PRIM(_I32, get_num_lobby_members, _UID);
DEFINE_PRIM(_UID, get_lobby_member_by_index, _UID _I32);
DEFINE_PRIM(_I32, get_lobby_member_limit, _UID);
DEFINE_PRIM(_VOID, set_lobby_member_limit, _UID _I32);
DEFINE_PRIM(_UID, get_lobby_owner, _UID);
DEFINE_PRIM(_VOID, lobby_invite_friends, _UID);
DEFINE_PRIM(_BOOL, lobby_invite_user, _UID _UID);
DEFINE_PRIM(_BOOL, send_lobby_chat_msg, _UID _BYTES _I32);
DEFINE_PRIM(_UID, get_lobby_chat_entry, _UID _I32 _BYTES _I32 _REF(_I32) _REF(_I32));
// --------- Lobby Data --------------------------
HL_PRIM bool HL_NAME(request_lobby_data)( vuid uid ) {
return SteamMatchmaking()->RequestLobbyData(hl_to_uid(uid));
}
HL_PRIM const char *HL_NAME(get_lobby_data)( vuid uid, const char *key ) {
return SteamMatchmaking()->GetLobbyData(hl_to_uid(uid),key);
}
HL_PRIM bool HL_NAME(set_lobby_data)( vuid uid, const char *key, const char *value ) {
return SteamMatchmaking()->SetLobbyData(hl_to_uid(uid), key, value);
}
HL_PRIM bool HL_NAME(delete_lobby_data)( vuid uid, const char *key ) {
return SteamMatchmaking()->DeleteLobbyData(hl_to_uid(uid),key);
}
HL_PRIM int HL_NAME(get_lobby_data_count)( vuid uid ) {
return SteamMatchmaking()->GetLobbyDataCount(hl_to_uid(uid));
}
HL_PRIM bool HL_NAME(get_lobby_data_byindex)( vuid uid, int index, char *key, int ksize, char *value, int vsize ) {
return SteamMatchmaking()->GetLobbyDataByIndex(hl_to_uid(uid), index, key, ksize, value, vsize);
}
HL_PRIM vbyte *HL_NAME(get_lobby_member_data)( vuid lid, vuid uid, const char *key ) {
return (vbyte*)SteamMatchmaking()->GetLobbyMemberData(hl_to_uid(lid), hl_to_uid(uid), key );
}
HL_PRIM void HL_NAME(set_lobby_member_data)( vuid lid, const char *key, const char *value ) {
SteamMatchmaking()->SetLobbyMemberData(hl_to_uid(lid), key, value);
}
DEFINE_PRIM(_BOOL, request_lobby_data, _UID);
DEFINE_PRIM(_BYTES, get_lobby_data, _UID _BYTES);
DEFINE_PRIM(_BOOL, set_lobby_data, _UID _BYTES _BYTES);
DEFINE_PRIM(_BOOL, delete_lobby_data, _UID _BYTES);
DEFINE_PRIM(_I32, get_lobby_data_count, _UID);
DEFINE_PRIM(_BOOL, get_lobby_data_byindex, _UID _I32 _BYTES _I32 _BYTES _I32);
DEFINE_PRIM(_BYTES, get_lobby_member_data, _UID _UID _BYTES);
DEFINE_PRIM(_VOID, set_lobby_member_data, _UID _BYTES _BYTES);
// ---------
|
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.
#include "RTSPServer.hh"
#include "RTSPCommon.hh"
#include "RTSPRegisterSender.hh"
#include "Base64.hh"
#include <GroupsockHelper.hh>
#include "RsCommon.h"
#include "RsRTSPServer.hh"
#include "RsServerMediaSession.h"
#include "RsServerMediaSubsession.h"
#include "librealsense2/hpp/rs_options.hpp"
#include <ipDeviceCommon/RsCommon.h>
#include "RsUsageEnvironment.h"
// RTSPServer implementation
RsRTSPServer* RsRTSPServer::createNew(UsageEnvironment& t_env, std::shared_ptr<RsDevice> t_device, Port t_ourPort, UserAuthenticationDatabase* t_authDatabase, unsigned t_reclamationSeconds)
{
int ourSocket = setUpOurSocket(t_env, t_ourPort);
if(ourSocket == -1)
return NULL;
return new RsRTSPServer(t_env, t_device, ourSocket, t_ourPort, t_authDatabase, t_reclamationSeconds);
}
RsRTSPServer::RsRTSPServer(UsageEnvironment& t_env, std::shared_ptr<RsDevice> t_device, int t_ourSocket, Port t_ourPort, UserAuthenticationDatabase* t_authDatabase, unsigned t_reclamationSeconds)
: RTSPServer(t_env, t_ourSocket, t_ourPort, t_authDatabase, t_reclamationSeconds)
, m_device(t_device)
{}
RsRTSPServer::~RsRTSPServer() {}
std::string getOptionString(rs2_option t_opt, float t_min, float t_max, float t_def, float t_step)
{
std::ostringstream oss;
oss << (int)t_opt << "{" << t_min << "," << t_max << "," << t_def << "," << t_step << "}"
<< ";";
return oss.str();
}
char const* RsRTSPServer::allowedCommandNames()
{
m_supportedOptionsStr.clear();
for(const auto& optionsPair : m_supportedOptions)
{
m_supportedOptionsStr.append(optionsPair.first);
m_supportedOptionsStr.append("[");
for(auto option : optionsPair.second)
{
m_supportedOptionsStr.append(getOptionString(option.m_opt, option.m_range.min, option.m_range.max, option.m_range.def, option.m_range.step));
}
m_supportedOptionsStr.append("]");
}
return m_supportedOptionsStr.c_str();
}
void RsRTSPServer::setSupportedOptions(std::string t_key, std::vector<RsOption> t_supportedOptions)
{
m_supportedOptions.insert(std::pair<std::string, std::vector<RsOption>>(t_key, t_supportedOptions));
}
// RTSPServer::RTSPClientConnection implementation
RsRTSPServer::RsRTSPClientConnection ::RsRTSPClientConnection(RsRTSPServer& t_ourServer, int t_clientSocket, struct sockaddr_storage const& t_clientAddr)
: RTSPClientConnection(t_ourServer, t_clientSocket, t_clientAddr)
, m_fOurRsRTSPServer(t_ourServer)
{}
RsRTSPServer::RsRTSPClientConnection::~RsRTSPClientConnection() {}
void RsRTSPServer::RsRTSPClientConnection::handleCmd_DESCRIBE(char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr) {
fOurRTSPServer.closeAllClientSessionsForServerMediaSession(STEREO_SENSOR_NAME.c_str());
fOurRTSPServer.closeAllClientSessionsForServerMediaSession(RGB_SENSOR_NAME.c_str());
RTSPServer::RTSPClientConnection::handleCmd_DESCRIBE(urlPreSuffix, urlSuffix, fullRequestStr);
}
void RsRTSPServer::RsRTSPClientConnection::handleCmd_GET_PARAMETER(char const* t_fullRequestStr)
{
std::ostringstream oss;
std::vector<RsSensor> sensors;
std::string str(t_fullRequestStr);
std::string ContentLength("Content-Length:");
std::string afterSplit;
afterSplit = str.substr(str.find(ContentLength) + ContentLength.size());
char* contLength = strtok((char*)afterSplit.c_str(), "\r\n: ");
char* sensorName = strtok(NULL, "_\r\n:");
char* option = strtok(NULL, "\r\n:");
sensors = m_fOurRsRTSPServer.m_device.get()->getSensors();
for(auto sensor : sensors)
{
if(sensor.getSensorName().compare(sensorName) == 0)
{
try
{
float value = sensor.getRsSensor().get_option((rs2_option)stoi(std::string(option)));
char* paramString = new char[strlen(sensorName) + 1 + strlen(option) + strlen(std::to_string(value).c_str()) + 10];
sprintf(paramString, "%s_%s: %s\r\n", sensorName, option, std::to_string(value).c_str());
envir() << "GET_PARAMETER: sensor '" << sensorName << "', option '" << option << "', value " << value << "\n";
setRTSPResponse("200 OK", paramString);
return;
}
catch(const std::exception& e)
{
std::string error("500 " + std::string(e.what()));
setRTSPResponse(error.c_str());
return;
}
}
}
setRTSPResponse("500 Invalid Option");
}
void RsRTSPServer::RsRTSPClientConnection::handleCmd_SET_PARAMETER(char const* t_fullRequestStr)
{
std::ostringstream oss;
std::vector<RsSensor> sensors;
std::string str(t_fullRequestStr);
std::string ContentLength("Content-Length:");
std::string afterSplit; //, opt, val;
afterSplit = str.substr(str.find(ContentLength) + ContentLength.size());
char* contLength = strtok((char*)afterSplit.c_str(), "\r\n: ");
char* sensorName = strtok(NULL, "_\r\n:");
char* option = strtok(NULL, "\r\n:");
char* value = strtok(NULL, "\r\n:");
envir() << "SET_PARAMETER: sensor '" << sensorName << "', option '" << option << "', value " << value << "\n";
sensors = m_fOurRsRTSPServer.m_device.get()->getSensors();
for(auto sensor : sensors)
{
if(sensor.getSensorName().compare(sensorName) == 0)
{
try
{
sensor.getRsSensor().set_option((rs2_option)stoi(std::string(option)), stof(std::string(value)));
setRTSPResponse("200 OK");
return;
}
catch(const std::exception& e)
{
std::string error("500 " + std::string(e.what()));
setRTSPResponse(error.c_str());
return;
}
}
}
setRTSPResponse("500 Invalid Option");
}
// RsRTSPServer::RsRTSPClientSession implementation
RsRTSPServer::RsRTSPClientSession ::RsRTSPClientSession(RTSPServer& t_ourServer, u_int32_t t_sessionId)
: RTSPClientSession(t_ourServer, t_sessionId)
{}
RsRTSPServer::RsRTSPClientSession::~RsRTSPClientSession() {
try
{
closeRsCamera();
}
catch(const std::exception& e)
{
std::cout << "Camera closed already\n";
}
}
void RsRTSPServer::RsRTSPClientSession::handleCmd_TEARDOWN(RTSPClientConnection* t_ourClientConnection, ServerMediaSubsession* t_subsession)
{
envir() << "TEARDOWN \n";
try
{
closeRsCamera();
}
catch(const std::exception& e)
{
std::string error("500 " + std::string(e.what()));
setRTSPResponse(t_ourClientConnection, error.c_str());
return;
}
RTSPServer::RTSPClientSession::handleCmd_TEARDOWN(t_ourClientConnection, t_subsession);
}
void RsRTSPServer::RsRTSPClientSession::handleCmd_PLAY(RTSPClientConnection* t_ourClientConnection, ServerMediaSubsession* t_subsession, char const* t_fullRequestStr)
{
envir() << "PLAY \n";
try
{
openRsCamera();
}
catch(const std::exception& e)
{
std::string error("500 " + std::string(e.what()));
setRTSPResponse(t_ourClientConnection, error.c_str());
return;
}
RTSPServer::RTSPClientSession::handleCmd_PLAY(t_ourClientConnection, t_subsession, t_fullRequestStr);
}
void RsRTSPServer::RsRTSPClientSession::handleCmd_PAUSE(RTSPClientConnection* t_ourClientConnection, ServerMediaSubsession* t_subsession)
{
envir() << "PAUSE \n";
RTSPServer::RTSPClientSession::handleCmd_PAUSE(t_ourClientConnection, t_subsession);
try
{
closeRsCamera();
}
catch(const std::exception& e)
{
std::string error("500 " + std::string(e.what()));
setRTSPResponse(t_ourClientConnection, error.c_str());
return;
}
}
void RsRTSPServer::RsRTSPClientSession::handleCmd_GET_PARAMETER(RTSPClientConnection* t_ourClientConnection, ServerMediaSubsession* t_subsession, char const* t_fullRequestStr)
{
std::ostringstream oss;
std::vector<RsSensor> sensors;
std::string str(t_fullRequestStr);
std::string ContentLength("Content-Length:");
std::string afterSplit; //, opt, val;
envir() << "GET_PARAMETER\n";
afterSplit = str.substr(str.find(ContentLength) + ContentLength.size());
char* contLength = strtok((char*)afterSplit.c_str(), "\r\n: ");
char* sensorName = strtok(NULL, "_\r\n:");
char* option = strtok(NULL, "\r\n:");
try
{
float value = static_cast<RsServerMediaSession*>(fOurServerMediaSession)->getRsSensor().getRsSensor().get_option((rs2_option)stoi(std::string(option)));
char* paramString = new char[strlen(sensorName) + 1 + strlen(option) + strlen(std::to_string(value).c_str()) + 10];
sprintf(paramString, "%s_%s: %s\r\n", sensorName, option, std::to_string(value).c_str());
setRTSPResponse(t_ourClientConnection, "200 OK", paramString);
}
catch(const std::exception& e)
{
std::string error("500 " + std::string(e.what()));
setRTSPResponse(t_ourClientConnection, error.c_str());
return;
}
}
void RsRTSPServer::RsRTSPClientSession::handleCmd_SET_PARAMETER(RTSPClientConnection* t_ourClientConnection, ServerMediaSubsession* t_subsession, char const* t_fullRequestStr)
{
std::ostringstream oss;
std::vector<RsSensor> sensors;
std::string str(t_fullRequestStr);
std::string ContentLength("Content-Length:");
std::string afterSplit; //, opt, val;
envir() << "SET_PARAMETER \n";
afterSplit = str.substr(str.find(ContentLength) + ContentLength.size());
char* contLength = strtok((char*)afterSplit.c_str(), "\r\n: ");
char* sensorName = strtok(NULL, "_\r\n:");
char* option = strtok(NULL, "\r\n:");
char* value = strtok(NULL, "\r\n:");
try
{
static_cast<RsServerMediaSession*>(fOurServerMediaSession)->getRsSensor().getRsSensor().set_option((rs2_option)stoi(std::string(option)), stof(std::string(value)));
setRTSPResponse(t_ourClientConnection, "200 OK");
}
catch(const std::exception& e)
{
std::string error("500 " + std::string(e.what()));
setRTSPResponse(t_ourClientConnection, error.c_str());
return;
}
}
void RsRTSPServer::RsRTSPClientSession::handleCmd_SETUP(RTSPServer::RTSPClientConnection* t_ourClientConnection, char const* t_urlPreSuffix, char const* t_urlSuffix, char const* t_fullRequestStr)
{
RTSPServer::RTSPClientSession::handleCmd_SETUP(t_ourClientConnection, t_urlPreSuffix, t_urlSuffix, t_fullRequestStr);
ServerMediaSubsession* subsession;
if(t_urlSuffix[0] != '\0' && strcmp(fOurServerMediaSession->streamName(), t_urlPreSuffix) == 0)
{
// Non-aggregated operation.
// Look up the media subsession whose track id is "urlSuffix":
ServerMediaSubsessionIterator iter(*fOurServerMediaSession);
while((subsession = iter.next()) != NULL)
{
if(strcmp(subsession->trackId(), t_urlSuffix) == 0)
{
long long int profileKey = static_cast<RsServerMediaSession*>(fOurServerMediaSession)->getRsSensor().getStreamProfileKey(((RsServerMediaSubsession*)(subsession))->getStreamProfile());
m_streamProfiles[profileKey] = ((RsServerMediaSubsession*)(subsession))->getFrameQueue();
break; // success
}
}
}
}
void RsRTSPServer::RsRTSPClientSession::openRsCamera()
{
static_cast<RsServerMediaSession*>(fOurServerMediaSession)->openRsCamera(m_streamProfiles);
}
void RsRTSPServer::RsRTSPClientSession::closeRsCamera()
{
((RsServerMediaSession*)fOurServerMediaSession)->closeRsCamera();
for(int i = 0; i < fNumStreamStates; ++i)
{
if(fStreamStates[i].subsession != NULL)
{
long long int profile_key = static_cast<RsServerMediaSession*>(fOurServerMediaSession)->getRsSensor().getStreamProfileKey(((RsServerMediaSubsession*)(fStreamStates[i].subsession))->getStreamProfile());
emptyStreamProfileQueue(profile_key);
}
}
}
void RsRTSPServer::RsRTSPClientSession::emptyStreamProfileQueue(long long int profile_key)
{
rs2::frame f;
if(m_streamProfiles.find(profile_key) != m_streamProfiles.end())
{
while(m_streamProfiles[profile_key].poll_for_frame(&f))
;
}
}
GenericMediaServer::ClientConnection* RsRTSPServer::createNewClientConnection(int clientSocket, struct sockaddr_storage const& clientAddr)
{
return new RsRTSPClientConnection(*this, clientSocket, clientAddr);
}
GenericMediaServer::ClientSession* RsRTSPServer::createNewClientSession(u_int32_t t_sessionId)
{
return new RsRTSPClientSession(*this, t_sessionId);
}
|
/******************************************************************************
*
* Project: GDAL TileDB Driver
* Purpose: Implement GDAL TileDB Support based on https://www.tiledb.io
* Author: TileDB, Inc
*
******************************************************************************
* Copyright (c) 2019, TileDB, Inc
*
* 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.
****************************************************************************/
#include <cassert>
#include <list>
#include "cpl_string.h"
#include "gdal_frmts.h"
#include "gdal_pam.h"
#include "tiledb_headers.h"
CPL_CVSID("$Id$")
#ifdef _MSC_VER
#pragma warning( push )
// 'tiledb::Query::set_buffer': was declared deprecated
// 'tiledb::Array::Array': was declared deprecated
#pragma warning( disable : 4996 ) /* XXXX was deprecated */
#endif
const CPLString TILEDB_VALUES( "TDB_VALUES" );
/************************************************************************/
/* ==================================================================== */
/* TileDBDataset */
/* ==================================================================== */
/************************************************************************/
class TileDBRasterBand;
class TileDBDataset final: public GDALPamDataset
{
friend class TileDBRasterBand;
protected:
uint64_t nTimestamp = 0;
int nBitsPerSample = 8;
GDALDataType eDataType = GDT_Unknown;
int nBlockXSize = -1;
int nBlockYSize = -1;
int nBlocksX = 0;
int nBlocksY = 0;
int nBandStart = 1;
bool bGlobalOrder = false;
bool bHasSubDatasets = false;
int nSubDataCount = 0;
char **papszSubDatasets = nullptr;
CPLStringList m_osSubdatasetMD{};
CPLXMLNode* psSubDatasetsTree = nullptr;
CPLString osMetaDoc;
TILEDB_INTERLEAVE_MODE eIndexMode = BAND;
std::unique_ptr<tiledb::Context> m_ctx;
std::unique_ptr<tiledb::Context> m_roCtx;
std::unique_ptr<tiledb::Array> m_array;
std::unique_ptr<tiledb::Array> m_roArray;
std::unique_ptr<tiledb::ArraySchema> m_schema;
std::unique_ptr<tiledb::FilterList> m_filterList;
char **papszAttributes = nullptr;
std::list<std::unique_ptr<GDALDataset>> lpoAttributeDS = {};
bool bStats = FALSE;
CPLErr AddFilter( const char* pszFilterName, const int level );
CPLErr CreateAttribute( GDALDataType eType, const CPLString& osAttrName,
const int nSubRasterCount=1 );
CPLErr AddDimensions( tiledb::Domain& domain,
tiledb::Dimension& y,
tiledb::Dimension& x,
tiledb::Dimension* poBands=nullptr );
CPLErr IRasterIO( GDALRWFlag, int, int, int, int,
void *, int, int, GDALDataType,
int, int *,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg ) override;
public:
virtual ~TileDBDataset();
CPLErr TryLoadCachedXML(char **papszSiblingFiles = nullptr, bool bReload=true);
CPLErr TryLoadXML(char **papszSiblingFiles = nullptr) override;
CPLErr TrySaveXML() override;
char** GetMetadata(const char *pszDomain) override;
static GDALDataset *Open( GDALOpenInfo * );
static int Identify( GDALOpenInfo * );
static CPLErr Delete( const char * pszFilename );
static CPLErr CopySubDatasets( GDALDataset* poSrcDS,
TileDBDataset* poDstDS,
GDALProgressFunc pfnProgress,
void *pProgressData );
static TileDBDataset *CreateLL( const char * pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType, char ** papszOptions );
static GDALDataset *Create( const char * pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType, char ** papszOptions );
static GDALDataset *CreateCopy( const char * pszFilename,
GDALDataset *poSrcDS,
int bStrict, char ** papszOptions,
GDALProgressFunc pfnProgress,
void *pProgressData);
static void ErrorHandler( const std::string& msg );
static void SetBlockSize( GDALRasterBand* poBand,
char ** &papszOptions );
virtual void FlushCache( bool bAtClosing ) override;
};
/************************************************************************/
/* ==================================================================== */
/* TileDBRasterBand */
/* ==================================================================== */
/************************************************************************/
class TileDBRasterBand final: public GDALPamRasterBand
{
friend class TileDBDataset;
protected:
TileDBDataset *poGDS;
bool bStats;
CPLString osAttrName;
int nCurrBlockX = 0;
int nCurrBlockY = 0;
std::unique_ptr<tiledb::Query> m_query;
std::unique_ptr<tiledb::Query> m_roQuery;
void Finalize( );
public:
TileDBRasterBand( TileDBDataset *, int, CPLString = TILEDB_VALUES );
virtual CPLErr IReadBlock( int, int, void * ) override;
virtual CPLErr IWriteBlock( int, int, void * ) override;
virtual GDALColorInterp GetColorInterpretation() override;
};
static CPLString vsi_to_tiledb_uri( const char* pszUri )
{
CPLString osUri;
if ( STARTS_WITH_CI( pszUri, "/VSIS3/") )
osUri.Printf("s3://%s", pszUri + 7);
else if ( STARTS_WITH_CI( pszUri, "/VSIGS/") )
osUri.Printf("gcs://%s", pszUri + 7);
else
{
osUri = pszUri;
// tiledb (at least at 2.4.2 on Conda) wrongly interprets relative
// directories on Windows as absolute ones.
if( CPLIsFilenameRelative(pszUri) )
{
char* pszCurDir = CPLGetCurrentDir();
if( pszCurDir )
osUri = CPLFormFilename(pszCurDir, pszUri, nullptr);
CPLFree(pszCurDir);
}
}
return osUri;
}
static CPLErr option_to_index_type( const char* pszIndexingType, TILEDB_INTERLEAVE_MODE& eMode )
{
CPLErr eErr = CE_None;
if ( pszIndexingType )
{
if EQUAL( pszIndexingType, "BAND" )
eMode = BAND;
else if EQUAL( pszIndexingType, "ATTRIBUTES" )
eMode = ATTRIBUTES;
else if EQUAL( pszIndexingType, "PIXEL" )
eMode = PIXEL;
else
{
eErr = CE_Failure;
CPLError( eErr, CPLE_AppDefined,
"Unable to identify TileDB index mode %s.",
pszIndexingType );
}
}
else
{
eMode = BAND;
}
return eErr;
}
static const char* index_type_name( TILEDB_INTERLEAVE_MODE eMode )
{
switch ( eMode )
{
case PIXEL:
return "PIXEL";
case ATTRIBUTES:
return "ATTRIBUTES";
case BAND:
return "BAND";
default:
return nullptr;
}
}
/************************************************************************/
/* SetBuffer() */
/************************************************************************/
static CPLErr SetBuffer( tiledb::Query* poQuery, GDALDataType eType,
const CPLString& osAttrName, void * pImage, int nSize )
{
switch (eType)
{
case GDT_Byte:
poQuery->set_buffer(
osAttrName, reinterpret_cast<unsigned char*>( pImage ), nSize );
break;
case GDT_UInt16:
poQuery->set_buffer(
osAttrName, reinterpret_cast<unsigned short*>( pImage ), nSize );
break;
case GDT_UInt32:
poQuery->set_buffer(
osAttrName, reinterpret_cast<unsigned int*>( pImage ), nSize );
break;
case GDT_Int16:
poQuery->set_buffer(
osAttrName, reinterpret_cast<short*>( pImage ), nSize );
break;
case GDT_Int32:
poQuery->set_buffer(
osAttrName, reinterpret_cast<int*>( pImage ), nSize );
break;
case GDT_Float32:
poQuery->set_buffer(
osAttrName, reinterpret_cast<float*>( pImage ), nSize );
break;
case GDT_Float64:
poQuery->set_buffer(
osAttrName, reinterpret_cast<double*>( pImage ), nSize );
break;
case GDT_CInt16:
poQuery->set_buffer(
osAttrName, reinterpret_cast<short*>( pImage ), nSize * 2 );
break;
case GDT_CInt32:
poQuery->set_buffer(
osAttrName, reinterpret_cast<int*>( pImage ), nSize * 2 );
break;
case GDT_CFloat32:
poQuery->set_buffer(
osAttrName, reinterpret_cast<float*>( pImage ), nSize * 2 );
break;
case GDT_CFloat64:
poQuery->set_buffer(
osAttrName, reinterpret_cast<double*>( pImage ), nSize * 2 );
break;
default:
return CE_Failure;
}
return CE_None;
}
/************************************************************************/
/* TileDBRasterBand() */
/************************************************************************/
TileDBRasterBand::TileDBRasterBand(
TileDBDataset *poDSIn, int nBandIn, CPLString osAttr ) :
poGDS( poDSIn ),
bStats( poDSIn->bStats ),
osAttrName(osAttr)
{
poDS = poDSIn;
nBand = nBandIn;
eDataType = poGDS->eDataType;
eAccess = poGDS->eAccess;
nRasterXSize = poGDS->nRasterXSize;
nRasterYSize = poGDS->nRasterYSize;
nBlockXSize = poGDS->nBlockXSize;
nBlockYSize = poGDS->nBlockYSize;
m_query.reset(new tiledb::Query( *poGDS->m_ctx, *poGDS->m_array ) );
if ( ( eAccess == GA_Update ) && ( poGDS->m_roArray ) )
{
m_roQuery.reset( new tiledb::Query( *poGDS->m_roCtx, *poGDS->m_roArray ) );
m_roQuery->set_layout( TILEDB_ROW_MAJOR );
}
if ( poGDS->bGlobalOrder )
{
m_query->set_layout( TILEDB_GLOBAL_ORDER );
int nBandIdx = poGDS->nBandStart + nBand - 1;
// initialize to complete image block layout
std::vector<uint64_t> oaSubarray = { uint64_t( nBandIdx ),
uint64_t( nBandIdx ),
0,
uint64_t(poDSIn->nBlocksY) * nBlockYSize - 1,
0,
uint64_t(poDSIn->nBlocksX) * nBlockXSize - 1,
};
if ( poGDS->m_array->schema().domain().ndim() == 3 )
{
if ( poGDS->eIndexMode == PIXEL )
std::rotate( oaSubarray.begin(),
oaSubarray.begin() + 2,
oaSubarray.end() );
m_query->set_subarray( oaSubarray );
}
else
{
m_query->set_subarray( std::vector<uint64_t> (
oaSubarray.cbegin() + 2,
oaSubarray.cend() ) );
}
}
else
m_query->set_layout( TILEDB_ROW_MAJOR );
}
/************************************************************************/
/* Finalize() */
/************************************************************************/
void TileDBRasterBand::Finalize()
{
if ( poGDS->bGlobalOrder )
{
m_query->finalize();
}
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr TileDBRasterBand::IReadBlock( int nBlockXOff,
int nBlockYOff,
void * pImage )
{
int nStartX = nBlockXSize * nBlockXOff;
int nStartY = nBlockYSize * nBlockYOff;
uint64_t nEndX = nStartX + nBlockXSize;
uint64_t nEndY = nStartY + nBlockYSize;
int nBandIdx = poGDS->nBandStart + nBand - 1;
std::vector<uint64_t> oaSubarray = {
uint64_t( nBandIdx ),
uint64_t( nBandIdx ),
(uint64_t) nStartY,
(uint64_t) nEndY - 1,
(uint64_t) nStartX,
(uint64_t) nEndX - 1 };
if ( poGDS->eIndexMode == PIXEL )
std::rotate( oaSubarray.begin(),
oaSubarray.begin() + 2,
oaSubarray.end() );
tiledb::Query* q;
if ( ( eAccess == GA_Update ) && ( poGDS->m_roArray ) )
q = m_roQuery.get();
else
q = m_query.get();
if ( poGDS->m_array->schema().domain().ndim() == 3 )
{
q->set_subarray( oaSubarray );
}
else
{
q->set_subarray( std::vector<uint64_t> (
oaSubarray.cbegin() + 2,
oaSubarray.cend() ) );
}
SetBuffer(q, eDataType, osAttrName,
pImage, nBlockXSize * nBlockYSize );
if ( bStats )
tiledb::Stats::enable();
auto status = q->submit();
if ( bStats )
{
tiledb::Stats::dump(stdout);
tiledb::Stats::disable();
}
if ( ( status == tiledb::Query::Status::FAILED ) )
return CE_Failure;
else
return CE_None;
}
/************************************************************************/
/* IWriteBlock() */
/************************************************************************/
CPLErr TileDBRasterBand::IWriteBlock( int nBlockXOff,
int nBlockYOff, void * pImage )
{
if( eAccess == GA_ReadOnly )
{
CPLError( CE_Failure, CPLE_NoWriteAccess,
"Unable to write block, dataset is opened read only.\n" );
return CE_Failure;
}
CPLAssert( poGDS != nullptr
&& nBlockXOff >= 0
&& nBlockYOff >= 0
&& pImage != nullptr );
int nBandIdx = poGDS->nBandStart + nBand - 1;
if ( !poGDS->bGlobalOrder )
{
int nStartX = nBlockXSize * nBlockXOff;
int nStartY = nBlockYSize * nBlockYOff;
uint64_t nEndX = nStartX + nBlockXSize;
uint64_t nEndY = nStartY + nBlockYSize;
std::vector<uint64_t> oaSubarray = {
uint64_t( nBandIdx ),
uint64_t( nBandIdx ),
(uint64_t) nStartY,
(uint64_t) nEndY - 1,
(uint64_t) nStartX,
(uint64_t) nEndX - 1 };
if ( poGDS->eIndexMode == PIXEL )
std::rotate( oaSubarray.begin(),
oaSubarray.begin() + 2,
oaSubarray.end() );
if ( poGDS->eIndexMode == ATTRIBUTES )
{
m_query->set_subarray( std::vector<uint64_t> (
oaSubarray.cbegin() + 2,
oaSubarray.cend() ) );
}
else
{
m_query->set_subarray( oaSubarray );
}
}
else
{
// global order requires ordered blocks (see FlushCache(bool bAtClosing))
if ( ( nCurrBlockX != nBlockXOff ) || ( nCurrBlockY != nBlockYOff ) )
{ CPLError( CE_Failure, CPLE_AppDefined,
"Non-sequential global write to TileDB.\n");
return CE_Failure;
}
else
{
if ( ++nCurrBlockX == poGDS->nBlocksX )
{
nCurrBlockX = 0;
nCurrBlockY++;
}
}
}
std::vector<std::unique_ptr<void, decltype(&VSIFree)>> aBlocks;
if ( poGDS->lpoAttributeDS.size() > 0 )
{
for ( auto const& poAttrDS: poGDS->lpoAttributeDS )
{
GDALRasterBand* poAttrBand = poAttrDS->GetRasterBand( nBandIdx );
GDALDataType eAttrType = poAttrBand->GetRasterDataType();
int nBytes = GDALGetDataTypeSizeBytes( eAttrType );
int nValues = nBlockXSize * nBlockYSize;
void* pAttrBlock = VSIMalloc( nBytes * nValues );
aBlocks.emplace_back(pAttrBlock, &VSIFree);
if ( pAttrBlock == nullptr )
{
CPLError(CE_Failure, CPLE_OutOfMemory,
"Cannot allocate attribute buffer");
return CE_Failure;
}
int nXSize = nBlockXSize;
int nYSize = nBlockYSize;
if( nBlockXOff + nXSize > nRasterXSize )
nXSize = nRasterXSize - nBlockXOff;
if( nBlockYOff + nYSize > nRasterYSize )
nYSize = nRasterYSize - nBlockYOff;
poAttrBand->AdviseRead(
nBlockXOff, nBlockYOff, nXSize, nYSize,
nBlockXSize, nBlockYSize, eAttrType, nullptr
);
CPLErr eErr = poAttrBand->RasterIO(
GF_Read,
nBlockXOff, nBlockYOff, nXSize, nYSize,
pAttrBlock, nBlockXSize, nBlockYSize,
eAttrType, 0, 0, nullptr );
if ( eErr == CE_None )
{
CPLString osName = CPLString().Printf( "%s",
CPLGetBasename( poAttrDS->GetDescription() ) );
SetBuffer(m_query.get(), eAttrType,
osName,
pAttrBlock, nBlockXSize * nBlockYSize );
}
else
{
return eErr;
}
}
}
if ( poGDS->eIndexMode == ATTRIBUTES )
{
if ( nBand != poGDS->GetRasterCount() )
{
tiledb::Query* q = ( ( TileDBRasterBand* ) poGDS->GetRasterBand( poGDS->nBands ) )->m_query.get();
SetBuffer( q, eDataType, osAttrName,
pImage, nBlockXSize * nBlockYSize );
}
else
{
SetBuffer( m_query.get(), eDataType, osAttrName, pImage, nBlockXSize * nBlockYSize );
}
}
else
{
SetBuffer( m_query.get(), eDataType, osAttrName,
pImage, nBlockXSize * nBlockYSize );
}
if ( ( poGDS->eIndexMode != ATTRIBUTES) ||
( nBand == poGDS->GetRasterCount() ) )
{
if ( bStats )
tiledb::Stats::enable();
auto status = m_query->submit();
if ( bStats )
{
tiledb::Stats::dump(stdout);
tiledb::Stats::disable();
}
if (status == tiledb::Query::Status::FAILED)
return CE_Failure;
}
return CE_None;
}
/************************************************************************/
/* GetColorInterpretation() */
/************************************************************************/
GDALColorInterp TileDBRasterBand::GetColorInterpretation()
{
if (poGDS->nBands == 1)
return GCI_GrayIndex;
if ( nBand == 1 )
return GCI_RedBand;
else if( nBand == 2 )
return GCI_GreenBand;
else if ( nBand == 3 )
return GCI_BlueBand;
return GCI_AlphaBand;
}
/************************************************************************/
/* ==================================================================== */
/* TileDBDataset */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* ~TileDBDataset() */
/************************************************************************/
TileDBDataset::~TileDBDataset()
{
TileDBDataset::FlushCache(true);
// important to finalize arrays before closing array when updating
if ( bGlobalOrder )
{
for( auto&& poBand: GetBands() )
{
static_cast<TileDBRasterBand*>( poBand )->Finalize();
}
}
try
{
if( m_array )
{
m_array->close();
}
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
}
CPLDestroyXMLNode( psSubDatasetsTree );
CSLDestroy( papszSubDatasets );
CSLDestroy( papszAttributes );
}
/************************************************************************/
/* AddDimensions() */
/************************************************************************/
CPLErr TileDBDataset::AddDimensions( tiledb::Domain& domain,
tiledb::Dimension& y,
tiledb::Dimension& x,
tiledb::Dimension* poBands )
{
CPLErr eErr = CE_None;
switch ( eIndexMode )
{
case ATTRIBUTES:
domain.add_dimensions( y, x );
CreateAttribute( eDataType, TILEDB_VALUES, nBands );
break;
case PIXEL:
assert( poBands );
domain.add_dimensions( y, x, *poBands );
CreateAttribute( eDataType, TILEDB_VALUES, 1 );
break;
default: // BAND
assert( poBands );
domain.add_dimensions( *poBands, y, x );
CreateAttribute( eDataType, TILEDB_VALUES, 1 );
break;
}
return eErr;
}
/************************************************************************/
/* FlushCache() */
/************************************************************************/
void TileDBDataset::FlushCache(bool bAtClosing)
{
BlockBasedFlushCache(bAtClosing);
if( nPamFlags & GPF_DIRTY )
TrySaveXML();
}
/************************************************************************/
/* TrySaveXML() */
/************************************************************************/
CPLErr TileDBDataset::TrySaveXML()
{
if( m_array == nullptr )
return CE_None;
CPLXMLNode *psTree = nullptr;
try
{
tiledb::VFS vfs( *m_ctx, m_ctx->config() );
nPamFlags &= ~GPF_DIRTY;
if( psPam == nullptr || (nPamFlags & GPF_NOSAVE) )
return CE_None;
/* -------------------------------------------------------------------- */
/* Make sure we know the filename we want to store in. */
/* -------------------------------------------------------------------- */
if( !BuildPamFilename() )
return CE_None;
/* -------------------------------------------------------------------- */
/* Build the XML representation of the auxiliary metadata. */
/* -------------------------------------------------------------------- */
psTree = SerializeToXML( nullptr );
if( psTree == nullptr )
{
/* If we have unset all metadata, we have to delete the PAM file */
#if TILEDB_VERSION_MAJOR == 1 && TILEDB_VERSION_MINOR < 7
vfs.remove_file(psPam->pszPamFilename);
#else
m_array->delete_metadata("_gdal");
#endif
return CE_None;
}
if ( psSubDatasetsTree != nullptr )
{
CPLAddXMLChild( psTree, CPLCloneXMLTree( psSubDatasetsTree->psChild ) );
}
/* -------------------------------------------------------------------- */
/* If we are working with a subdataset, we need to integrate */
/* the subdataset tree within the whole existing pam tree, */
/* after removing any old version of the same subdataset. */
/* -------------------------------------------------------------------- */
if( !psPam->osSubdatasetName.empty() )
{
CPLXMLNode *psOldTree, *psSubTree;
CPLErrorReset();
{
CPLErrorHandlerPusher oQuietError( CPLQuietErrorHandler );
psOldTree = CPLParseXMLFile( psPam->pszPamFilename );
}
if( psOldTree == nullptr )
psOldTree = CPLCreateXMLNode( nullptr, CXT_Element, "PAMDataset" );
for( psSubTree = psOldTree->psChild;
psSubTree != nullptr;
psSubTree = psSubTree->psNext )
{
if( psSubTree->eType != CXT_Element
|| !EQUAL(psSubTree->pszValue,"Subdataset") )
continue;
if( !EQUAL(CPLGetXMLValue( psSubTree, "name", "" ),
psPam->osSubdatasetName) )
continue;
break;
}
if( psSubTree == nullptr )
{
psSubTree = CPLCreateXMLNode( psOldTree, CXT_Element,
"Subdataset" );
CPLCreateXMLNode(
CPLCreateXMLNode( psSubTree, CXT_Attribute, "name" ),
CXT_Text, psPam->osSubdatasetName );
}
CPLXMLNode *psOldPamDataset = CPLGetXMLNode( psSubTree, "PAMDataset");
if( psOldPamDataset != nullptr )
{
CPLRemoveXMLChild( psSubTree, psOldPamDataset );
CPLDestroyXMLNode( psOldPamDataset );
}
CPLAddXMLChild( psSubTree, psTree );
psTree = psOldTree;
}
/* -------------------------------------------------------------------- */
/* Try saving the auxiliary metadata. */
/* -------------------------------------------------------------------- */
bool bSaved = false;
CPLErrorHandlerPusher oQuietError( CPLQuietErrorHandler );
char* pszTree = CPLSerializeXMLTree( psTree );
#if TILEDB_VERSION_MAJOR > 1 || TILEDB_VERSION_MINOR >= 7
if ( eAccess == GA_ReadOnly )
{
if ( nTimestamp )
{
auto oMeta = std::unique_ptr<tiledb::Array>(
new tiledb::Array( *m_ctx, m_array->uri(), TILEDB_WRITE, nTimestamp )
);
oMeta->put_metadata("_gdal", TILEDB_UINT8, static_cast<int>(strlen( pszTree )), pszTree);
oMeta->close();
}
else
{
auto oMeta = std::unique_ptr<tiledb::Array>(
new tiledb::Array( *m_ctx, m_array->uri(), TILEDB_WRITE )
);
oMeta->put_metadata("_gdal", TILEDB_UINT8, static_cast<int>(strlen( pszTree )), pszTree);
oMeta->close();
}
}
else
{
m_array->put_metadata("_gdal", TILEDB_UINT8, static_cast<int>(strlen( pszTree )), pszTree);
}
bSaved = true;
#endif
// cppcheck-suppress knownConditionTrueFalse
if (!bSaved)
{
vfs.touch( psPam->pszPamFilename );
tiledb::VFS::filebuf fbuf( vfs );
fbuf.open( psPam->pszPamFilename, std::ios::out );
std::ostream os(&fbuf);
if (os.good())
{
os.write( pszTree, strlen(pszTree));
bSaved = true;
}
fbuf.close();
}
CPLFree( pszTree );
/* -------------------------------------------------------------------- */
/* If it fails, check if we have a proxy directory for auxiliary */
/* metadata to be stored in, and try to save there. */
/* -------------------------------------------------------------------- */
CPLErr eErr = CE_None;
if( bSaved )
eErr = CE_None;
else
{
const char *pszBasename = GetDescription();
if( psPam->osPhysicalFilename.length() > 0 )
pszBasename = psPam->osPhysicalFilename;
const char *pszNewPam = nullptr;
if( PamGetProxy(pszBasename) == nullptr
&& ((pszNewPam = PamAllocateProxy(pszBasename)) != nullptr))
{
CPLErrorReset();
CPLFree( psPam->pszPamFilename );
psPam->pszPamFilename = CPLStrdup(pszNewPam);
eErr = TrySaveXML();
}
/* No way we can save into a /vsicurl resource */
else if( !STARTS_WITH(psPam->pszPamFilename, "/vsicurl") )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Unable to save auxiliary information in %s.",
psPam->pszPamFilename );
eErr = CE_Warning;
}
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
if ( psTree )
CPLDestroyXMLNode( psTree );
return eErr;
}
catch(const std::exception& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
if ( psTree )
CPLDestroyXMLNode( psTree );
return CE_Failure;
}
}
/************************************************************************/
/* TryLoadXML() */
/************************************************************************/
CPLErr TileDBDataset::TryLoadXML( char ** papszSiblingFiles )
{
return TryLoadCachedXML( papszSiblingFiles, true );
}
/************************************************************************/
/* TryLoadCachedXML() */
/************************************************************************/
CPLErr TileDBDataset::TryLoadCachedXML( char ** /*papszSiblingFiles*/, bool bReload )
{
CPLXMLNode *psTree = nullptr;
try
{
PamInitialize();
tiledb::VFS vfs( *m_ctx, m_ctx->config() );
/* -------------------------------------------------------------------- */
/* Clear dirty flag. Generally when we get to this point is */
/* from a call at the end of the Open() method, and some calls */
/* may have already marked the PAM info as dirty (for instance */
/* setting metadata), but really everything to this point is */
/* reproducible, and so the PAM info should not really be */
/* thought of as dirty. */
/* -------------------------------------------------------------------- */
nPamFlags &= ~GPF_DIRTY;
/* -------------------------------------------------------------------- */
/* Try reading the file. */
/* -------------------------------------------------------------------- */
if( !BuildPamFilename() )
return CE_None;
/* -------------------------------------------------------------------- */
/* In case the PAM filename is a .aux.xml file next to the */
/* physical file and we have a siblings list, then we can skip */
/* stat'ing the filesystem. */
/* -------------------------------------------------------------------- */
CPLErr eLastErr = CPLGetLastErrorType();
int nLastErrNo = CPLGetLastErrorNo();
CPLString osLastErrorMsg = CPLGetLastErrorMsg();
CPLErrorReset();
{
CPLErrorHandlerPusher oQuietError( CPLQuietErrorHandler );
#if TILEDB_VERSION_MAJOR > 1 || TILEDB_VERSION_MINOR >= 7
if ( bReload )
{
tiledb_datatype_t v_type = TILEDB_UINT8; // CPLSerializeXMLTree returns char*
const void* v_r = nullptr;
uint32_t v_num = 0;
if ( ( eAccess == GA_Update ) && ( m_roArray ) )
{
m_roArray->get_metadata("_gdal", &v_type, &v_num, &v_r);
if ( v_r )
{
osMetaDoc = CPLString( static_cast<const char*>( v_r ), v_num);
}
}
else
{
m_array->get_metadata("_gdal", &v_type, &v_num, &v_r);
if ( v_r )
{
osMetaDoc = CPLString( static_cast<const char*>( v_r ), v_num);
}
}
psTree = CPLParseXMLString( osMetaDoc );
}
#endif
if ( bReload &&
psTree == nullptr &&
vfs.is_file( psPam->pszPamFilename ) )
{
auto nBytes = vfs.file_size( psPam->pszPamFilename );
tiledb::VFS::filebuf fbuf( vfs );
fbuf.open( psPam->pszPamFilename, std::ios::in );
std::istream is ( &fbuf );
osMetaDoc.resize(nBytes);
is.read( ( char* ) osMetaDoc.data(), nBytes );
fbuf.close();
psTree = CPLParseXMLString( osMetaDoc );
}
if ( !bReload )
{
psTree = CPLParseXMLString( osMetaDoc );
}
}
CPLErrorReset();
if( eLastErr != CE_None )
CPLErrorSetState( eLastErr, nLastErrNo, osLastErrorMsg.c_str() );
/* -------------------------------------------------------------------- */
/* If we are looking for a subdataset, search for its subtree not. */
/* -------------------------------------------------------------------- */
if( psTree && !psPam->osSubdatasetName.empty() )
{
CPLXMLNode *psSubTree = psTree->psChild;
for( ;
psSubTree != nullptr;
psSubTree = psSubTree->psNext )
{
if( psSubTree->eType != CXT_Element
|| !EQUAL(psSubTree->pszValue,"Subdataset") )
continue;
if( !EQUAL(CPLGetXMLValue( psSubTree, "name", "" ),
psPam->osSubdatasetName) )
continue;
psSubTree = CPLGetXMLNode( psSubTree, "PAMDataset" );
break;
}
if( psSubTree != nullptr )
psSubTree = CPLCloneXMLTree( psSubTree );
CPLDestroyXMLNode( psTree );
psTree = psSubTree;
}
if( psTree == nullptr )
return CE_Failure;
/* -------------------------------------------------------------------- */
/* Initialize ourselves from this XML tree. */
/* -------------------------------------------------------------------- */
CPLString osPath(CPLGetPath(psPam->pszPamFilename));
const CPLErr eErr = XMLInit( psTree, osPath );
CPLDestroyXMLNode( psTree );
if( eErr != CE_None )
PamClear();
return eErr;
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
if ( psTree )
CPLDestroyXMLNode( psTree );
return CE_Failure;
}
}
/************************************************************************/
/* GetMetadata() */
/************************************************************************/
char **TileDBDataset::GetMetadata(const char *pszDomain)
{
if( pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS") )
{
char** papszMeta = CSLDuplicate(GDALPamDataset::GetMetadata( pszDomain ));
for ( int i = 0; papszMeta && papszMeta[i];i++ )
{
if( STARTS_WITH(papszMeta[i], "SUBDATASET_") &&
strstr(papszMeta[i], "_NAME=") )
{
char* pszKey = nullptr;
const char* pszAttr = CPLParseNameValue(papszMeta[i], &pszKey);
if ( pszAttr && !STARTS_WITH( pszAttr, "TILEDB:" ) )
{
CPLString osAttr(pszAttr);
CPLFree( papszMeta[i] );
papszMeta[i] = CPLStrdup(
CPLString().Printf(
"%s=TILEDB:\"%s\":%s",
pszKey,
GetDescription(),
osAttr.c_str()
)
);
}
CPLFree(pszKey);
}
}
m_osSubdatasetMD.Assign(papszMeta);
return m_osSubdatasetMD.List();
}
else
{
return GDALPamDataset::GetMetadata( pszDomain );
}
}
/************************************************************************/
/* AddFilter() */
/************************************************************************/
CPLErr TileDBDataset::AddFilter( const char* pszFilterName, const int level )
{
try
{
if (pszFilterName == nullptr)
m_filterList->add_filter( tiledb::Filter( *m_ctx, TILEDB_FILTER_NONE )
.set_option( TILEDB_COMPRESSION_LEVEL, level ) );
else if EQUAL(pszFilterName, "GZIP")
m_filterList->add_filter( tiledb::Filter( *m_ctx, TILEDB_FILTER_GZIP )
.set_option( TILEDB_COMPRESSION_LEVEL, level ) );
else if EQUAL(pszFilterName, "ZSTD")
m_filterList->add_filter( tiledb::Filter( *m_ctx, TILEDB_FILTER_ZSTD )
.set_option( TILEDB_COMPRESSION_LEVEL, level ) );
else if EQUAL(pszFilterName, "LZ4")
m_filterList->add_filter( tiledb::Filter( *m_ctx, TILEDB_FILTER_LZ4 )
.set_option( TILEDB_COMPRESSION_LEVEL, level ) );
else if EQUAL(pszFilterName, "RLE")
m_filterList->add_filter( tiledb::Filter( *m_ctx, TILEDB_FILTER_RLE )
.set_option( TILEDB_COMPRESSION_LEVEL, level ) );
else if EQUAL(pszFilterName, "BZIP2")
m_filterList->add_filter( tiledb::Filter( *m_ctx, TILEDB_FILTER_BZIP2 )
.set_option( TILEDB_COMPRESSION_LEVEL, level ) );
else if EQUAL(pszFilterName, "DOUBLE-DELTA")
m_filterList->add_filter( tiledb::Filter( *m_ctx,
TILEDB_FILTER_DOUBLE_DELTA ) );
else if EQUAL(pszFilterName, "POSITIVE-DELTA")
m_filterList->add_filter( tiledb::Filter( *m_ctx,
TILEDB_FILTER_POSITIVE_DELTA ) );
else
return CE_Failure;
return CE_None;
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
return CE_Failure;
}
}
/************************************************************************/
/* Delete() */
/************************************************************************/
CPLErr TileDBDataset::Delete( const char * pszFilename )
{
try
{
tiledb::Context ctx;
tiledb::VFS vfs( ctx );
CPLString osArrayPath = vsi_to_tiledb_uri( pszFilename );
if ( vfs.is_dir( osArrayPath ) )
{
vfs.remove_dir( osArrayPath );
return CE_None;
}
else
return CE_Failure;
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
return CE_Failure;
}
}
/************************************************************************/
/* Identify() */
/************************************************************************/
int TileDBDataset::Identify( GDALOpenInfo * poOpenInfo )
{
if( STARTS_WITH_CI(poOpenInfo->pszFilename, "TILEDB:") )
{
return TRUE;
}
try
{
const char* pszConfig = CSLFetchNameValue(
poOpenInfo->papszOpenOptions, "TILEDB_CONFIG" );
if ( pszConfig != nullptr )
{
return TRUE;
}
if( poOpenInfo->bIsDirectory ||
( (STARTS_WITH_CI( poOpenInfo->pszFilename, "/VSIS3/" ) ||
STARTS_WITH_CI( poOpenInfo->pszFilename, "/VSIGS/" )) &&
!EQUAL(CPLGetExtension(poOpenInfo->pszFilename), "tif")) )
{
tiledb::Context ctx;
CPLString osArrayPath = vsi_to_tiledb_uri( poOpenInfo->pszFilename );
return tiledb::Object::object( ctx, osArrayPath ).type() == tiledb::Object::Type::Array;
}
return FALSE;
}
catch( ... )
{
return FALSE;
}
}
/************************************************************************/
/* Open() */
/************************************************************************/
GDALDataset *TileDBDataset::Open( GDALOpenInfo * poOpenInfo )
{
try
{
if( !Identify( poOpenInfo ) )
return nullptr;
auto poDS = cpl::make_unique<TileDBDataset>();
const char* pszConfig = CSLFetchNameValue(
poOpenInfo->papszOpenOptions,
"TILEDB_CONFIG" );
const char* pszTimestamp = CSLFetchNameValue(
poOpenInfo->papszOpenOptions,
"TILEDB_TIMESTAMP" );
if( pszConfig != nullptr )
{
tiledb::Config cfg( pszConfig );
poDS->m_ctx.reset( new tiledb::Context( cfg ) );
}
else
{
poDS->m_ctx.reset( new tiledb::Context() );
}
if ( pszTimestamp )
poDS->nTimestamp = atoi ( pszTimestamp );
CPLString osArrayPath;
CPLString osAux;
CPLString osSubdataset;
const char* pszAttr = CSLFetchNameValue(
poOpenInfo->papszOpenOptions,
"TILEDB_ATTRIBUTE" );
if( STARTS_WITH_CI(poOpenInfo->pszFilename, "TILEDB:") &&
!STARTS_WITH_CI(poOpenInfo->pszFilename, "TILEDB://") )
{
// form required read attributes and open file
// Create a corresponding GDALDataset.
CPLStringList apszName(
CSLTokenizeString2(poOpenInfo->pszFilename, ":",
CSLT_HONOURSTRINGS | CSLT_PRESERVEESCAPES));
if( apszName.size() != 3 )
{
return nullptr;
}
osArrayPath = vsi_to_tiledb_uri(apszName[1]);
osSubdataset = apszName[2];
poDS->SetSubdatasetName( osSubdataset.c_str() );
}
else
{
if ( pszAttr != nullptr )
{
poDS->SetSubdatasetName( pszAttr );
}
osArrayPath = vsi_to_tiledb_uri( poOpenInfo->pszFilename );
}
const char* pszArrayName = CPLGetBasename( osArrayPath );
osAux.Printf( "%s.tdb", pszArrayName );
// aux file is in array folder
poDS->SetPhysicalFilename( CPLFormFilename( osArrayPath, osAux, nullptr ) );
// Initialize any PAM information.
poDS->SetDescription( osArrayPath );
tiledb_query_type_t eMode = TILEDB_READ;
if ( poOpenInfo->eAccess == GA_Update )
{
eMode = TILEDB_WRITE;
poDS->m_roCtx.reset(new tiledb::Context( poDS->m_ctx->config() ) );
if ( poDS->nTimestamp )
poDS->m_roArray.reset(
new tiledb::Array( *poDS->m_roCtx, osArrayPath,
TILEDB_READ, poDS->nTimestamp ) );
else
poDS->m_roArray.reset(
new tiledb::Array( *poDS->m_roCtx, osArrayPath, TILEDB_READ )
);
}
if ( poDS->nTimestamp )
poDS->m_array.reset(
new tiledb::Array( *poDS->m_ctx, osArrayPath,
eMode, poDS->nTimestamp ) );
else
poDS->m_array.reset(
new tiledb::Array( *poDS->m_ctx, osArrayPath, eMode ) );
poDS->eAccess = poOpenInfo->eAccess;
// dependent on PAM metadata for information about array
poDS->TryLoadXML();
tiledb::ArraySchema schema = poDS->m_array->schema();
char ** papszStructMeta = poDS->GetMetadata( "IMAGE_STRUCTURE" );
const char* pszXSize = CSLFetchNameValue( papszStructMeta, "X_SIZE");
if ( pszXSize )
{
poDS->nRasterXSize = atoi( pszXSize );
if ( poDS->nRasterXSize <= 0 )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Width %i should be greater than zero.", poDS->nRasterXSize );
return nullptr;
}
}
const char* pszYSize = CSLFetchNameValue( papszStructMeta, "Y_SIZE");
if ( pszYSize )
{
poDS->nRasterYSize = atoi( pszYSize );
if ( poDS->nRasterYSize <= 0 )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Height %i should be greater than zero.", poDS->nRasterYSize );
return nullptr;
}
}
const char* pszNBits = CSLFetchNameValue( papszStructMeta, "NBITS");
if ( pszNBits )
{
poDS->nBitsPerSample = atoi( pszNBits );
}
const char* pszDataType = CSLFetchNameValue( papszStructMeta, "DATA_TYPE");
if ( pszDataType )
{
// handle the case where arrays have been written with int type (2.5.0)
GDALDataType eDT = GDALGetDataTypeByName( pszDataType );
if ( eDT == GDT_Unknown )
{
int t = atoi( pszDataType );
if ( ( t > 0 ) && ( t < GDT_TypeCount ) )
poDS->eDataType = static_cast<GDALDataType>( atoi( pszDataType ) );
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Unknown data type %s.", pszDataType );
return nullptr;
}
}
else
{
poDS->eDataType = eDT;
}
}
const char* pszIndexMode = CSLFetchNameValue( papszStructMeta, "INTERLEAVE");
if ( pszIndexMode )
option_to_index_type( pszIndexMode, poDS->eIndexMode );
std::vector<tiledb::Dimension> dims = schema.domain().dimensions();
if( ( dims.size() == 2 ) || ( dims.size() == 3) )
{
if ( dims.size() == 3 )
{
if ( ( pszAttr != nullptr ) && ( schema.attributes().count( pszAttr ) == 0 ) )
{
CPLError( CE_Failure, CPLE_NotSupported,
"%s attribute is not found in TileDB schema.",
pszAttr );
return nullptr;
}
if ( poDS->eIndexMode == PIXEL )
std::rotate( dims.begin(), dims.begin() + 2, dims.end() );
poDS->nBandStart = static_cast<int>(dims[0].domain<uint64_t>().first);
poDS->nBands = static_cast<int>(dims[0].domain<uint64_t>().second
- dims[0].domain<uint64_t>().first + 1);
poDS->nBlockYSize = static_cast<int>(dims[1].tile_extent<uint64_t>());
poDS->nBlockXSize = static_cast<int>(dims[2].tile_extent<uint64_t>());
}
else
{
const char* pszBands = poDS->GetMetadataItem("NUM_BANDS",
"IMAGE_STRUCTURE");
if ( pszBands )
{
poDS->nBands = atoi( pszBands );
poDS->nBlockYSize = static_cast<int>(dims[0].tile_extent<uint64_t>());
poDS->nBlockXSize = static_cast<int>(dims[1].tile_extent<uint64_t>());
}
poDS->eIndexMode = ATTRIBUTES;
}
}
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Wrong number of dimensions %li expected 2 or 3.", dims.size() );
return nullptr;
}
poDS->nBlocksX = DIV_ROUND_UP( poDS->nRasterXSize, poDS->nBlockXSize );
poDS->nBlocksY = DIV_ROUND_UP( poDS->nRasterYSize, poDS->nBlockYSize );
if ( dims.size() == 3 )
{
// Create band information objects.
for ( int i = 1;i <= poDS->nBands;++i )
{
if ( pszAttr == nullptr )
poDS->SetBand( i, new TileDBRasterBand( poDS.get(), i ) );
else
poDS->SetBand( i,
new TileDBRasterBand(
poDS.get(), i, CPLString( pszAttr ) ) );
}
}
else // subdatasets or only attributes
{
if ( ( poOpenInfo->eAccess == GA_Update ) &&
( poDS->GetMetadata( "SUBDATASETS" ) != nullptr ) )
{
CPLError( CE_Failure, CPLE_NotSupported,
"The TileDB driver does not support update access "
"to subdatasets." );
return nullptr;
}
if( !osSubdataset.empty() )
{
// do we have the attribute in the schema
if ( schema.attributes().count( osSubdataset ) )
{
poDS->SetBand(1,
new TileDBRasterBand(
poDS.get(), 1, osSubdataset ) );
}
else
{
if ( schema.attributes().count( osSubdataset + "_1" ) )
{
// Create band information objects.
for ( int i = 1;i <= poDS->nBands;++i )
{
CPLString osAttr = CPLString().Printf("%s_%d",
osSubdataset.c_str(), i);
poDS->SetBand( i,
new TileDBRasterBand(
poDS.get(), i,
osAttr ) );
}
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"%s attribute is not found in TileDB schema.",
osSubdataset.c_str() );
return nullptr;
}
}
}
else
{
char** papszMeta = poDS->GetMetadata( "SUBDATASETS" );
if ( papszMeta != nullptr )
{
if ( ( CSLCount( papszMeta ) / 2 ) == 1 )
{
CPLString osDSName =
CSLFetchNameValueDef(poDS->papszSubDatasets,
"SUBDATASET_1_NAME", "");
return (GDALDataset *)GDALOpen( osDSName, poOpenInfo->eAccess );
}
}
else if ( poDS->eIndexMode == ATTRIBUTES )
{
poDS->nBands = schema.attribute_num();
poDS->nBlockYSize = static_cast<int>(dims[0].tile_extent<uint64_t>());
poDS->nBlockXSize = static_cast<int>(dims[1].tile_extent<uint64_t>());
// Create band information objects.
for ( int i = 1;i <= poDS->nBands;++i )
{
CPLString osAttr = TILEDB_VALUES + CPLString().Printf( "_%i", i+1 );
poDS->SetBand( i,
new TileDBRasterBand(
poDS.get(), i,
osAttr ) );
}
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"%s is missing required TileDB subdataset metadata.",
osArrayPath.c_str() );
return nullptr;
}
}
}
// reload metadata now that bands are created to populate band metadata
poDS->TryLoadCachedXML( nullptr, false );
tiledb::VFS vfs( *poDS->m_ctx, poDS->m_ctx->config() );
if ( !STARTS_WITH_CI(osArrayPath, "TILEDB:")
&& vfs.is_dir( osArrayPath ) )
poDS->oOvManager.Initialize( poDS.get(), ":::VIRTUAL:::" );
else
CPLError( CE_Warning, CPLE_AppDefined,
"Overviews not supported for network writes." );
return poDS.release();
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
return nullptr;
}
}
/************************************************************************/
/* CreateAttribute() */
/************************************************************************/
CPLErr TileDBDataset::CreateAttribute( GDALDataType eType,
const CPLString& osAttrName, const int nSubRasterCount )
{
try
{
for ( int i = 0; i < nSubRasterCount;++i )
{
CPLString osName( osAttrName );
// a few special cases
// remove any leading slashes or
// additional slashes as in the case of hdf5
if STARTS_WITH( osName, "//" )
{
osName = osName.substr(2);
}
osName.replaceAll( "/", "_" );
CPLString osPrettyName = osName;
if ( ( eIndexMode == ATTRIBUTES ) ||
( ( bHasSubDatasets ) && ( nSubRasterCount > 1 ) ) )
{
osName = CPLString().Printf( "%s_%d", osName.c_str(), i + 1);
}
switch (eType)
{
case GDT_Byte:
{
m_schema->add_attribute( tiledb::Attribute::create<unsigned char>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 8;
break;
}
case GDT_UInt16:
{
m_schema->add_attribute( tiledb::Attribute::create<unsigned short>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 16;
break;
}
case GDT_UInt32:
{
m_schema->add_attribute( tiledb::Attribute::create<unsigned int>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 32;
break;
}
case GDT_Int16:
{
m_schema->add_attribute( tiledb::Attribute::create<short>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 16;
break;
}
case GDT_Int32:
{
m_schema->add_attribute( tiledb::Attribute::create<int>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 32;
break;
}
case GDT_Float32:
{
m_schema->add_attribute( tiledb::Attribute::create<float>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 32;
break;
}
case GDT_Float64:
{
m_schema->add_attribute( tiledb::Attribute::create<double>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 64;
break;
}
case GDT_CInt16:
{
m_schema->add_attribute( tiledb::Attribute::create<short[2]>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 16;
break;
}
case GDT_CInt32:
{
m_schema->add_attribute( tiledb::Attribute::create<int[2]>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 32;
break;
}
case GDT_CFloat32:
{
m_schema->add_attribute( tiledb::Attribute::create<float[2]>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 32;
break;
}
case GDT_CFloat64:
{
m_schema->add_attribute( tiledb::Attribute::create<double[2]>( *m_ctx, osName, *m_filterList ) );
nBitsPerSample = 64;
break;
}
default:
return CE_Failure;
}
if ( ( bHasSubDatasets ) && ( i == 0 ) )
{
++nSubDataCount;
CPLString osDim;
switch( nSubRasterCount )
{
case 2:
osDim.Printf( "%dx%d", nRasterXSize, nRasterYSize );
break;
default:
osDim.Printf( "%dx%dx%d", nSubRasterCount,
nRasterXSize, nRasterYSize );
break;
}
papszSubDatasets = CSLSetNameValue( papszSubDatasets,
CPLString().Printf( "SUBDATASET_%d_NAME",
nSubDataCount ),
CPLString().Printf( "%s", osPrettyName.c_str() ) );
papszSubDatasets = CSLSetNameValue( papszSubDatasets,
CPLString().Printf( "SUBDATASET_%d_DESC", nSubDataCount ),
CPLString().Printf( "[%s] %s (%s)",
osDim.c_str(),
osPrettyName.c_str(),
GDALGetDataTypeName( eType )
) );
// add to PAM metadata
if ( psSubDatasetsTree == nullptr )
{
psSubDatasetsTree = CPLCreateXMLNode( nullptr,
CXT_Element, "PAMDataset" );
}
CPLXMLNode* psSubNode = CPLCreateXMLNode(
psSubDatasetsTree, CXT_Element, "Subdataset" );
CPLAddXMLAttributeAndValue( psSubNode, "name", osPrettyName.c_str() );
CPLXMLNode* psMetaNode = CPLCreateXMLNode(
CPLCreateXMLNode(
psSubNode, CXT_Element, "PAMDataset" ),
CXT_Element, "Metadata");
CPLAddXMLAttributeAndValue( psMetaNode, "domain", "IMAGE_STRUCTURE" );
CPLAddXMLAttributeAndValue(
CPLCreateXMLElementAndValue( psMetaNode, "MDI",
CPLString().Printf( "%d", nRasterXSize ) ),
"KEY",
"X_SIZE"
);
CPLAddXMLAttributeAndValue(
CPLCreateXMLElementAndValue( psMetaNode, "MDI",
CPLString().Printf( "%d", nRasterYSize ) ),
"KEY",
"Y_SIZE"
);
CPLAddXMLAttributeAndValue(
CPLCreateXMLElementAndValue( psMetaNode, "MDI",
CPLString().Printf( "%s", GDALGetDataTypeName( eType ) ) ),
"KEY",
"DATA_TYPE"
);
if ( lpoAttributeDS.size() > 0 )
{
CPLAddXMLAttributeAndValue(
CPLCreateXMLElementAndValue( psMetaNode, "MDI",
CPLString().Printf( "%d", nBands ) ),
"KEY",
"NUM_BANDS"
);
}
else
{
CPLAddXMLAttributeAndValue(
CPLCreateXMLElementAndValue( psMetaNode, "MDI",
CPLString().Printf( "%d", nSubRasterCount ) ),
"KEY",
"NUM_BANDS"
);
}
CPLAddXMLAttributeAndValue(
CPLCreateXMLElementAndValue( psMetaNode, "MDI",
CPLString().Printf( "%d", nBitsPerSample ) ),
"KEY",
"NBITS"
);
}
}
return CE_None;
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
return CE_Failure;
}
}
/************************************************************************/
/* SetBlockSize() */
/************************************************************************/
void TileDBDataset::SetBlockSize( GDALRasterBand* poBand, char** &papszOptions)
{
int nX = 0;
int nY = 0;
poBand->GetBlockSize( &nX, &nY );
if ( CSLFetchNameValue(papszOptions, "BLOCKXSIZE") == nullptr )
{
papszOptions = CSLSetNameValue(
papszOptions, "BLOCKXSIZE",
CPLString().Printf( "%d", nX ) );
}
if ( CSLFetchNameValue(papszOptions, "BLOCKYSIZE") == nullptr )
{
papszOptions = CSLSetNameValue(
papszOptions, "BLOCKYSIZE",
CPLString().Printf( "%d", nY ) );
}
}
/************************************************************************/
/* CreateLL() */
/* */
/* Shared functionality between TileDBDataset::Create() and */
/* TileDBDataset::CreateCopy() for creating TileDB array based on */
/* a set of options and a configuration. */
/************************************************************************/
TileDBDataset* TileDBDataset::CreateLL( const char *pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType,
char **papszOptions )
{
try
{
if( ( nXSize <= 0 && nYSize <= 0 ) )
{
return nullptr;
}
auto poDS = cpl::make_unique<TileDBDataset>();
poDS->nRasterXSize = nXSize;
poDS->nRasterYSize = nYSize;
poDS->eDataType = eType;
poDS->nBands = nBands;
poDS->eAccess = GA_Update;
poDS->bGlobalOrder = true;
if ( nBands == 0 ) // subdatasets
{
poDS->eIndexMode = ATTRIBUTES;
}
else
{
const char* pszIndexMode = CSLFetchNameValue(
papszOptions, "INTERLEAVE" );
if ( option_to_index_type( pszIndexMode, poDS->eIndexMode ) )
return nullptr;
}
const char* pszConfig = CSLFetchNameValue( papszOptions, "TILEDB_CONFIG" );
if( pszConfig != nullptr )
{
tiledb::Config cfg( pszConfig );
poDS->m_ctx.reset( new tiledb::Context( cfg ) );
}
else
{
poDS->m_ctx.reset( new tiledb::Context() );
}
const char* pszCompression = CSLFetchNameValue(
papszOptions, "COMPRESSION" );
const char* pszCompressionLevel = CSLFetchNameValue(
papszOptions, "COMPRESSION_LEVEL" );
const char* pszBlockXSize = CSLFetchNameValue( papszOptions, "BLOCKXSIZE" );
poDS->nBlockXSize = ( pszBlockXSize ) ? atoi( pszBlockXSize ) : 256;
const char* pszBlockYSize = CSLFetchNameValue( papszOptions, "BLOCKYSIZE" );
poDS->nBlockYSize = ( pszBlockYSize ) ? atoi( pszBlockYSize ) : 256;
poDS->bStats = CSLFetchBoolean( papszOptions, "STATS", FALSE );
const char* pszTimestamp = CSLFetchNameValue(
papszOptions,
"TILEDB_TIMESTAMP" );
if ( pszTimestamp != nullptr )
poDS->nTimestamp = atoi( pszTimestamp );
// set dimensions and attribute type for schema
poDS->m_schema.reset( new tiledb::ArraySchema( *poDS->m_ctx, TILEDB_DENSE ) );
poDS->m_schema->set_tile_order( TILEDB_ROW_MAJOR );
poDS->m_schema->set_cell_order( TILEDB_ROW_MAJOR );
poDS->m_filterList.reset(new tiledb::FilterList(*poDS->m_ctx));
if (pszCompression != nullptr)
{
int nLevel = ( pszCompressionLevel ) ? atoi( pszCompressionLevel ) : -1;
if ( poDS->AddFilter( pszCompression, nLevel ) == CE_None )
{
poDS->SetMetadataItem( "COMPRESSION", pszCompression,
"IMAGE_STRUCTURE" );
poDS->m_schema->set_coords_filter_list( *poDS->m_filterList );
}
}
CPLString osAux;
const char* pszArrayName = CPLGetBasename( pszFilename );
osAux.Printf( "%s.tdb", pszArrayName );
poDS->SetPhysicalFilename( CPLFormFilename(
pszFilename, osAux.c_str(), nullptr ) );
// Initialize PAM information.
poDS->SetDescription( pszFilename );
// this driver enforces that all subdatasets are the same size
tiledb::Domain domain( *poDS->m_ctx );
// Note the dimension bounds are inclusive and are expanded to the match the block size
poDS->nBlocksX = DIV_ROUND_UP( nXSize, poDS->nBlockXSize );
poDS->nBlocksY = DIV_ROUND_UP( nYSize, poDS->nBlockYSize );
uint64_t w = (uint64_t)poDS->nBlocksX * poDS->nBlockXSize - 1;
uint64_t h = (uint64_t)poDS->nBlocksY * poDS->nBlockYSize - 1;
auto d1 = tiledb::Dimension::create<uint64_t>(
*poDS->m_ctx, "X", {0, w},
uint64_t( poDS->nBlockXSize ) );
auto d2 = tiledb::Dimension::create<uint64_t>(
*poDS->m_ctx, "Y",{0, h},
uint64_t( poDS->nBlockYSize ) );
if ( ( nBands == 0 ) || ( poDS->eIndexMode == ATTRIBUTES ) )
{
poDS->AddDimensions( domain, d2, d1, nullptr );
}
else
{
auto d3 = tiledb::Dimension::create<uint64_t>( *poDS->m_ctx, "BANDS", {1, uint64_t( nBands )}, 1);
poDS->AddDimensions( domain, d2, d1, &d3 );
}
poDS->m_schema->set_domain( domain ).set_order({{TILEDB_ROW_MAJOR, TILEDB_ROW_MAJOR}});;
// register additional attributes to the pixel value, these will be
// be reported as subdatasets on future reads
poDS->papszAttributes = CSLFetchNameValueMultiple(
papszOptions, "TILEDB_ATTRIBUTE" );
for( int i = 0;
poDS->papszAttributes != nullptr &&
poDS->papszAttributes[i] != nullptr;
i++ )
{
// modeling additional attributes as subdatasets
poDS->bHasSubDatasets = true;
// check each attribute is a GDAL source
std::unique_ptr<GDALDataset> poAttrDS(
GDALDataset::Open( poDS->papszAttributes[i],
GA_ReadOnly ));
if ( poAttrDS != nullptr )
{
const char* pszAttrName = CPLGetBasename(
poAttrDS->GetDescription());
// check each is co-registered
// candidate band
int nAttrBands = poAttrDS->GetRasterCount();
if ( nAttrBands > 0 )
{
GDALRasterBand* poAttrBand = poAttrDS->GetRasterBand( 1 );
if ( ( poAttrBand->GetXSize() == poDS->nRasterXSize )
&& ( poAttrBand->GetYSize() == poDS->nRasterYSize )
&& ( poDS->nBands == nAttrBands ) )
{
// could check geotransform, but it is sufficient
// that cartesian dimensions are equal
poDS->lpoAttributeDS.push_back( std::move( poAttrDS ) );
poDS->CreateAttribute( poAttrBand->GetRasterDataType(),
pszAttrName,
1
);
}
else
{
CPLError( CE_Warning, CPLE_AppDefined,
"Skipping %s as it has a different dimension\n",
poDS->papszAttributes[i]);
}
}
else
{
CPLError( CE_Warning, CPLE_AppDefined,
"Skipping %s as it doesn't have any bands\n",
poDS->papszAttributes[i]);
}
}
else
{
CPLError( CE_Warning, CPLE_AppDefined,
"Skipping %s, not recognized as a GDAL dataset\n",
poDS->papszAttributes[i]);
}
}
return poDS.release();
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "TileDB: %s", e.what() );
return nullptr;
}
}
/************************************************************************/
/* CopySubDatasets() */
/* */
/* Copy SubDatasets from src to a TileDBDataset */
/* */
/************************************************************************/
CPLErr TileDBDataset::CopySubDatasets( GDALDataset* poSrcDS,
TileDBDataset* poDstDS,
GDALProgressFunc pfnProgress,
void *pProgressData )
{
try
{
std::vector<std::unique_ptr<GDALDataset>> apoDatasets;
poDstDS->bHasSubDatasets = true;
char ** papszSrcSubDatasets = poSrcDS->GetMetadata( "SUBDATASETS" );
if( !papszSrcSubDatasets )
return CE_Failure;
const char* pszSubDSName = CSLFetchNameValue(papszSrcSubDatasets,
"SUBDATASET_1_NAME");
if( !pszSubDSName )
return CE_Failure;
CPLStringList apszTokens(
CSLTokenizeString2(pszSubDSName, ":",
CSLT_HONOURSTRINGS | CSLT_PRESERVEESCAPES));
// FIXME? this is tailored for HDF5-like subdataset names
// HDF5:foo.hdf5:attrname.
if( apszTokens.size() != 3 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot guess attribute name in %s", pszSubDSName);
return CE_Failure;
}
std::unique_ptr<GDALDataset> poSubDataset(GDALDataset::Open(pszSubDSName));
if( poSubDataset.get() == nullptr || poSubDataset->GetRasterCount() == 0 )
{
return CE_Failure;
}
uint64_t nSubXSize = poSubDataset->GetRasterXSize();
uint64_t nSubYSize = poSubDataset->GetRasterYSize();
const char* pszAttrName = apszTokens[2];
poDstDS->CreateAttribute( poSubDataset->GetRasterBand( 1 )
->GetRasterDataType(),
pszAttrName,
poSubDataset->GetRasterCount() );
apoDatasets.push_back( std::move(poSubDataset) );
for( int i = 0; papszSrcSubDatasets[i] != nullptr;i ++ )
{
if( STARTS_WITH_CI(papszSrcSubDatasets[i], "SUBDATASET_1_NAME=") ||
strstr(papszSrcSubDatasets[i], "_DESC=") )
{
continue;
}
pszSubDSName = CPLParseNameValue(papszSrcSubDatasets[i], nullptr);
apszTokens =
CSLTokenizeString2(pszSubDSName, ":",
CSLT_HONOURSTRINGS | CSLT_PRESERVEESCAPES);
if( apszTokens.size() != 3 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot guess attribute name in %s", pszSubDSName);
continue;
}
std::unique_ptr<GDALDataset> poSubDS(GDALDataset::Open(pszSubDSName));
if ( ( poSubDS != nullptr ) && poSubDS->GetRasterCount() > 0 )
{
GDALRasterBand* poBand = poSubDS->GetRasterBand( 1 );
int nBlockXSize, nBlockYSize;
poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
if ( ( poSubDS->GetRasterXSize() != (int) nSubXSize ) ||
( poSubDS->GetRasterYSize() != (int) nSubYSize ) ||
( nBlockXSize != poDstDS->nBlockXSize) ||
( nBlockYSize != poDstDS->nBlockYSize ))
{
CPLError( CE_Warning, CPLE_AppDefined,
"Sub-datasets must have the same dimension,"
" and block sizes, skipping %s\n",
pszSubDSName );
}
else
{
pszAttrName = apszTokens[2];
poDstDS->CreateAttribute(
poSubDS->GetRasterBand(1)->GetRasterDataType(),
pszAttrName, poSubDS->GetRasterCount() );
apoDatasets.push_back( std::move(poSubDS) );
}
}
else
{
CPLError( CE_Warning, CPLE_AppDefined,
"Sub-datasets must be not null and contain data in bands,"
"skipping %s\n",
pszSubDSName );
}
}
poDstDS->SetMetadata( poDstDS->papszSubDatasets, "SUBDATASETS" );
tiledb::Array::create( poDstDS->GetDescription(), *poDstDS->m_schema );
if ( poDstDS->nTimestamp )
poDstDS->m_array.reset( new tiledb::Array(
*poDstDS->m_ctx, poDstDS->GetDescription(),
TILEDB_WRITE, poDstDS->nTimestamp ) );
else
poDstDS->m_array.reset( new tiledb::Array(
*poDstDS->m_ctx, poDstDS->GetDescription(), TILEDB_WRITE ) );
/* -------------------------------------------------------- */
/* Report preliminary (0) progress. */
/* --------------------------------------------------------- */
if( !pfnProgress( 0.0, nullptr, pProgressData ) )
{
CPLError( CE_Failure, CPLE_UserInterrupt,
"User terminated CreateCopy()" );
return CE_Failure;
}
// copy over subdatasets by block
tiledb::Query query( *poDstDS->m_ctx, *poDstDS->m_array );
query.set_layout( TILEDB_GLOBAL_ORDER );
int nTotalBlocks = poDstDS->nBlocksX * poDstDS->nBlocksY;
// row-major
for ( int j = 0; j < poDstDS->nBlocksY;++j )
{
for ( int i = 0; i < poDstDS->nBlocksX;++i)
{
std::vector<std::unique_ptr<void, decltype(&VSIFree)>> aBlocks;
// have to write set all tiledb attributes on write
int iAttr = 0;
for ( auto& poSubDS : apoDatasets )
{
GDALDataType eDT = poSubDS->GetRasterBand( 1 )->
GetRasterDataType();
for ( int b = 1;b <= poSubDS->GetRasterCount();++b )
{
int nBytes = GDALGetDataTypeSizeBytes( eDT );
int nValues = nBytes * poDstDS->nBlockXSize * poDstDS->nBlockYSize;
void* pBlock = VSIMalloc( nBytes * nValues );
aBlocks.emplace_back( pBlock, &VSIFree );
GDALRasterBand* poBand = poSubDS->GetRasterBand( b );
if ( poBand->ReadBlock( i, j, pBlock ) == CE_None )
{
SetBuffer( &query, eDT,
poDstDS->m_schema->attribute( iAttr++ ).name(),
pBlock, poDstDS->nBlockXSize * poDstDS->nBlockYSize );
}
}
}
if ( poDstDS->bStats )
tiledb::Stats::enable();
auto status = query.submit();
if ( poDstDS->bStats )
{
tiledb::Stats::dump(stdout);
tiledb::Stats::disable();
}
if ( status == tiledb::Query::Status::FAILED )
{
return CE_Failure;
}
int nBlocks = ( (j + 1) * poDstDS->nBlocksX );
if( !pfnProgress( nBlocks / static_cast<double>( nTotalBlocks),
nullptr, pProgressData ) )
{
CPLError( CE_Failure, CPLE_UserInterrupt,
"User terminated CreateCopy()" );
return CE_Failure;
}
}
}
query.finalize();
return CE_None;
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
return CE_Failure;
}
}
/************************************************************************/
/* Create() */
/************************************************************************/
GDALDataset *
TileDBDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands,
GDALDataType eType, char ** papszOptions )
{
try
{
CPLString osArrayPath = vsi_to_tiledb_uri( pszFilename );
std::unique_ptr<TileDBDataset> poDS(
TileDBDataset::CreateLL( osArrayPath, nXSize, nYSize,
nBands, eType, papszOptions ));
if( !poDS )
return nullptr;
tiledb::Array::create( osArrayPath, *poDS->m_schema );
if ( poDS->nTimestamp )
poDS->m_array.reset( new tiledb::Array( *poDS->m_ctx, osArrayPath,
TILEDB_WRITE, poDS->nTimestamp ) );
else
poDS->m_array.reset( new tiledb::Array( *poDS->m_ctx,
osArrayPath, TILEDB_WRITE ) );
for( int i = 0; i < poDS->nBands;i++ )
{
if ( poDS->eIndexMode == ATTRIBUTES )
{
poDS->SetBand( i+1, new TileDBRasterBand( poDS.get(), i+1,
TILEDB_VALUES + CPLString().Printf( "_%i", i+1 ) ) );
}
else
poDS->SetBand( i+1, new TileDBRasterBand( poDS.get(), i+1 ) );
}
char** papszImageStruct = nullptr;
papszImageStruct = CSLAddNameValue(papszImageStruct, "NBITS",
CPLString().Printf( "%d", poDS->nBitsPerSample ) );
papszImageStruct = CSLAddNameValue(papszImageStruct, "DATA_TYPE",
CPLString().Printf( "%s", GDALGetDataTypeName( poDS->eDataType ) ) );
papszImageStruct = CSLAddNameValue(papszImageStruct, "X_SIZE",
CPLString().Printf( "%d", poDS->nRasterXSize ) );
papszImageStruct = CSLAddNameValue(papszImageStruct, "Y_SIZE",
CPLString().Printf( "%d", poDS->nRasterYSize ) );
papszImageStruct = CSLAddNameValue(papszImageStruct, "INTERLEAVE",
index_type_name( poDS->eIndexMode ) );
if ( poDS->lpoAttributeDS.size() > 0 )
{
int i = 0;
for ( auto const& poAttrDS: poDS->lpoAttributeDS )
{
papszImageStruct = CSLAddNameValue( papszImageStruct,
CPLString().Printf( "TILEDB_ATTRIBUTE_%i", ++i ),
CPLGetBasename( poAttrDS->GetDescription() ) );
}
}
poDS->SetMetadata(papszImageStruct, "IMAGE_STRUCTURE");
CSLDestroy( papszImageStruct );
return poDS.release();
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
return nullptr;
}
}
/************************************************************************/
/* CreateCopy() */
/************************************************************************/
GDALDataset *
TileDBDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
int bStrict, char ** papszOptions,
GDALProgressFunc pfnProgress,
void *pProgressData )
{
char** papszCopyOptions = CSLDuplicate( papszOptions );
CPLString osArrayPath = vsi_to_tiledb_uri( pszFilename );
try
{
std::unique_ptr<TileDBDataset> poDstDS;
if ( CSLFetchNameValue(papszOptions, "APPEND_SUBDATASET" ) )
{
// TileDB schemas are fixed
CPLError(CE_Failure, CPLE_NotSupported,
"TileDB driver does not support "
"appending to an existing schema.");
CSLDestroy( papszCopyOptions );
return nullptr;
}
char** papszSrcSubDatasets = poSrcDS->GetMetadata( "SUBDATASETS" );
if ( papszSrcSubDatasets == nullptr )
{
const int nBands = poSrcDS->GetRasterCount();
if ( nBands > 0 )
{
GDALRasterBand* poBand = poSrcDS->GetRasterBand( 1 );
GDALDataType eType = poBand->GetRasterDataType();
for (int i = 2; i <= nBands; ++i)
{
if (eType != poSrcDS->GetRasterBand( i )->GetRasterDataType( ) )
{
CPLError(CE_Failure, CPLE_NotSupported,
"TileDB driver does not support "
"source dataset with different band data types.");
CSLDestroy( papszCopyOptions );
return nullptr;
}
}
poDstDS.reset(
static_cast<TileDBDataset*>(TileDBDataset::Create( osArrayPath,
poSrcDS->GetRasterXSize(),
poSrcDS->GetRasterYSize(),
nBands, eType, papszOptions )));
if( !poDstDS )
{
CSLDestroy( papszCopyOptions );
return nullptr;
}
CPLErr eErr = GDALDatasetCopyWholeRaster( poSrcDS, poDstDS.get(),
papszOptions, pfnProgress,
pProgressData );
if ( eErr != CE_None )
{
CPLError(eErr, CPLE_AppDefined,
"Error copying raster to TileDB.");
}
}
else
{
CPLError(CE_Failure, CPLE_NotSupported,
"TileDB driver does not support "
"source dataset with zero bands.");
}
}
else
{
if ( bStrict )
{
CPLError(CE_Failure, CPLE_NotSupported,
"TileDB driver does not support copying "
"subdatasets in strict mode.");
CSLDestroy( papszCopyOptions );
return nullptr;
}
if ( CSLFetchNameValue(papszOptions, "BLOCKXSIZE" ) ||
CSLFetchNameValue(papszOptions, "BLOCKYSIZE" ) )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Changing block size is not supported when copying subdatasets.");
CSLDestroy( papszCopyOptions );
return nullptr;
}
const int nSubDatasetCount = CSLCount( papszSrcSubDatasets ) / 2;
const int nMaxFiles =
atoi(CPLGetConfigOption( "GDAL_READDIR_LIMIT_ON_OPEN", "1000" ) );
if ( nSubDatasetCount <= nMaxFiles )
{
const char* pszSource = CSLFetchNameValue(
papszSrcSubDatasets, "SUBDATASET_1_NAME");
if( pszSource )
{
std::unique_ptr<GDALDataset> poSubDataset(GDALDataset::Open( pszSource ));
if ( poSubDataset && poSubDataset->GetRasterCount() > 0 )
{
GDALRasterBand* poBand = poSubDataset->GetRasterBand( 1 );
TileDBDataset::SetBlockSize( poBand, papszCopyOptions );
poDstDS.reset(TileDBDataset::CreateLL(
osArrayPath, poBand->GetXSize(),
poBand->GetYSize(), 0, poBand->GetRasterDataType(),
papszCopyOptions ));
if ( poDstDS &&
TileDBDataset::CopySubDatasets( poSrcDS, poDstDS.get(),
pfnProgress, pProgressData ) != CE_None )
{
poDstDS.reset();
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to copy subdatasets.");
}
}
}
}
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Please increase GDAL_READDIR_LIMIT_ON_OPEN variable.");
}
}
// TODO Supporting mask bands is a possible future task
if ( poDstDS != nullptr )
{
int nCloneFlags = GCIF_PAM_DEFAULT & ~GCIF_MASK;
poDstDS->CloneInfo( poSrcDS, nCloneFlags );
}
CSLDestroy( papszCopyOptions );
return poDstDS.release();
}
catch(const tiledb::TileDBError& e)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", e.what() );
CSLDestroy( papszCopyOptions );
return nullptr;
}
}
/************************************************************************/
/* IRasterIO() */
/* */
/* Multi-band raster io handler. We will use block based */
/* loading for attribute only arrays and for */
/* arrays that are indexed band last as they */
/* are effectively pixel interleaved, so processing all bands */
/* for a given block together avoid extra seeks. */
/************************************************************************/
CPLErr TileDBDataset::IRasterIO( GDALRWFlag eRWFlag,
int nXOff, int nYOff, int nXSize, int nYSize,
void *pData, int nBufXSize, int nBufYSize,
GDALDataType eBufType,
int nBandCount, int *panBandMap,
GSpacing nPixelSpace, GSpacing nLineSpace,
GSpacing nBandSpace,
GDALRasterIOExtraArg* psExtraArg )
{
if ( ( eIndexMode == PIXEL ) ||
( eIndexMode == ATTRIBUTES ))
{
return GDALDataset::BlockBasedRasterIO(
eRWFlag, nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize, eBufType,
nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace, psExtraArg );
}
else
return
GDALDataset::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize, eBufType,
nBandCount, panBandMap,
nPixelSpace, nLineSpace, nBandSpace, psExtraArg );
}
/************************************************************************/
/* GDALRegister_TILEDB() */
/************************************************************************/
void GDALRegister_TileDB()
{
if( GDALGetDriverByName( "TileDB" ) != nullptr )
return;
GDALDriver *poDriver = new GDALDriver();
poDriver->SetDescription( "TileDB" );
poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" );
poDriver->SetMetadataItem( GDAL_DCAP_SUBCREATECOPY, "YES" );
poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "TileDB" );
poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/tiledb.html" );
poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES,
"Byte UInt16 Int16 UInt32 Int32 Float32 "
"Float64 CInt16 CInt32 CFloat32 CFloat64" );
poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
poDriver->SetMetadataItem( GDAL_DMD_SUBDATASETS, "YES" );
poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
"<CreationOptionList>\n"
" <Option name='COMPRESSION' type='string-select' description='image compression to use' default='NONE'>\n"
" <Value>NONE</Value>\n"
" <Value>GZIP</Value>\n"
" <Value>ZSTD</Value>\n"
" <Value>LZ4</Value>\n"
" <Value>RLE</Value>\n"
" <Value>BZIP2</Value>\n"
" <Value>DOUBLE-DELTA</Value>\n"
" <Value>POSITIVE-DELTA</Value>\n"
" </Option>\n"
" <Option name='COMPRESSION_LEVEL' type='int' description='Compression level'/>\n"
" <Option name='BLOCKXSIZE' type='int' description='Tile Width'/>"
" <Option name='BLOCKYSIZE' type='int' description='Tile Height'/>"
" <Option name='STATS' type='boolean' description='Dump TileDB stats'/>"
" <Option name='TILEDB_CONFIG' type='string' description='location of configuration file for TileDB'/>"
" <Option name='TILEDB_ATTRIBUTE' type='string' description='co-registered file to add as TileDB attributes, only applicable for interleave types of band or pixel'/>"
" <Option name='INTERLEAVE' type='string-select' description='Indexing order' default='BAND'>\n"
" <Value>BAND</Value>\n"
" <Value>PIXEL</Value>\n"
" <Value>ATTRIBUTES</Value>\n"
" </Option>\n"
" <Option name='TILEDB_TIMESTAMP' type='int' description='Create array at this timestamp, the timestamp should be > 0'/>\n"
"</CreationOptionList>\n" );
poDriver->SetMetadataItem( GDAL_DMD_OPENOPTIONLIST,
"<OpenOptionList>"
" <Option name='STATS' type='boolean' description='Dump TileDB stats'/>"
" <Option name='TILEDB_ATTRIBUTE' type='string' description='Attribute to read from each band'/>"
" <Option name='TILEDB_CONFIG' type='string' description='location of configuration file for TileDB'/>"
" <Option name='TILEDB_TIMESTAMP' type='int' description='Open array at this timestamp, the timestamp should be > 0'/>"
"</OpenOptionList>" );
poDriver->pfnIdentify = TileDBDataset::Identify;
poDriver->pfnOpen = TileDBDataset::Open;
poDriver->pfnCreate = TileDBDataset::Create;
poDriver->pfnCreateCopy = TileDBDataset::CreateCopy;
poDriver->pfnDelete = TileDBDataset::Delete;
GetGDALDriverManager()->RegisterDriver( poDriver );
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "FilterOutputStreamTest.h"
#include <decaf/io/ByteArrayOutputStream.h>
#include <decaf/io/ByteArrayInputStream.h>
using namespace std;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::io;
using namespace decaf::util;
////////////////////////////////////////////////////////////////////////////////
void FilterOutputStreamTest::testConstructor() {
try {
ByteArrayOutputStream baos;
FilterOutputStream os( &baos );
os.write( 't' );
} catch( IOException& e ) {
CPPUNIT_FAIL("Constructor test failed : " + e.getMessage());
}
}
////////////////////////////////////////////////////////////////////////////////
void FilterOutputStreamTest::testClose() {
try {
ByteArrayOutputStream baos;
FilterOutputStream os( &baos );
os.write( (unsigned char*)&testString[0], (int)testString.size(), 0, 500 );
os.flush();
CPPUNIT_ASSERT_MESSAGE( "Bytes not written after flush",
500 == baos.size() );
os.close();
} catch( IOException& e ) {
CPPUNIT_FAIL("Close test failed : " + e.getMessage());
}
}
////////////////////////////////////////////////////////////////////////////////
void FilterOutputStreamTest::testFlush() {
try {
ByteArrayOutputStream baos;
FilterOutputStream os( &baos );
os.write( (unsigned char*)&testString[0], (int)testString.size(), 0, 500 );
os.flush();
CPPUNIT_ASSERT_MESSAGE( "Bytes not written after flush",
500 == baos.size() );
os.close();
} catch( IOException& e ) {
CPPUNIT_FAIL("Flush test failed : " + e.getMessage());
}
}
////////////////////////////////////////////////////////////////////////////////
void FilterOutputStreamTest::testWrite1() {
try {
ByteArrayOutputStream baos;
FilterOutputStream os( &baos );
os.write( (unsigned char*)&testString[0], (int)testString.size(), 0, (int)testString.size() );
std::pair<const unsigned char*, int> array = baos.toByteArray();
ByteArrayInputStream bais( array.first, array.second, true );
os.flush();
CPPUNIT_ASSERT_MESSAGE( "Bytes not written after flush",
bais.available() == (int)testString.length() );
unsigned char* wbytes = new unsigned char[ testString.length() ];
bais.read( wbytes, (int)testString.length(), 0, (int)testString.length() );
CPPUNIT_ASSERT_MESSAGE("Incorrect bytes written",
testString == string( (const char*)wbytes, testString.length() ) );
delete [] wbytes;
} catch( IOException& e ) {
CPPUNIT_FAIL("Write test failed : " + e.getMessage());
}
}
////////////////////////////////////////////////////////////////////////////////
void FilterOutputStreamTest::testWrite2() {
try {
ByteArrayOutputStream baos;
FilterOutputStream os( &baos );
os.write('t');
std::pair<const unsigned char*, int> array = baos.toByteArray();
ByteArrayInputStream bais( array.first, array.second, true );
os.flush();
CPPUNIT_ASSERT_MESSAGE( "Byte not written after flush", 1 == bais.available() );
unsigned char wbytes[1];
bais.read( wbytes, 1, 0, 1 );
CPPUNIT_ASSERT_MESSAGE("Incorrect byte written", 't' == wbytes[0] );
} catch( IOException& e ) {
CPPUNIT_FAIL("Write test failed : " + e.getMessage());
}
}
////////////////////////////////////////////////////////////////////////////////
void FilterOutputStreamTest::testWriteBIIIExceptions() {
ByteArrayOutputStream baos;
FilterOutputStream os( &baos );
CPPUNIT_ASSERT_THROW_MESSAGE(
"Should have thrown an NullPointerException",
os.write( NULL, 1000, 0, 1001 ),
NullPointerException );
unsigned char buffer[1000];
CPPUNIT_ASSERT_THROW_MESSAGE(
"Should have thrown an IndexOutOfBoundsException",
os.write( buffer, 1000, 0, 1001 ),
IndexOutOfBoundsException );
CPPUNIT_ASSERT_THROW_MESSAGE(
"Should have thrown an IndexOutOfBoundsException",
os.write( buffer, 1000, 1001, 0 ),
IndexOutOfBoundsException );
CPPUNIT_ASSERT_THROW_MESSAGE(
"Should have thrown an IndexOutOfBoundsException",
os.write( buffer, 1000, 500, 501 ),
IndexOutOfBoundsException );
os.close();
CPPUNIT_ASSERT_THROW_MESSAGE(
"Should have thrown an IOException",
os.write( buffer, 1000, 0, 100 ),
IOException );
}
|
#pragma once
#include "../headers/Utilities.hpp"
#include <string>
class INodeUser {
public:
// set the id of the node.
virtual void setid(std::string id) = 0;
// connect to node given ip and port, return file descriptor
virtual int connect_to(Utilities::Address &address) = 0;
// send message of length len, to node(id).
virtual void send_message(std::vector<std::string> userinput) = 0;
// print the rout to a given node ( exp 1->5->3->2 ).
virtual void route(std::string id) = 0;
// print the list of all connected nodes.
virtual void peers() = 0;
bool formatCheck(std::vector<std::string> vec, uint size) {
if (vec.size() != size) {
std::cout << "Invalid argument's : ";
std::cout << "Nack" << std::endl;
return false;
}
return true;
}
};
|
/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
#include "3d/CCSprite3DMaterial.h"
#include "3d/CCMesh.h"
#include "platform/CCFileUtils.h"
#include "renderer/CCTexture2D.h"
#include "renderer/CCGLProgram.h"
#include "renderer/CCGLProgramCache.h"
#include "renderer/CCGLProgramState.h"
#include "renderer/CCGLProgramStateCache.h"
#include "base/CCDirector.h"
#include "base/CCEventType.h"
NS_CC_BEGIN
Sprite3DMaterialCache* Sprite3DMaterialCache::_cacheInstance = nullptr;
std::unordered_map<std::string, Sprite3DMaterial*> Sprite3DMaterial::_materials;
Sprite3DMaterial* Sprite3DMaterial::_unLitMaterial = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_unLitNoTexMaterial = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_vertexLitMaterial = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_diffuseMaterial = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_diffuseNoTexMaterial = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_bumpedDiffuseMaterial = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_unLitMaterialSkin = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_vertexLitMaterialSkin = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_diffuseMaterialSkin = nullptr;
Sprite3DMaterial* Sprite3DMaterial::_bumpedDiffuseMaterialSkin = nullptr;
void Sprite3DMaterial::createBuiltInMaterial()
{
releaseBuiltInMaterial();
auto glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_SKINPOSITION_TEXTURE);
auto glprogramstate = GLProgramState::create(glProgram);
_unLitMaterialSkin = new (std::nothrow) Sprite3DMaterial();
if (_unLitMaterialSkin && _unLitMaterialSkin->initWithGLProgramState(glprogramstate))
{
_unLitMaterialSkin->_type = Sprite3DMaterial::MaterialType::UNLIT;
}
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_SKINPOSITION_NORMAL_TEXTURE);
glprogramstate = GLProgramState::create(glProgram);
_diffuseMaterialSkin = new (std::nothrow) Sprite3DMaterial();
if (_diffuseMaterialSkin && _diffuseMaterialSkin->initWithGLProgramState(glprogramstate))
{
_diffuseMaterialSkin->_type = Sprite3DMaterial::MaterialType::DIFFUSE;
}
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_POSITION_NORMAL_TEXTURE);
glprogramstate = GLProgramState::create(glProgram);
_diffuseMaterial = new (std::nothrow) Sprite3DMaterial();
if (_diffuseMaterial && _diffuseMaterial->initWithGLProgramState(glprogramstate))
{
_diffuseMaterial->_type = Sprite3DMaterial::MaterialType::DIFFUSE;
}
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_POSITION_TEXTURE);
glprogramstate = GLProgramState::create(glProgram);
_unLitMaterial = new (std::nothrow) Sprite3DMaterial();
if (_unLitMaterial && _unLitMaterial->initWithGLProgramState(glprogramstate))
{
_unLitMaterial->_type = Sprite3DMaterial::MaterialType::UNLIT;
}
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_POSITION);
glprogramstate = GLProgramState::create(glProgram);
_unLitNoTexMaterial = new (std::nothrow) Sprite3DMaterial();
if (_unLitNoTexMaterial && _unLitNoTexMaterial->initWithGLProgramState(glprogramstate))
{
_unLitNoTexMaterial->_type = Sprite3DMaterial::MaterialType::UNLIT_NOTEX;
}
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_POSITION_NORMAL);
glprogramstate = GLProgramState::create(glProgram);
_diffuseNoTexMaterial = new (std::nothrow) Sprite3DMaterial();
if (_diffuseNoTexMaterial && _diffuseNoTexMaterial->initWithGLProgramState(glprogramstate))
{
_diffuseNoTexMaterial->_type = Sprite3DMaterial::MaterialType::DIFFUSE_NOTEX;
}
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_POSITION_BUMPEDNORMAL_TEXTURE);
glprogramstate = GLProgramState::create(glProgram);
_bumpedDiffuseMaterial = new (std::nothrow) Sprite3DMaterial();
if (_bumpedDiffuseMaterial && _bumpedDiffuseMaterial->initWithGLProgramState(glprogramstate))
{
_bumpedDiffuseMaterial->_type = Sprite3DMaterial::MaterialType::BUMPED_DIFFUSE;
}
glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_SKINPOSITION_BUMPEDNORMAL_TEXTURE);
glprogramstate = GLProgramState::create(glProgram);
_bumpedDiffuseMaterialSkin = new (std::nothrow) Sprite3DMaterial();
if (_bumpedDiffuseMaterialSkin && _bumpedDiffuseMaterialSkin->initWithGLProgramState(glprogramstate))
{
_bumpedDiffuseMaterialSkin->_type = Sprite3DMaterial::MaterialType::BUMPED_DIFFUSE;
}
}
void Sprite3DMaterial::releaseBuiltInMaterial()
{
CC_SAFE_RELEASE_NULL(_unLitMaterial);
CC_SAFE_RELEASE_NULL(_unLitMaterialSkin);
CC_SAFE_RELEASE_NULL(_unLitNoTexMaterial);
CC_SAFE_RELEASE_NULL(_vertexLitMaterial);
CC_SAFE_RELEASE_NULL(_diffuseMaterial);
CC_SAFE_RELEASE_NULL(_diffuseNoTexMaterial);
CC_SAFE_RELEASE_NULL(_bumpedDiffuseMaterial);
CC_SAFE_RELEASE_NULL(_vertexLitMaterialSkin);
CC_SAFE_RELEASE_NULL(_diffuseMaterialSkin);
CC_SAFE_RELEASE_NULL(_bumpedDiffuseMaterialSkin);
}
void Sprite3DMaterial::releaseCachedMaterial()
{
for (auto& it : _materials) {
if (it.second)
it.second->release();
}
_materials.clear();
}
Material* Sprite3DMaterial::clone() const
{
auto material = new (std::nothrow) Sprite3DMaterial();
if (material)
{
RenderState::cloneInto(material);
for (const auto& technique: _techniques)
{
auto t = technique->clone();
t->setParent(material);
for (ssize_t i = 0; i < t->getPassCount(); i++) {
t->getPassByIndex(i)->setParent(t);
}
material->_techniques.pushBack(t);
}
// current technique
auto name = _currentTechnique->getName();
material->_currentTechnique = material->getTechniqueByName(name);
material->_type = _type;
material->autorelease();
}
return material;
}
Sprite3DMaterial* Sprite3DMaterial::createBuiltInMaterial(MaterialType type, bool skinned)
{
/////
if (_diffuseMaterial == nullptr)
createBuiltInMaterial();
Sprite3DMaterial* material = nullptr;
switch (type) {
case Sprite3DMaterial::MaterialType::UNLIT:
material = skinned ? _unLitMaterialSkin : _unLitMaterial;
break;
case Sprite3DMaterial::MaterialType::UNLIT_NOTEX:
material = _unLitNoTexMaterial;
break;
case Sprite3DMaterial::MaterialType::VERTEX_LIT:
CCASSERT(0, "not implement");
break;
case Sprite3DMaterial::MaterialType::DIFFUSE:
material = skinned ? _diffuseMaterialSkin : _diffuseMaterial;
break;
case Sprite3DMaterial::MaterialType::DIFFUSE_NOTEX:
material = _diffuseNoTexMaterial;
break;
case Sprite3DMaterial::MaterialType::BUMPED_DIFFUSE:
material = skinned ? _bumpedDiffuseMaterialSkin : _bumpedDiffuseMaterial;
break;
default:
break;
}
if (material)
return (Sprite3DMaterial*)material->clone();
return nullptr;
}
Sprite3DMaterial* Sprite3DMaterial::createWithFilename(const std::string& path)
{
auto validfilename = FileUtils::getInstance()->fullPathForFilename(path);
if (validfilename.size() > 0) {
auto it = _materials.find(validfilename);
if (it != _materials.end())
return (Sprite3DMaterial*)it->second->clone();
auto material = new (std::nothrow) Sprite3DMaterial();
if (material->initWithFile(path))
{
material->_type = Sprite3DMaterial::MaterialType::CUSTOM;
_materials[validfilename] = material;
return (Sprite3DMaterial*)material->clone();
}
CC_SAFE_DELETE(material);
}
return nullptr;
}
Sprite3DMaterial* Sprite3DMaterial::createWithGLStateProgram(GLProgramState* programState)
{
CCASSERT(programState, "Invalid GL Program State");
auto mat = new (std::nothrow) Sprite3DMaterial();
if (mat && mat->initWithGLProgramState(programState))
{
mat->_type = Sprite3DMaterial::MaterialType::CUSTOM;
mat->autorelease();
return mat;
}
CC_SAFE_DELETE(mat);
return nullptr;
}
void Sprite3DMaterial::setTexture(Texture2D* tex, NTextureData::Usage usage)
{
const auto& passes = getTechnique()->getPasses();
for (auto& pass : passes) {
pass->getGLProgramState()->setUniformTexture(s_uniformSamplerName[(int)usage], tex);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
Sprite3DMaterialCache::Sprite3DMaterialCache()
{
}
Sprite3DMaterialCache::~Sprite3DMaterialCache()
{
removeAllSprite3DMaterial();
}
Sprite3DMaterialCache* Sprite3DMaterialCache::getInstance()
{
if (! _cacheInstance)
{
_cacheInstance = new (std::nothrow) Sprite3DMaterialCache();
}
return _cacheInstance;
}
void Sprite3DMaterialCache::destroyInstance()
{
if (_cacheInstance)
{
CC_SAFE_DELETE(_cacheInstance);
}
}
bool Sprite3DMaterialCache::addSprite3DMaterial(const std::string& key, Texture2D* texture)
{
auto itr = _materials.find(key);
if (itr == _materials.end())
{
CC_SAFE_RETAIN(texture);
_materials[key] = texture;
return true;
}
return false;
}
Texture2D* Sprite3DMaterialCache::getSprite3DMaterial(const std::string& key)
{
auto itr = _materials.find(key);
if (itr != _materials.end())
{
return itr->second;
}
return nullptr;
}
void Sprite3DMaterialCache::removeAllSprite3DMaterial()
{
for (auto itr = _materials.begin(); itr != _materials.end(); itr++) {
CC_SAFE_RELEASE_NULL(itr->second);
}
_materials.clear();
}
void Sprite3DMaterialCache::removeUnusedSprite3DMaterial()
{
for( auto it=_materials.cbegin(); it!=_materials.cend(); /* nothing */) {
auto value = it->second;
if( value->getReferenceCount() == 1 ) {
CCLOG("cocos2d: GLProgramStateCache: removing unused GLProgramState");
value->release();
_materials.erase(it++);
} else {
++it;
}
}
}
NS_CC_END
|
/*
* Copyright (C) 2017 Intel Corporation. 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.
*/
#include "iagent_base.h"
extern "C" {
#include "connection.h"
}
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <sys/time.h>
#include "iagent_base.h"
#include "rd.h"
#include "url-parser-c/url_parser.h"
#include "CRefresherPoint.h"
#include "message.h"
#include "broker_rest_convert.h"
#include "CClientManager.h"
#include "coap_ext.h"
#include "CResRefresher.h"
#include "CResource.h"
#include <map>
#include "ams_constants.h"
// source: the identify of the user who add the refresher point
//
extern "C" int AddResourceRefresher(char *device, char *resource, fresher_para_t *param)
{
return ResRefresher().NewRefresherPoint(device, resource, param);
}
extern "C" bool RemoveResourceRefresher(char *device, char *resource, char *source)
{
return ResRefresher().DelRefresherPoint(device, resource, source);
}
// url: /[lwm2m|ep/ocf]/[device id]/[resource...]
extern "C" void OnDataPoint(char *device, char *uri, int fmt, char *payload, int payload_len)
{
CRefresherPoint *point = ResRefresher().FindRes(uri, device, true);
if (point == NULL)
{
TraceI(FLAG_DATA_POINT, "OnDataPoint but no observe: fmt=%d, device=%s,uri=%s, payload_len=%d",
fmt, device, uri,payload_len);
return;
}
TraceI(FLAG_DATA_POINT, "OnDataPoint: fmt=%d, device=%s, uri=%s, payload_len=%d",
fmt, device, uri, payload_len);
point->OnRefresherData(fmt, payload, payload_len);
point->SetExpiry();
}
typedef struct
{
bh_async_callback response_handler;
void * response_user_data;
} transaction_handle_for_coap_t;
static int coap_response_callback(void *data, void *response)
{
transaction_handle_for_coap_t * ctx = (transaction_handle_for_coap_t*) data;
ctx->response_handler(ctx->response_user_data, response, 0, T_Coap_Parsed);
free(data);
return 0;
}
/*
*
1) gwbus://[lwm2m|ocf|ep|modbus|dev]/[:device id]/{:resource href]
���С�gwbus://������ʡ�ԣ�/[lwm2m|ocf|ep|modbus|dev]/[:device id]/{:resource
href]Ҳ��ʾ��ͬ�����塣�����?) 3)��ͬ??
2) gwbus:///ibroker/...
ֱ�ӷ����ƶˣ�����ǰ��url�е�ibroker/ǰ����??
3��gwbus://....
local service on the gw bus??use broadcast to send
4) gwbus://module/[:module id]/...
����ǰ��Ҫ��urlת������module id��ȡ����������bus message��dest�ֶΡ�ʣ�µ�url������ΪĿ��url.
5) coap://127.0.0.1:7777/...
6) obs://[token id]/.... (��ʱ��ʵ??
*/
unsigned long SendRequest(IURL target, int fmt, char *payload, int payload_len, bool require_response,
uint8_t msgcode, char *query,
bh_async_callback response_handler, void * response_user_data)
{
TraceI(FLAG_DATA_POINT, "SendRequest target=%s\n", target);
unsigned long msg_id = ULONG_MAX;
iUrl_t iurl_body = {0};
int error;
url_parser_url_t parsed_url = {0};
if (NULL == strstr(target, "://"))
{
parsed_url.protocol = strdup(ADDR_BUS);
while (*target != 0 && *target == '/') target++;
if (*target == 0)
{
WARNING("SEND REQUEST: TARGET IS EMPTY");
goto end;
}
parsed_url.path = strdup(target);
}
else
{
error = parse_url(target, true, &parsed_url);
if (error != 0 || parsed_url.path == NULL)
{
WARNING("SEND REQUEST: Invalid URL \"%s\".\n", target);
goto end;
}
}
if (0 == strcmp (parsed_url.protocol, ADDR_BUS))
{
MESSAGE_CONFIG msgConfig = {0};
char uri_buffer[200] = {0};
char *bus_module_name = NULL;
char *standard = NULL;
char *uri = NULL;
if (0 == check_url_start(parsed_url.path, strlen(parsed_url.path), (char *)"ibroker"))
{
if (!parse_iUrl_body(parsed_url.path, &iurl_body))
LOG_GOTO("unable to parse the url path" ,end)
// the clients can set protocol section in the url to "dev" for unknown type devices.
// we will convert the url to known protocol for those devices we know.
standard = iurl_body.standard;
uri = parsed_url.path;
// for /module/[:module name]/.. url, we will set the module name into the XKDEST tag in the bus message
if (0 == strcmp (iurl_body.standard, "module"))
{
uri = iurl_body.res_uri;
bus_module_name = iurl_body.device;
}
else if (0 == strcmp (iurl_body.standard, "dev"))
{
CClient *client = ClientManager().FindClient(iurl_body.device);
if(client)
{
if(!client->m_standard.empty())
{
standard = (char* )client->m_standard.c_str();
snprintf (uri_buffer, sizeof(uri_buffer), "/%s/%s%s", client->m_standard.c_str(), iurl_body.device, iurl_body.res_uri);
uri = &uri_buffer[0];
}
}
}
}
else
{
standard = (char*)"ibroker";
}
// send to coap endpoint
if (0 == strcmp (standard, "ep") ||
0 == strcmp (standard, "coap"))// Bugzilla-2431(1)
{
coap_packet_t request[1];
msg_id = bh_gen_id(get_outgoing_requests_ctx());
if (require_response || response_handler)
coap_init_message((void *)request, COAP_TYPE_CON, msgcode, (uint16_t)msg_id);
else
coap_init_message((void *)request, COAP_TYPE_NON, msgcode, (uint16_t)msg_id);
coap_set_header_uri_path(request, iurl_body.res_uri);
coap_set_header_content_format(request, fmt);
coap_set_payload(request, payload, payload_len);
connection_t *conn = get_endpoint_conn((const char *) iurl_body.device);
if(conn == NULL)
{
WARNING ("SEND REQUEST: connection to [%s] is NULL. ", iurl_body.device);
goto end;
}
uip_ipaddr_t addr;
memset(&addr, 0, sizeof(addr));
addr.addr_type = A_Sock_Addr;
memcpy(&addr.sock_addr, &conn->addr, conn->addrLen);
addr.addr_len = conn->addrLen;
//
transaction_handle_for_coap_t * user_data = NULL;
if(response_handler)
{
user_data = (transaction_handle_for_coap_t* ) malloc(sizeof(transaction_handle_for_coap_t));
memset(user_data, 0, sizeof(*user_data));
user_data->response_handler = response_handler;
user_data->response_user_data = response_user_data;
response_user_data = NULL;
coap_nonblocking_request(g_endpoint_coap_ctx, &addr, request, coap_response_callback, user_data);
}
else
{
coap_nonblocking_request(g_endpoint_coap_ctx, &addr, request, NULL, NULL);
}
}
#ifdef BUILTIN_IBROKER
// send to icloud
else if (0 == strcmp (standard, "ibroker")) // Bugzilla-2431(2)
{
if (g_cloud_status != iReady_For_Work)
{
int offset = check_url_start(parsed_url.path, strlen(parsed_url.path), (char *)"ibroker/dp/");
if (offset)
{
char new_uri[1024];
snprintf(new_uri, 1024, "/dp-cache/%s", parsed_url.path+offset);
if(!setup_bus_restful_message(&msgConfig, (char*)TAG_REST_REQ, fmt, new_uri, NULL, msgcode, payload, payload_len)) goto end;
msg_id = bh_gen_id(get_outgoing_requests_ctx());
char c_mid[32];
memset(c_mid, 0, 32);
snprintf (c_mid, 32, "%ld", msg_id);
set_bus_message_property(&msgConfig, XK_MID, c_mid);
struct timeval tv;
gettimeofday(&tv, NULL);
char c_time[64];
memset(c_time, 0, 64);
snprintf (c_time, 64, "%ld", tv.tv_sec * 1000 + tv.tv_usec / 1000);
set_bus_message_property(&msgConfig, XK_TM, c_time);
publish_message_cfg_on_broker(&msgConfig);
}
goto end;
}
// forward the request to the cloud and strip the "ibroker/"
ilink_message_t contact;
ilink_vheader_t vheader;
vheader_node_t *node;
int len;
init_ilink_message(&contact, COAP_OVER_TCP);
ilink_set_req_resp(&contact, 1, bh_gen_id(get_outgoing_requests_ctx()));
memset(&vheader, 0, sizeof(vheader));
if((node = vheader_find_node(&vheader, (char *)K_AGENT_ID, (bool)1, (bool)0)) == NULL)
{
WARNING ("SEND REQUEST: vheader_find_node failed");
goto end;
}
char *self_id = get_self_agent_id();
vheader_set_node_str(node, self_id, 1);
ilink_set_vheader(&contact, &vheader);
coap_packet_t request[1];
char *response_buf = NULL;
if (require_response)
coap_init_message(request, COAP_TYPE_CON, msgcode, contact.msgID);
else
coap_init_message(request, COAP_TYPE_NON, msgcode, contact.msgID);
int offset = check_url_start(parsed_url.path, strlen(parsed_url.path), (char *)"/ibroker");
if (offset)
coap_set_header_uri_path(request, parsed_url.path+offset);
else
coap_set_header_uri_path(request, parsed_url.path);
coap_set_header_content_format(request, fmt);
if (query)
coap_set_header_uri_query(request, query);
coap_set_payload_tcp(request, payload, payload_len);
coap_set_token(request, (const uint8_t *) &contact.msgID, sizeof(contact.msgID));
len = coap_serialize_message_tcp(request, (uint8_t **)&response_buf);
ilink_set_payload(&contact, response_buf, len);
ilink_msg_send(&contact);
reset_ilink_message(&contact);
vheader_destroy(&vheader);
free(response_buf);
}
#endif
else // by default send it to the gateway bus. Bugzilla-2431(3)
{
char *tag = NULL;
if (require_response)
tag = (char *)TAG_REST_REQ;
else
tag = (char *)TAG_EVENT;
msg_id = bh_gen_id(get_outgoing_requests_ctx());
char c_mid[32];
sprintf (c_mid, "%ld", msg_id);
if(!setup_bus_restful_message(&msgConfig, tag, fmt, uri, NULL, msgcode, payload, payload_len)) goto end;
if (bus_module_name)// Bugzilla-2431(4)
{
set_bus_message_property(&msgConfig, XK_DEST, bus_module_name);
}
set_bus_message_property(&msgConfig, XK_MID, c_mid);
if(response_handler)
{
bh_wait_response_async(get_outgoing_requests_ctx(),
msg_id,
(void *)response_handler,
response_user_data,
2*1000,
NULL);
}
response_user_data = NULL;
publish_message_cfg_on_broker(&msgConfig);
}
}
// send to coap device
else if (0 == strcmp (parsed_url.protocol, ADDR_COAP)) // Bugzilla-2431(5)
{
coap_packet_t request[1];
msg_id = bh_gen_id(get_outgoing_requests_ctx());
if (require_response || response_handler)
coap_init_message((void *)request, COAP_TYPE_CON, msgcode, (uint16_t)msg_id);
else
coap_init_message((void *)request, COAP_TYPE_NON, msgcode, (uint16_t)msg_id);
// token must be set for the java SDK
coap_set_token(request, (const uint8_t*) &msg_id, sizeof(msg_id));
coap_set_header_content_format(request, fmt);
coap_set_payload_tcp(request, payload, payload_len);
coap_set_header_uri_path(request,parsed_url.path);
if (parsed_url.host_exists && parsed_url.port)
{
uip_ipaddr_t addr;
memset(&addr, 0, sizeof(addr));
addr.addr_type = A_Sock_Addr;
addr.sock_addr.sin_family = AF_INET;
addr.sock_addr.sin_addr.s_addr = inet_addr(parsed_url.host_ip);
addr.sock_addr.sin_port = htons(parsed_url.port);
addr.addr_len = sizeof(addr);
transaction_handle_for_coap_t * user_data = NULL;
if(response_handler)
{
user_data = (transaction_handle_for_coap_t*) malloc(sizeof(transaction_handle_for_coap_t));
memset(user_data, 0, sizeof(*user_data));
user_data->response_handler = response_handler;
user_data->response_user_data = response_user_data;
response_user_data = NULL;
coap_nonblocking_request(g_endpoint_coap_ctx, &addr, request, coap_response_callback, user_data);
}
else
{
coap_nonblocking_request(g_endpoint_coap_ctx, &addr, request, NULL, NULL);
}
//coap_nonblocking_request(g_endpoint_coap_ctx, &addr, resquest, coap_response_callback, response_user_data);
}
else
{
msg_id = ULONG_MAX;
LOG_GOTO("coap device not available", end)
}
}
else if (0 == strcmp (parsed_url.protocol, ADDR_OBS)) // Bugzilla-2431(6)
{
goto end;
}
end:
// ensure the response_user_data is freed if it not posted to the transaction
if(response_user_data && response_handler)
{
response_handler(response_user_data, NULL, 0, T_Empty);
}
free_parsed_url(&parsed_url);
free_iUrl_body(&iurl_body);
return msg_id;
}
extern "C" int cb_refresher_request(void *ctx_data, void *data, int len, unsigned char format)
{
int content_format, payload_len;
char *payload;
CRefresherPoint *point = NULL;
char mid[100]={0};
uint32_t ms_used;
context_refresher_request_t *ctx = (context_refresher_request_t*) ctx_data;
point = CRefresherPoint::FindPoint(ctx->refresher_id);
if(point == NULL)
{
ERROR("Refresh response returned for [%d], but can't find refresher point ", ctx->refresher_id);
goto end;
}
ms_used = get_elpased_ms(&ctx->request_time_ms);
point->m_read_in_progerss = 0;
if(data == NULL)
{
TraceI(FLAG_DATA_POINT, "Refresher request timeout in %d ms, url=[%s], len=%d",
ms_used, point->m_resource_url.c_str(), len);
if(ctx->observing) point->m_observe = CRefresherPoint::Obs_Failed;
point->m_read_fails ++;
goto end;
}
else if(T_Coap_Raw == format)
{
coap_packet_t coap_message[1];
int coap_error_code = coap_parse_message(coap_message, (uint8_t *)data, len);
if(coap_error_code != NO_ERROR) {
WARNING("%s, parse coap error (%d)", __FUNCTION__, coap_error_code);
goto end;
}
content_format = coap_message->content_format;
payload_len = coap_message->payload_len;
payload = (char *)coap_message->payload;
sprintf(mid, "%d", coap_message->mid);
}
else if(T_Broker_Message_Handle == format)
{
// todo: implement it
CONSTMAP_HANDLE properties = Message_GetProperties((MESSAGE_HANDLE) data); /*by contract this is never NULL*/
const char *format = ConstMap_GetValue(properties, XK_FMT);
const char *msg_id = ConstMap_GetValue(properties, XK_MID);
mid[0] = 0;
if(msg_id)
{
strncpy(mid, msg_id, sizeof(mid));
}
if(format !=NULL)
content_format= atoi(format);
else
content_format = IA_TEXT_PLAIN; //default
ConstMap_Destroy(properties);
const CONSTBUFFER *content = Message_GetContent((MESSAGE_HANDLE)data);
payload_len = content->size;
payload = (char *)content->buffer;
}
else
{
WARNING("Refresh response returned for device [%s], res [%s] , but format [%d] not supported ",
point->m_client_id.c_str(), point->m_resource_url.c_str(), format);
assert (1);
}
if(payload_len == 0)
{
point->m_read_fails ++;
TraceI(FLAG_DATA_POINT, "Refresher response (mid=%s) returned in %d ms. No payload, url=[%s], fails=%d",
mid, ms_used, point->m_resource_url.c_str(), point->m_read_fails);
goto end;
}
TraceI(FLAG_DATA_POINT, "Refresher response (mid=%s) returned in %d ms.url=%s, lenth=%d",
mid, ms_used, point->m_resource_url.c_str(), len);
point->m_read_fails = 0;
point->OnRefresherData(content_format, payload, payload_len);
if(ctx->observing)
{
point->m_observe = CRefresherPoint::Obs_Success;
WARNING("Refresh point for device [%s], res [%s] is in observing mode ",
point->m_client_id.c_str(), point->m_resource_url.c_str());
}
end:
if (T_Broker_Message_Handle == format && data)
{
Message_Destroy((MESSAGE_HANDLE)data);
}
trans_free_ctx(ctx_data);
return 0;
}
/// there are three message sources:
/// 1. from gateway message bus
/// 2. from coap client
/// 3. from ilink
/// 4. from the response feedback which can be in gw bus, coap or ilink
extern "C" dlist_entry_ctx_t g_internal_queue;
typedef void (*handler)(void *msg);
void agent_post_message_handler(void *handler, void *message)
{
dlist_post(&g_internal_queue, T_Message_Handler, message, handler);
wakeup_ports_thread();
}
// post the callback to ports handler thread for avoiding thread confliction
extern "C" int post_cb_rd_thread(callback_t *cb)
{
if(cb->format == T_Broker_Message_Handle)
cb->data = Message_Clone((MESSAGE_HANDLE)cb->data);
else if(cb->format != T_Empty)
{
WARNING("Fomrat %d is Not broker message handle in the post_cb_rd_thread", cb->format);
}
dlist_post(&g_internal_queue, T_Callback, cb, NULL);
wakeup_ports_thread();
return 0;
}
extern "C" void check_internal_message()
{
while(1)
{
dlist_node_t *msg = dlist_get(&g_internal_queue);
if(msg == NULL)
return;
if(msg->type == T_Bus_Message)
{
//
}
free(msg);
}
}
extern "C" void ResRefresherExpiry(uint32_t *next_expiry_ms)
{
uint32_t timeout;
ResRefresher().RunRefresh();
tick_time_t expiry = ResRefresher().GetNearExpiry();
if (expiry == -1)
return;
timeout = (expiry - bh_get_tick_sec()) * 1000;
if(timeout < *next_expiry_ms )
*next_expiry_ms = timeout;
}
#if 0
int ReadResource(char *device, char *res, void *cb, bool observe)
{
CClient *client = ClientManager().FindClient(device);
if(client == NULL || client->m_standard == "ilink" ||
client->m_standard == "agent")
return -1;
context_refresher_request_t *ctx = (context_refresher_request_t*)
trans_malloc_ctx(sizeof(context_refresher_request_t));
memset(ctx, 0, sizeof(context_refresher_request_t));
ctx->device = strdup(device);
ctx->res = strdup(res);
ctx->observing = observe;
if(client->m_standard == "ep")
{
char sendbuf[COAP_MAX_PACKET_SIZE];
coap_packet_t message[1];
coap_init_message((void *)message, COAP_TYPE_CON, (uint8_t)COAP_GET,
(uint16_t)bh_gen_id(get_outgoing_requests_ctx()));
coap_set_header_uri_path(message, res);
if(observe) coap_set_header_observe (message, 1);
int len = coap_serialize_message((void *)message, (uint8_t *)sendbuf);
//
bh_wait_response_async(get_outgoing_requests_ctx(),
message->mid,
cb,
ctx,
10*1000,
NULL);
// todo: need to setup the connection
connection_send(client->GetConnection(), (uint8_t *)sendbuf, (size_t)len);
}
else
{
MESSAGE_CONFIG msgConfig;
char url[128];
sprintf(url, "/%s/%s%s", client->m_standard.data(), client->m_epname.data(), res);
if(!setup_bus_restful_message(&msgConfig, (char *)TAG_REST_REQ, -1, url, NULL, COAP_GET, NULL, 0))
return -1;
unsigned long mid = bh_gen_id(get_outgoing_requests_ctx());
char buffer[50];
sprintf(buffer, "%ld", mid);
set_bus_message_property(&msgConfig, XK_MID, buffer);
bh_wait_response_async(get_outgoing_requests_ctx(),
mid,
cb,
ctx,
10*1000,
(void *)post_cb_rd_thread);
publish_message_cfg_on_broker(&msgConfig);
}
return 0;
}
#endif
static int handle_data_observing_json(JSON_Value *json, char *purl_prefix)
{
fresher_para_t param;
int id=-1, interval;
const char *device, *res, *purl, * rt;
int sequence = -1;
char buffer[256];
memset(¶m, 0, sizeof(param));
if (json == NULL) LOG_RETURN(-1)
JSON_Object *obj = json_value_get_object(json);
if( obj== NULL) LOG_GOTO("observing payload was NULL", end);
device = json_object_get_string(obj, "di");
purl = json_object_get_string(obj, "purl");
if(purl == NULL || *purl == 0) LOG_GOTO("No publish url info", end);
if(device == NULL || *device == 0) LOG_GOTO("no device info", end);
rt = json_object_get_string(obj, "rt");
res = json_object_get_string(obj, "ri");
if(res != NULL && *res != 0 && rt != NULL)
{
TraceI(FLAG_DATA_POINT, "creating refresher point, rt is [%s] in the request, but res is also set to [%s]. rt is discarded",
rt, res);
rt = NULL;
}
interval = (int)get_json_number_safe(obj, "interval");
if (interval <= 0)
interval = 10; //default interval is ten seconds
if(purl_prefix && purl_prefix[0])
{
if(strstr (purl, "://") == NULL)
{
if(purl[0] == '/') purl ++;
snprintf(buffer, sizeof(buffer), "%s%s%s", purl_prefix, purl[0]=='/'?"":"/",purl);
purl=buffer;
}
}
param.sequence = (int)get_json_number_safe(obj, "sequence");
if(param.sequence < 0 ) param.sequence = 0;
param.process = (char*) json_object_get_string(obj, "process");
param.min_duration = interval;
param.publish_point = (char*) purl;
TraceI(FLAG_DATA_POINT, "handle_data_observing payload. device=%s, res=%s, interval=%d, purl=%s, seq=%d, process=%s",
device, res, interval, purl, param.sequence, param.process?param.process:"");
if(res == NULL || * res == 0)
{
id = ResRefresher().NewRefresherPointforRT(device, rt, ¶m);
}
else
{
id = AddResourceRefresher((char *)device, (char *)res, ¶m);
}
end:
return id;
}
extern "C" int handle_data_observing(const char *playload, char *purl_prefix)
{
JSON_Value *json = json_parse_string( playload);
int ret = handle_data_observing_json(json, purl_prefix);
if(json)json_value_free(json);
return ret;
}
extern "C" void load_configured_data_monitors()
{
char *content = NULL;
char ini_path[MAX_PATH_LEN] = {0};
char *path = get_product_config_pathname((char*)"data_monitors.cfg", (char*)TT_DEVICE, (char*)NULL, ini_path);
load_file_to_memory(path, &content);
if(content == NULL)
return;
TraceI(FLAG_DEVICE_REG, "loading data_monitors.cfg for static data monitors");
JSON_Array *monitors;
JSON_Value *root_value = json_parse_string(content);
free(content);
if (root_value == NULL)
{
LOG_MSG("data_monitors.cfg is not valid json format");
return;
}
if (json_value_get_type(root_value) != JSONArray)
{
WARNING("data_monitors.cfg is json array format");
goto end;
}
monitors = json_value_get_array(root_value);
for (int i = 0; i < (int)json_array_get_count(monitors); i++)
{
JSON_Value * one_monitor = json_array_get_value(monitors, i);
handle_data_observing_json(one_monitor, NULL);
}
end:
json_value_free(root_value);
}
|
#include <tcpserver.h>
#include <iostream>
using namespace std;
int main()
{
// Initialize server socket..
TCPServer tcpServer;
// When a new client connected:
tcpServer.onNewConnection = [&](TCPSocket *newClient) {
cout << "New client: [";
cout << newClient->remoteAddress() << ":" << newClient->remotePort() << "]" << endl;
newClient->onMessageReceived = [newClient](string message) {
cout << newClient->remoteAddress() << ":" << newClient->remotePort() << " => " << message << endl;
};
newClient->onSocketClosed = [newClient]() {
cout << "Socket closed:" << newClient->remoteAddress() << ":" << newClient->remotePort() << endl;
};
};
// Bind the server to a port.
tcpServer.Bind(8888);
// Start Listening the server.
tcpServer.Listen();
// You should do an input loop so the program will not terminated immediately:
string input;
getline(cin, input);
while (input != "exit")
{
getline(cin, input);
}
// Close the server before exiting the program.
tcpServer.Close();
return 0;
}
|
#include <DB/Storages/MergeTree/MergeTreeData.h>
#include <DB/Interpreters/ExpressionAnalyzer.h>
#include <DB/Storages/MergeTree/MergeTreeBlockInputStream.h>
#include <DB/Storages/MergeTree/MergedBlockOutputStream.h>
#include <DB/Storages/MergeTree/MergeTreePartChecker.h>
#include <DB/Parsers/ASTIdentifier.h>
#include <DB/Parsers/ASTNameTypePair.h>
#include <DB/DataStreams/ExpressionBlockInputStream.h>
#include <DB/DataStreams/copyData.h>
#include <DB/IO/WriteBufferFromFile.h>
#include <DB/IO/CompressedReadBuffer.h>
#include <DB/IO/HexWriteBuffer.h>
#include <DB/DataTypes/DataTypeDate.h>
#include <DB/DataTypes/DataTypeDateTime.h>
#include <DB/DataTypes/DataTypeFixedString.h>
#include <DB/DataTypes/DataTypeEnum.h>
#include <DB/DataTypes/DataTypeNested.h>
#include <DB/DataTypes/DataTypeArray.h>
#include <DB/DataTypes/DataTypeNullable.h>
#include <DB/Common/localBackup.h>
#include <DB/Functions/FunctionFactory.h>
#include <Poco/DirectoryIterator.h>
#include <DB/Common/Increment.h>
#include <DB/Common/escapeForFileName.h>
#include <DB/Common/StringUtils.h>
#include <DB/IO/Operators.h>
#include <algorithm>
#include <iomanip>
#include <thread>
namespace ProfileEvents
{
extern const Event RejectedInserts;
extern const Event DelayedInserts;
extern const Event DelayedInsertsMilliseconds;
}
namespace CurrentMetrics
{
extern const Metric DelayedInserts;
}
namespace DB
{
namespace ErrorCodes
{
extern const int MEMORY_LIMIT_EXCEEDED;
}
MergeTreeData::MergeTreeData(
const String & full_path_, NamesAndTypesListPtr columns_,
const NamesAndTypesList & materialized_columns_,
const NamesAndTypesList & alias_columns_,
const ColumnDefaults & column_defaults_,
Context & context_,
ASTPtr & primary_expr_ast_,
const String & date_column_name_, const ASTPtr & sampling_expression_,
size_t index_granularity_,
const MergingParams & merging_params_,
const MergeTreeSettings & settings_,
const String & log_name_,
bool require_part_metadata_,
BrokenPartCallback broken_part_callback_)
: ITableDeclaration{materialized_columns_, alias_columns_, column_defaults_}, context(context_),
date_column_name(date_column_name_), sampling_expression(sampling_expression_),
index_granularity(index_granularity_),
merging_params(merging_params_),
settings(settings_), primary_expr_ast(primary_expr_ast_ ? primary_expr_ast_->clone() : nullptr),
require_part_metadata(require_part_metadata_),
full_path(full_path_), columns(columns_),
broken_part_callback(broken_part_callback_),
log_name(log_name_), log(&Logger::get(log_name + " (Data)"))
{
/// Проверяем, что столбец с датой существует и имеет тип Date.
const auto check_date_exists = [this] (const NamesAndTypesList & columns)
{
for (const auto & column : columns)
{
if (column.name == date_column_name)
{
if (!typeid_cast<const DataTypeDate *>(column.type.get()))
throw Exception("Date column (" + date_column_name + ") for storage of MergeTree family must have type Date."
" Provided column of type " + column.type->getName() + "."
" You may have separate column with type " + column.type->getName() + ".", ErrorCodes::BAD_TYPE_OF_FIELD);
return true;
}
}
return false;
};
if (!check_date_exists(*columns) && !check_date_exists(materialized_columns))
throw Exception{
"Date column (" + date_column_name + ") does not exist in table declaration.",
ErrorCodes::NO_SUCH_COLUMN_IN_TABLE};
merging_params.check(*columns);
/// Creating directories, if not exist.
Poco::File(full_path).createDirectories();
Poco::File(full_path + "detached").createDirectory();
if (primary_expr_ast)
initPrimaryKey();
else if (merging_params.mode != MergingParams::Unsorted)
throw Exception("Primary key could be empty only for UnsortedMergeTree", ErrorCodes::BAD_ARGUMENTS);
}
void MergeTreeData::initPrimaryKey()
{
/// Initialize description of sorting.
sort_descr.clear();
sort_descr.reserve(primary_expr_ast->children.size());
for (const ASTPtr & ast : primary_expr_ast->children)
{
String name = ast->getColumnName();
sort_descr.emplace_back(name, 1);
}
primary_expr = ExpressionAnalyzer(primary_expr_ast, context, nullptr, getColumnsList()).getActions(false);
ExpressionActionsPtr projected_expr = ExpressionAnalyzer(primary_expr_ast, context, nullptr, getColumnsList()).getActions(true);
primary_key_sample = projected_expr->getSampleBlock();
size_t primary_key_size = primary_key_sample.columns();
/// A primary key cannot contain constants. It is meaningless.
/// (And also couldn't work because primary key is serialized with method of IDataType that doesn't support constants).
/// Also a primary key must not contain any nullable column.
for (size_t i = 0; i < primary_key_size; ++i)
{
const auto & element = primary_key_sample.getByPosition(i);
const ColumnPtr & column = element.column;
if (column && column->isConst())
throw Exception{"Primary key cannot contain constants", ErrorCodes::ILLEGAL_COLUMN};
if (element.type->isNullable())
throw Exception{"Primary key cannot contain nullable columns", ErrorCodes::ILLEGAL_COLUMN};
}
primary_key_data_types.resize(primary_key_size);
for (size_t i = 0; i < primary_key_size; ++i)
primary_key_data_types[i] = primary_key_sample.getByPosition(i).type;
}
void MergeTreeData::MergingParams::check(const NamesAndTypesList & columns) const
{
/// Проверяем, что столбец sign_column, если нужен, существует, и имеет тип Int8.
if (mode == MergingParams::Collapsing)
{
if (sign_column.empty())
throw Exception("Logical error: Sign column for storage CollapsingMergeTree is empty", ErrorCodes::LOGICAL_ERROR);
for (const auto & column : columns)
{
if (column.name == sign_column)
{
if (!typeid_cast<const DataTypeInt8 *>(column.type.get()))
throw Exception("Sign column (" + sign_column + ")"
" for storage CollapsingMergeTree must have type Int8."
" Provided column of type " + column.type->getName() + ".", ErrorCodes::BAD_TYPE_OF_FIELD);
break;
}
}
}
else if (!sign_column.empty())
throw Exception("Sign column for MergeTree cannot be specified in all modes except Collapsing.", ErrorCodes::LOGICAL_ERROR);
/// Если заданы columns_to_sum, проверяем, что такие столбцы существуют.
if (!columns_to_sum.empty())
{
if (mode != MergingParams::Summing)
throw Exception("List of columns to sum for MergeTree cannot be specified in all modes except Summing.",
ErrorCodes::LOGICAL_ERROR);
for (const auto & column_to_sum : columns_to_sum)
if (columns.end() == std::find_if(columns.begin(), columns.end(),
[&](const NameAndTypePair & name_and_type) { return column_to_sum == name_and_type.name; }))
throw Exception("Column " + column_to_sum + " listed in columns to sum does not exist in table declaration.");
}
/// Проверяем, что столбец version_column, если допустим, имеет тип целого беззнакового числа.
if (!version_column.empty())
{
if (mode != MergingParams::Replacing)
throw Exception("Version column for MergeTree cannot be specified in all modes except Replacing.",
ErrorCodes::LOGICAL_ERROR);
for (const auto & column : columns)
{
if (column.name == version_column)
{
if (!typeid_cast<const DataTypeUInt8 *>(column.type.get())
&& !typeid_cast<const DataTypeUInt16 *>(column.type.get())
&& !typeid_cast<const DataTypeUInt32 *>(column.type.get())
&& !typeid_cast<const DataTypeUInt64 *>(column.type.get())
&& !typeid_cast<const DataTypeDate *>(column.type.get())
&& !typeid_cast<const DataTypeDateTime *>(column.type.get()))
throw Exception("Version column (" + version_column + ")"
" for storage ReplacingMergeTree must have type of UInt family or Date or DateTime."
" Provided column of type " + column.type->getName() + ".", ErrorCodes::BAD_TYPE_OF_FIELD);
break;
}
}
}
/// TODO Проверки для Graphite
}
String MergeTreeData::MergingParams::getModeName() const
{
switch (mode)
{
case Ordinary: return "";
case Collapsing: return "Collapsing";
case Summing: return "Summing";
case Aggregating: return "Aggregating";
case Unsorted: return "Unsorted";
case Replacing: return "Replacing";
case Graphite: return "Graphite";
default:
throw Exception("Unknown mode of operation for MergeTreeData: " + toString(mode), ErrorCodes::LOGICAL_ERROR);
}
}
Int64 MergeTreeData::getMaxDataPartIndex()
{
std::lock_guard<std::mutex> lock_all(all_data_parts_mutex);
Int64 max_part_id = 0;
for (const auto & part : all_data_parts)
max_part_id = std::max(max_part_id, part->right);
return max_part_id;
}
void MergeTreeData::loadDataParts(bool skip_sanity_checks)
{
LOG_DEBUG(log, "Loading data parts");
std::lock_guard<std::mutex> lock(data_parts_mutex);
std::lock_guard<std::mutex> lock_all(all_data_parts_mutex);
data_parts.clear();
all_data_parts.clear();
Strings part_file_names;
Poco::DirectoryIterator end;
for (Poco::DirectoryIterator it(full_path); it != end; ++it)
{
/// Пропускаем временные директории старше суток.
if (startsWith(it.name(), "tmp_"))
continue;
part_file_names.push_back(it.name());
}
DataPartsVector broken_parts_to_remove;
DataPartsVector broken_parts_to_detach;
size_t suspicious_broken_parts = 0;
Poco::RegularExpression::MatchVec matches;
for (const String & file_name : part_file_names)
{
if (!ActiveDataPartSet::isPartDirectory(file_name, &matches))
continue;
MutableDataPartPtr part = std::make_shared<DataPart>(*this);
ActiveDataPartSet::parsePartName(file_name, *part, &matches);
part->name = file_name;
bool broken = false;
try
{
part->loadColumns(require_part_metadata);
part->loadChecksums(require_part_metadata);
part->loadIndex();
part->checkNotBroken(require_part_metadata);
}
catch (const Exception & e)
{
/** Если не хватает памяти для загрузки куска - не нужно считать его битым.
* На самом деле, похожих ситуаций может быть ещё много.
* Но это не страшно, так как ниже есть защита от слишком большого количества кусков для удаления.
*/
if (e.code() == ErrorCodes::MEMORY_LIMIT_EXCEEDED)
throw;
broken = true;
tryLogCurrentException(__PRETTY_FUNCTION__);
}
catch (...)
{
broken = true;
tryLogCurrentException(__PRETTY_FUNCTION__);
}
/// Игнорируем и, возможно, удаляем битые куски, которые могут образовываться после грубого перезапуска сервера.
if (broken)
{
if (part->level == 0)
{
/// Восстановить куски нулевого уровня невозможно.
LOG_ERROR(log, "Considering to remove broken part " << full_path + file_name << " because it's impossible to repair.");
broken_parts_to_remove.push_back(part);
}
else
{
/// Посмотрим, сколько кусков покрыты битым. Если хотя бы два, предполагаем, что битый кусок образован их
/// слиянием, и мы ничего не потеряем, если его удалим.
int contained_parts = 0;
LOG_ERROR(log, "Part " << full_path + file_name << " is broken. Looking for parts to replace it.");
++suspicious_broken_parts;
for (const String & contained_name : part_file_names)
{
if (contained_name == file_name)
continue;
if (!ActiveDataPartSet::isPartDirectory(contained_name, &matches))
continue;
DataPart contained_part(*this);
ActiveDataPartSet::parsePartName(contained_name, contained_part, &matches);
if (part->contains(contained_part))
{
LOG_ERROR(log, "Found part " << full_path + contained_name);
++contained_parts;
}
}
if (contained_parts >= 2)
{
LOG_ERROR(log, "Considering to remove broken part " << full_path + file_name << " because it covers at least 2 other parts");
broken_parts_to_remove.push_back(part);
}
else
{
LOG_ERROR(log, "Detaching broken part " << full_path + file_name
<< " because it covers less than 2 parts. You need to resolve this manually");
broken_parts_to_detach.push_back(part);
}
}
continue;
}
part->modification_time = Poco::File(full_path + file_name).getLastModified().epochTime();
data_parts.insert(part);
}
if (suspicious_broken_parts > settings.max_suspicious_broken_parts && !skip_sanity_checks)
throw Exception("Suspiciously many (" + toString(suspicious_broken_parts) + ") broken parts to remove.",
ErrorCodes::TOO_MANY_UNEXPECTED_DATA_PARTS);
for (const auto & part : broken_parts_to_remove)
part->remove();
for (const auto & part : broken_parts_to_detach)
part->renameAddPrefix(true, "");
all_data_parts = data_parts;
/** Удаляем из набора актуальных кусков куски, которые содержатся в другом куске (которые были склеены),
* но по каким-то причинам остались лежать в файловой системе.
* Удаление файлов будет произведено потом в методе clearOldParts.
*/
if (data_parts.size() >= 2)
{
DataParts::iterator prev_jt = data_parts.begin();
DataParts::iterator curr_jt = prev_jt;
++curr_jt;
while (curr_jt != data_parts.end())
{
/// Куски данных за разные месяцы рассматривать не будем
if ((*curr_jt)->month != (*prev_jt)->month)
{
++prev_jt;
++curr_jt;
continue;
}
if ((*curr_jt)->contains(**prev_jt))
{
(*prev_jt)->remove_time = (*prev_jt)->modification_time;
data_parts.erase(prev_jt);
prev_jt = curr_jt;
++curr_jt;
}
else if ((*prev_jt)->contains(**curr_jt))
{
(*curr_jt)->remove_time = (*curr_jt)->modification_time;
data_parts.erase(curr_jt++);
}
else
{
++prev_jt;
++curr_jt;
}
}
}
calculateColumnSizes();
LOG_DEBUG(log, "Loaded data parts (" << data_parts.size() << " items)");
}
/** Является ли директория куска старой.
* Это так, если её дата модификации,
* и одновременно дата модификации всех файлов внутри неё
* (рассматриваются файлы только на одном уровне вложенности),
* меньше threshold.
*/
static bool isOldPartDirectory(Poco::File & directory, time_t threshold)
{
if (directory.getLastModified().epochTime() >= threshold)
return false;
Poco::DirectoryIterator end;
for (Poco::DirectoryIterator it(directory); it != end; ++it)
if (it->getLastModified().epochTime() >= threshold)
return false;
return true;
}
void MergeTreeData::clearOldTemporaryDirectories()
{
/// Если метод уже вызван из другого потока, то можно ничего не делать.
std::unique_lock<std::mutex> lock(clear_old_temporary_directories_mutex, std::defer_lock);
if (!lock.try_lock())
return;
time_t current_time = time(0);
/// Удаляем временные директории старше суток.
Poco::DirectoryIterator end;
for (Poco::DirectoryIterator it{full_path}; it != end; ++it)
{
if (startsWith(it.name(), "tmp_"))
{
Poco::File tmp_dir(full_path + it.name());
try
{
if (tmp_dir.isDirectory() && isOldPartDirectory(tmp_dir, current_time - settings.temporary_directories_lifetime))
{
LOG_WARNING(log, "Removing temporary directory " << full_path << it.name());
Poco::File(full_path + it.name()).remove(true);
}
}
catch (const Poco::FileNotFoundException &)
{
/// Ничего не делаем, если файл уже удалён.
}
}
}
}
MergeTreeData::DataPartsVector MergeTreeData::grabOldParts()
{
DataPartsVector res;
/// Если метод уже вызван из другого потока, то можно ничего не делать.
std::unique_lock<std::mutex> lock(grab_old_parts_mutex, std::defer_lock);
if (!lock.try_lock())
return res;
time_t now = time(0);
{
std::lock_guard<std::mutex> lock(all_data_parts_mutex);
for (DataParts::iterator it = all_data_parts.begin(); it != all_data_parts.end();)
{
if (it->unique() && /// После этого ref_count не может увеличиться.
(*it)->remove_time < now &&
now - (*it)->remove_time > settings.old_parts_lifetime)
{
res.push_back(*it);
all_data_parts.erase(it++);
}
else
++it;
}
}
if (!res.empty())
LOG_TRACE(log, "Found " << res.size() << " old parts to remove.");
return res;
}
void MergeTreeData::addOldParts(const MergeTreeData::DataPartsVector & parts)
{
std::lock_guard<std::mutex> lock(all_data_parts_mutex);
all_data_parts.insert(parts.begin(), parts.end());
}
void MergeTreeData::clearOldParts()
{
auto parts_to_remove = grabOldParts();
for (const DataPartPtr & part : parts_to_remove)
{
LOG_DEBUG(log, "Removing part " << part->name);
part->remove();
}
}
void MergeTreeData::setPath(const String & new_full_path, bool move_data)
{
if (move_data)
{
if (Poco::File{new_full_path}.exists())
throw Exception{
"Target path already exists: " + new_full_path,
/// @todo existing target can also be a file, not directory
ErrorCodes::DIRECTORY_ALREADY_EXISTS
};
Poco::File(full_path).renameTo(new_full_path);
/// Если данные перемещать не нужно, значит их переместил кто-то другой. Расчитываем, что он еще и сбросил кеши.
context.resetCaches();
}
full_path = new_full_path;
}
void MergeTreeData::dropAllData()
{
LOG_TRACE(log, "dropAllData: waiting for locks.");
std::lock_guard<std::mutex> lock(data_parts_mutex);
std::lock_guard<std::mutex> lock_all(all_data_parts_mutex);
LOG_TRACE(log, "dropAllData: removing data from memory.");
data_parts.clear();
all_data_parts.clear();
column_sizes.clear();
context.resetCaches();
LOG_TRACE(log, "dropAllData: removing data from filesystem.");
Poco::File(full_path).remove(true);
LOG_TRACE(log, "dropAllData: done.");
}
void MergeTreeData::checkAlter(const AlterCommands & params)
{
/// Проверим, что указанные преобразования можно совершить над списком столбцов без учета типов.
auto new_columns = *columns;
auto new_materialized_columns = materialized_columns;
auto new_alias_columns = alias_columns;
auto new_column_defaults = column_defaults;
params.apply(new_columns, new_materialized_columns, new_alias_columns, new_column_defaults);
/// Список столбцов, которые нельзя трогать.
/// sampling_expression можно не учитывать, потому что он обязан содержаться в первичном ключе.
Names keys;
if (primary_expr)
keys = primary_expr->getRequiredColumns();
if (!merging_params.sign_column.empty())
keys.push_back(merging_params.sign_column);
std::sort(keys.begin(), keys.end());
for (const AlterCommand & command : params)
{
if (std::binary_search(keys.begin(), keys.end(), command.column_name))
throw Exception("trying to ALTER key column " + command.column_name, ErrorCodes::ILLEGAL_COLUMN);
}
/// Проверим, что преобразования типов возможны.
ExpressionActionsPtr unused_expression;
NameToNameMap unused_map;
bool unused_bool;
/// augment plain columns with materialized columns for convert expression creation
new_columns.insert(std::end(new_columns),
std::begin(new_materialized_columns), std::end(new_materialized_columns));
createConvertExpression(nullptr, getColumnsList(), new_columns, unused_expression, unused_map, unused_bool);
}
void MergeTreeData::createConvertExpression(const DataPartPtr & part, const NamesAndTypesList & old_columns, const NamesAndTypesList & new_columns,
ExpressionActionsPtr & out_expression, NameToNameMap & out_rename_map, bool & out_force_update_metadata) const
{
out_expression = nullptr;
out_rename_map = {};
out_force_update_metadata = false;
using NameToType = std::map<String, DataTypePtr>;
NameToType new_types;
for (const NameAndTypePair & column : new_columns)
new_types.emplace(column.name, column.type);
/// Сколько столбцов сейчас в каждой вложенной структуре. Столбцы не из вложенных структур сюда тоже попадут и не помешают.
std::map<String, size_t> nested_table_counts;
for (const NameAndTypePair & column : old_columns)
++nested_table_counts[DataTypeNested::extractNestedTableName(column.name)];
/// For every column that need to be converted: source column name, column name of calculated expression for conversion.
std::vector<std::pair<String, String>> conversions;
for (const NameAndTypePair & column : old_columns)
{
if (!new_types.count(column.name))
{
bool is_nullable = column.type.get()->isNullable();
if (!part || part->hasColumnFiles(column.name))
{
/// Столбец нужно удалить.
const IDataType * observed_type;
if (is_nullable)
{
const DataTypeNullable & nullable_type = static_cast<const DataTypeNullable &>(*column.type);
observed_type = nullable_type.getNestedType().get();
}
else
observed_type = column.type.get();
String escaped_column = escapeForFileName(column.name);
out_rename_map[escaped_column + ".bin"] = "";
out_rename_map[escaped_column + ".mrk"] = "";
if (is_nullable)
{
out_rename_map[escaped_column + ".null.bin"] = "";
out_rename_map[escaped_column + ".null.mrk"] = "";
}
/// Если это массив или последний столбец вложенной структуры, нужно удалить файлы с размерами.
if (typeid_cast<const DataTypeArray *>(observed_type))
{
String nested_table = DataTypeNested::extractNestedTableName(column.name);
/// Если это был последний столбец, относящийся к этим файлам .size0, удалим файлы.
if (!--nested_table_counts[nested_table])
{
String escaped_nested_table = escapeForFileName(nested_table);
out_rename_map[escaped_nested_table + ".size0.bin"] = "";
out_rename_map[escaped_nested_table + ".size0.mrk"] = "";
}
}
}
}
else
{
const auto new_type = new_types[column.name].get();
const String new_type_name = new_type->getName();
const auto old_type = column.type.get();
if (new_type_name != old_type->getName() && (!part || part->hasColumnFiles(column.name)))
{
bool is_nullable = new_type->isNullable();
const IDataType * observed_type;
if (is_nullable)
{
const DataTypeNullable & nullable_type = static_cast<const DataTypeNullable &>(*new_type);
observed_type = nullable_type.getNestedType().get();
}
else
observed_type = new_type;
/// When ALTERing between Enums with same underlying type, don't modify columns, just update columns.txt.
/// Same for Arrays of Enums, arbitary depth.
if (part)
{
const IDataType * type_from = old_type;
const IDataType * type_to = observed_type;
bool enums_with_same_type = false;
while (true)
{
if ((typeid_cast<const DataTypeEnum8 *>(type_to) && typeid_cast<const DataTypeEnum8 *>(type_from))
|| (typeid_cast<const DataTypeEnum16 *>(type_to) && typeid_cast<const DataTypeEnum16 *>(type_from)))
{
enums_with_same_type = true;
break;
}
const DataTypeArray * arr_from = typeid_cast<const DataTypeArray *>(type_from);
const DataTypeArray * arr_to = typeid_cast<const DataTypeArray *>(type_to);
if (arr_from && arr_to)
{
type_from = arr_from->getNestedType().get();
type_to = arr_to->getNestedType().get();
}
else
break;
}
if (enums_with_same_type)
{
out_force_update_metadata = true;
continue;
}
}
/// Need to modify column type.
if (!out_expression)
out_expression = std::make_shared<ExpressionActions>(NamesAndTypesList(), context.getSettingsRef());
out_expression->addInput(ColumnWithTypeAndName(nullptr, column.type, column.name));
Names out_names;
/// @todo invent the name more safely
const auto new_type_name_column = '#' + new_type_name + "_column";
out_expression->add(ExpressionAction::addColumn(
{ std::make_shared<ColumnConstString>(1, new_type_name), std::make_shared<DataTypeString>(), new_type_name_column }));
const FunctionPtr & function = FunctionFactory::instance().get("CAST", context);
out_expression->add(ExpressionAction::applyFunction(
function, Names{column.name, new_type_name_column}), out_names);
out_expression->add(ExpressionAction::removeColumn(new_type_name_column));
out_expression->add(ExpressionAction::removeColumn(column.name));
conversions.emplace_back(column.name, out_names.at(0));
}
}
}
if (!conversions.empty())
{
/// Give proper names for temporary columns with conversion results.
NamesWithAliases projection;
projection.reserve(conversions.size());
for (const auto & source_and_expression : conversions)
{
String converting_column_name = source_and_expression.first + " converting";
projection.emplace_back(source_and_expression.second, converting_column_name);
const String escaped_converted_column = escapeForFileName(converting_column_name);
const String escaped_source_column = escapeForFileName(source_and_expression.first);
/// After conversion, we need to rename temporary files into original.
out_rename_map[escaped_converted_column + ".bin"] = escaped_source_column + ".bin";
out_rename_map[escaped_converted_column + ".mrk"] = escaped_source_column + ".mrk";
const IDataType * new_type = new_types[source_and_expression.first].get();
/// NOTE Sizes of arrays are not updated during conversion.
/// Information on how to update the null map if it is a nullable column.
if (new_type->isNullable())
{
out_rename_map[escaped_converted_column + ".null.bin"] = escaped_source_column + ".null.bin";
out_rename_map[escaped_converted_column + ".null.mrk"] = escaped_source_column + ".null.mrk";
}
}
out_expression->add(ExpressionAction::project(projection));
}
if (part && !out_rename_map.empty())
{
std::string message;
{
WriteBufferFromString out(message);
out << "Will rename ";
bool first = true;
for (const auto & from_to : out_rename_map)
{
if (!first)
out << ", ";
first = false;
out << from_to.first << " to " << from_to.second;
}
out << " in part " << part->name;
}
LOG_DEBUG(log, message);
}
}
MergeTreeData::AlterDataPartTransactionPtr MergeTreeData::alterDataPart(
const DataPartPtr & part,
const NamesAndTypesList & new_columns,
const ASTPtr & new_primary_key,
bool skip_sanity_checks)
{
ExpressionActionsPtr expression;
AlterDataPartTransactionPtr transaction(new AlterDataPartTransaction(part)); /// Блокирует изменение куска.
bool force_update_metadata;
createConvertExpression(part, part->columns, new_columns, expression, transaction->rename_map, force_update_metadata);
size_t num_files_to_modify = transaction->rename_map.size();
size_t num_files_to_remove = 0;
for (const auto & from_to : transaction->rename_map)
if (from_to.second.empty())
++num_files_to_remove;
if (!skip_sanity_checks
&& (num_files_to_modify > settings.max_files_to_modify_in_alter_columns
|| num_files_to_remove > settings.max_files_to_remove_in_alter_columns))
{
transaction->clear();
std::stringstream exception_message;
exception_message << "Suspiciously many (" << transaction->rename_map.size()
<< ") files (";
bool first = true;
for (const auto & from_to : transaction->rename_map)
{
if (!first)
exception_message << ", ";
exception_message << "from '" << from_to.first << "' to '" << from_to.second << "'";
first = false;
}
exception_message << ") need to be modified in part " << part->name << " of table at " << full_path << ". Aborting just in case. "
<< " If it is not an error, you could increase merge_tree/max_files_to_modify_in_alter_columns parameter in configuration file.";
throw Exception(exception_message.str(), ErrorCodes::TABLE_DIFFERS_TOO_MUCH);
}
DataPart::Checksums add_checksums;
/// Обновление первичного ключа, если нужно.
size_t new_primary_key_file_size{};
uint128 new_primary_key_hash{};
if (new_primary_key.get() != primary_expr_ast.get())
{
ExpressionActionsPtr new_primary_expr = ExpressionAnalyzer(new_primary_key, context, nullptr, new_columns).getActions(true);
Block new_primary_key_sample = new_primary_expr->getSampleBlock();
size_t new_key_size = new_primary_key_sample.columns();
Columns new_index(new_key_size);
/// Копируем существующие столбцы первичного ключа. Новые заполняем значениями по-умолчанию.
/// NOTE Не поддерживаются вычислимые значения по-умолчанию.
ssize_t prev_position_of_existing_column = -1;
for (size_t i = 0; i < new_key_size; ++i)
{
const String & column_name = new_primary_key_sample.safeGetByPosition(i).name;
if (primary_key_sample.has(column_name))
{
ssize_t position_of_existing_column = primary_key_sample.getPositionByName(column_name);
if (position_of_existing_column < prev_position_of_existing_column)
throw Exception("Permuting of columns of primary key is not supported", ErrorCodes::BAD_ARGUMENTS);
new_index[i] = part->index.at(position_of_existing_column);
prev_position_of_existing_column = position_of_existing_column;
}
else
{
const IDataType & type = *new_primary_key_sample.safeGetByPosition(i).type;
new_index[i] = type.createConstColumn(part->size, type.getDefault())->convertToFullColumnIfConst();
}
}
if (prev_position_of_existing_column == -1)
throw Exception("No common columns while modifying primary key", ErrorCodes::BAD_ARGUMENTS);
String index_tmp_path = full_path + part->name + "/primary.idx.tmp";
WriteBufferFromFile index_file(index_tmp_path);
HashingWriteBuffer index_stream(index_file);
for (size_t i = 0, size = part->size; i < size; ++i)
for (size_t j = 0; j < new_key_size; ++j)
new_primary_key_sample.getByPosition(j).type.get()->serializeBinary(*new_index[j].get(), i, index_stream);
transaction->rename_map["primary.idx.tmp"] = "primary.idx";
index_stream.next();
new_primary_key_file_size = index_stream.count();
new_primary_key_hash = index_stream.getHash();
}
if (transaction->rename_map.empty() && !force_update_metadata)
{
transaction->clear();
return nullptr;
}
/// Применим выражение и запишем результат во временные файлы.
if (expression)
{
MarkRanges ranges(1, MarkRange(0, part->size));
BlockInputStreamPtr part_in = std::make_shared<MergeTreeBlockInputStream>(full_path + part->name + '/',
DEFAULT_MERGE_BLOCK_SIZE, expression->getRequiredColumns(), *this, part, ranges,
false, nullptr, "", false, 0, DBMS_DEFAULT_BUFFER_SIZE, false);
ExpressionBlockInputStream in(part_in, expression);
MergedColumnOnlyOutputStream out(*this, full_path + part->name + '/', true, CompressionMethod::LZ4, false);
in.readPrefix();
out.writePrefix();
while (Block b = in.read())
out.write(b);
in.readSuffix();
add_checksums = out.writeSuffixAndGetChecksums();
}
/// Обновим контрольные суммы.
DataPart::Checksums new_checksums = part->checksums;
for (auto it : transaction->rename_map)
{
if (it.second == "")
new_checksums.files.erase(it.first);
else
new_checksums.files[it.second] = add_checksums.files[it.first];
}
if (new_primary_key_file_size)
{
new_checksums.files["primary.idx"].file_size = new_primary_key_file_size;
new_checksums.files["primary.idx"].file_hash = new_primary_key_hash;
}
/// Запишем обновленные контрольные суммы во временный файл
if (!part->checksums.empty())
{
transaction->new_checksums = new_checksums;
WriteBufferFromFile checksums_file(full_path + part->name + "/checksums.txt.tmp", 4096);
new_checksums.write(checksums_file);
transaction->rename_map["checksums.txt.tmp"] = "checksums.txt";
}
/// Запишем обновленный список столбцов во временный файл.
{
transaction->new_columns = new_columns.filter(part->columns.getNames());
WriteBufferFromFile columns_file(full_path + part->name + "/columns.txt.tmp", 4096);
transaction->new_columns.writeText(columns_file);
transaction->rename_map["columns.txt.tmp"] = "columns.txt";
}
return transaction;
}
void MergeTreeData::AlterDataPartTransaction::commit()
{
if (!data_part)
return;
try
{
Poco::ScopedWriteRWLock lock(data_part->columns_lock);
String path = data_part->storage.full_path + data_part->name + "/";
/// NOTE: checking that a file exists before renaming or deleting it
/// is justified by the fact that, when converting an ordinary column
/// to a nullable column, new files are created which did not exist
/// before, i.e. they do not have older versions.
/// 1) Переименуем старые файлы.
for (auto it : rename_map)
{
String name = it.second.empty() ? it.first : it.second;
Poco::File file{path + name};
if (file.exists())
file.renameTo(path + name + ".tmp2");
}
/// 2) Переместим на их место новые и обновим метаданные в оперативке.
for (auto it : rename_map)
{
if (!it.second.empty())
Poco::File{path + it.first}.renameTo(path + it.second);
}
DataPart & mutable_part = const_cast<DataPart &>(*data_part);
mutable_part.checksums = new_checksums;
mutable_part.columns = new_columns;
/// 3) Удалим старые файлы.
for (auto it : rename_map)
{
String name = it.second.empty() ? it.first : it.second;
Poco::File file{path + name + ".tmp2"};
if (file.exists())
file.remove();
}
mutable_part.size_in_bytes = MergeTreeData::DataPart::calcTotalSize(path);
/// TODO: можно не сбрасывать кеши при добавлении столбца.
data_part->storage.context.resetCaches();
clear();
}
catch (...)
{
/// Если что-то пошло не так, не будем удалять временные файлы в деструкторе.
clear();
throw;
}
}
MergeTreeData::AlterDataPartTransaction::~AlterDataPartTransaction()
{
try
{
if (!data_part)
return;
LOG_WARNING(data_part->storage.log, "Aborting ALTER of part " << data_part->name);
String path = data_part->storage.full_path + data_part->name + "/";
for (auto it : rename_map)
{
if (!it.second.empty())
{
try
{
Poco::File file(path + it.first);
if (file.exists())
file.remove();
}
catch (Poco::Exception & e)
{
LOG_WARNING(data_part->storage.log, "Can't remove " << path + it.first << ": " << e.displayText());
}
}
}
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
void MergeTreeData::renameTempPartAndAdd(MutableDataPartPtr & part, SimpleIncrement * increment, Transaction * out_transaction)
{
auto removed = renameTempPartAndReplace(part, increment, out_transaction);
if (!removed.empty())
throw Exception("Added part " + part->name + " covers " + toString(removed.size())
+ " existing part(s) (including " + removed[0]->name + ")", ErrorCodes::LOGICAL_ERROR);
}
MergeTreeData::DataPartsVector MergeTreeData::renameTempPartAndReplace(
MutableDataPartPtr & part, SimpleIncrement * increment, Transaction * out_transaction)
{
if (out_transaction && out_transaction->data)
throw Exception("Using the same MergeTreeData::Transaction for overlapping transactions is invalid", ErrorCodes::LOGICAL_ERROR);
LOG_TRACE(log, "Renaming " << part->name << ".");
String old_name = part->name;
String old_path = getFullPath() + old_name + "/";
DataPartsVector replaced;
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
/** It is important that obtaining new block number and adding that block to parts set is done atomically.
* Otherwise there is race condition - merge of blocks could happen in interval that doesn't yet contain new part.
*/
if (increment)
part->left = part->right = increment->get();
String new_name = ActiveDataPartSet::getPartName(part->left_date, part->right_date, part->left, part->right, part->level);
part->is_temp = false;
part->name = new_name;
bool duplicate = data_parts.count(part);
part->name = old_name;
part->is_temp = true;
if (duplicate)
throw Exception("Part " + new_name + " already exists", ErrorCodes::DUPLICATE_DATA_PART);
String new_path = getFullPath() + new_name + "/";
/// Переименовываем кусок.
Poco::File(old_path).renameTo(new_path);
part->is_temp = false;
part->name = new_name;
bool obsolete = false; /// Покрыт ли part каким-нибудь куском.
/// Куски, содержащиеся в part, идут в data_parts подряд, задевая место, куда вставился бы сам part.
DataParts::iterator it = data_parts.lower_bound(part);
/// Пойдем влево.
while (it != data_parts.begin())
{
--it;
if (!part->contains(**it))
{
if ((*it)->contains(*part))
obsolete = true;
++it;
break;
}
replaced.push_back(*it);
(*it)->remove_time = time(0);
removePartContributionToColumnSizes(*it);
data_parts.erase(it++); /// Да, ++, а не --.
}
std::reverse(replaced.begin(), replaced.end()); /// Нужно получить куски в порядке возрастания.
/// Пойдем вправо.
while (it != data_parts.end())
{
if (!part->contains(**it))
{
if ((*it)->name == part->name || (*it)->contains(*part))
obsolete = true;
break;
}
replaced.push_back(*it);
(*it)->remove_time = time(0);
removePartContributionToColumnSizes(*it);
data_parts.erase(it++);
}
if (obsolete)
{
LOG_WARNING(log, "Obsolete part " << part->name << " added");
part->remove_time = time(0);
}
else
{
data_parts.insert(part);
addPartContributionToColumnSizes(part);
}
{
std::lock_guard<std::mutex> lock_all(all_data_parts_mutex);
all_data_parts.insert(part);
}
}
if (out_transaction)
{
out_transaction->data = this;
out_transaction->parts_to_add_on_rollback = replaced;
out_transaction->parts_to_remove_on_rollback = DataPartsVector(1, part);
}
return replaced;
}
void MergeTreeData::replaceParts(const DataPartsVector & remove, const DataPartsVector & add, bool clear_without_timeout)
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
for (const DataPartPtr & part : remove)
{
part->remove_time = clear_without_timeout ? 0 : time(0);
if (data_parts.erase(part))
removePartContributionToColumnSizes(part);
}
for (const DataPartPtr & part : add)
{
if (data_parts.insert(part).second)
addPartContributionToColumnSizes(part);
}
}
void MergeTreeData::attachPart(const DataPartPtr & part)
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
std::lock_guard<std::mutex> lock_all(all_data_parts_mutex);
if (!all_data_parts.insert(part).second)
throw Exception("Part " + part->name + " is already attached", ErrorCodes::DUPLICATE_DATA_PART);
data_parts.insert(part);
addPartContributionToColumnSizes(part);
}
void MergeTreeData::renameAndDetachPart(const DataPartPtr & part, const String & prefix, bool restore_covered, bool move_to_detached)
{
LOG_INFO(log, "Renaming " << part->name << " to " << prefix << part->name << " and detaching it.");
std::lock_guard<std::mutex> lock(data_parts_mutex);
std::lock_guard<std::mutex> lock_all(all_data_parts_mutex);
if (!all_data_parts.erase(part))
throw Exception("No such data part", ErrorCodes::NO_SUCH_DATA_PART);
removePartContributionToColumnSizes(part);
data_parts.erase(part);
if (move_to_detached || !prefix.empty())
part->renameAddPrefix(move_to_detached, prefix);
if (restore_covered)
{
auto it = all_data_parts.lower_bound(part);
Strings restored;
bool error = false;
Int64 pos = part->left;
if (it != all_data_parts.begin())
{
--it;
if (part->contains(**it))
{
if ((*it)->left != part->left)
error = true;
data_parts.insert(*it);
addPartContributionToColumnSizes(*it);
pos = (*it)->right + 1;
restored.push_back((*it)->name);
}
else
error = true;
++it;
}
else
error = true;
for (; it != all_data_parts.end() && part->contains(**it); ++it)
{
if ((*it)->left < pos)
continue;
if ((*it)->left > pos)
error = true;
data_parts.insert(*it);
addPartContributionToColumnSizes(*it);
pos = (*it)->right + 1;
restored.push_back((*it)->name);
}
if (pos != part->right + 1)
error = true;
for (const String & name : restored)
{
LOG_INFO(log, "Activated part " << name);
}
if (error)
LOG_ERROR(log, "The set of parts restored in place of " << part->name << " looks incomplete. There might or might not be a data loss.");
}
}
void MergeTreeData::detachPartInPlace(const DataPartPtr & part)
{
renameAndDetachPart(part, "", false, false);
}
MergeTreeData::DataParts MergeTreeData::getDataParts() const
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
return data_parts;
}
MergeTreeData::DataPartsVector MergeTreeData::getDataPartsVector() const
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
return DataPartsVector(std::begin(data_parts), std::end(data_parts));
}
size_t MergeTreeData::getTotalActiveSizeInBytes() const
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
size_t res = 0;
for (auto & part : data_parts)
res += part->size_in_bytes;
return res;
}
MergeTreeData::DataParts MergeTreeData::getAllDataParts() const
{
std::lock_guard<std::mutex> lock(all_data_parts_mutex);
return all_data_parts;
}
size_t MergeTreeData::getMaxPartsCountForMonth() const
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
size_t res = 0;
size_t cur_count = 0;
DayNum_t cur_month = DayNum_t(0);
for (const auto & part : data_parts)
{
if (part->month == cur_month)
{
++cur_count;
}
else
{
cur_month = part->month;
cur_count = 1;
}
res = std::max(res, cur_count);
}
return res;
}
std::pair<Int64, bool> MergeTreeData::getMinBlockNumberForMonth(DayNum_t month) const
{
std::lock_guard<std::mutex> lock(all_data_parts_mutex);
for (const auto & part : all_data_parts) /// Поиск можно сделать лучше.
if (part->month == month)
return { part->left, true }; /// Блоки в data_parts упорядочены по month и left.
return { 0, false };
}
bool MergeTreeData::hasBlockNumberInMonth(Int64 block_number, DayNum_t month) const
{
std::lock_guard<std::mutex> lock(data_parts_mutex);
for (const auto & part : data_parts) /// Поиск можно сделать лучше.
{
if (part->month == month && part->left <= block_number && part->right >= block_number)
return true;
if (part->month > month)
break;
}
return false;
}
void MergeTreeData::delayInsertIfNeeded(Poco::Event * until)
{
const size_t parts_count = getMaxPartsCountForMonth();
if (parts_count < settings.parts_to_delay_insert)
return;
if (parts_count >= settings.parts_to_throw_insert)
{
ProfileEvents::increment(ProfileEvents::RejectedInserts);
throw Exception("Too much parts. Merges are processing significantly slower than inserts.", ErrorCodes::TOO_MUCH_PARTS);
}
const size_t max_k = settings.parts_to_throw_insert - settings.parts_to_delay_insert; /// always > 0
const size_t k = 1 + parts_count - settings.parts_to_delay_insert; /// from 1 to max_k
const double delay_sec = ::pow(settings.max_delay_to_insert, static_cast<double>(k) / max_k);
ProfileEvents::increment(ProfileEvents::DelayedInserts);
ProfileEvents::increment(ProfileEvents::DelayedInsertsMilliseconds, delay_sec * 1000);
CurrentMetrics::Increment metric_increment(CurrentMetrics::DelayedInserts);
LOG_INFO(log, "Delaying inserting block by "
<< std::fixed << std::setprecision(4) << delay_sec << " sec. because there are " << parts_count << " parts");
if (until)
until->tryWait(delay_sec * 1000);
else
std::this_thread::sleep_for(std::chrono::duration<double>(delay_sec));
}
MergeTreeData::DataPartPtr MergeTreeData::getActiveContainingPart(const String & part_name)
{
MutableDataPartPtr tmp_part(new DataPart(*this));
ActiveDataPartSet::parsePartName(part_name, *tmp_part);
std::lock_guard<std::mutex> lock(data_parts_mutex);
/// Кусок может покрываться только предыдущим или следующим в data_parts.
DataParts::iterator it = data_parts.lower_bound(tmp_part);
if (it != data_parts.end())
{
if ((*it)->name == part_name)
return *it;
if ((*it)->contains(*tmp_part))
return *it;
}
if (it != data_parts.begin())
{
--it;
if ((*it)->contains(*tmp_part))
return *it;
}
return nullptr;
}
MergeTreeData::DataPartPtr MergeTreeData::getPartIfExists(const String & part_name)
{
MutableDataPartPtr tmp_part(new DataPart(*this));
ActiveDataPartSet::parsePartName(part_name, *tmp_part);
std::lock_guard<std::mutex> lock(all_data_parts_mutex);
DataParts::iterator it = all_data_parts.lower_bound(tmp_part);
if (it != all_data_parts.end() && (*it)->name == part_name)
return *it;
return nullptr;
}
MergeTreeData::DataPartPtr MergeTreeData::getShardedPartIfExists(const String & part_name, size_t shard_no)
{
const MutableDataPartPtr & part_from_shard = per_shard_data_parts.at(shard_no);
if (part_from_shard->name == part_name)
return part_from_shard;
else
return nullptr;
}
MergeTreeData::MutableDataPartPtr MergeTreeData::loadPartAndFixMetadata(const String & relative_path)
{
MutableDataPartPtr part = std::make_shared<DataPart>(*this);
part->name = relative_path;
ActiveDataPartSet::parsePartName(Poco::Path(relative_path).getFileName(), *part);
/// Раньше список столбцов записывался неправильно. Удалим его и создадим заново.
if (Poco::File(full_path + relative_path + "/columns.txt").exists())
Poco::File(full_path + relative_path + "/columns.txt").remove();
part->loadColumns(false);
part->loadChecksums(false);
part->loadIndex();
part->checkNotBroken(false);
part->modification_time = Poco::File(full_path + relative_path).getLastModified().epochTime();
/// Если нет файла с чексуммами, посчитаем чексуммы и запишем. Заодно проверим данные.
if (part->checksums.empty())
{
MergeTreePartChecker::Settings settings;
settings.setIndexGranularity(index_granularity);
settings.setRequireColumnFiles(true);
MergeTreePartChecker::checkDataPart(full_path + relative_path, settings, primary_key_data_types, &part->checksums);
{
WriteBufferFromFile out(full_path + relative_path + "/checksums.txt.tmp", 4096);
part->checksums.write(out);
}
Poco::File(full_path + relative_path + "/checksums.txt.tmp").renameTo(full_path + relative_path + "/checksums.txt");
}
return part;
}
void MergeTreeData::calculateColumnSizes()
{
column_sizes.clear();
for (const auto & part : data_parts)
addPartContributionToColumnSizes(part);
}
void MergeTreeData::addPartContributionToColumnSizes(const DataPartPtr & part)
{
const auto & files = part->checksums.files;
for (const auto & column : *columns)
{
const auto escaped_name = escapeForFileName(column.name);
const auto bin_file_name = escaped_name + ".bin";
const auto mrk_file_name = escaped_name + ".mrk";
auto & column_size = column_sizes[column.name];
if (files.count(bin_file_name))
column_size += files.find(bin_file_name)->second.file_size;
if (files.count(mrk_file_name))
column_size += files.find(mrk_file_name)->second.file_size;
}
}
void MergeTreeData::removePartContributionToColumnSizes(const DataPartPtr & part)
{
const auto & files = part->checksums.files;
for (const auto & column : *columns)
{
const auto escaped_name = escapeForFileName(column.name);
const auto bin_file_name = escaped_name + ".bin";
const auto mrk_file_name = escaped_name + ".mrk";
auto & column_size = column_sizes[column.name];
if (files.count(bin_file_name))
column_size -= files.find(bin_file_name)->second.file_size;
if (files.count(mrk_file_name))
column_size -= files.find(mrk_file_name)->second.file_size;
}
}
void MergeTreeData::freezePartition(const std::string & prefix, const String & with_name)
{
LOG_DEBUG(log, "Freezing parts with prefix " + prefix);
String clickhouse_path = Poco::Path(context.getPath()).makeAbsolute().toString();
String shadow_path = clickhouse_path + "shadow/";
Poco::File(shadow_path).createDirectories();
String backup_path = shadow_path
+ (!with_name.empty()
? escapeForFileName(with_name)
: toString(Increment(shadow_path + "increment.txt").get(true)))
+ "/";
LOG_DEBUG(log, "Snapshot will be placed at " + backup_path);
size_t parts_processed = 0;
Poco::DirectoryIterator end;
for (Poco::DirectoryIterator it(full_path); it != end; ++it)
{
if (startsWith(it.name(), prefix))
{
LOG_DEBUG(log, "Freezing part " << it.name());
String part_absolute_path = it.path().absolute().toString();
if (!startsWith(part_absolute_path, clickhouse_path))
throw Exception("Part path " + part_absolute_path + " is not inside " + clickhouse_path, ErrorCodes::LOGICAL_ERROR);
String backup_part_absolute_path = part_absolute_path;
backup_part_absolute_path.replace(0, clickhouse_path.size(), backup_path);
localBackup(part_absolute_path, backup_part_absolute_path);
++parts_processed;
}
}
LOG_DEBUG(log, "Freezed " << parts_processed << " parts");
}
size_t MergeTreeData::getPartitionSize(const std::string & partition_name) const
{
size_t size = 0;
Poco::DirectoryIterator end;
Poco::DirectoryIterator end2;
for (Poco::DirectoryIterator it(full_path); it != end; ++it)
{
const auto filename = it.name();
if (!ActiveDataPartSet::isPartDirectory(filename))
continue;
if (!startsWith(filename, partition_name))
continue;
const auto part_path = it.path().absolute().toString();
for (Poco::DirectoryIterator it2(part_path); it2 != end2; ++it2)
{
const auto part_file_path = it2.path().absolute().toString();
size += Poco::File(part_file_path).getSize();
}
}
return size;
}
static std::pair<String, DayNum_t> getMonthNameAndDayNum(const Field & partition)
{
String month_name = partition.getType() == Field::Types::UInt64
? toString(partition.get<UInt64>())
: partition.safeGet<String>();
if (month_name.size() != 6 || !std::all_of(month_name.begin(), month_name.end(), isdigit))
throw Exception("Invalid partition format: " + month_name + ". Partition should consist of 6 digits: YYYYMM",
ErrorCodes::INVALID_PARTITION_NAME);
DayNum_t date = DateLUT::instance().YYYYMMDDToDayNum(parse<UInt32>(month_name + "01"));
/// Не можем просто сравнить date с нулем, потому что 0 тоже валидный DayNum.
if (month_name != toString(DateLUT::instance().toNumYYYYMMDD(date) / 100))
throw Exception("Invalid partition format: " + month_name + " doesn't look like month.",
ErrorCodes::INVALID_PARTITION_NAME);
return std::make_pair(month_name, date);
}
String MergeTreeData::getMonthName(const Field & partition)
{
return getMonthNameAndDayNum(partition).first;
}
String MergeTreeData::getMonthName(DayNum_t month)
{
return toString(DateLUT::instance().toNumYYYYMMDD(month) / 100);
}
DayNum_t MergeTreeData::getMonthDayNum(const Field & partition)
{
return getMonthNameAndDayNum(partition).second;
}
DayNum_t MergeTreeData::getMonthFromName(const String & month_name)
{
DayNum_t date = DateLUT::instance().YYYYMMDDToDayNum(parse<UInt32>(month_name + "01"));
/// Не можем просто сравнить date с нулем, потому что 0 тоже валидный DayNum.
if (month_name != toString(DateLUT::instance().toNumYYYYMMDD(date) / 100))
throw Exception("Invalid partition format: " + month_name + " doesn't look like month.",
ErrorCodes::INVALID_PARTITION_NAME);
return date;
}
DayNum_t MergeTreeData::getMonthFromPartPrefix(const String & part_prefix)
{
return getMonthFromName(part_prefix.substr(0, strlen("YYYYMM")));
}
}
|
/* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/core/lib/strings/str_util.h"
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/kernels/reduction_gpu_kernels.cu.h"
#include "tensorflow/core/kernels/reduction_ops_common.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
#if GOOGLE_CUDA
namespace gpuprim = ::cub;
#elif TENSORFLOW_USE_ROCM
namespace gpuprim = ::hipcub;
#endif
namespace tensorflow {
namespace {
template <typename U, typename T>
__device__ __host__ EIGEN_STRONG_INLINE
typename std::enable_if<!std::is_same<T, U>::value, U>::type
strict_cast(T t);
template <typename U, typename T>
__device__ __host__ EIGEN_STRONG_INLINE
typename std::enable_if<std::is_same<T, U>::value, U>::type
strict_cast(T t) {
return t;
}
template <>
__device__ __host__ EIGEN_STRONG_INLINE float strict_cast<float, Eigen::half>(
Eigen::half t) {
return functor::HalfToFloat()(t);
}
template <>
__device__ __host__ EIGEN_STRONG_INLINE Eigen::half
strict_cast<Eigen::half, float>(float t) {
return functor::FloatToHalf()(t);
}
template <typename T>
struct softmax_traits {
using accumulator_type = T;
};
template <>
struct softmax_traits<Eigen::half> {
using accumulator_type = float;
};
template <typename T, typename U>
__global__ void GenerateNormalizedProb(const T* logits, const U* sum_probs,
const T* max_logits, T* output,
const int num_rows, const int num_cols,
const bool in_log_space) {
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int row = tid / num_cols;
const int col = tid % num_cols;
// TODO(jamesqin): change to half2 load when inputs are Eigen::half.
U input = strict_cast<U>(logits[tid]);
U max_val = strict_cast<U>(ldg(max_logits + row));
U result;
if (row < num_rows && col < num_cols) {
if (in_log_space) {
result = input - max_val - log(ldg(sum_probs + row));
} else {
result = exp(input - max_val) / ldg(sum_probs + row);
}
output[tid] = strict_cast<T>(result);
}
}
template <typename T, typename U>
struct SubtractAndExpFunctor {
__host__ __device__ SubtractAndExpFunctor(const T* logits,
const T* max_logits,
const int num_cols)
: logits_(logits), max_logits_(max_logits), num_cols_(num_cols) {}
__host__ __device__ U operator()(const int gid) const {
// TODO(jamesqin): change to half2 load when inputs are Eigen::half.
const U diff =
strict_cast<U>(logits_[gid] - ldg(max_logits_ + gid / num_cols_));
return exp(diff);
}
const T* logits_;
const T* max_logits_;
const int num_cols_;
};
template <typename T, typename Op, typename InputIter>
void DoRowReduction(OpKernelContext* context, T* output, InputIter input,
int rows, int cols) {
typedef const Eigen::array<TTypes<float>::Tensor::Index, 1>& ReductionAxes;
Constants<GPUDevice> constants;
Op op;
functor::ReduceImpl<T, Op, T*, InputIter, ReductionAxes>(
context, output, input, 2, rows, cols, 1, 1, constants.kOne, op);
}
} // namespace
template <typename T>
class SoftmaxOpGPU : public OpKernel {
public:
explicit SoftmaxOpGPU(OpKernelConstruction* context) : OpKernel(context) {
log_ = absl::StartsWith(type_string(), "Log");
}
void Compute(OpKernelContext* context) override {
const Tensor& logits_in_ = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(logits_in_.shape()),
errors::InvalidArgument("logits must have >= 1 dimension, got ",
logits_in_.shape().DebugString()));
auto logits_in = logits_in_.flat_inner_dims<T>();
const int rows = logits_in.dimension(0);
const int cols = logits_in.dimension(1);
Tensor* softmax_out = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 0, logits_in_.shape(), &softmax_out));
const auto& cu_stream = GetCudaStream(context);
if (logits_in_.NumElements() > 0) {
Tensor max_logits;
Tensor sum_probs;
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<T>::value,
softmax_out->shape(), &max_logits));
typedef typename softmax_traits<T>::accumulator_type acc_type;
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<acc_type>::value,
softmax_out->shape(), &sum_probs));
DoRowReduction<T, gpuprim::Max, const T*>(
context, const_cast<T*>(max_logits.flat<T>().data()),
reinterpret_cast<const T*>(logits_in_.flat<T>().data()), rows, cols);
const int numThreads = 128;
const int numBlocks = Eigen::divup(rows * cols, numThreads);
gpuprim::CountingInputIterator<int> counting_iterator(0);
using InputIterType =
gpuprim::TransformInputIterator<acc_type,
SubtractAndExpFunctor<T, acc_type>,
gpuprim::CountingInputIterator<int>>;
InputIterType input_itr(
counting_iterator,
SubtractAndExpFunctor<T, acc_type>(
reinterpret_cast<const T*>(logits_in_.flat<T>().data()),
reinterpret_cast<const T*>(max_logits.flat<T>().data()), cols));
DoRowReduction<acc_type, gpuprim::Sum, InputIterType>(
context, const_cast<acc_type*>(sum_probs.flat<acc_type>().data()),
input_itr, rows, cols);
TF_CHECK_OK(GpuLaunchKernel(
GenerateNormalizedProb<T, acc_type>, numBlocks, numThreads, 0,
cu_stream, reinterpret_cast<const T*>(logits_in_.flat<T>().data()),
reinterpret_cast<const acc_type*>(sum_probs.flat<acc_type>().data()),
reinterpret_cast<const T*>(max_logits.flat<T>().data()),
const_cast<T*>(softmax_out->flat<T>().data()), rows, cols, log_));
}
}
private:
bool log_;
};
REGISTER_KERNEL_BUILDER(
Name("Softmax").Device(DEVICE_GPU).TypeConstraint<Eigen::half>("T"),
SoftmaxOpGPU<Eigen::half>);
REGISTER_KERNEL_BUILDER(
Name("Softmax").Device(DEVICE_GPU).TypeConstraint<float>("T"),
SoftmaxOpGPU<float>);
REGISTER_KERNEL_BUILDER(
Name("Softmax").Device(DEVICE_GPU).TypeConstraint<double>("T"),
SoftmaxOpGPU<double>);
REGISTER_KERNEL_BUILDER(
Name("LogSoftmax").Device(DEVICE_GPU).TypeConstraint<Eigen::half>("T"),
SoftmaxOpGPU<Eigen::half>);
REGISTER_KERNEL_BUILDER(
Name("LogSoftmax").Device(DEVICE_GPU).TypeConstraint<float>("T"),
SoftmaxOpGPU<float>);
} // end namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
|
#ifndef STLPLUS_PERSISTENT_SMART_PTR
#define STLPLUS_PERSISTENT_SMART_PTR
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// Persistence of STLplus smart_ptr
////////////////////////////////////////////////////////////////////////////////
#include "persistence_fixes.hpp"
#include "persistent_contexts.hpp"
#include "smart_ptr.hpp"
////////////////////////////////////////////////////////////////////////////////
namespace stlplus
{
// smart_ptr - uses dump/restore_pointer on the contents
// exceptions: persistent_dump_failed
template<typename T, typename DE>
void dump_smart_ptr(dump_context&, const smart_ptr<T>& data, DE dump_element);
// exceptions: persistent_restore_failed
template<typename T, typename RE>
void restore_smart_ptr(restore_context&, smart_ptr<T>& data, RE restore_element);
// smart_ptr_clone using the polymorphic callback approach - uses dump/restore_callback on the contents
// exceptions: persistent_dump_failed
template<typename T>
void dump_smart_ptr_clone_callback(dump_context&, const smart_ptr_clone<T>& data);
// exceptions: persistent_restore_failed
template<typename T>
void restore_smart_ptr_clone_callback(restore_context&, smart_ptr_clone<T>& data);
// smart_ptr_clone using the interface approach - uses dump/restore_interface on the contents
// exceptions: persistent_dump_failed
template<typename T>
void dump_smart_ptr_clone_interface(dump_context&, const smart_ptr_clone<T>& data);
// exceptions: persistent_restore_failed
template<typename T>
void restore_smart_ptr_clone_interface(restore_context&, smart_ptr_clone<T>& data);
// smart_ptr_nocopy is not made persistent because if it is uncopyable, it must be undumpable
} // end namespace stlplus
////////////////////////////////////////////////////////////////////////////////
#include "persistent_smart_ptr.tpp"
#endif
|
/**
* \file dnn/src/common/argmxx/base_impl.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "megdnn/oprs.h"
#include "src/common/utils.h"
namespace megdnn {
void ArgmxxBase::check_layout_fwd(const TensorLayout& src, const TensorLayout& dst) {
auto errmsg = [&]() {
return megdnn_layout_msg(src) + ", " + megdnn_layout_msg(dst);
};
MEGDNN_MARK_USED_VAR(errmsg);
megdnn_assert_contiguous(src);
megdnn_assert_contiguous(dst);
megdnn_assert(src.ndim > 0_z, "%s", errmsg().c_str());
megdnn_assert(src.ndim == dst.ndim, "%s", errmsg().c_str());
megdnn_assert(
param().axis < static_cast<int32_t>(src.ndim), "%s", errmsg().c_str());
for (size_t i = 0; i < src.ndim; ++i) {
if (i != static_cast<size_t>(param().axis)) {
megdnn_assert_eq_size_t(src.shape[i], dst.shape[i]);
} else {
megdnn_assert_eq_size_t(dst.shape[i], 1_z);
}
}
megdnn_assert(dst.dtype == dtype::Int32());
}
void ArgmaxForward::deduce_layout(const TensorLayout& src, TensorLayout& dst) {
dst = src;
dst.shape[param().axis] = 1;
dst.dtype = dtype::Int32();
dst.init_contiguous_stride();
}
void ArgmaxForward::check_exec(
const TensorLayout& src, const TensorLayout& dst, size_t workspace_in_bytes) {
check_layout_fwd(src, dst);
auto required_workspace_in_bytes = get_workspace_in_bytes(src, dst);
megdnn_assert(workspace_in_bytes >= required_workspace_in_bytes);
}
void ArgminForward::deduce_layout(const TensorLayout& src, TensorLayout& dst) {
dst = src;
dst.shape[param().axis] = 1;
dst.dtype = dtype::Int32();
dst.init_contiguous_stride();
}
void ArgminForward::check_exec(
const TensorLayout& src, const TensorLayout& dst, size_t workspace_in_bytes) {
check_layout_fwd(src, dst);
auto required_workspace_in_bytes = get_workspace_in_bytes(src, dst);
megdnn_assert(workspace_in_bytes >= required_workspace_in_bytes);
}
} // namespace megdnn
// vim: syntax=cpp.doxygen
|
/*
@file=espADC.cpp
Provides ADC Readings for each channel
add following to the setup() in your main.cpp
espADC::setup();
add following to the loop in you main.cpp
espADC:readADCChannel(channel);
@dependency=
*/
// #include <SPI.h>
// SPI mySpi;
#include <Adafruit_MCP3008.h>
Adafruit_MCP3008 adc;
#include "LittleFS.h" // LittleFS is declared
#include <ArduinoJson.h>
#include <string.h>
#include "espADC.h"
espADC myAdc;
espADCcfg myAdcCfg;
ADCconfig myadccfg, *adcCfgP = &myadccfg;
// adcCfg = &myadccfg;
static const char *cfgFilename = "/espADCconfig.json";
#define _DEBUG_ myadccfg.debug
/*Label GPIO Input Output Notes
D0 GPIO16 no interrupt no PWM or I2C support HIGH at boot
used to wake up from deep sleep
D1 GPIO5 OK OK often used as SCL (I2C)
D2 GPIO4 OK OK often used as SDA (I2C)
D3 GPIO0 pulled up OK connected to FLASH button, boot fails if pulled LOW
D4 GPIO2 pulled up OK HIGH at boot
connected to on-board LED, boot fails if pulled LOW
D5 GPIO14 OK OK SPI (SCLK)
D6 GPIO12 OK OK SPI (MISO)
D7 GPIO13 OK OK SPI (MOSI)
D8 GPIO15 pulled to GND OK SPI (CS)
Boot fails if pulled HIGH
RX GPIO3 OK RX pin HIGH at boot
TX GPIO1 TX pin OK HIGH at boot
debug output at boot, boot fails if pulled LOW
A0 ADC0 Analog Input X
*/
//define pin connections
#define MISO_PIN myadccfg.spicfg.MISOpin //MISO -- D7
#define MOSI_PIN myadccfg.spicfg.MOSIpin //MOSI -- D6
#define SCLK_PIN myadccfg.spicfg.SCLKpin // SCLK -- D4
#define CS_PIN myadccfg.spicfg.CSpin // CS -- D8
/* MCP3008 ESP8266
V_DD 3v3
V_REF 3v3
AGND GND
CLK GPIO14 (D5)
D_OUT GPIO12 (D6)
D_IN GPIO13 (D7)
CS GPIO15 (D8)
DGND GND
*/
//MCP3008 adc(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN);
// MCP3008 adc;
// Adafruit_MCP3008 adc;
espADC::espADC() { //Class constructor
};
espADC::~espADC() { //Class destructor
};
bool espADC::setup(){
// read configuraton file
myAdcCfg.loadConfiguration();
if (_DEBUG_) {
Serial.printf("Chip ID: %s", String(ESP.getChipId()).c_str()); Serial.println();
Serial.printf("Device Vcc: %s", String(ESP.getVcc()).c_str()); Serial.println();
Serial.print("Configuration JSON File: ");Serial.println(cfgFilename);
myAdcCfg.printFile();
Serial.println("Configuration: ");
myAdcCfg.printCFG();
}
// Initialize for hardware SPI
// /*!
// * @brief Initialize for hardware SPI
// * @param cs
// * number of CSPIN (Chip Select)
// * @param theSPI
// * optional SPI object
// * @return true if process is successful
// */
// bool Adafruit_MCP3008::begin(uint8_t cs, SPIClass *theSPI)
// /*!
// * @brief Initialize for software SPI
// * @param sck
// * number of pin used for SCK (Serial Clock)
// * @param mosi
// * number of pin used for MOSI (Master Out Slave In)
// * @param miso
// * number of pin used for MISO (Master In Slave Out)
// * @param cs
// * number of pin used for CS (Chip Select)
// * @return true if process is successful
// */
// bool Adafruit_MCP3008::begin(uint8_t sck, uint8_t mosi, uint8_t miso, uint8_t cs) {
// Use the default SPI hardware interface.
// bool ADCReady = adc.begin(CS_PIN);
// bool ADCReady = adc.begin(SCLK_PIN, MOSI_PIN, MISO_PIN, CS_PIN);
// bool ADCReady = adc.begin(14, 13, 12, 15);
// Or use custom pins to use a software SPI interface.
// adc.begin(SS, MOSI, MISO, SCK);
// adc.begin(CS_PIN, MOSI_PIN, MISO_PIN, SCLK_PIN);
// Or use custom pins to use a software SPI interface.
// adc.begin(SS, MOSI, MISO, SCK);
// Initializing serial port for SPI comms
int _spibaud = myadccfg.adccfg.Bauds;
if(_spibaud <= 0){ _spibaud = 74880;};
Serial.begin(_spibaud);
// pinMode(CS_PIN, OUTPUT);
// myAdc.ADCoff();
Serial.println(F("Enabling ADC"));
myAdc.ADCon();
delay(20);
if (_DEBUG_) {
Serial.println(SCLK_PIN);
Serial.println(MISO_PIN);
Serial.println(MOSI_PIN);
Serial.println(CS_PIN);
}
bool ADCReady;
// if (mySpi.pins(SCLK_PIN, MISO_PIN, MOSI_PIN, CS_PIN)) {
// mySpi.begin();
// mySpi.setBitOrder(MSBFIRST);
// mySpi.setDataMode(SPI_MODE0);
// mySpi.setFrequency(10000); // 1 MHz -- remove line when running on Arduino UNO
// (sck, mosi, miso, cs);
adc.begin(SCLK_PIN, MOSI_PIN, MISO_PIN, CS_PIN);
ADCReady = true;
Serial.println(F("ADC Ready"));
// }
return ADCReady;
}
ADCdata espADC::readAllchannel(ADCdata &myadcdata) {
for (int chan=0; chan<myadccfg.adccfg.numChannels; chan++) {
if (_DEBUG_) {
Serial.print(myAdc.adcRead(chan)); Serial.print(",\t");
}
myadcdata.ADC[chan] = myAdc.adcRead(chan);
}
return myadcdata;
}
int espADC::readChannel(uint8_t channel) {
int chan_val = myAdc.adcRead(channel);
if (_DEBUG_) {
Serial.printf("Channel %i: %i",channel,chan_val); Serial.println();
}
return chan_val;
}
void espADC::error(int err) {
if (!myAdc.ADCtest()) {
Serial.printf("ADC read error: %d\n", err);
}
}
int espADC::adcRead(int channel) {
if ((channel > myadccfg.adccfg.numChannels) || (channel < 0)) {
Serial.println(F("ADC Channel Read error"));
return -1;
}
myAdc.ADCon();
// mySpi.transfer(1);
// uint8_t r1 = mySpi.transfer((channel + 8) << 4);
// uint8_t r2 = mySpi.transfer(0);
int chan_val = adc.readADC(channel);
myAdc.ADCoff();
int chlo = myadccfg.calib.CHlo[channel];
int chhi = myadccfg.calib.CHhi[channel];
if (_DEBUG_) {
Serial.print(F("CH Lo: ")); Serial.println(chlo);
Serial.print(F("CH Hi: ")); Serial.println(chhi);
}
// return ((r1 & 3) << 8) + r2;
return map(chan_val, chlo, chhi, 0, 100);
}
float espADC::ADCcalib(int reading, int chloval, int chhival) {
return 0;
}
void espADC::ADCoff() {
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
// mySpi.end();
}
void espADC::ADCon() {
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, LOW);
}
bool espADC::ADCtest() {
// myAdc.readAllchannel();
return 1;
}
espADCcfg::espADCcfg() { //Class constructor
};
espADCcfg::~espADCcfg() { //Class destructor
};
bool espADCcfg::loadConfiguration(const char *filename, ADCconfig &myadccfg){
//mounts file system.
LittleFS.begin();
FSInfo fs_info;
LittleFS.info(fs_info);
Serial.print(F("Total Bytes: "));Serial.println( fs_info.totalBytes);
Serial.print(F("used Bytes: "));Serial.println(fs_info.usedBytes);
Serial.print(F("Block Size: "));Serial.println(fs_info.blockSize);
Serial.print(F("Page Size: "));Serial.println(fs_info.pageSize);
Serial.print(F("max open files: "));Serial.println(fs_info.maxOpenFiles);
Serial.print(F("max path lengt: "));Serial.println(fs_info.maxPathLength);
// Open file for reading
if (LittleFS.exists(filename)) {
File file = LittleFS.open(filename, "r");
Serial.print(F("Opening myadccfg file: ")); Serial.println(filename);
if (!file) {
Serial.print(F("Failed to read file")); Serial.println(filename);
return 0;
};
const int capacity = 3*JSON_OBJECT_SIZE(2) +
JSON_OBJECT_SIZE(4) +
JSON_OBJECT_SIZE(16) +
200;
Serial.print("JsonBufferCapacity: "); Serial.println(capacity);
StaticJsonDocument<capacity> doc;
// StaticJsonDocument<300> doc;
// Deserialize the JSON document
DeserializationError error = deserializeJson(doc, file);
if (error) {
Serial.print(F("Failed to read file, using default configuration"));
Serial.println(error.f_str());
return 0;
};
// Copy values from the JsonDocument to the myadccfg
//Release
myadccfg.cfg_rel = doc["release"] | 99.99;
myadccfg.debug = doc["debug"] | false;
//SPI
JsonObject SPI = doc["SPI"];
myadccfg.spicfg.SCLKpin = SPI["SCLK"]; // 14
myadccfg.spicfg.MISOpin = SPI["MISO"]; // 12
myadccfg.spicfg.MOSIpin = SPI["MOSI"]; // 13
myadccfg.spicfg.CSpin = SPI["CS"]; // 15
//ADC
JsonObject ADC = doc["ADC"];
myadccfg.adccfg.Bauds = ADC["bauds"] | 74880;
myadccfg.adccfg.numChannels = ADC["numChannel"] | 74880;
//UART
JsonObject UART = doc["UART"];
myadccfg.uartcfg.TXpin = UART["TX"]; // 3
myadccfg.uartcfg.RXpin = UART["RX"];// 1
//Calibration
JsonArray Calib = doc["ADCcalibration"];
int arraySize = Calib.size();
if (_DEBUG_) {
Serial.print(F("arraySize: ")); Serial.println(arraySize);
}
JsonArray ADCcalibLo = Calib[0];
int arrayLoSize = ADCcalibLo.size();
for (int j = 0; j < arrayLoSize; j++) {
adcCfgP->calib.CHlo[j] = ADCcalibLo[j];
if (_DEBUG_) {
Serial.print(F("CHLo-"));Serial.print(j);Serial.print(F(": "));Serial.println(adcCfgP->calib.CHlo[j]);
}
}
JsonArray ADCcalibHi = Calib[1];
int arrayHiSize = ADCcalibHi.size();
for (int j = 0; j < arrayHiSize; j++) {
adcCfgP->calib.CHhi[j] = ADCcalibHi[j];
if (_DEBUG_) {
Serial.print(F("CHHi-"));Serial.print(j);Serial.print(F(": "));Serial.println(adcCfgP->calib.CHhi[j]);
}
}
file.close(); // Close the file (Curiously, File's destructor doesn't close the file)
} else {
Serial.print(F("File not found: ")); Serial.println(filename);
return 0;
};
Serial.println("done processing JSON");
LittleFS.end(); //unmounts file system.
return 1;
};
void espADCcfg::loadConfiguration(){
espADCcfg::loadConfiguration(cfgFilename, myadccfg);
};
bool espADCcfg::saveConfiguration(const char *filename, const ADCconfig &myadccfg) {
//mounts file system.
LittleFS.begin();
// Delete existing file, otherwise the configuration is appended to the file
LittleFS.remove(filename);
// Open file for writing
File file = LittleFS.open(filename, "r+");
if (!file) {
Serial.print(F("Failed to create file: ")); Serial.println(filename);
return 0;
}
// Allocate a temporary JsonDocument
// Don't forget to change the capacity to match your requirements.
// Use arduinojson.org/assistant to compute the capacity.
StaticJsonDocument<256> doc;
// Set the values in the document
// doc["hostname"] = myadccfg.wirelesscfg.hostname;
// doc["port"] = myadccfg.wirelesscfg.port;
// Serialize JSON to file
if (serializeJson(doc, file) == 0) {
Serial.println(F("Failed to write to file")); Serial.println(filename);
return 0;
}
// Close the file
file.close();
//unmounts file system.
LittleFS.end();
return 1;
};
void espADCcfg::saveConfiguration(){
espADCcfg::saveConfiguration(cfgFilename, myadccfg);
};
void espADCcfg::printFile(const char *filename){
//mounts file system.
LittleFS.begin();
FSInfo fs_info;
LittleFS.info(fs_info);
Serial.print(F("Total Bytes: "));Serial.println( fs_info.totalBytes);
Serial.print(F("used Bytes: "));Serial.println(fs_info.usedBytes);
Serial.print(F("Block Size: "));Serial.println(fs_info.blockSize);
Serial.print(F("Page Size: "));Serial.println(fs_info.pageSize);
Serial.print(F("max open files: "));Serial.println(fs_info.maxOpenFiles);
Serial.print(F("max path lengt: "));Serial.println(fs_info.maxPathLength);
// Open file for reading
File file = LittleFS.open(filename, "r");
if (!file) {
Serial.print(F("Failed to read file: "));Serial.println(filename);
return;
}
// Extract each characters by one by one
while (file.available()) {
Serial.print((char)file.read());
}
Serial.println();
// Close the file
file.close();
//unmounts file system.
LittleFS.end();
};
void espADCcfg::printFile(){
espADCcfg::printFile(cfgFilename);
};
void espADCcfg::printCFG(){
Serial.printf("Release: %f ",myadccfg.cfg_rel); Serial.println();
Serial.printf("Debug mode: %s ", myadccfg.debug? "true" : "false"); Serial.println();
Serial.println(F("SPI myadccfg"));
Serial.println(myadccfg.spicfg.MISOpin);
Serial.println(myadccfg.spicfg.MOSIpin);
Serial.println(myadccfg.spicfg.SCLKpin);
Serial.println(myadccfg.spicfg.CSpin);
Serial.println(F("UART myadccfg"));
Serial.println(myadccfg.uartcfg.TXpin);
Serial.println(myadccfg.uartcfg.RXpin);
Serial.println(F("ADC myadccfg"));
Serial.println(myadccfg.adccfg.Bauds);
Serial.println(myadccfg.adccfg.numChannels);
Serial.println(myadccfg.adccfg.Type);
Serial.println(F("Calibration myadccfg"));
int arrayLoSize = sizeof(myadccfg.calib.CHlo)/sizeof(myadccfg.calib.CHlo[0]);
for (int j = 0; j < arrayLoSize; j++) {
Serial.print(F("CH"));Serial.print(j);Serial.print(F("Lo: "));Serial.println(myadccfg.calib.CHlo[j]);
}
int arrayHiSize = sizeof(myadccfg.calib.CHhi)/sizeof(myadccfg.calib.CHhi[0]);
for (int j = 0; j < arrayHiSize; j++) {
Serial.print(F("CH"));Serial.print(j);Serial.print(F("Lo: "));Serial.println(myadccfg.calib.CHhi[j]);
}
};
|
/*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#include <alibabacloud/drds/model/CreateOrderForRdsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Drds;
using namespace AlibabaCloud::Drds::Model;
CreateOrderForRdsResult::CreateOrderForRdsResult() :
ServiceResult()
{}
CreateOrderForRdsResult::CreateOrderForRdsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
CreateOrderForRdsResult::~CreateOrderForRdsResult()
{}
void CreateOrderForRdsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Data"].isNull())
data_ = value["Data"].asString();
}
std::string CreateOrderForRdsResult::getData()const
{
return data_;
}
bool CreateOrderForRdsResult::getSuccess()const
{
return success_;
}
|
/*--------------------------------------------------------------------------*\
| |
| 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, 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) 2003 |
| |
| , __ , __ |
| /|/ \ /|/ \ |
| | __/ _ ,_ | __/ _ ,_ |
| | \|/ / | | | | \|/ / | | | |
| |(__/|__/ |_/ \_/|/|(__/|__/ |_/ \_/|/ |
| /| /| |
| \| \| |
| |
| Enrico Bertolazzi |
| Dipartimento di Ingegneria Meccanica e Strutturale |
| Universita` degli Studi di Trento |
| Via Mesiano 77, I-38050 Trento, Italy |
| email: enrico.bertolazzi@unitn.it |
| |
\*--------------------------------------------------------------------------*/
/*
http://www.sfu.ca/~ssurjano/optimization.html
http://www-optima.amp.i.kyoto-u.ac.jp/member/student/hedar/Hedar_files/TestGO_files/Page364.htm
*/
#ifndef TESTS_NONLIN_HH
#define TESTS_NONLIN_HH
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdint>
#include <cstdio>
#include <cmath>
#include <map>
#define DEBUG 1
#define EIGEN_NO_AUTOMATIC_RESIZING 1
#include <Utils.hh>
#include <Eigen/Core>
#include <Eigen/Dense>
namespace NLproblem {
typedef std::basic_ostream<char> ostream_type;
using std::string;
using std::map;
using std::vector;
using std::pair;
using std::max;
using std::min;
using std::numeric_limits;
typedef double real_type;
typedef int32_t integer;
//! `m_e` the value of \f$ e \f$.
static real_type const m_e = 2.718281828459045235360287471352662497757;
//! `m_pi` the value of \f$ \pi \f$.
static real_type const m_pi = 3.141592653589793238462643383279502884197;
//! `m_2pi` the value of \f$ 2\pi \f$.
static real_type const m_2pi = 6.283185307179586476925286766559005768394;
//! `m_pi_2` the value of \f$ \pi/2 \f$.
static real_type const m_pi_2 = 1.570796326794896619231321691639751442098;
//! `m_pi_4` the value of \f$ \pi/4 \f$.
static real_type const m_pi_4 = 0.7853981633974483096156608458198757210492;
//! `m_1_pi` the value of \f$ 1/\pi \f$.
static real_type const m_1_pi = 0.3183098861837906715377675267450287240689;
//! `m_2_pi` the value of \f$ 2/\pi \f$.
static real_type const m_2_pi = 0.6366197723675813430755350534900574481378;
//! `m_sqrtpi` the value of \f$ \sqrt{\pi} \f$.
static real_type const m_sqrtpi = 1.772453850905516027298167483341145182798;
//! `m_2_sqrtpi` the value of \f$ 2/\sqrt{\pi} \f$.
static real_type const m_2_sqrtpi = 1.128379167095512573896158903121545171688;
//! `m_sqrt2` the value of \f$ \sqrt{2} \f$.
static real_type const m_sqrt2 = 1.414213562373095048801688724209698078570;
//! `m_1_sqrt2` the value of \f$ 1/\sqrt{2} \f$.
static real_type const m_1_sqrt2 = 0.7071067811865475244008443621048490392850;
static real_type real_max = numeric_limits<real_type>::max();
typedef Eigen::Matrix<real_type,Eigen::Dynamic,Eigen::Dynamic> dmat_t;
typedef Eigen::Matrix<real_type,Eigen::Dynamic,1> dvec_t;
typedef Eigen::Matrix<integer,Eigen::Dynamic,1> ivec_t;
class nonlinearBase {
string const _title;
string const _bibtex;
nonlinearBase();
nonlinearBase( nonlinearBase const & );
nonlinearBase const & operator = ( nonlinearBase const & );
protected:
// U T I L I T Y F U N C T I O N S -----------------------------------------
real_type power2( real_type a ) const { return a*a; }
real_type power3( real_type a ) const { return a*a*a; }
real_type power4( real_type a ) const { real_type a2 = a*a; return a2*a2; }
real_type power5( real_type a ) const { real_type a2 = a*a; return a2*a2*a; }
real_type power6( real_type a ) const { real_type a2 = a*a; return a2*a2*a2; }
void
checkMinEquations( integer i, integer i_min ) const {
UTILS_ASSERT(
i >= i_min, "checkMinEquations:: i = {} < {}", i, i_min
);
}
void
checkEven( integer i, integer i_min ) const {
UTILS_ASSERT(
(i % 2) == 0 && i >= i_min, "checkEven:: odd index i = {}", i
);
}
void
checkOdd( integer i, integer i_min ) const {
UTILS_ASSERT(
(i % 2) != 0 && i >= i_min, "checkOdd:: odd index i = {}", i
);
}
void
checkThree( integer i, integer i_min ) const {
UTILS_ASSERT(
(i % 3) == 0 && i >= i_min, "checkThree:: index i = {}", i
);
}
void
checkFour( integer i, integer i_min ) const {
UTILS_ASSERT(
(i % 4) == 0 && i >= i_min, "checkFour:: index i = {}", i
);
}
public:
explicit nonlinearBase( string const & t, string const & b )
: _title( t )
, _bibtex( b )
{}
virtual ~nonlinearBase() {}
string const & bibtex() const { return _bibtex; }
string const & title() const { return _title; }
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class multivariateFunction : public nonlinearBase {
multivariateFunction( multivariateFunction const & );
multivariateFunction const & operator = ( multivariateFunction const & );
protected:
integer n;
public:
multivariateFunction( string const & t, string const & b, integer _n )
: nonlinearBase( fmt::format("{} neq = {}", t, _n ), b )
, n(_n)
{ }
virtual ~multivariateFunction() {}
virtual real_type eval( dvec_t const & x ) const = 0;
virtual void gradient( dvec_t const & x, dvec_t & g ) const = 0;
virtual integer hessianNnz() const = 0;
virtual void hessian( dvec_t const & x, dvec_t & jac ) const = 0;
virtual void hessianPattern( ivec_t & i, ivec_t & j ) const = 0;
virtual integer numExactSolution() const = 0;
virtual void getExactSolution( dvec_t & x, integer idx ) const = 0;
virtual integer numInitialPoint() const = 0;
virtual void getInitialPoint( dvec_t & x, integer idx ) const = 0;
virtual void checkIfAdmissible( dvec_t const & x ) const = 0;
virtual void
boundingBox( dvec_t & L, dvec_t & U ) const {
L.fill( -real_max );
U.fill( real_max );
}
integer dimX( void ) const { return n; }
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class nonlinearLeastSquares: public nonlinearBase {
nonlinearLeastSquares( nonlinearLeastSquares const & );
nonlinearLeastSquares const & operator = ( nonlinearLeastSquares const & );
protected:
integer n, m;
public:
nonlinearLeastSquares(
string const & t,
string const & b,
integer _n,
integer _m
)
: nonlinearBase(
fmt::format( "{} dimF = {}, dimX = {}", t, _n, _m ), b
)
, n(_n)
, m(_m)
{}
virtual ~nonlinearLeastSquares() {}
virtual real_type evalFk( dvec_t const & x, integer k ) const = 0;
virtual void evalF ( dvec_t const & x, dvec_t & f ) const = 0;
virtual integer jacobianNnz() const = 0;
virtual void jacobian( dvec_t const & x, dvec_t & jac ) const = 0;
virtual void jacobianPattern( ivec_t & i, ivec_t & j ) const = 0;
virtual integer tensorNnz() const = 0;
virtual void tensor( dvec_t const & x, dvec_t const & lambda, dvec_t & jac ) const = 0;
virtual void tensorPattern( ivec_t & i, ivec_t & j ) const = 0;
virtual integer numExactSolution() const = 0;
virtual void getExactSolution( dvec_t & x, integer idx ) const = 0;
virtual integer numInitialPoint() const = 0;
virtual void getInitialPoint( dvec_t & x, integer idx ) const = 0;
virtual void checkIfAdmissible( dvec_t const & x ) const = 0;
virtual void
boundingBox( dvec_t & L, dvec_t & U ) const {
L.fill( -real_max );
U.fill( real_max );
}
integer dimF( void ) const { return n; }
integer dimX( void ) const { return m; }
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class nonlinearSystem: public nonlinearBase {
nonlinearSystem( nonlinearSystem const & );
nonlinearSystem const & operator = ( nonlinearSystem const & );
protected:
// U T I L I T Y F U N C T I O N S -----------------------------------------
// n = dimensione matrice
// i = riga
// j = colonna
// indirizzamento fortran
integer faddr( integer i, integer j ) const
{ return (i-1) + (j-1) * n; }
integer caddr( integer i, integer j ) const
{ return i + j * n; }
integer n;
public:
nonlinearSystem( string const & t, string const & b, integer _n )
: nonlinearBase( fmt::format("{} neq = {}", t, _n ), b )
, n(_n)
{ }
virtual ~nonlinearSystem() {}
//void
//setup( string const & t, integer _n )
//{ theTitle = t; n = _n; }
virtual real_type evalFk( dvec_t const & x, integer k ) const = 0;
virtual void evalF ( dvec_t const & x, dvec_t & f ) const = 0;
virtual integer jacobianNnz() const = 0;
virtual void jacobian( dvec_t const & x, dvec_t & jac ) const = 0;
virtual void jacobianPattern( ivec_t & i, ivec_t & j ) const = 0;
virtual integer numExactSolution() const = 0;
virtual void getExactSolution( dvec_t & x, integer idx ) const = 0;
virtual integer numInitialPoint() const = 0;
virtual void getInitialPoint( dvec_t & x, integer idx ) const = 0;
virtual void checkIfAdmissible( dvec_t const & x ) const = 0;
virtual void
boundingBox( dvec_t & L, dvec_t & U ) const {
L.fill( -real_max );
U.fill( real_max );
}
integer numEqns( void ) const { return n; }
integer
fill_CSR(
dvec_t const & x,
ivec_t & R,
ivec_t & J,
dvec_t & values
) const;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class nonlinearSystemFromMultivariateFunction: public nonlinearSystem {
nonlinearSystemFromMultivariateFunction(
nonlinearSystemFromMultivariateFunction const &
);
nonlinearSystemFromMultivariateFunction const &
operator = (nonlinearSystemFromMultivariateFunction const &);
multivariateFunction const * pMF;
public:
nonlinearSystemFromMultivariateFunction(
multivariateFunction const * _pMF
)
: nonlinearSystem( _pMF->title(), _pMF->bibtex(), _pMF->dimX() )
, pMF(_pMF) {
}
virtual ~nonlinearSystemFromMultivariateFunction() {}
virtual
real_type
evalFk( dvec_t const & x, integer k ) const {
dvec_t g(n);
evalF( x, g );
return g(k);
}
virtual
void
evalF( dvec_t const & x, dvec_t & g ) const {
pMF->gradient( x, g );
}
virtual
integer
jacobianNnz() const
{ return pMF->hessianNnz(); }
virtual
void
jacobian( dvec_t const & x, dvec_t & hess ) const
{ pMF->hessian(x,hess); }
virtual
void
jacobianPattern( ivec_t & i, ivec_t & j ) const
{ pMF->hessianPattern( i, j ); }
virtual
integer
numExactSolution() const
{ return pMF->numExactSolution(); }
virtual
void
getExactSolution( dvec_t & x, integer idx ) const
{ pMF->getExactSolution( x, idx ); }
virtual
integer
numInitialPoint() const
{ return pMF->numInitialPoint(); }
virtual
void
getInitialPoint( dvec_t & x, integer idx ) const
{ pMF->getInitialPoint( x, idx ); }
virtual
void
checkIfAdmissible( dvec_t const & x ) const
{ pMF->checkIfAdmissible( x ); }
virtual
void
boundingBox( dvec_t & L, dvec_t & U ) const
{ pMF->boundingBox( L, U ); }
integer numEqns( void ) const { return pMF->dimX(); }
string const & title(void) const { return pMF->title(); }
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if 0
class nonlinearSystemFromLeastSquares: public nonlinearSystem {
nonlinearSystemFromLeastSquares(nonlinearSystemFromLeastSquares const &);
nonlinearSystemFromLeastSquares const &
operator = (nonlinearSystemFromLeastSquares const &);
nonlinearLeastSquares const * pLS;
public:
nonlinearSystemFromLeastSquares( nonlinearLeastSquares const * _pLS )
: nonlinearSystem( _pLS->title(), _pLS->dimX() )
, pLS(_pLS) {
}
virtual ~nonlinearSystemFromLeastSquares() {}
virtual
real_type
evalFk( dvec_t const & x, integer k ) const {
dvec_t g(n);
evalF( x, g );
return g(k);
}
virtual
void
evalF( dvec_t const & x, dvec_t & g ) const {
pLS->gradient( x, g );
}
virtual
integer
jacobianNnz() const
{ return pMF->hessianNnz(); }
virtual
void
jacobian( dvec_t const & x, dmat_t & hess ) const
{ pMF->hessian(x,hess); }
virtual
void
jacobianPattern( ivec_t & i, ivec_t & j ) const
{ pMF->hessianPattern(i,j); }
virtual
integer
numExactSolution() const
{ return pMF->numExactSolution(); }
virtual
void
getExactSolution( dvec_t & x, integer idx ) const
{ pMF->getExactSolution(x,idx); }
virtual
integer
numInitialPoint() const
{ return pMF->numInitialPoint(); }
virtual
void
getInitialPoint( dvec_t & x, integer idx ) const
{ pMF->getInitialPoint(x,idx); }
virtual
void
checkIfAdmissible( dvec_t const & x ) const
{ pMF->checkIfAdmissible(x); }
virtual
void
boundingBox( dvec_t & L, dvec_t & U ) const
{ pMF->boundingBox(L,U); }
integer numEqns( void ) const { return pMF->dimX(); }
string const & title(void) const { return pMF->title(); }
};
#endif
extern vector<nonlinearSystem*> theProblems;
extern map<string,integer> theProblemsMap;
void initProblems();
}
#endif
|
#pragma once
#include "utils/util.hpp"
#include "vectors/sorted_array.hpp"
namespace tongrams {
template <typename Vocabulary, typename Mapper, typename Values, typename Ranks,
typename Grams, typename Pointers>
struct trie_count_lm {
typedef sorted_array<Grams, Ranks, Pointers> sorted_array_type;
struct builder {
builder() {}
builder(const char* input_dir, uint8_t order, uint8_t remapping_order)
: m_input_dir(input_dir)
, m_order(order)
, m_remapping_order(remapping_order) {
essentials::timer_type timer;
timer.start();
building_util::check_order(m_order);
building_util::check_remapping_order(m_remapping_order);
m_arrays.reserve(m_order);
typename Values::builder counts_builder(m_order);
for (uint8_t ord = 1; ord <= m_order; ++ord) {
std::string filename;
util::input_filename(m_input_dir, ord, filename);
util::check_filename(filename);
grams_gzparser gp(filename.c_str());
m_arrays.push_back(sorted_array_type(gp.num_lines()));
essentials::logger("Reading " + std::to_string(ord) +
"-grams counts");
for (auto const& l : gp) {
counts_builder.eat_value(l.count);
}
counts_builder.build_sequence();
}
essentials::logger("Building vocabulary");
build_vocabulary(counts_builder);
for (uint8_t ord = 2; ord <= m_order; ++ord) {
std::string order_grams(std::to_string(ord) + "-grams");
std::string prv_order_filename;
std::string cur_order_filename;
util::input_filename(m_input_dir, ord - 1, prv_order_filename);
util::input_filename(m_input_dir, ord, cur_order_filename);
grams_gzparser gp_prv_order(prv_order_filename.c_str());
grams_gzparser gp_cur_order(cur_order_filename.c_str());
uint64_t n = gp_cur_order.num_lines();
typename sorted_array_type::builder sa_builder(
n,
m_vocab.size(), // max_gram_id
counts_builder.size(ord - 1), // max_count_rank
0); // quantization_bits not used
uint64_t num_pointers = gp_prv_order.num_lines() + 1;
// NOTE: we could use this to save pointers' space
// compact_vector::builder pointers(num_pointers,
// util::ceil_log2(n + 1));
std::vector<uint64_t> pointers;
pointers.reserve(num_pointers);
essentials::logger("Building " + order_grams);
build_ngrams(ord, pointers, gp_cur_order, gp_prv_order,
counts_builder, sa_builder);
assert(pointers.back() == n);
assert(pointers.size() == num_pointers);
essentials::logger("Writing " + order_grams);
sa_builder.build(m_arrays[ord - 1], pointers, ord,
value_type::count);
essentials::logger("Writing pointers");
sorted_array_type::builder::build_pointers(m_arrays[ord - 2],
pointers);
}
counts_builder.build(m_distinct_counts);
timer.stop();
std::cout << "data structure built in " << timer.elapsed() / 1000000
<< " seconds" << std::endl;
}
void build(trie_count_lm& trie) {
trie.m_order = m_order;
trie.m_remapping_order = m_remapping_order;
trie.m_distinct_counts.swap(m_distinct_counts);
trie.m_vocab.swap(m_vocab);
trie.m_arrays.swap(m_arrays);
builder().swap(*this);
}
void swap(builder& other) {
std::swap(m_order, other.m_order);
std::swap(m_remapping_order, other.m_remapping_order);
m_distinct_counts.swap(other.m_distinct_counts);
m_vocab.swap(other.m_vocab);
m_arrays.swap(other.m_arrays);
}
private:
const char* m_input_dir;
uint8_t m_order;
uint8_t m_remapping_order;
Mapper m_mapper;
Values m_distinct_counts;
Vocabulary m_vocab;
std::vector<sorted_array_type> m_arrays;
void build_vocabulary(typename Values::builder const& counts_builder) {
size_t available_ram =
sysconf(_SC_PAGESIZE) * sysconf(_SC_PHYS_PAGES);
grams_counts_pool unigrams_pool(available_ram * 0.8);
std::string filename;
util::input_filename(m_input_dir, 1, filename);
unigrams_pool.load_from<grams_gzparser>(filename.c_str());
auto& unigrams_pool_index = unigrams_pool.index();
uint64_t n = unigrams_pool_index.size();
std::vector<byte_range> bytes;
bytes.reserve(n);
typename sorted_array_type::builder sa_builder(
n, 0, counts_builder.size(0), 0);
for (auto const& record : unigrams_pool_index) {
bytes.push_back(record.gram);
uint64_t rank = counts_builder.rank(0, record.count);
sa_builder.add_count_rank(rank);
}
sa_builder.build_counts_ranks(m_arrays.front(), 1);
compact_vector::builder ids_cvb(n, util::ceil_log2(n + 1));
for (uint64_t id = 0; id < n; ++id) {
ids_cvb.push_back(id);
}
// NOTE:
// build vocabulary excluding null terminators
// from unigrams strings so that we can lookup
// for any substring of a n-gram
// without allocating a std::string
typename Vocabulary::builder builder(bytes, compact_vector(ids_cvb),
identity_adaptor());
builder.build(m_vocab);
}
template <typename T>
void build_ngrams(uint8_t order, T& pointers,
grams_gzparser& gp_cur_order,
grams_gzparser& gp_prv_order,
typename Values::builder const& counts_builder,
typename sorted_array_type::builder& sa_builder) {
assert(order > 1);
pointers.push_back(0);
identity_adaptor adaptor;
uint64_t pointer = 0;
auto prv_order_begin = gp_prv_order.begin();
auto prv_order_end = gp_prv_order.end();
auto end = gp_cur_order.end();
for (auto begin = gp_cur_order.begin(); begin != end; ++begin) {
auto const& l = *begin;
auto gram = l.gram;
// NOTE:
// in a FORWARD trie, 'pattern' is the predecessor of 'gram'
// and 'token' is the last token of 'gram'
byte_range pattern = bytes::predecessor(gram);
assert(pattern.first != pattern.second);
byte_range token(pattern.second + 1, gram.second);
while (prv_order_begin != prv_order_end and
!bytes::equal_bytes(pattern, (*prv_order_begin).gram)) {
// NOTE:
// this test is here only to
// guarantee termination in
// case of wrong data:
// 'pattern' should ALWAYS
// be found within previous order grams
pointers.push_back(pointer);
++prv_order_begin;
}
if (prv_order_begin == prv_order_end) { // correctness check
std::cerr << "Error at line: " << pointer << "/"
<< gp_cur_order.num_lines() << std::endl;
std::cerr << "gram is: '"
<< std::string(gram.first, gram.second) << "'"
<< std::endl;
std::cerr << int(order) << "-grams file is incomplete:\n";
std::cerr
<< "\t'" << std::string(pattern.first, pattern.second)
<< "'"
<< " should have been found among " << int(order - 1)
<< "-grams" << std::endl;
exit(1);
}
++pointer;
uint64_t token_id = m_vocab.lookup(token, adaptor);
if (Mapper::context_remapping and
order > m_remapping_order + 1) {
token_id =
m_mapper.map_id(gram, token_id, &m_vocab,
&m_arrays.front(), m_remapping_order,
false); // FORWARD trie
if (token_id == global::not_found) { // correctness check
std::cerr << int(order)
<< "-grams file is incomplete:\n";
std::cerr
<< "\t'" << std::string(token.first, token.second)
<< "'"
<< " should have been found among the children of "
<< "'" << std::string(pattern.first, pattern.second)
<< "'" << std::endl;
exit(1);
}
}
sa_builder.add_gram(token_id);
uint64_t rank = counts_builder.rank(order - 1, l.count);
sa_builder.add_count_rank(rank);
}
// set remaining pointers (if any)
for (; prv_order_begin != prv_order_end; ++prv_order_begin) {
pointers.push_back(pointer);
}
}
};
trie_count_lm() : m_order(0), m_remapping_order(0) {}
template <typename T, typename Adaptor>
uint64_t lookup(T gram, Adaptor adaptor) {
static uint64_t word_ids[global::max_order];
uint64_t o = m_mapper.map_query(adaptor(gram), word_ids, &m_vocab,
&m_arrays.front(), m_remapping_order);
if (o == global::not_found or o > order()) {
return global::not_found;
}
pointer_range r;
uint64_t pos = word_ids[0];
for (uint64_t i = 1; i <= o; ++i) {
r = m_arrays[i - 1].range(pos);
pos = m_arrays[i].position(r, word_ids[i]);
if (pos == global::not_found) {
return global::not_found;
}
}
uint64_t count_rank = m_arrays[o].count_rank(pos);
return m_distinct_counts.access(o, count_rank);
}
inline uint64_t order() const {
return uint64_t(m_order);
}
uint64_t remapping_order() const {
return uint64_t(m_remapping_order);
}
void print_stats(size_t bytes) const;
uint64_t size() const {
uint64_t size = 0;
for (auto const& a : m_arrays) {
size += a.size();
}
return size;
}
void save(std::ostream& os) const {
essentials::save_pod(os, m_order);
essentials::save_pod(os, m_remapping_order);
m_distinct_counts.save(os);
m_vocab.save(os);
m_arrays.front().save(os, 1, value_type::count);
for (uint8_t order = 1; order < m_order; ++order) {
m_arrays[order].save(os, order + 1, value_type::count);
}
}
void load(std::istream& is) {
essentials::load_pod(is, m_order);
essentials::load_pod(is, m_remapping_order);
m_distinct_counts.load(is, m_order);
m_vocab.load(is);
m_arrays.resize(m_order);
m_arrays.front().load(is, 1, value_type::count);
for (uint8_t order = 1; order < m_order; ++order) {
m_arrays[order].load(is, order + 1, value_type::count);
}
}
private:
uint8_t m_order;
uint8_t m_remapping_order;
Mapper m_mapper;
Values m_distinct_counts;
Vocabulary m_vocab;
std::vector<sorted_array_type> m_arrays;
};
} // namespace tongrams
|
/*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#include <alibabacloud/idrsservice/model/DeleteDepartmentResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Idrsservice;
using namespace AlibabaCloud::Idrsservice::Model;
DeleteDepartmentResult::DeleteDepartmentResult() :
ServiceResult()
{}
DeleteDepartmentResult::DeleteDepartmentResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DeleteDepartmentResult::~DeleteDepartmentResult()
{}
void DeleteDepartmentResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Data"].isNull())
data_ = value["Data"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string DeleteDepartmentResult::getMessage()const
{
return message_;
}
std::string DeleteDepartmentResult::getData()const
{
return data_;
}
std::string DeleteDepartmentResult::getCode()const
{
return code_;
}
|
/*
* Copyright 2016 WebAssembly Community Group participants
*
* 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 "src/ir.h"
#include <cassert>
#include <cstddef>
#include <numeric>
#include "src/cast.h"
namespace {
const char* ExprTypeName[] = {
"AtomicLoad",
"AtomicRmw",
"AtomicRmwCmpxchg",
"AtomicStore",
"AtomicNotify",
"AtomicWait",
"Binary",
"Block",
"Br",
"BrIf",
"BrOnExn",
"BrTable",
"Call",
"CallIndirect",
"Compare",
"Const",
"Convert",
"Drop",
"GlobalGet",
"GlobalSet",
"If",
"Load",
"LocalGet",
"LocalSet",
"LocalTee",
"Loop",
"MemoryCopy",
"DataDrop",
"MemoryFill",
"MemoryGrow",
"MemoryInit",
"MemorySize",
"Nop",
"RefIsNull",
"RefFunc",
"RefNull",
"Rethrow",
"Return",
"ReturnCall",
"ReturnCallIndirect",
"Select",
"SimdLaneOp",
"SimdShuffleOp",
"LoadSplat",
"Store",
"TableCopy",
"ElemDrop",
"TableInit",
"TableGet",
"TableGrow",
"TableSize",
"TableSet",
"TableFill",
"Ternary",
"Throw",
"Try",
"Unary",
"Unreachable",
};
} // end of anonymous namespace
namespace wabt {
const char* GetExprTypeName(ExprType type) {
static_assert(WABT_ENUM_COUNT(ExprType) == WABT_ARRAY_SIZE(ExprTypeName),
"Malformed ExprTypeName array");
return ExprTypeName[size_t(type)];
}
const char* GetExprTypeName(const Expr& expr) {
return GetExprTypeName(expr.type());
}
bool FuncSignature::operator==(const FuncSignature& rhs) const {
return param_types == rhs.param_types && result_types == rhs.result_types;
}
const Export* Module::GetExport(string_view name) const {
Index index = export_bindings.FindIndex(name);
if (index >= exports.size()) {
return nullptr;
}
return exports[index];
}
Index Module::GetFuncIndex(const Var& var) const {
return func_bindings.FindIndex(var);
}
Index Module::GetGlobalIndex(const Var& var) const {
return global_bindings.FindIndex(var);
}
Index Module::GetTableIndex(const Var& var) const {
return table_bindings.FindIndex(var);
}
Index Module::GetMemoryIndex(const Var& var) const {
return memory_bindings.FindIndex(var);
}
Index Module::GetFuncTypeIndex(const Var& var) const {
return type_bindings.FindIndex(var);
}
Index Module::GetEventIndex(const Var& var) const {
return event_bindings.FindIndex(var);
}
Index Module::GetDataSegmentIndex(const Var& var) const {
return data_segment_bindings.FindIndex(var);
}
Index Module::GetElemSegmentIndex(const Var& var) const {
return elem_segment_bindings.FindIndex(var);
}
bool Module::IsImport(ExternalKind kind, const Var& var) const {
switch (kind) {
case ExternalKind::Func:
return GetFuncIndex(var) < num_func_imports;
case ExternalKind::Global:
return GetGlobalIndex(var) < num_global_imports;
case ExternalKind::Memory:
return GetMemoryIndex(var) < num_memory_imports;
case ExternalKind::Table:
return GetTableIndex(var) < num_table_imports;
case ExternalKind::Event:
return GetEventIndex(var) < num_event_imports;
default:
return false;
}
}
void LocalTypes::Set(const TypeVector& types) {
decls_.clear();
if (types.empty()) {
return;
}
Type type = types[0];
Index count = 1;
for (Index i = 1; i < types.size(); ++i) {
if (types[i] != type) {
decls_.emplace_back(type, count);
type = types[i];
count = 1;
} else {
++count;
}
}
decls_.emplace_back(type, count);
}
Index LocalTypes::size() const {
return std::accumulate(
decls_.begin(), decls_.end(), 0,
[](Index sum, const Decl& decl) { return sum + decl.second; });
}
Type LocalTypes::operator[](Index i) const {
Index count = 0;
for (auto decl: decls_) {
if (i < count + decl.second) {
return decl.first;
}
count += decl.second;
}
assert(i < count);
return Type::Any;
}
Type Func::GetLocalType(Index index) const {
Index num_params = decl.GetNumParams();
if (index < num_params) {
return GetParamType(index);
} else {
index -= num_params;
assert(index < local_types.size());
return local_types[index];
}
}
Type Func::GetLocalType(const Var& var) const {
return GetLocalType(GetLocalIndex(var));
}
Index Func::GetLocalIndex(const Var& var) const {
if (var.is_index()) {
return var.index();
}
return bindings.FindIndex(var);
}
const Func* Module::GetFunc(const Var& var) const {
return const_cast<Module*>(this)->GetFunc(var);
}
Func* Module::GetFunc(const Var& var) {
Index index = func_bindings.FindIndex(var);
if (index >= funcs.size()) {
return nullptr;
}
return funcs[index];
}
const Global* Module::GetGlobal(const Var& var) const {
return const_cast<Module*>(this)->GetGlobal(var);
}
Global* Module::GetGlobal(const Var& var) {
Index index = global_bindings.FindIndex(var);
if (index >= globals.size()) {
return nullptr;
}
return globals[index];
}
const Table* Module::GetTable(const Var& var) const {
return const_cast<Module*>(this)->GetTable(var);
}
Table* Module::GetTable(const Var& var) {
Index index = table_bindings.FindIndex(var);
if (index >= tables.size()) {
return nullptr;
}
return tables[index];
}
const Memory* Module::GetMemory(const Var& var) const {
return const_cast<Module*>(this)->GetMemory(var);
}
Memory* Module::GetMemory(const Var& var) {
Index index = memory_bindings.FindIndex(var);
if (index >= memories.size()) {
return nullptr;
}
return memories[index];
}
Event* Module::GetEvent(const Var& var) const {
Index index = GetEventIndex(var);
if (index >= events.size()) {
return nullptr;
}
return events[index];
}
const DataSegment* Module::GetDataSegment(const Var& var) const {
return const_cast<Module*>(this)->GetDataSegment(var);
}
DataSegment* Module::GetDataSegment(const Var& var) {
Index index = data_segment_bindings.FindIndex(var);
if (index >= data_segments.size()) {
return nullptr;
}
return data_segments[index];
}
const ElemSegment* Module::GetElemSegment(const Var& var) const {
return const_cast<Module*>(this)->GetElemSegment(var);
}
ElemSegment* Module::GetElemSegment(const Var& var) {
Index index = elem_segment_bindings.FindIndex(var);
if (index >= elem_segments.size()) {
return nullptr;
}
return elem_segments[index];
}
const FuncType* Module::GetFuncType(const Var& var) const {
return const_cast<Module*>(this)->GetFuncType(var);
}
FuncType* Module::GetFuncType(const Var& var) {
Index index = type_bindings.FindIndex(var);
if (index >= types.size()) {
return nullptr;
}
return cast<FuncType>(types[index]);
}
Index Module::GetFuncTypeIndex(const FuncSignature& sig) const {
for (size_t i = 0; i < types.size(); ++i) {
if (auto* func_type = dyn_cast<FuncType>(types[i])) {
if (func_type->sig == sig) {
return i;
}
}
}
return kInvalidIndex;
}
Index Module::GetFuncTypeIndex(const FuncDeclaration& decl) const {
if (decl.has_func_type) {
return GetFuncTypeIndex(decl.type_var);
} else {
return GetFuncTypeIndex(decl.sig);
}
}
void Module::AppendField(std::unique_ptr<DataSegmentModuleField> field) {
DataSegment& data_segment = field->data_segment;
if (!data_segment.name.empty()) {
data_segment_bindings.emplace(data_segment.name,
Binding(field->loc, data_segments.size()));
}
data_segments.push_back(&data_segment);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<ElemSegmentModuleField> field) {
ElemSegment& elem_segment = field->elem_segment;
if (!elem_segment.name.empty()) {
elem_segment_bindings.emplace(elem_segment.name,
Binding(field->loc, elem_segments.size()));
}
elem_segments.push_back(&elem_segment);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<EventModuleField> field) {
Event& event = field->event;
if (!event.name.empty()) {
event_bindings.emplace(event.name, Binding(field->loc, events.size()));
}
events.push_back(&event);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<ExportModuleField> field) {
// Exported names are allowed to be empty.
Export& export_ = field->export_;
export_bindings.emplace(export_.name, Binding(field->loc, exports.size()));
exports.push_back(&export_);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<FuncModuleField> field) {
Func& func = field->func;
if (!func.name.empty()) {
func_bindings.emplace(func.name, Binding(field->loc, funcs.size()));
}
funcs.push_back(&func);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<TypeModuleField> field) {
TypeEntry& type = *field->type;
if (!type.name.empty()) {
type_bindings.emplace(type.name, Binding(field->loc, types.size()));
}
types.push_back(&type);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<GlobalModuleField> field) {
Global& global = field->global;
if (!global.name.empty()) {
global_bindings.emplace(global.name, Binding(field->loc, globals.size()));
}
globals.push_back(&global);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<ImportModuleField> field) {
Import* import = field->import.get();
const std::string* name = nullptr;
BindingHash* bindings = nullptr;
Index index = kInvalidIndex;
switch (import->kind()) {
case ExternalKind::Func: {
Func& func = cast<FuncImport>(import)->func;
name = &func.name;
bindings = &func_bindings;
index = funcs.size();
funcs.push_back(&func);
++num_func_imports;
break;
}
case ExternalKind::Table: {
Table& table = cast<TableImport>(import)->table;
name = &table.name;
bindings = &table_bindings;
index = tables.size();
tables.push_back(&table);
++num_table_imports;
break;
}
case ExternalKind::Memory: {
Memory& memory = cast<MemoryImport>(import)->memory;
name = &memory.name;
bindings = &memory_bindings;
index = memories.size();
memories.push_back(&memory);
++num_memory_imports;
break;
}
case ExternalKind::Global: {
Global& global = cast<GlobalImport>(import)->global;
name = &global.name;
bindings = &global_bindings;
index = globals.size();
globals.push_back(&global);
++num_global_imports;
break;
}
case ExternalKind::Event: {
Event& event = cast<EventImport>(import)->event;
name = &event.name;
bindings = &event_bindings;
index = events.size();
events.push_back(&event);
++num_event_imports;
break;
}
}
assert(name && bindings && index != kInvalidIndex);
if (!name->empty()) {
bindings->emplace(*name, Binding(field->loc, index));
}
imports.push_back(import);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<MemoryModuleField> field) {
Memory& memory = field->memory;
if (!memory.name.empty()) {
memory_bindings.emplace(memory.name, Binding(field->loc, memories.size()));
}
memories.push_back(&memory);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<StartModuleField> field) {
starts.push_back(&field->start);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<TableModuleField> field) {
Table& table = field->table;
if (!table.name.empty()) {
table_bindings.emplace(table.name, Binding(field->loc, tables.size()));
}
tables.push_back(&table);
fields.push_back(std::move(field));
}
void Module::AppendField(std::unique_ptr<ModuleField> field) {
switch (field->type()) {
case ModuleFieldType::Func:
AppendField(cast<FuncModuleField>(std::move(field)));
break;
case ModuleFieldType::Global:
AppendField(cast<GlobalModuleField>(std::move(field)));
break;
case ModuleFieldType::Import:
AppendField(cast<ImportModuleField>(std::move(field)));
break;
case ModuleFieldType::Export:
AppendField(cast<ExportModuleField>(std::move(field)));
break;
case ModuleFieldType::Type:
AppendField(cast<TypeModuleField>(std::move(field)));
break;
case ModuleFieldType::Table:
AppendField(cast<TableModuleField>(std::move(field)));
break;
case ModuleFieldType::ElemSegment:
AppendField(cast<ElemSegmentModuleField>(std::move(field)));
break;
case ModuleFieldType::Memory:
AppendField(cast<MemoryModuleField>(std::move(field)));
break;
case ModuleFieldType::DataSegment:
AppendField(cast<DataSegmentModuleField>(std::move(field)));
break;
case ModuleFieldType::Start:
AppendField(cast<StartModuleField>(std::move(field)));
break;
case ModuleFieldType::Event:
AppendField(cast<EventModuleField>(std::move(field)));
break;
}
}
void Module::AppendFields(ModuleFieldList* fields) {
while (!fields->empty())
AppendField(std::unique_ptr<ModuleField>(fields->extract_front()));
}
const Module* Script::GetFirstModule() const {
return const_cast<Script*>(this)->GetFirstModule();
}
Module* Script::GetFirstModule() {
for (const std::unique_ptr<Command>& command : commands) {
if (auto* module_command = dyn_cast<ModuleCommand>(command.get())) {
return &module_command->module;
}
}
return nullptr;
}
const Module* Script::GetModule(const Var& var) const {
Index index = module_bindings.FindIndex(var);
if (index >= commands.size()) {
return nullptr;
}
auto* command = cast<ModuleCommand>(commands[index].get());
return &command->module;
}
void MakeTypeBindingReverseMapping(
size_t num_types,
const BindingHash& bindings,
std::vector<std::string>* out_reverse_mapping) {
out_reverse_mapping->clear();
out_reverse_mapping->resize(num_types);
for (const auto& pair : bindings) {
assert(static_cast<size_t>(pair.second.index) <
out_reverse_mapping->size());
(*out_reverse_mapping)[pair.second.index] = pair.first;
}
}
Var::Var(Index index, const Location& loc)
: loc(loc), type_(VarType::Index), index_(index) {}
Var::Var(string_view name, const Location& loc)
: loc(loc), type_(VarType::Name), name_(name) {}
Var::Var(Var&& rhs) : Var(kInvalidIndex) {
*this = std::move(rhs);
}
Var::Var(const Var& rhs) : Var(kInvalidIndex) {
*this = rhs;
}
Var& Var::operator=(Var&& rhs) {
loc = rhs.loc;
if (rhs.is_index()) {
set_index(rhs.index_);
} else {
set_name(rhs.name_);
}
return *this;
}
Var& Var::operator=(const Var& rhs) {
loc = rhs.loc;
if (rhs.is_index()) {
set_index(rhs.index_);
} else {
set_name(rhs.name_);
}
return *this;
}
Var::~Var() {
Destroy();
}
void Var::set_index(Index index) {
Destroy();
type_ = VarType::Index;
index_ = index;
}
void Var::set_name(std::string&& name) {
Destroy();
type_ = VarType::Name;
Construct(name_, std::move(name));
}
void Var::set_name(string_view name) {
set_name(name.to_string());
}
void Var::Destroy() {
if (is_name()) {
Destruct(name_);
}
}
uint8_t ElemSegment::GetFlags(const Module* module) const {
uint8_t flags = 0;
bool all_ref_func = elem_type == Type::Funcref;
switch (kind) {
case SegmentKind::Active: {
Index table_index = module->GetTableIndex(table_var);
if (table_index != 0) {
flags |= SegExplicitIndex;
}
break;
}
case SegmentKind::Passive:
flags |= SegPassive;
break;
case SegmentKind::Declared:
flags |= SegDeclared;
break;
}
all_ref_func = all_ref_func &&
std::all_of(elem_exprs.begin(), elem_exprs.end(),
[](const ElemExpr& elem_expr) {
return elem_expr.kind == ElemExprKind::RefFunc;
});
if (!all_ref_func) {
flags |= SegUseElemExprs;
}
return flags;
}
uint8_t DataSegment::GetFlags(const Module* module) const {
uint8_t flags = 0;
if (kind == SegmentKind::Passive) {
flags |= SegPassive;
}
Index memory_index = module->GetMemoryIndex(memory_var);
if (memory_index != 0) {
flags |= SegExplicitIndex;
}
return flags;
}
} // namespace wabt
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2019 The ALQO & Bitfineon developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentserver.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "base58.h"
#include "chainparams.h"
#include "ui_interface.h"
#include "util.h"
#include "wallet.h"
#include <cstdlib>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QApplication>
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileOpenEvent>
#include <QHash>
#include <QList>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslCertificate>
#include <QSslError>
#include <QSslSocket>
#include <QStringList>
#include <QTextDocument>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
using namespace boost;
using namespace std;
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("alqo:");
// BIP70 payment protocol messages
const char* BIP70_MESSAGE_PAYMENTACK = "PaymentACK";
const char* BIP70_MESSAGE_PAYMENTREQUEST = "PaymentRequest";
// BIP71 payment protocol media types
const char* BIP71_MIMETYPE_PAYMENT = "application/alqo-payment";
const char* BIP71_MIMETYPE_PAYMENTACK = "application/alqo-paymentack";
const char* BIP71_MIMETYPE_PAYMENTREQUEST = "application/alqo-paymentrequest";
// BIP70 max payment request size in bytes (DoS protection)
const qint64 BIP70_MAX_PAYMENTREQUEST_SIZE = 50000;
struct X509StoreDeleter {
void operator()(X509_STORE* b) {
X509_STORE_free(b);
}
};
struct X509Deleter {
void operator()(X509* b) { X509_free(b); }
};
namespace // Anon namespace
{
std::unique_ptr<X509_STORE, X509StoreDeleter> certStore;
}
//
// Create a name that is unique for:
// testnet / non-testnet
// data directory
//
static QString ipcServerName()
{
QString name("ALQOQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(QString::fromStdString(GetDataDir(true).string()));
name.append(QString::number(qHash(ddir)));
return name;
}
//
// We store payment URIs and requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QList<QString> savedPaymentRequests;
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
qDebug() << "ReportInvalidCertificate : Payment server found an invalid certificate: " << cert.subjectInfo(QSslCertificate::CommonName);
}
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
// Unit tests mostly use this, to pass in fake root CAs:
if (_store) {
certStore.reset(_store);
return;
}
// Normal execution, use either -rootcertificates or system certs:
certStore.reset(X509_STORE_new());
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));
if (certFile.isEmpty())
return; // Empty store
QList<QSslCertificate> certList;
if (certFile != "-system-") {
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslSocket::setDefaultCaCertificates(certList);
} else
certList = QSslSocket::systemCaCertificates();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
foreach (const QSslCertificate& cert, certList) {
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
ReportInvalidCertificate(cert);
continue;
}
#if QT_VERSION >= 0x050000
if (cert.isBlacklisted()) {
ReportInvalidCertificate(cert);
continue;
}
#endif
QByteArray certData = cert.toDer();
const unsigned char* data = (const unsigned char*)certData.data();
std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size()));
if (x509 && X509_STORE_add_cert(certStore.get(), x509.get())) {
// Note: X509_STORE increases the reference count to the X509 object,
// we still have to release our reference to it.
++nRootCerts;
} else {
ReportInvalidCertificate(cert);
continue;
}
}
qWarning() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
// Warning: ipcSendCommandLine() is called early in init,
// so don't use "emit message()", but "QMessageBox::"!
//
void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
{
for (int i = 1; i < argc; i++) {
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
// If the alqo: URI contains a payment request, we are not able to detect the
// network as that would require fetching and parsing the payment request.
// That means clicking such an URI which contains a testnet payment request
// will start a mainnet instance and throw a "wrong network" error.
if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // alqo: URI
{
savedPaymentRequests.append(arg);
SendCoinsRecipient r;
if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty()) {
CBitcoinAddress address(r.address.toStdString());
if (address.IsValid(Params(CBaseChainParams::MAIN))) {
SelectParams(CBaseChainParams::MAIN);
} else if (address.IsValid(Params(CBaseChainParams::TESTNET))) {
SelectParams(CBaseChainParams::TESTNET);
}
}
} else if (QFile::exists(arg)) // Filename
{
savedPaymentRequests.append(arg);
PaymentRequestPlus request;
if (readPaymentRequestFromFile(arg, request)) {
if (request.getDetails().network() == "main") {
SelectParams(CBaseChainParams::MAIN);
} else if (request.getDetails().network() == "test") {
SelectParams(CBaseChainParams::TESTNET);
}
}
} else {
// Printing to debug.log is about the best we can do here, the
// GUI hasn't started yet so we can't pop up a message box.
qWarning() << "PaymentServer::ipcSendCommandLine : Payment request file does not exist: " << arg;
}
}
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
foreach (const QString& r, savedPaymentRequests) {
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) {
delete socket;
socket = NULL;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
socket = NULL;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) : QObject(parent),
saveURIs(true),
uriServer(0),
netManager(0),
optionsModel(0)
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Install global event filter to catch QFileOpenEvents
// on Mac: sent when you click alqo: links
// other OSes: helpful when dealing with payment request files (in the future)
if (parent)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
if (startLocalServer) {
uriServer = new QLocalServer(this);
if (!uriServer->listen(name)) {
// constructor is called early in init, so don't use "emit message()" here
QMessageBox::critical(0, tr("Payment request error"),
tr("Cannot start alqo: click-to-pay handler"));
} else {
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString)));
}
}
}
PaymentServer::~PaymentServer()
{
google::protobuf::ShutdownProtobufLibrary();
}
//
// OSX-specific way of handling alqo: URIs and
// PaymentRequest mime types
//
bool PaymentServer::eventFilter(QObject* object, QEvent* event)
{
// clicking on alqo: URIs creates FileOpen events on the Mac
if (event->type() == QEvent::FileOpen) {
QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->file().isEmpty())
handleURIOrFile(fileEvent->file());
else if (!fileEvent->url().isEmpty())
handleURIOrFile(fileEvent->url().toString());
return true;
}
return QObject::eventFilter(object, event);
}
void PaymentServer::initNetManager()
{
if (!optionsModel)
return;
if (netManager != NULL)
delete netManager;
// netManager is used to fetch paymentrequests given in alqo: URIs
netManager = new QNetworkAccessManager(this);
QNetworkProxy proxy;
// Query active SOCKS5 proxy
if (optionsModel->getProxySettings(proxy)) {
netManager->setProxy(proxy);
qDebug() << "PaymentServer::initNetManager : Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port();
} else
qDebug() << "PaymentServer::initNetManager : No active proxy server found.";
connect(netManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(netRequestFinished(QNetworkReply*)));
connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)),
this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError>&)));
}
void PaymentServer::uiReady()
{
initNetManager();
saveURIs = false;
foreach (const QString& s, savedPaymentRequests) {
handleURIOrFile(s);
}
savedPaymentRequests.clear();
}
void PaymentServer::handleURIOrFile(const QString& s)
{
if (saveURIs) {
savedPaymentRequests.append(s);
return;
}
if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // alqo: URI
{
#if QT_VERSION < 0x050000
QUrl uri(s);
#else
QUrlQuery uri((QUrl(s)));
#endif
if (uri.hasQueryItem("r")) // payment request URI
{
QByteArray temp;
temp.append(uri.queryItemValue("r"));
QString decoded = QUrl::fromPercentEncoding(temp);
QUrl fetchUrl(decoded, QUrl::StrictMode);
if (fetchUrl.isValid()) {
qDebug() << "PaymentServer::handleURIOrFile : fetchRequest(" << fetchUrl << ")";
fetchRequest(fetchUrl);
} else {
qWarning() << "PaymentServer::handleURIOrFile : Invalid URL: " << fetchUrl;
emit message(tr("URI handling"),
tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
CClientUIInterface::ICON_WARNING);
}
return;
} else // normal URI
{
SendCoinsRecipient recipient;
if (GUIUtil::parseBitcoinURI(s, &recipient)) {
CBitcoinAddress address(recipient.address.toStdString());
if (!address.IsValid()) {
emit message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address),
CClientUIInterface::MSG_ERROR);
} else
emit receivedPaymentRequest(recipient);
} else
emit message(tr("URI handling"),
tr("URI cannot be parsed! This can be caused by an invalid ALQO address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
return;
}
}
if (QFile::exists(s)) // payment request file
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!readPaymentRequestFromFile(s, request)) {
emit message(tr("Payment request file handling"),
tr("Payment request file cannot be read! This can be caused by an invalid payment request file."),
CClientUIInterface::ICON_WARNING);
} else if (processPaymentRequest(request, recipient))
emit receivedPaymentRequest(recipient);
return;
}
}
void PaymentServer::handleURIConnection()
{
QLocalSocket* clientConnection = uriServer->nextPendingConnection();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString msg;
in >> msg;
handleURIOrFile(msg);
}
//
// Warning: readPaymentRequestFromFile() is used in ipcSendCommandLine()
// so don't use "emit message()", but "QMessageBox::"!
//
bool PaymentServer::readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
qWarning() << QString("PaymentServer::%1: Failed to open %2").arg(__func__).arg(filename);
return false;
}
// BIP70 DoS protection
if (f.size() > BIP70_MAX_PAYMENTREQUEST_SIZE) {
qWarning() << QString("PaymentServer::%1: Payment request %2 is too large (%3 bytes, allowed %4 bytes).")
.arg(__func__)
.arg(filename)
.arg(f.size())
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE);
return false;
}
QByteArray data = f.readAll();
return request.parse(data);
}
bool PaymentServer::processPaymentRequest(PaymentRequestPlus& request, SendCoinsRecipient& recipient)
{
if (!optionsModel)
return false;
if (request.IsInitialized()) {
const payments::PaymentDetails& details = request.getDetails();
// Payment request network matches client network?
if (details.network() != Params().NetworkIDString()) {
emit message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Expired payment request?
if (details.has_expires() && (int64_t)details.expires() < GetTime()) {
emit message(tr("Payment request rejected"), tr("Payment request has expired."),
CClientUIInterface::MSG_ERROR);
return false;
}
} else {
emit message(tr("Payment request error"), tr("Payment request is not initialized."),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.paymentRequest = request;
recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());
request.getMerchant(certStore.get(), recipient.authenticatedMerchant);
QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo();
QStringList addresses;
foreach (const PAIRTYPE(CScript, CAmount) & sendingTo, sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
// Append destination address
addresses.append(QString::fromStdString(CBitcoinAddress(dest).ToString()));
} else if (!recipient.authenticatedMerchant.isEmpty()) {
// Insecure payments to custom alqo addresses are not supported
// (there is no good way to tell the user where they are paying in a way
// they'd have a chance of understanding).
emit message(tr("Payment request rejected"),
tr("Unverified payment requests to custom payment scripts are unsupported."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
if (txOut.IsDust(::minRelayTxFee)) {
emit message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).").arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.amount += sendingTo.second;
}
// Store addresses and format them to fit nicely into the GUI
recipient.address = addresses.join("<br />");
if (!recipient.authenticatedMerchant.isEmpty()) {
qDebug() << "PaymentServer::processPaymentRequest : Secure payment request from " << recipient.authenticatedMerchant;
} else {
qDebug() << "PaymentServer::processPaymentRequest : Insecure payment request to " << addresses.join(", ");
}
return true;
}
void PaymentServer::fetchRequest(const QUrl& url)
{
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTREQUEST);
netRequest.setUrl(url);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTREQUEST);
netManager->get(netRequest);
}
void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
return;
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTACK);
netRequest.setUrl(QString::fromStdString(details.payment_url()));
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BIP71_MIMETYPE_PAYMENT);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTACK);
payments::Payment payment;
payment.set_merchant_data(details.merchant_data());
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant);
std::string strAccount = account.toStdString();
set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount);
if (!refundAddresses.empty()) {
CScript s = GetScriptForDestination(*refundAddresses.begin());
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
} else {
CPubKey newKey;
if (wallet->GetKeyFromPool(newKey)) {
CKeyID keyID = newKey.GetID();
wallet->SetAddressBook(keyID, strAccount, "refund");
CScript s = GetScriptForDestination(keyID);
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
} else {
// This should never happen, because sending coins should have
// just unlocked the wallet and refilled the keypool.
qWarning() << "PaymentServer::fetchPaymentACK : Error getting refund key, refund_to not set";
}
}
int length = payment.ByteSize();
netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);
QByteArray serData(length, '\0');
if (payment.SerializeToArray(serData.data(), length)) {
netManager->post(netRequest, serData);
} else {
// This should never happen, either.
qWarning() << "PaymentServer::fetchPaymentACK : Error serializing payment message";
}
}
void PaymentServer::netRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
// BIP70 DoS protection
if (reply->size() > BIP70_MAX_PAYMENTREQUEST_SIZE) {
QString msg = tr("Payment request %1 is too large (%2 bytes, allowed %3 bytes).")
.arg(reply->request().url().toString())
.arg(reply->size())
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE);
qWarning() << QString("PaymentServer::%1:").arg(__func__) << msg;
emit message(tr("Payment request DoS protection"), msg, CClientUIInterface::MSG_ERROR);
return;
}
if (reply->error() != QNetworkReply::NoError) {
QString msg = tr("Error communicating with %1: %2")
.arg(reply->request().url().toString())
.arg(reply->errorString());
qWarning() << "PaymentServer::netRequestFinished: " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return;
}
QByteArray data = reply->readAll();
QString requestType = reply->request().attribute(QNetworkRequest::User).toString();
if (requestType == BIP70_MESSAGE_PAYMENTREQUEST) {
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!request.parse(data)) {
qWarning() << "PaymentServer::netRequestFinished : Error parsing payment request";
emit message(tr("Payment request error"),
tr("Payment request cannot be parsed!"),
CClientUIInterface::MSG_ERROR);
} else if (processPaymentRequest(request, recipient))
emit receivedPaymentRequest(recipient);
return;
} else if (requestType == BIP70_MESSAGE_PAYMENTACK) {
payments::PaymentACK paymentACK;
if (!paymentACK.ParseFromArray(data.data(), data.size())) {
QString msg = tr("Bad response from server %1")
.arg(reply->request().url().toString());
qWarning() << "PaymentServer::netRequestFinished : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
} else {
emit receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));
}
}
}
void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError>& errs)
{
Q_UNUSED(reply);
QString errString;
foreach (const QSslError& err, errs) {
qWarning() << "PaymentServer::reportSslErrors : " << err;
errString += err.errorString() + "\n";
}
emit message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR);
}
void PaymentServer::setOptionsModel(OptionsModel* optionsModel)
{
this->optionsModel = optionsModel;
}
void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
{
// currently we don't futher process or store the paymentACK message
emit message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
X509_STORE* PaymentServer::getCertStore()
{
return certStore.get();
}
|
/**
* @project identt
* @file src/store/LookupService.cc
* @author S Roychowdhury <sroycode AT gmail DOT com>
* @version 1.0.0
*
* @section LICENSE
*
* Copyright (c) 2017 S Roychowdhury.
*
* 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.
*
* @section DESCRIPTION
*
* LookupService.cc : Implementation of Lookup Service
*
*/
#include <async++.h>
#include <store/LookupService.hpp>
#include <query/bin2ascii.h>
#include <store/GlobalAssocTable.hpp>
#include <store/LocalAssocTable.hpp>
/**
* LookupAction : Service Endpoint Lookup
*
*/
void identt::store::LookupService::LookupAction(
::identt::utils::SharedTable::pointer stptr,
::identt::query::LookupDataT* lact)
{
bool lookup_uses_local = stptr->lookup_uses_local.Get();
if (lookup_uses_local)
this->LookupLocal(stptr,lact->mutable_query(),lact->mutable_result());
else
this->LookupGlobal(stptr,lact->mutable_query(),lact->mutable_result());
}
/**
* BulkLookupAction : Service Endpoint Lookup
*
*/
void identt::store::LookupService::BulkLookupAction(
::identt::utils::SharedTable::pointer stptr,
::identt::query::BulkLookupDataT* blact)
{
::identt::query::BulkLookupQueryT* query = blact->mutable_query();
::identt::query::BulkLookupResultT* result = blact->mutable_result();
bool lookup_uses_local = stptr->lookup_uses_local.Get();
// globalassoc
size_t s_size = query->threepids_size();
if (lookup_uses_local)
this->BulkLookupLocal(stptr,blact,0,s_size-1);
else
this->BulkLookupGlobal(stptr,blact,0,s_size-1);
}
/**
* LookupGlobal : Service Endpoint Lookup private
*
*/
void identt::store::LookupService::LookupGlobal(
::identt::utils::SharedTable::pointer stptr,
::identt::query::LookupQueryT* query,
::identt::query::LookupResultT* result)
{
// uint64_t expires = THREEPID_SESSION_VALID_LIFETIME_MS + currtime;
// globalassoc
::identt::store::GlobalAssocT globalassoc;
::identt::store::GlobalAssocTable::MapT globalassoc_map;
::identt::store::GlobalAssocTable globalassoc_table{stptr->maindb.Get()};
globalassoc.set_medium( query->medium() );
globalassoc.set_address( query->address() );
bool globalassoc_found = globalassoc_table.GetMany(
&globalassoc,&globalassoc_map,
::identt::store::I_GLOBALASSOC_MEDIUM_ADDRESS,
0,1
);
if (globalassoc_found && globalassoc_map.size()>0) {
// get one anyway shreos
auto it = globalassoc_map.begin();
it->second.Swap(&globalassoc);
result->set_address( globalassoc.address() );
result->set_medium( globalassoc.medium() );
result->set_mxid( globalassoc.mxid() );
result->set_not_after( globalassoc.not_after() );
result->set_not_before( globalassoc.not_before() );
result->set_ts( globalassoc.ts() );
}
}
/**
* BulkLookupGlobal : Bulk Lookup Implementation
*
*/
void identt::store::LookupService::BulkLookupGlobal(
::identt::utils::SharedTable::pointer stptr, ::identt::query::BulkLookupDataT* blact, size_t start, size_t end)
{
// globalassoc
::identt::store::GlobalAssocTable globalassoc_table{stptr->maindb.Get()};
::identt::store::GlobalAssocT globalassoc;
::identt::store::GlobalAssocTable::MapT globalassoc_map;
::identt::query::BulkLookupQueryT* query = blact->mutable_query();
::identt::query::BulkLookupResultT* result = blact->mutable_result();
size_t total = query->threepids_size();
if (start >= total || end >= total || start > end ) return;
for (auto i=start; i<=end; ++i) {
globalassoc.Clear();
globalassoc.set_medium( query->mutable_threepids(i)->medium() );
globalassoc.set_address( query->mutable_threepids(i)->address() );
bool globalassoc_found = globalassoc_table.GetMany(
&globalassoc,&globalassoc_map,
::identt::store::I_GLOBALASSOC_MEDIUM_ADDRESS,
0,1
);
}
for (auto it= globalassoc_map.begin(); it!=globalassoc_map.end(); ++it) {
it->second.Swap(&globalassoc);
::identt::query::LookupResultT one_result;
one_result.set_address( globalassoc.address() );
one_result.set_medium( globalassoc.medium() );
one_result.set_mxid( globalassoc.mxid() );
one_result.set_not_after( globalassoc.not_after() );
one_result.set_not_before( globalassoc.not_before() );
one_result.set_ts( globalassoc.ts() );
if (one_result.mutable_mxid()->length()>0) {
std::lock_guard<std::mutex> lock(read_mutex);
one_result.Swap(result->add_threepids());
}
}
}
/**
* LookupLocal : Lookup from LocalAssoc private
*
*/
void identt::store::LookupService::LookupLocal(
::identt::utils::SharedTable::pointer stptr,
::identt::query::LookupQueryT* query,
::identt::query::LookupResultT* result)
{
// uint64_t expires = THREEPID_SESSION_VALID_LIFETIME_MS + currtime;
// localassoc
std::string data;
std::string medium_address = stptr->dbcache->EncodeSecondaryKey<std::string,std::string>(
::identt::store::U_LOCALASSOC_MEDIUM_ADDRESS,
query->medium(),query->address() );
bool stat = stptr->dbcache->GetAssoc(medium_address,data);
if (!stat) return;
::identt::store::LocalAssocT localassoc;
stat = localassoc.ParseFromString(data);
if (!stat) return;
result->set_address( localassoc.address() );
result->set_medium( localassoc.medium() );
result->set_mxid( localassoc.mxid() );
result->set_not_after( localassoc.not_after() );
result->set_not_before( localassoc.not_before() );
result->set_ts( localassoc.ts() );
}
/**
* BulkLookupLocal : Bulk Lookup Implementation with LocalAssoc
*
*/
void identt::store::LookupService::BulkLookupLocal(
::identt::utils::SharedTable::pointer stptr, ::identt::query::BulkLookupDataT* blact, size_t start, size_t end)
{
// localassoc
::identt::store::LocalAssocTable localassoc_table{stptr->maindb.Get()};
::identt::store::LocalAssocT localassoc;
::identt::store::LocalAssocTable::MapT localassoc_map;
::identt::query::BulkLookupQueryT* query = blact->mutable_query();
::identt::query::BulkLookupResultT* result = blact->mutable_result();
size_t total = query->threepids_size();
if (start >= total || end >= total || start > end ) return;
for (auto i=start; i<=end; ++i) {
std::string data;
std::string medium_address = stptr->dbcache->EncodeSecondaryKey<std::string,std::string>(
::identt::store::U_LOCALASSOC_MEDIUM_ADDRESS,
query->mutable_threepids(i)->medium(),
query->mutable_threepids(i)->address() );
if ( ! stptr->dbcache->GetAssoc(medium_address,data) ) continue;
localassoc.Clear();
if ( localassoc.ParseFromString(data) ) {
localassoc_map[localassoc.id()]=localassoc;
}
}
for (auto it= localassoc_map.begin(); it!=localassoc_map.end(); ++it) {
it->second.Swap(&localassoc);
::identt::query::LookupResultT one_result;
one_result.set_address( localassoc.address() );
one_result.set_medium( localassoc.medium() );
one_result.set_mxid( localassoc.mxid() );
one_result.set_not_after( localassoc.not_after() );
one_result.set_not_before( localassoc.not_before() );
one_result.set_ts( localassoc.ts() );
if (one_result.mutable_mxid()->length()>0) {
std::lock_guard<std::mutex> lock(read_mutex);
one_result.Swap(result->add_threepids());
}
}
}
|
#include <stdint.h>
#include <GBAemu/memory/cartridgeStorage.h>
#include <GBAemu/util/log.h>
CartridgeStorage::CartridgeStorage(Memory &memory) :
_memory(memory)
{
}
CartridgeStorage::~CartridgeStorage()
{
}
uint32_t CartridgeStorage::GetSize()
{
return 0;
}
uint8_t CartridgeStorage::ReadMemory(uint32_t address)
{
return 0;
}
uint32_t CartridgeStorage::Read32(uint32_t address)
{
Log(Warn, "32 Bit read from unimplemented cartridge at address 0x%08x", address);
return 0;
}
uint32_t CartridgeStorage::Read16(uint32_t address)
{
Log(Warn, "16 Bit read from unimplemented cartridge at address 0x%08x", address);
return 0;
}
uint32_t CartridgeStorage::Read8(uint32_t address)
{
Log(Warn, "8 Bit read from unimplemented cartridge at address 0x%08x", address);
return 0;
}
void CartridgeStorage::Write32(uint32_t address, uint32_t val)
{
Log(Warn, "32 Bit write to unimplemented cartridge at address 0x%08x with data 0x%08x", address, val);
}
void CartridgeStorage::Write16(uint32_t address, uint16_t val)
{
Log(Warn, "16 Bit write to unimplemented cartridge at address 0x%08x with data 0x%04x", address, val);
}
void CartridgeStorage::Write8(uint32_t address, uint8_t val)
{
Log(Warn, "8 Bit write to unimplemented cartridge at address 0x%08x with data 0x%02x", address, val);
}
|
#include "model/output_layer.h"
|
/**
* @file unit-capi-config.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB Inc.
*
* 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.
*
* @section DESCRIPTION
*
* Tests the C API config object.
*/
#include "catch.hpp"
#include "tiledb/sm/c_api/tiledb.h"
#include <tiledb/sm/misc/constants.h>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <thread>
void remove_file(const std::string& filename) {
// Remove file
tiledb_ctx_t* ctx = nullptr;
int rc = tiledb_ctx_alloc(nullptr, &ctx);
REQUIRE(rc == TILEDB_OK);
tiledb_vfs_t* vfs = nullptr;
REQUIRE(tiledb_vfs_alloc(ctx, nullptr, &vfs) == TILEDB_OK);
CHECK(tiledb_vfs_remove_file(ctx, vfs, filename.c_str()) == TILEDB_OK);
tiledb_vfs_free(&vfs);
tiledb_ctx_free(&ctx);
}
void check_load_correct_file() {
// Create a test config file
std::ofstream ofs("test_config.txt");
ofs << " # comment line\n";
ofs << "sm.tile_cache_size 1000\n";
ofs << "# another comment line\n";
ofs << "sm.consolidation.steps 2 # some comment\n";
ofs << "# last comment line\n";
ofs.close();
// Set config from file
tiledb_config_t* config = nullptr;
tiledb_error_t* error = nullptr;
int rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_load_from_file(config, "test_config.txt", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
tiledb_ctx_t* ctx = nullptr;
rc = tiledb_ctx_alloc(config, &ctx);
CHECK(rc == TILEDB_OK);
tiledb_ctx_free(&ctx);
tiledb_config_free(&config);
remove_file("test_config.txt");
}
void check_error(tiledb_error_t* error, const std::string& msg) {
const char* err_msg;
int rc = tiledb_error_message(error, &err_msg);
CHECK(rc == TILEDB_OK);
CHECK(std::string(err_msg) == msg);
}
void check_load_incorrect_file_cannot_open() {
// Set config from file
tiledb_config_t* config = nullptr;
tiledb_error_t* error = nullptr;
int rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_load_from_file(config, "non_existent_file", &error);
CHECK(rc == TILEDB_ERR);
CHECK(error != nullptr);
check_error(
error,
"[TileDB::Config] Error: Failed to open config file 'non_existent_file'");
tiledb_error_free(&error);
tiledb_config_free(&config);
CHECK(config == nullptr);
}
void check_load_incorrect_file_missing_value() {
// Create a test config file
std::ofstream ofs("test_config.txt");
ofs << " # comment line\n";
ofs << "sm.tile_cache_size \n";
ofs << "# another comment line\n";
ofs << "sm.consolidation.steps 2 # some comment\n";
ofs << "# last comment line\n";
ofs.close();
// Set config from file
tiledb_config_t* config = nullptr;
tiledb_error_t* error = nullptr;
int rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_load_from_file(config, "test_config.txt", &error);
CHECK(rc == TILEDB_ERR);
CHECK(error != nullptr);
check_error(
error,
"[TileDB::Config] Error: Failed to parse config file 'test_config.txt'; "
"Missing parameter value (line: 1)");
tiledb_error_free(&error);
CHECK(error == nullptr);
tiledb_config_free(&config);
CHECK(config == nullptr);
remove_file("test_config.txt");
}
void check_load_incorrect_file_extra_word() {
// Create a test config file
std::ofstream ofs("test_config.txt");
ofs << " # comment line\n";
ofs << "sm.tile_cache_size 1000\n";
ofs << "# another comment line\n";
ofs << "sm.consolidation.steps 2 some comment\n";
ofs << "# last comment line\n";
ofs.close();
// Set config from file
tiledb_config_t* config = nullptr;
tiledb_error_t* error = nullptr;
int rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_load_from_file(config, "test_config.txt", &error);
CHECK(rc == TILEDB_ERR);
CHECK(error != nullptr);
check_error(
error,
"[TileDB::Config] Error: Failed to parse config file 'test_config.txt'; "
"Invalid line format (line: 3)");
tiledb_error_free(&error);
tiledb_config_free(&config);
remove_file("test_config.txt");
}
void check_save_to_file() {
tiledb_config_t* config;
tiledb_error_t* error;
int rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check that azure storage account name is not serialized.
rc = tiledb_config_set(
config, "vfs.azure.storage_account_name", "storagename", &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check that azure account key is not serialized.
rc = tiledb_config_set(
config, "vfs.azure.storage_account_key", "secret", &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check that azure SAS token is not serialized.
rc = tiledb_config_set(
config, "vfs.azure.storage_sas_token", "secret", &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check that password is not serialized.
rc = tiledb_config_set(config, "vfs.s3.proxy_password", "password", &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check that aws access key id is not serialized.
rc = tiledb_config_set(config, "vfs.s3.aws_access_key_id", "keyid", &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check that aws secret access key is not serialized.
rc = tiledb_config_set(
config, "vfs.s3.aws_secret_access_key", "secret", &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check that aws session token is not serialized.
rc = tiledb_config_set(
config, "vfs.s3.aws_session_token", "session_token", &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_save_to_file(config, "test_config.txt", &error);
REQUIRE(rc == TILEDB_OK);
std::stringstream ss;
// Items here need to be assigned to 'ss' in alphabetical order as
// an std::[ordered_]map is where the comparison values saved to file
// come from.
ss << "config.env_var_prefix TILEDB_\n";
ss << "config.logging_format DEFAULT\n";
#ifdef TILEDB_VERBOSE
ss << "config.logging_level 1\n";
#else
ss << "config.logging_level 0\n";
#endif
ss << "rest.http_compressor any\n";
ss << "rest.retry_count 25\n";
ss << "rest.retry_delay_factor 1.25\n";
ss << "rest.retry_http_codes 503\n";
ss << "rest.retry_initial_delay_ms 500\n";
ss << "rest.server_address https://api.tiledb.com\n";
ss << "rest.server_serialization_format CAPNP\n";
ss << "sm.check_coord_dups true\n";
ss << "sm.check_coord_oob true\n";
ss << "sm.check_global_order true\n";
ss << "sm.compute_concurrency_level " << std::thread::hardware_concurrency()
<< "\n";
ss << "sm.consolidation.amplification 1.0\n";
ss << "sm.consolidation.buffer_size 50000000\n";
ss << "sm.consolidation.mode fragments\n";
ss << "sm.consolidation.step_max_frags 4294967295\n";
ss << "sm.consolidation.step_min_frags 4294967295\n";
ss << "sm.consolidation.step_size_ratio 0.0\n";
ss << "sm.consolidation.steps 4294967295\n";
ss << "sm.consolidation.timestamp_end " << std::to_string(UINT64_MAX) << "\n";
ss << "sm.consolidation.timestamp_start 0\n";
ss << "sm.dedup_coords false\n";
ss << "sm.enable_signal_handlers true\n";
ss << "sm.encryption_key 0\n";
ss << "sm.encryption_type NO_ENCRYPTION\n";
ss << "sm.io_concurrency_level " << std::thread::hardware_concurrency()
<< "\n";
ss << "sm.max_tile_overlap_size 314572800\n";
ss << "sm.mem.malloc_trim true\n";
ss << "sm.mem.reader.sparse_global_order.ratio_array_data 0.1\n";
ss << "sm.mem.reader.sparse_global_order.ratio_coords 0.5\n";
ss << "sm.mem.reader.sparse_global_order.ratio_query_condition 0.25\n";
ss << "sm.mem.reader.sparse_global_order.ratio_rcs 0.05\n";
ss << "sm.mem.reader.sparse_global_order.ratio_tile_ranges 0.1\n";
ss << "sm.mem.reader.sparse_unordered_with_dups.ratio_array_data 0.1\n";
ss << "sm.mem.reader.sparse_unordered_with_dups.ratio_coords 0.5\n";
ss << "sm.mem.reader.sparse_unordered_with_dups.ratio_query_condition "
"0.25\n";
ss << "sm.mem.reader.sparse_unordered_with_dups.ratio_tile_ranges 0.1\n";
ss << "sm.mem.total_budget 10737418240\n";
ss << "sm.memory_budget 5368709120\n";
ss << "sm.memory_budget_var 10737418240\n";
ss << "sm.query.dense.reader legacy\n";
ss << "sm.query.sparse_global_order.reader legacy\n";
ss << "sm.query.sparse_unordered_with_dups.non_overlapping_ranges false\n";
ss << "sm.query.sparse_unordered_with_dups.reader refactored\n";
ss << "sm.read_range_oob warn\n";
ss << "sm.skip_checksum_validation false\n";
ss << "sm.skip_est_size_partitioning false\n";
ss << "sm.tile_cache_size 10000000\n";
ss << "sm.vacuum.mode fragments\n";
ss << "sm.vacuum.timestamp_end " << std::to_string(UINT64_MAX) << "\n";
ss << "sm.vacuum.timestamp_start 0\n";
ss << "sm.var_offsets.bitsize 64\n";
ss << "sm.var_offsets.extra_element false\n";
ss << "sm.var_offsets.mode bytes\n";
ss << "vfs.azure.block_list_block_size 5242880\n";
ss << "vfs.azure.max_parallel_ops " << std::thread::hardware_concurrency()
<< "\n";
ss << "vfs.azure.use_block_list_upload true\n";
ss << "vfs.azure.use_https true\n";
ss << "vfs.file.enable_filelocks true\n";
ss << "vfs.file.max_parallel_ops " << std::thread::hardware_concurrency()
<< "\n";
ss << "vfs.file.posix_directory_permissions 755\n";
ss << "vfs.file.posix_file_permissions 644\n";
ss << "vfs.gcs.max_parallel_ops " << std::thread::hardware_concurrency()
<< "\n";
ss << "vfs.gcs.multi_part_size 5242880\n";
ss << "vfs.gcs.request_timeout_ms 3000\n";
ss << "vfs.gcs.use_multi_part_upload true\n";
ss << "vfs.min_batch_gap 512000\n";
ss << "vfs.min_batch_size 20971520\n";
ss << "vfs.min_parallel_size 10485760\n";
ss << "vfs.read_ahead_cache_size 10485760\n";
ss << "vfs.read_ahead_size 102400\n";
ss << "vfs.s3.bucket_canned_acl NOT_SET\n";
ss << "vfs.s3.connect_max_tries 5\n";
ss << "vfs.s3.connect_scale_factor 25\n";
ss << "vfs.s3.connect_timeout_ms 10800\n";
ss << "vfs.s3.logging_level Off\n";
ss << "vfs.s3.max_parallel_ops " << std::thread::hardware_concurrency()
<< "\n";
ss << "vfs.s3.multipart_part_size 5242880\n";
ss << "vfs.s3.object_canned_acl NOT_SET\n";
ss << "vfs.s3.proxy_port 0\n";
ss << "vfs.s3.proxy_scheme http\n";
ss << "vfs.s3.region us-east-1\n";
ss << "vfs.s3.request_timeout_ms 3000\n";
ss << "vfs.s3.requester_pays false\n";
ss << "vfs.s3.scheme https\n";
ss << "vfs.s3.skip_init false\n";
ss << "vfs.s3.use_multipart_upload true\n";
ss << "vfs.s3.use_virtual_addressing true\n";
ss << "vfs.s3.verify_ssl true\n";
std::ifstream ifs("test_config.txt");
std::stringstream ss_file;
for (std::string line; std::getline(ifs, line);)
ss_file << line << "\n";
ifs.close();
CHECK(ss.str() == ss_file.str());
remove_file("test_config.txt");
tiledb_config_free(&config);
}
TEST_CASE("C API: Test config", "[capi][config]") {
tiledb_config_t* config = nullptr;
tiledb_error_t* error = nullptr;
int rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check correct parameter, correct argument
rc = tiledb_config_set(config, "sm.tile_cache_size", "100", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
tiledb_ctx_t* ctx;
rc = tiledb_ctx_alloc(config, &ctx);
CHECK(rc == TILEDB_OK);
tiledb_ctx_free(&ctx);
CHECK(ctx == nullptr);
// Check get for existing argument
const char* value = nullptr;
rc = tiledb_config_get(config, "sm.tile_cache_size", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!strcmp(value, "100"));
// Check get for non-existing argument
rc = tiledb_config_get(config, "foo", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(value == nullptr);
// Check get config from context
rc = tiledb_ctx_alloc(config, &ctx);
CHECK(rc == TILEDB_OK);
tiledb_config_t* get_config = nullptr;
rc = tiledb_ctx_get_config(ctx, &get_config);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_get(get_config, "sm.tile_cache_size", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!strcmp(value, "100"));
tiledb_config_free(&get_config);
tiledb_ctx_free(&ctx);
// Check correct parameter, correct argument
rc = tiledb_config_set(config, "sm.tile_cache_size", "+100", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_ctx_alloc(config, &ctx);
CHECK(rc == TILEDB_OK);
tiledb_ctx_free(&ctx);
// Check invalid argument for correct parameter
rc = tiledb_config_set(config, "sm.tile_cache_size", "xadf", &error);
CHECK(rc == TILEDB_ERR);
CHECK(error != nullptr);
check_error(
error,
"[TileDB::Utils] Error: Failed to convert string 'xadf' to uint64_t; "
"Invalid argument");
tiledb_error_free(&error);
// Check invalid argument for correct parameter
rc = tiledb_config_set(config, "sm.tile_cache_size", "10xadf", &error);
CHECK(rc == TILEDB_ERR);
CHECK(error != nullptr);
check_error(
error,
"[TileDB::Utils] Error: Failed to convert string '10xadf' to uint64_t; "
"Invalid argument");
tiledb_error_free(&error);
// Check invalid argument for correct parameter
rc = tiledb_config_set(config, "sm.tile_cache_size", "-10", &error);
CHECK(rc == TILEDB_ERR);
CHECK(error != nullptr);
check_error(
error,
"[TileDB::Utils] Error: Failed to convert string '-10' to uint64_t; "
"Invalid argument");
tiledb_error_free(&error);
// Set valid
rc = tiledb_config_set(config, "sm.tile_cache_size", "10", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
// Check invalid parameters are ignored
rc = tiledb_config_set(config, "sm.unknown_config_param", "10", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
// Unset invalid parameter (ignore)
rc = tiledb_config_unset(config, "slkjs", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
// Unset valid parameter
rc = tiledb_config_unset(config, "sm.tile_cache_size", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_get(config, "sm.tile_cache_size", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!strcmp(value, "10000000"));
// Set valid, defaulting parameter
rc = tiledb_config_set(config, "vfs.s3.region", "pluto", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_get(config, "vfs.s3.region", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!strcmp(value, "pluto"));
// Unset valid, defaulting parameter
rc = tiledb_config_unset(config, "vfs.s3.region", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_get(config, "vfs.s3.region", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!strcmp(value, "us-east-1"));
// Set valid, non-defaulting parameter
rc = tiledb_config_set(config, "foo", "123", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_get(config, "foo", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!strcmp(value, "123"));
// Unset valid, non-defaulting parameter
rc = tiledb_config_unset(config, "foo", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_get(config, "foo", &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(value == nullptr);
// Check out of range argument for correct parameter
rc = tiledb_config_set(
config, "sm.tile_cache_size", "100000000000000000000", &error);
CHECK(rc == TILEDB_ERR);
CHECK(error != nullptr);
check_error(
error,
"[TileDB::Utils] Error: Failed to convert string '100000000000000000000' "
"to uint64_t; Value out of range");
// Check config and config2 are the same
tiledb_config_t* config2 = config;
uint8_t equal = 2;
rc = tiledb_config_compare(config, config2, &equal);
CHECK(rc == TILEDB_OK);
CHECK(equal == 1);
// Check config and config3 are not the same
tiledb_config_t* config3 = nullptr;
tiledb_error_t* error2 = nullptr;
rc = tiledb_config_alloc(&config3, &error2);
REQUIRE(rc == TILEDB_OK);
CHECK(error2 == nullptr);
uint8_t equal2 = 0;
rc = tiledb_config_compare(config, config3, &equal2);
CHECK(rc == TILEDB_OK);
CHECK(equal2 == 0);
tiledb_error_free(&error);
tiledb_config_free(&config);
tiledb_error_free(&error2);
tiledb_config_free(&config3);
}
TEST_CASE("C API: Test config iter", "[capi][config]") {
tiledb_ctx_t* ctx;
int rc = tiledb_ctx_alloc(nullptr, &ctx);
REQUIRE(rc == TILEDB_OK);
// Populate a config
tiledb_config_t* config = nullptr;
tiledb_error_t* error = nullptr;
rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_set(config, "config.logging_level", "2", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_set(config, "config.logging_format", "JSON", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_set(config, "sm.tile_cache_size", "100", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_set(config, "vfs.s3.scheme", "https", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_set(config, "vfs.hdfs.username", "stavros", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_set(config, "sm.var_offsets.mode", "elements", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc =
tiledb_config_set(config, "sm.var_offsets.extra_element", "true", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_set(config, "sm.var_offsets.bitsize", "32", &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
// Prepare maps
std::map<std::string, std::string> all_param_values;
all_param_values["config.env_var_prefix"] = "TILEDB_";
all_param_values["config.logging_level"] = "2";
all_param_values["config.logging_format"] = "JSON";
all_param_values["rest.server_address"] = "https://api.tiledb.com";
all_param_values["rest.server_serialization_format"] = "CAPNP";
all_param_values["rest.http_compressor"] = "any";
all_param_values["rest.retry_count"] = "25";
all_param_values["rest.retry_delay_factor"] = "1.25";
all_param_values["rest.retry_initial_delay_ms"] = "500";
all_param_values["rest.retry_http_codes"] = "503";
all_param_values["sm.encryption_key"] = "0";
all_param_values["sm.encryption_type"] = "NO_ENCRYPTION";
all_param_values["sm.dedup_coords"] = "false";
all_param_values["sm.check_coord_dups"] = "true";
all_param_values["sm.check_coord_oob"] = "true";
all_param_values["sm.check_global_order"] = "true";
all_param_values["sm.tile_cache_size"] = "100";
all_param_values["sm.skip_est_size_partitioning"] = "false";
all_param_values["sm.memory_budget"] = "5368709120";
all_param_values["sm.memory_budget_var"] = "10737418240";
all_param_values["sm.query.dense.reader"] = "legacy";
all_param_values["sm.query.sparse_global_order.reader"] = "legacy";
all_param_values["sm.query.sparse_unordered_with_dups.reader"] = "refactored";
all_param_values
["sm.query.sparse_unordered_with_dups.non_overlapping_ranges"] = "false";
all_param_values["sm.mem.malloc_trim"] = "true";
all_param_values["sm.mem.total_budget"] = "10737418240";
all_param_values["sm.mem.reader.sparse_global_order.ratio_coords"] = "0.5";
all_param_values["sm.mem.reader.sparse_global_order.ratio_query_condition"] =
"0.25";
all_param_values["sm.mem.reader.sparse_global_order.ratio_tile_ranges"] =
"0.1";
all_param_values["sm.mem.reader.sparse_global_order.ratio_array_data"] =
"0.1";
all_param_values["sm.mem.reader.sparse_global_order.ratio_rcs"] = "0.05";
all_param_values["sm.mem.reader.sparse_unordered_with_dups.ratio_coords"] =
"0.5";
all_param_values
["sm.mem.reader.sparse_unordered_with_dups.ratio_query_condition"] =
"0.25";
all_param_values
["sm.mem.reader.sparse_unordered_with_dups.ratio_tile_ranges"] = "0.1";
all_param_values
["sm.mem.reader.sparse_unordered_with_dups.ratio_array_data"] = "0.1";
all_param_values["sm.enable_signal_handlers"] = "true";
all_param_values["sm.compute_concurrency_level"] =
std::to_string(std::thread::hardware_concurrency());
all_param_values["sm.io_concurrency_level"] =
std::to_string(std::thread::hardware_concurrency());
all_param_values["sm.skip_checksum_validation"] = "false";
all_param_values["sm.consolidation.amplification"] = "1.0";
all_param_values["sm.consolidation.steps"] = "4294967295";
all_param_values["sm.consolidation.timestamp_start"] = "0";
all_param_values["sm.consolidation.timestamp_end"] =
std::to_string(UINT64_MAX);
all_param_values["sm.consolidation.step_min_frags"] = "4294967295";
all_param_values["sm.consolidation.step_max_frags"] = "4294967295";
all_param_values["sm.consolidation.buffer_size"] = "50000000";
all_param_values["sm.consolidation.step_size_ratio"] = "0.0";
all_param_values["sm.consolidation.mode"] = "fragments";
all_param_values["sm.read_range_oob"] = "warn";
all_param_values["sm.vacuum.mode"] = "fragments";
all_param_values["sm.vacuum.timestamp_start"] = "0";
all_param_values["sm.vacuum.timestamp_end"] = std::to_string(UINT64_MAX);
all_param_values["sm.var_offsets.bitsize"] = "32";
all_param_values["sm.var_offsets.extra_element"] = "true";
all_param_values["sm.var_offsets.mode"] = "elements";
all_param_values["sm.max_tile_overlap_size"] = "314572800";
all_param_values["vfs.min_batch_gap"] = "512000";
all_param_values["vfs.min_batch_size"] = "20971520";
all_param_values["vfs.min_parallel_size"] = "10485760";
all_param_values["vfs.read_ahead_size"] = "102400";
all_param_values["vfs.read_ahead_cache_size"] = "10485760";
all_param_values["vfs.gcs.project_id"] = "";
all_param_values["vfs.gcs.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
all_param_values["vfs.gcs.multi_part_size"] = "5242880";
all_param_values["vfs.gcs.use_multi_part_upload"] = "true";
all_param_values["vfs.gcs.request_timeout_ms"] = "3000";
all_param_values["vfs.azure.storage_account_name"] = "";
all_param_values["vfs.azure.storage_account_key"] = "";
all_param_values["vfs.azure.storage_sas_token"] = "";
all_param_values["vfs.azure.blob_endpoint"] = "";
all_param_values["vfs.azure.block_list_block_size"] = "5242880";
all_param_values["vfs.azure.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
all_param_values["vfs.azure.use_block_list_upload"] = "true";
all_param_values["vfs.azure.use_https"] = "true";
all_param_values["vfs.file.posix_file_permissions"] = "644";
all_param_values["vfs.file.posix_directory_permissions"] = "755";
all_param_values["vfs.file.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
all_param_values["vfs.file.enable_filelocks"] = "true";
all_param_values["vfs.s3.scheme"] = "https";
all_param_values["vfs.s3.region"] = "us-east-1";
all_param_values["vfs.s3.aws_access_key_id"] = "";
all_param_values["vfs.s3.aws_secret_access_key"] = "";
all_param_values["vfs.s3.aws_session_token"] = "";
all_param_values["vfs.s3.aws_role_arn"] = "";
all_param_values["vfs.s3.aws_external_id"] = "";
all_param_values["vfs.s3.aws_load_frequency"] = "";
all_param_values["vfs.s3.aws_session_name"] = "";
all_param_values["vfs.s3.endpoint_override"] = "";
all_param_values["vfs.s3.use_virtual_addressing"] = "true";
all_param_values["vfs.s3.skip_init"] = "false";
all_param_values["vfs.s3.use_multipart_upload"] = "true";
all_param_values["vfs.s3.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
all_param_values["vfs.s3.multipart_part_size"] = "5242880";
all_param_values["vfs.s3.ca_file"] = "";
all_param_values["vfs.s3.ca_path"] = "";
all_param_values["vfs.s3.connect_timeout_ms"] = "10800";
all_param_values["vfs.s3.connect_max_tries"] = "5";
all_param_values["vfs.s3.connect_scale_factor"] = "25";
all_param_values["vfs.s3.sse"] = "";
all_param_values["vfs.s3.sse_kms_key_id"] = "";
all_param_values["vfs.s3.logging_level"] = "Off";
all_param_values["vfs.s3.request_timeout_ms"] = "3000";
all_param_values["vfs.s3.requester_pays"] = "false";
all_param_values["vfs.s3.proxy_host"] = "";
all_param_values["vfs.s3.proxy_password"] = "";
all_param_values["vfs.s3.proxy_port"] = "0";
all_param_values["vfs.s3.proxy_scheme"] = "http";
all_param_values["vfs.s3.proxy_username"] = "";
all_param_values["vfs.s3.verify_ssl"] = "true";
all_param_values["vfs.hdfs.username"] = "stavros";
all_param_values["vfs.hdfs.kerb_ticket_cache_path"] = "";
all_param_values["vfs.hdfs.name_node_uri"] = "";
all_param_values["vfs.s3.bucket_canned_acl"] = "NOT_SET";
all_param_values["vfs.s3.object_canned_acl"] = "NOT_SET";
std::map<std::string, std::string> vfs_param_values;
vfs_param_values["min_batch_gap"] = "512000";
vfs_param_values["min_batch_size"] = "20971520";
vfs_param_values["min_parallel_size"] = "10485760";
vfs_param_values["read_ahead_size"] = "102400";
vfs_param_values["read_ahead_cache_size"] = "10485760";
vfs_param_values["gcs.project_id"] = "";
vfs_param_values["gcs.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
vfs_param_values["gcs.multi_part_size"] = "5242880";
vfs_param_values["gcs.use_multi_part_upload"] = "true";
vfs_param_values["gcs.request_timeout_ms"] = "3000";
vfs_param_values["azure.storage_account_name"] = "";
vfs_param_values["azure.storage_account_key"] = "";
vfs_param_values["azure.storage_sas_token"] = "";
vfs_param_values["azure.blob_endpoint"] = "";
vfs_param_values["azure.block_list_block_size"] = "5242880";
vfs_param_values["azure.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
vfs_param_values["azure.use_block_list_upload"] = "true";
vfs_param_values["azure.use_https"] = "true";
vfs_param_values["file.posix_file_permissions"] = "644";
vfs_param_values["file.posix_directory_permissions"] = "755";
vfs_param_values["file.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
vfs_param_values["file.enable_filelocks"] = "true";
vfs_param_values["s3.scheme"] = "https";
vfs_param_values["s3.region"] = "us-east-1";
vfs_param_values["s3.aws_access_key_id"] = "";
vfs_param_values["s3.aws_secret_access_key"] = "";
vfs_param_values["s3.aws_session_token"] = "";
vfs_param_values["s3.aws_role_arn"] = "";
vfs_param_values["s3.aws_external_id"] = "";
vfs_param_values["s3.aws_load_frequency"] = "";
vfs_param_values["s3.aws_session_name"] = "";
vfs_param_values["s3.endpoint_override"] = "";
vfs_param_values["s3.use_virtual_addressing"] = "true";
vfs_param_values["s3.skip_init"] = "false";
vfs_param_values["s3.use_multipart_upload"] = "true";
vfs_param_values["s3.max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
vfs_param_values["s3.multipart_part_size"] = "5242880";
vfs_param_values["s3.ca_file"] = "";
vfs_param_values["s3.ca_path"] = "";
vfs_param_values["s3.connect_timeout_ms"] = "10800";
vfs_param_values["s3.connect_max_tries"] = "5";
vfs_param_values["s3.connect_scale_factor"] = "25";
vfs_param_values["s3.sse"] = "";
vfs_param_values["s3.sse_kms_key_id"] = "";
vfs_param_values["s3.logging_level"] = "Off";
vfs_param_values["s3.request_timeout_ms"] = "3000";
vfs_param_values["s3.requester_pays"] = "false";
vfs_param_values["s3.proxy_host"] = "";
vfs_param_values["s3.proxy_password"] = "";
vfs_param_values["s3.proxy_port"] = "0";
vfs_param_values["s3.proxy_scheme"] = "http";
vfs_param_values["s3.proxy_username"] = "";
vfs_param_values["s3.verify_ssl"] = "true";
vfs_param_values["s3.bucket_canned_acl"] = "NOT_SET";
vfs_param_values["s3.object_canned_acl"] = "NOT_SET";
vfs_param_values["hdfs.username"] = "stavros";
vfs_param_values["hdfs.kerb_ticket_cache_path"] = "";
vfs_param_values["hdfs.name_node_uri"] = "";
std::map<std::string, std::string> gcs_param_values;
gcs_param_values["project_id"] = "";
gcs_param_values["max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
gcs_param_values["multi_part_size"] = "5242880";
gcs_param_values["use_multi_part_upload"] = "true";
gcs_param_values["request_timeout_ms"] = "3000";
std::map<std::string, std::string> azure_param_values;
azure_param_values["storage_account_name"] = "";
azure_param_values["storage_account_key"] = "";
azure_param_values["storage_sas_token"] = "";
azure_param_values["blob_endpoint"] = "";
azure_param_values["block_list_block_size"] = "5242880";
azure_param_values["max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
azure_param_values["use_block_list_upload"] = "true";
azure_param_values["use_https"] = "true";
std::map<std::string, std::string> s3_param_values;
s3_param_values["scheme"] = "https";
s3_param_values["region"] = "us-east-1";
s3_param_values["aws_access_key_id"] = "";
s3_param_values["aws_secret_access_key"] = "";
s3_param_values["aws_session_token"] = "";
s3_param_values["aws_role_arn"] = "";
s3_param_values["aws_external_id"] = "";
s3_param_values["aws_load_frequency"] = "";
s3_param_values["aws_session_name"] = "";
s3_param_values["endpoint_override"] = "";
s3_param_values["use_virtual_addressing"] = "true";
s3_param_values["skip_init"] = "false";
s3_param_values["use_multipart_upload"] = "true";
s3_param_values["max_parallel_ops"] =
std::to_string(std::thread::hardware_concurrency());
s3_param_values["multipart_part_size"] = "5242880";
s3_param_values["ca_file"] = "";
s3_param_values["ca_path"] = "";
s3_param_values["connect_timeout_ms"] = "10800";
s3_param_values["connect_max_tries"] = "5";
s3_param_values["connect_scale_factor"] = "25";
s3_param_values["sse"] = "";
s3_param_values["sse_kms_key_id"] = "";
s3_param_values["logging_level"] = "Off";
s3_param_values["request_timeout_ms"] = "3000";
s3_param_values["requester_pays"] = "false";
s3_param_values["proxy_host"] = "";
s3_param_values["proxy_password"] = "";
s3_param_values["proxy_port"] = "0";
s3_param_values["proxy_scheme"] = "http";
s3_param_values["proxy_username"] = "";
s3_param_values["verify_ssl"] = "true";
s3_param_values["bucket_canned_acl"] = "NOT_SET";
s3_param_values["object_canned_acl"] = "NOT_SET";
// Create an iterator and iterate over all parameters
tiledb_config_iter_t* config_iter = nullptr;
rc = tiledb_config_iter_alloc(config, nullptr, &config_iter, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
int done;
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!(bool)done);
const char *param, *value;
std::map<std::string, std::string> all_iter_map;
do {
rc = tiledb_config_iter_here(config_iter, ¶m, &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(param != nullptr);
CHECK(value != nullptr);
all_iter_map[std::string(param)] = std::string(value);
rc = tiledb_config_iter_next(config_iter, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
} while (!done);
// highlight any difference to aid the poor developer in event CHECK() fails.
// If tiledb environment config variables have been set to something different
// from default configuration (such as
// "set/export TILEDB_VFS_S3_AWS_ACCESS_KEY_ID=minio"),
// these can legitimately differ from the defaults expected!
for (auto i1 = all_param_values.begin(); i1 != all_param_values.end(); ++i1) {
if (auto i2 = all_iter_map.find(i1->first); i2 == all_iter_map.end()) {
std::cout << "all_iter_map[\"" << i1->first << "\"] not found!"
<< std::endl;
} else {
if (i1->first != i2->first) {
std::cout << "huh? i1->first != i2->first, \"" << i1->first
<< "\" vs \"" << i2->first << std::endl;
} else if (i2->second != i1->second) {
std::cout << "values for key \"" << i1->first << "\", "
<< "\"" << i2->second << "\" != "
<< "\"" << i1->second << "\"" << std::endl;
} else if (all_param_values[i1->first] != all_iter_map[i1->first]) {
// if i1->first == i2->first, then should not be possible to be here,
// but just in case...
std::cout << " apv[k] != aim[k], k \"" << i1->first << "\", "
<< "\"" << all_param_values[i1->first] << "\" != \""
<< all_iter_map[i1->first] << "\"" << std::endl;
}
}
}
for (auto i1 = all_iter_map.begin(); i1 != all_iter_map.end(); ++i1) {
if (all_param_values.find(i1->first) == all_param_values.end()) {
std::cout << "all_param_values[\"" << i1->first << "\"] not found!"
<< std::endl;
}
// else, for all like keys, unlike values should have been reported in
// previous loop.
}
CHECK(all_param_values == all_iter_map);
tiledb_config_iter_free(&config_iter);
CHECK(error == nullptr);
// Create an iterator and iterate over vfs parameters
rc = tiledb_config_iter_alloc(config, "vfs.", &config_iter, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!(bool)done);
std::map<std::string, std::string> vfs_iter_map;
do {
rc = tiledb_config_iter_here(config_iter, ¶m, &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(param != nullptr);
CHECK(value != nullptr);
vfs_iter_map[std::string(param)] = std::string(value);
rc = tiledb_config_iter_next(config_iter, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
} while (!done);
// highlight any difference to aid the poor developer in event CHECK() fails.
for (auto i1 = vfs_param_values.begin(); i1 != vfs_param_values.end(); ++i1) {
if (auto i2 = vfs_iter_map.find(i1->first); i2 == vfs_iter_map.end()) {
std::cout << "vfs_iter_map[\"" << i1->first << "\"] not found!"
<< std::endl;
} else {
if (i1->first != i2->first) {
std::cout << "huh? i1->first != i2->first, \"" << i1->first
<< "\" vs \"" << i2->first << std::endl;
} else if (i2->second != i1->second) {
std::cout << "values for key \"" << i1->first << "\", "
<< "\"" << i2->second << "\" != "
<< "\"" << i1->second << "\"" << std::endl;
} else if (vfs_param_values[i1->first] != vfs_iter_map[i1->first]) {
// if i1->first == i2->first, then should not be possible to be here,
// but just in case...
std::cout << " apv[k] != aim[k], k \"" << i1->first << "\", "
<< "\"" << vfs_param_values[i1->first] << "\" != \""
<< vfs_iter_map[i1->first] << "\"" << std::endl;
// std::cout << " apv/aim [\"" << i1->first << "\"], \"" <<
// all_param_values[i1->first] << " != \"" <<
}
}
}
for (auto i1 = vfs_iter_map.begin(); i1 != vfs_iter_map.end(); ++i1) {
if (vfs_param_values.find(i1->first) == vfs_param_values.end()) {
std::cout << "vfs_param_values[\"" << i1->first << "\"] not found!"
<< std::endl;
}
}
CHECK(vfs_param_values == vfs_iter_map);
tiledb_config_iter_free(&config_iter);
// Create an iterator and iterate over gcs parameters
rc = tiledb_config_iter_alloc(config, "vfs.gcs.", &config_iter, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!(bool)done);
std::map<std::string, std::string> gcs_iter_map;
do {
rc = tiledb_config_iter_here(config_iter, ¶m, &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(param != nullptr);
CHECK(value != nullptr);
gcs_iter_map[std::string(param)] = std::string(value);
rc = tiledb_config_iter_next(config_iter, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
} while (!done);
CHECK(gcs_param_values == gcs_iter_map);
tiledb_config_iter_free(&config_iter);
CHECK(error == nullptr);
// Create an iterator and iterate over azure parameters
rc = tiledb_config_iter_alloc(config, "vfs.azure.", &config_iter, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!(bool)done);
std::map<std::string, std::string> azure_iter_map;
do {
rc = tiledb_config_iter_here(config_iter, ¶m, &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(param != nullptr);
CHECK(value != nullptr);
azure_iter_map[std::string(param)] = std::string(value);
rc = tiledb_config_iter_next(config_iter, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
} while (!done);
CHECK(azure_param_values == azure_iter_map);
tiledb_config_iter_free(&config_iter);
CHECK(error == nullptr);
// Create an iterator and iterate over s3 parameters
rc = tiledb_config_iter_alloc(config, "vfs.s3.", &config_iter, &error);
REQUIRE(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(!(bool)done);
std::map<std::string, std::string> s3_iter_map;
do {
rc = tiledb_config_iter_here(config_iter, ¶m, &value, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
CHECK(param != nullptr);
CHECK(value != nullptr);
s3_iter_map[std::string(param)] = std::string(value);
rc = tiledb_config_iter_next(config_iter, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
rc = tiledb_config_iter_done(config_iter, &done, &error);
CHECK(rc == TILEDB_OK);
CHECK(error == nullptr);
} while (!done);
// highlight any difference to aid the poor developer in event CHECK() fails.
for (auto i1 = s3_param_values.begin(); i1 != s3_param_values.end(); ++i1) {
if (auto i2 = s3_iter_map.find(i1->first); i2 == s3_iter_map.end()) {
std::cout << "s3_iter_map[\"" << i1->first << "\"] not found!"
<< std::endl;
} else {
if (i1->first != i2->first) {
std::cout << "huh? i1->first != i2->first, \"" << i1->first
<< "\" vs \"" << i2->first << std::endl;
} else if (i2->second != i1->second) {
std::cout << "values for key \"" << i1->first << "\", "
<< "\"" << i2->second << "\" != "
<< "\"" << i1->second << "\"" << std::endl;
} else if (s3_param_values[i1->first] != s3_iter_map[i1->first]) {
// if i1->first == i2->first, then should not be possible to be here,
// but just in case...
std::cout << " apv[k] != aim[k], k \"" << i1->first << "\", "
<< "\"" << s3_param_values[i1->first] << "\" != \""
<< s3_iter_map[i1->first] << "\"" << std::endl;
// std::cout << " apv/aim [\"" << i1->first << "\"], \"" <<
// all_param_values[i1->first] << " != \"" <<
}
}
}
for (auto i1 = s3_iter_map.begin(); i1 != s3_iter_map.end(); ++i1) {
if (s3_param_values.find(i1->first) == s3_param_values.end()) {
std::cout << "s3_param_values[\"" << i1->first << "\"] not found!"
<< std::endl;
}
}
CHECK(s3_param_values == s3_iter_map);
tiledb_config_iter_free(&config_iter);
CHECK(error == nullptr);
// Clean up
tiledb_config_free(&config);
tiledb_ctx_free(&ctx);
}
TEST_CASE("C API: Test config from file", "[capi][config]") {
check_load_correct_file();
check_load_incorrect_file_cannot_open();
check_load_incorrect_file_missing_value();
check_load_incorrect_file_extra_word();
check_save_to_file();
}
TEST_CASE(
"C API: Test boolean config values are normalized", "[capi][config]") {
tiledb_error_t* err;
tiledb_config_t* config = nullptr;
int rc = tiledb_config_alloc(&config, &err);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.use_virtual_addressing", "TRUE", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.use_virtual_addressing", "True", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.skip_init", "FALSE", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.skip_init", "False", &err);
CHECK(rc == TILEDB_OK);
rc =
tiledb_config_set(config, "vfs.s3.use_virtual_addressing", "FALSE", &err);
CHECK(rc == TILEDB_OK);
rc =
tiledb_config_set(config, "vfs.s3.use_virtual_addressing", "False", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.skit_init", "TRUE", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.skip_init", "True", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.use_multipart_upload", "TRUE", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.use_multipart_upload", "True", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.use_multipart_upload", "FALSE", &err);
CHECK(rc == TILEDB_OK);
rc = tiledb_config_set(config, "vfs.s3.use_multipart_upload", "False", &err);
CHECK(rc == TILEDB_OK);
tiledb_config_free(&config);
}
TEST_CASE("C API: Test VFS config inheritance", "[capi][config][vfs-inherit]") {
tiledb_error_t* err;
tiledb_config_t* config = nullptr;
int rc = tiledb_config_alloc(&config, &err);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_config_set(config, "sm.tile_cache_size", "100", &err);
CHECK(rc == TILEDB_OK);
tiledb_config_t* vfs_config = nullptr;
rc = tiledb_config_alloc(&vfs_config, &err);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_config_set(vfs_config, "vfs.s3.ca_file", "path", &err);
CHECK(rc == TILEDB_OK);
tiledb_ctx_t* ctx = nullptr;
rc = tiledb_ctx_alloc(config, &ctx);
CHECK(rc == TILEDB_OK);
tiledb_vfs_t* vfs = nullptr;
tiledb_config_t* vfs_config_get = nullptr;
rc = tiledb_vfs_alloc(ctx, vfs_config, &vfs);
CHECK(rc == TILEDB_OK);
rc = tiledb_vfs_get_config(ctx, vfs, &vfs_config_get);
CHECK(rc == TILEDB_OK);
const char* value = nullptr;
rc = tiledb_config_get(vfs_config_get, "sm.tile_cache_size", &value, &err);
CHECK(rc == TILEDB_OK);
CHECK(!strcmp(value, "100"));
rc = tiledb_config_get(vfs_config_get, "vfs.s3.ca_file", &value, &err);
CHECK(rc == TILEDB_OK);
CHECK(!strcmp(value, "path"));
tiledb_config_free(&config);
tiledb_config_free(&vfs_config);
tiledb_config_free(&vfs_config_get);
tiledb_vfs_free(&vfs);
tiledb_ctx_free(&ctx);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "ArrowTypeUtils.h"
using namespace facebook::velox;
std::shared_ptr<arrow::DataType> toArrowTypeFromName(const std::string& type_name) {
if (type_name == "BOOLEAN") {
return arrow::boolean();
}
if (type_name == "INTEGER") {
return arrow::int32();
}
if (type_name == "BIGINT") {
return arrow::int64();
}
if (type_name == "DOUBLE") {
return arrow::float64();
}
if (type_name == "VARCHAR") {
return arrow::utf8();
}
throw std::runtime_error("Type name is not supported");
}
std::shared_ptr<arrow::DataType> toArrowType(const TypePtr& type) {
switch (type->kind()) {
case TypeKind::INTEGER:
return arrow::int32();
case TypeKind::BIGINT:
return arrow::int64();
case TypeKind::DOUBLE:
return arrow::float64();
case TypeKind::VARCHAR:
return arrow::utf8();
default:
throw std::runtime_error("Type conversion is not supported.");
}
}
const char* arrowTypeIdToFormatStr(arrow::Type::type typeId) {
switch (typeId) {
case arrow::Type::type::BOOL:
return "b"; // boolean
case arrow::Type::type::INT32:
return "i"; // int32
case arrow::Type::type::INT64:
return "l"; // int64
case arrow::Type::type::DOUBLE:
return "g"; // float64
case arrow::Type::type::STRING:
return "u"; // utf-8 string
default:
// Unsupported types.
throw std::runtime_error("Arrow type id not supported.");
}
}
|
/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
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.
=============================================================================*/
#ifndef ComponentConfigurationState_hpp
#define ComponentConfigurationState_hpp
#include "cppmicroservices/Bundle.h"
#include "cppmicroservices/ServiceReference.h"
#include <future>
#include <memory>
#include <string>
#include <vector>
#include "cppmicroservices/servicecomponent/detail/ComponentInstance.hpp"
#include "cppmicroservices/servicecomponent/runtime/dto/ComponentConfigurationDTO.hpp"
using cppmicroservices::service::component::detail::ComponentInstance;
using cppmicroservices::service::component::runtime::dto::ComponentState;
namespace cppmicroservices {
namespace scrimpl {
class ComponentConfigurationImpl;
/**
* Interface for state objects used in {@link ComponentConfigurationImpl} class
*/
class ComponentConfigurationState
: public std::enable_shared_from_this<ComponentConfigurationState>
{
public:
ComponentConfigurationState() = default;
virtual ~ComponentConfigurationState() = default;
ComponentConfigurationState(const ComponentConfigurationState&) = delete;
ComponentConfigurationState& operator=(const ComponentConfigurationState&) =
delete;
ComponentConfigurationState(ComponentConfigurationState&&) = delete;
ComponentConfigurationState& operator=(ComponentConfigurationState&&) =
delete;
/**
* Implementation must handle the transition from \c UNSATISFIED_REFERENCE to \c SATISFIED
*
* \param mgr is the {@link ComponentConfigurationImpl} object whose state needs to change
*/
virtual void Register(ComponentConfigurationImpl& mgr) = 0;
/**
* Implementation must handle the transition from \c SATISFIED to \c ACTIVE
*
* \param mgr is the {@link ComponentConfigurationImpl} object whose state needs to change
* \param clientBundle is the bundle responsible for triggering the state change
*/
virtual std::shared_ptr<ComponentInstance> Activate(
ComponentConfigurationImpl& mgr,
const cppmicroservices::Bundle& clientBundle) = 0;
/**
* Implementation must handle the transition from \c SATISFIED or \c ACTIVE to \c UNSATISFIED_REFERENCE
*
* @param mgr is the {@link ComponentConfigurationImpl} object whose state needs to change
*/
virtual void Deactivate(ComponentConfigurationImpl& mgr) = 0;
/**
* Implementation must modify the properties of a component instance when a configuration
* object on which it is dependent changes.
* @return boolean
* - true if the component has a Modified method.
* - false if the component does not have a Modified method. The
* component has been Deactivated
*/
virtual bool Modified(ComponentConfigurationImpl& mgr) = 0;
/**
* Implementation must handle dynamic rebinding in any state.
*
* \param mgr is the {@link ComponentConfigurationImpl} object whose state needs to change
* \param refName is the name of the reference as defined in the SCR JSON
* \param svcRefToBind is the service reference to the target service to bind. A default
* constructed \c ServiceReference<void> denotes that there is no service to bind.
* \param svcRefToUnbind is the service reference to the target service to unbind.
* A default constructed \c ServiceReference<void> denotes that there is no service to unbind.
*/
virtual void Rebind(ComponentConfigurationImpl& mgr,
const std::string& refName,
const ServiceReference<void>& svcRefToBind,
const ServiceReference<void>& svcRefToUnbind) = 0;
/**
* Returns the state as a {@link ComponentState} enum value
*/
virtual ComponentState GetValue() const = 0;
/**
* Implementation must wait until the transition task is finished
*/
virtual void WaitForTransitionTask() = 0;
};
}
}
#endif // ComponentConfigurationState_hpp
|
#include <stdio.h>
#include <time.h>
// Enter the day you were born
// mmddyyyy
int main (void){
int month, day, year, monthT, dayT, yearT;
printf("Enter your Date in ddmmyyyy format\n");
scanf("%2d%2d%4d", &month, &day, &year);
time_t seconds = time(NULL);
struct tm *now = localtime(&seconds);
monthT = now->tm_mon + 1;
dayT = now->tm_mday;
yearT = now->tm_year + 1900;
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(yearT % 4 == 0){
days[1] = 29;
}
int day_month = days[now->tm_mon];
int month_before = days[month - 2];
if(month == 0){
month_before = days[12];
}
printf("The current date is %02d-%02d-%d\n", monthT, dayT, yearT);
if(month < monthT)
if(day > dayT)
printf("\nYou are %d years, %d months, and %d days old.", yearT - 1 - year, 12 - month + now->tm_mon - 1, dayT + month_before - day);
else
printf("\nYou are %d years, %d months, and %d days old.", yearT - 1 - year, 12 - month + now->tm_mon, dayT - day);
else if(month > monthT)
if(day > dayT)
printf("\nYou are %d years, %d months, and %d days old.", yearT - 1 - year, 12 - month + now->tm_mon - 1, dayT + month_before - day);
else
printf("\nYou are %d years, %d months, and %d days old.", yearT - 1 - year, 12 - month + now->tm_mon, dayT - day);
else
if(day > dayT)
printf("\nYou are %d years, %d months, and %d days old.", yearT - 1 - year, 11, day_month - (day - dayT));
else
printf("\nYou are %d years, %d months, and %d days old.", yearT - year, 0, dayT - day);
}
|
// 1613. 역사
// 2019.05.18
// 플로이드 와샬 알고리즘
#include<iostream>
using namespace std;
int d[401][401];
int main()
{
int n, m;
int from, to;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++)
{
scanf("%d %d", &from, &to);
// 대소방향을 나타내기 위해 1과 -1로 저장
d[from][to] = -1;
d[to][from] = 1;
}
// 1>2, 2>3 일때 1>3인 경우들을 찾는 과정
for (int i = 1; i <= n; i++)
{
for (int from = 1; from <= n; from++)
{
for (int to = 1; to <= n; to++)
{
if (d[from][to] == 0)
{
if (d[from][i] + d[i][to] == 0)
{
continue;
}
else if (d[from][i] == -1 && d[i][to] == -1)
{
d[from][to] = -1;
}
else if (d[from][i] == 1 && d[i][to] == 1)
{
d[from][to] = 1;
}
}
}
}
}
int s;
scanf("%d", &s);
for (int i = 0; i < s; i++)
{
scanf("%d %d", &from, &to);
printf("%d\n", d[from][to]);
}
return 0;
}
|
// Copyright 2016 The Fuchsia 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 "peridot/lib/callback/capture.h"
#include <memory>
#include "gtest/gtest.h"
namespace callback {
namespace {
TEST(Capture, CaptureVariable) {
int a1 = 0;
std::string a2;
std::unique_ptr<std::string> a3;
bool called = false;
Capture([&called] { called = true; }, &a1, &a2, &a3)(
1, "hello", std::make_unique<std::string>("world"));
EXPECT_TRUE(called);
EXPECT_EQ(1, a1);
EXPECT_EQ("hello", a2);
EXPECT_TRUE(a3);
EXPECT_EQ("world", *a3);
}
TEST(Capture, CaptureConstReference) {
int a1 = 0;
int a2 = 0;
bool called = false;
std::function<void(int, const int&)> capture =
Capture([&called] { called = true; }, &a1, &a2);
capture(1, 2);
EXPECT_TRUE(called);
EXPECT_EQ(1, a1);
EXPECT_EQ(2, a2);
}
} // namespace
} // namespace callback
|
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/bcm/BcmTableStats.h"
#include "fboss/agent/hw/bcm/BcmHost.h"
#include "fboss/agent/hw/bcm/BcmMirrorTable.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include <fb303/ServiceData.h>
#include <folly/logging/xlog.h>
#include <array>
#include "fboss/agent/hw/bcm/gen-cpp2/bcmswitch_constants.h"
extern "C" {
#include <bcm/field.h>
#include <bcm/l3.h>
#include <bcm/switch.h>
}
DECLARE_int32(acl_gid);
namespace facebook::fboss {
namespace {
constexpr auto kPerIpv6Mask65_127SlotUsage = 2;
}
bool BcmHwTableStatManager::refreshHwStatusStats(BcmHwTableStats* stats) {
// HW status info
bcm_l3_info_t l3HwStatus;
auto ret = bcm_l3_info(hw_->getUnit(), &l3HwStatus);
if (ret) {
XLOG(ERR) << "Unable to get HW status, host table and ipv4 LPM"
" stats will be stale";
return false;
}
*stats->l3_host_max_ref() = std::max(0, l3HwStatus.l3info_max_host);
*stats->l3_host_used_ref() = std::max(0, l3HwStatus.l3info_used_host);
*stats->l3_host_free_ref() =
std::max(0, *stats->l3_host_max_ref() - *stats->l3_host_used_ref());
*stats->l3_nexthops_max_ref() = std::max(0, l3HwStatus.l3info_max_nexthop);
*stats->l3_nexthops_used_ref() = std::max(0, l3HwStatus.l3info_used_nexthop);
*stats->l3_nexthops_free_ref() = std::max(
0, *stats->l3_nexthops_max_ref() - *stats->l3_nexthops_used_ref());
*stats->l3_ipv4_host_used_ref() =
std::max(0, l3HwStatus.l3info_used_host_ip4);
*stats->l3_ipv6_host_used_ref() =
std::max(0, l3HwStatus.l3info_used_host_ip6);
*stats->l3_ecmp_groups_max_ref() =
std::max(0, l3HwStatus.l3info_max_ecmp_groups);
*stats->l3_ecmp_groups_used_ref() =
hw_->getMultiPathNextHopTable()->getEcmpEgressCount();
*stats->l3_ecmp_groups_free_ref() = std::max(
0, *stats->l3_ecmp_groups_max_ref() - *stats->l3_ecmp_groups_used_ref());
return true;
}
bool BcmHwTableStatManager::refreshLPMStats(BcmHwTableStats* stats) {
// IPv6 LPM table info
std::array<int, 6> routeSlots = {0, 0, 0, 0, 0, 0};
std::array<bcm_switch_object_t, routeSlots.size()> bcmFreeEntryTypes = {
bcmSwitchObjectL3RouteV4RoutesMax,
bcmSwitchObjectL3RouteV6Routes64bMax,
bcmSwitchObjectL3RouteV6Routes128bMax,
bcmSwitchObjectL3RouteV4RoutesUsed,
bcmSwitchObjectL3RouteV6Routes64bUsed,
bcmSwitchObjectL3RouteV6Routes128bUsed,
};
auto ret = bcm_switch_object_count_multi_get(
hw_->getUnit(),
routeSlots.size(),
bcmFreeEntryTypes.data(),
routeSlots.data());
if (ret) {
XLOG(ERR) << "Unable to get LPM table usage, LPM table "
"stats will be stale";
return false;
}
// Max
*stats->lpm_ipv4_max_ref() = routeSlots[0];
*stats->lpm_ipv6_mask_0_64_max_ref() = routeSlots[1];
*stats->lpm_ipv6_mask_65_127_max_ref() = routeSlots[2];
// Used
*stats->lpm_ipv4_used_ref() = routeSlots[3];
*stats->lpm_ipv6_mask_0_64_used_ref() = routeSlots[4];
*stats->lpm_ipv6_mask_65_127_used_ref() = routeSlots[5];
// Ideally lpm slots max and used should come from SDK.
// However SDK always has these set to 0 in bcm_l3_info_t.
// There is a case open with BCM for this. If we get a patch
// or newer SDK fixes this, we can get rid of the calculation
// below.
// Note that v4 and v6 /0-/64 share same TCAM area so we
// only need to count them once.
*stats->lpm_slots_max_ref() = *stats->lpm_ipv6_mask_0_64_max_ref() +
*stats->lpm_ipv6_mask_65_127_max_ref() * kPerIpv6Mask65_127SlotUsage;
return true;
}
bool BcmHwTableStatManager::refreshLPMOnlyStats(BcmHwTableStats* stats) {
// IPv6 LPM table info
std::array<int, 3> routeSlots = {0, 0, 0};
std::array<bcm_switch_object_t, routeSlots.size()> bcmFreeEntryTypes = {
bcmSwitchObjectL3RouteV4RoutesFree,
bcmSwitchObjectL3RouteV6Routes64bFree,
bcmSwitchObjectL3RouteV6Routes128bFree,
};
auto ret = bcm_switch_object_count_multi_get(
hw_->getUnit(),
routeSlots.size(),
bcmFreeEntryTypes.data(),
routeSlots.data());
if (ret) {
XLOG(ERR) << "Unable to get LPM free stats, these "
"will be stale";
return false;
}
// Free
*stats->lpm_ipv4_free_ref() = routeSlots[0];
*stats->lpm_ipv6_mask_0_64_free_ref() = routeSlots[1];
*stats->lpm_ipv6_mask_65_127_free_ref() = routeSlots[2];
*stats->lpm_slots_free_ref() = *stats->lpm_ipv6_mask_0_64_free_ref() +
*stats->lpm_ipv6_mask_65_127_free_ref() * kPerIpv6Mask65_127SlotUsage;
// refreshLPMStats must be called first
*stats->lpm_slots_used_ref() =
*stats->lpm_slots_max_ref() - *stats->lpm_slots_free_ref();
return true;
}
bool BcmHwTableStatManager::refreshFPStats(BcmHwTableStats* stats) {
bcm_field_group_status_t aclStatus;
auto ret =
bcm_field_group_status_get(hw_->getUnit(), FLAGS_acl_gid, &aclStatus);
if (ret) {
return false;
}
// Entries
*stats->acl_entries_used_ref() = aclStatus.entry_count;
*stats->acl_entries_max_ref() = aclStatus.entries_total;
*stats->acl_entries_free_ref() = aclStatus.entries_free;
// Counters
*stats->acl_counters_used_ref() = aclStatus.counter_count;
*stats->acl_counters_free_ref() = aclStatus.counters_free;
// compute max via used + free rather than using counters total
// The latter is higher than what is available to this group
*stats->acl_counters_max_ref() =
*stats->acl_counters_used_ref() + *stats->acl_counters_free_ref();
// Meters
*stats->acl_meters_used_ref() = aclStatus.meter_count;
*stats->acl_meters_free_ref() = aclStatus.meters_free;
*stats->acl_meters_max_ref() = aclStatus.meters_total;
return true;
}
void BcmHwTableStatManager::updateBcmStateChangeStats(
const StateDelta& delta,
BcmHwTableStats* stats) {
if (*stats->mirrors_erspan_ref() ==
bcmswitch_constants::STAT_UNINITIALIZED_) {
*stats->mirrors_erspan_ref() = 0;
}
if (*stats->mirrors_span_ref() == bcmswitch_constants::STAT_UNINITIALIZED_) {
*stats->mirrors_span_ref() = 0;
}
if (*stats->mirrors_sflow_ref() == bcmswitch_constants::STAT_UNINITIALIZED_) {
*stats->mirrors_sflow_ref() = 0;
}
DeltaFunctions::forEachChanged(
delta.getMirrorsDelta(),
[=](const std::shared_ptr<Mirror>& oldMirror,
const std::shared_ptr<Mirror>& newMirror) {
if (oldMirror->isResolved()) {
decrementBcmMirrorStat(oldMirror, stats);
}
if (newMirror->isResolved()) {
incrementBcmMirrorStat(newMirror, stats);
}
},
[=](const std::shared_ptr<Mirror>& addedMirror) {
if (addedMirror->isResolved()) {
incrementBcmMirrorStat(addedMirror, stats);
}
},
[=](const std::shared_ptr<Mirror>& removedMirror) {
if (removedMirror->isResolved()) {
decrementBcmMirrorStat(removedMirror, stats);
}
});
*stats->mirrors_max_ref() = bcmswitch_constants::MAX_MIRRORS_;
*stats->mirrors_used_ref() = *stats->mirrors_erspan_ref() +
*stats->mirrors_span_ref() + *stats->mirrors_sflow_ref();
*stats->mirrors_free_ref() =
*stats->mirrors_max_ref() - *stats->mirrors_used_ref();
}
void BcmHwTableStatManager::decrementBcmMirrorStat(
const std::shared_ptr<Mirror>& removedMirror,
BcmHwTableStats* stats) {
CHECK(removedMirror->isResolved());
auto tunnel = removedMirror->getMirrorTunnel();
if (!tunnel) {
(*stats->mirrors_span_ref())--;
} else if (tunnel && !tunnel->udpPorts) {
(*stats->mirrors_erspan_ref())--;
} else if (tunnel && tunnel->udpPorts) {
(*stats->mirrors_sflow_ref())--;
}
}
void BcmHwTableStatManager::incrementBcmMirrorStat(
const std::shared_ptr<Mirror>& addedMirror,
BcmHwTableStats* stats) {
CHECK(addedMirror->isResolved());
auto tunnel = addedMirror->getMirrorTunnel();
if (!tunnel) {
(*stats->mirrors_span_ref())++;
} else if (tunnel && !tunnel->udpPorts) {
(*stats->mirrors_erspan_ref())++;
} else if (tunnel && tunnel->udpPorts) {
(*stats->mirrors_sflow_ref())++;
}
}
void BcmHwTableStatManager::publish(BcmHwTableStats stats) const {
fb303::fbData->setCounter(
"hw_table_stats_stale", *stats.hw_table_stats_stale_ref() ? 1 : 0);
fb303::fbData->setCounter("l3_host_max", *stats.l3_host_max_ref());
fb303::fbData->setCounter("l3_host_used", *stats.l3_host_used_ref());
fb303::fbData->setCounter("l3_host_free", *stats.l3_host_free_ref());
fb303::fbData->setCounter("l3_nexthops_max", *stats.l3_nexthops_max_ref());
fb303::fbData->setCounter("l3_nexthops_used", *stats.l3_nexthops_used_ref());
fb303::fbData->setCounter("l3_nexthops_free", *stats.l3_nexthops_free_ref());
fb303::fbData->setCounter(
"l3_ecmp_groups_used", *stats.l3_ecmp_groups_used_ref());
fb303::fbData->setCounter(
"l3_ipv4_host_used", *stats.l3_ipv4_host_used_ref());
fb303::fbData->setCounter(
"l3_ipv6_host_used", *stats.l3_ipv6_host_used_ref());
fb303::fbData->setCounter(
"l3_ecmp_groups_max", *stats.l3_ecmp_groups_max_ref());
fb303::fbData->setCounter(
"l3_ecmp_groups_free", *stats.l3_ecmp_groups_free_ref());
// LPM
fb303::fbData->setCounter("lpm_ipv4_max", *stats.lpm_ipv4_max_ref());
fb303::fbData->setCounter("lpm_ipv4_free", *stats.lpm_ipv4_free_ref());
fb303::fbData->setCounter("lpm_ipv4_used", *stats.lpm_ipv4_used_ref());
fb303::fbData->setCounter(
"lpm_ipv6_mask_0_64_max", *stats.lpm_ipv6_mask_0_64_max_ref());
fb303::fbData->setCounter(
"lpm_ipv6_mask_0_64_free", *stats.lpm_ipv6_mask_0_64_free_ref());
fb303::fbData->setCounter(
"lpm_ipv6_mask_0_64_used", *stats.lpm_ipv6_mask_0_64_used_ref());
fb303::fbData->setCounter(
"lpm_ipv6_mask_65_127_max", *stats.lpm_ipv6_mask_65_127_max_ref());
fb303::fbData->setCounter(
"lpm_ipv6_mask_0_64_free", *stats.lpm_ipv6_mask_0_64_free_ref());
fb303::fbData->setCounter(
"lpm_ipv6_mask_65_127_free", *stats.lpm_ipv6_mask_65_127_free_ref());
fb303::fbData->setCounter(
"lpm_ipv6_mask_65_127_used", *stats.lpm_ipv6_mask_65_127_used_ref());
fb303::fbData->setCounter("lpm_table_max", *stats.lpm_slots_max_ref());
fb303::fbData->setCounter("lpm_table_used", *stats.lpm_slots_used_ref());
fb303::fbData->setCounter("lpm_table_free", *stats.lpm_slots_free_ref());
// Acl
fb303::fbData->setCounter("acl_entries_used", *stats.acl_entries_used_ref());
fb303::fbData->setCounter("acl_entries_free", *stats.acl_entries_free_ref());
fb303::fbData->setCounter("acl_entries_max", *stats.acl_entries_max_ref());
fb303::fbData->setCounter(
"acl_counters_used", *stats.acl_counters_used_ref());
fb303::fbData->setCounter(
"acl_counters_free", *stats.acl_counters_free_ref());
fb303::fbData->setCounter("acl_counters_max", *stats.acl_counters_max_ref());
fb303::fbData->setCounter("acl_meters_used", *stats.acl_meters_used_ref());
fb303::fbData->setCounter("acl_meters_free", *stats.acl_meters_free_ref());
fb303::fbData->setCounter("acl_meters_max", *stats.acl_meters_max_ref());
// Mirrors
fb303::fbData->setCounter("mirrors_used", *stats.mirrors_used_ref());
fb303::fbData->setCounter("mirrors_free", *stats.mirrors_free_ref());
fb303::fbData->setCounter("mirrors_max", *stats.mirrors_max_ref());
fb303::fbData->setCounter("mirrors_span", *stats.mirrors_span_ref());
fb303::fbData->setCounter("mirrors_erspan", *stats.mirrors_erspan_ref());
fb303::fbData->setCounter("mirrors_sflow", *stats.mirrors_sflow_ref());
}
void BcmHwTableStatManager::refresh(
const StateDelta& delta,
BcmHwTableStats* stats) {
*stats->hw_table_stats_stale_ref() =
!(refreshHwStatusStats(stats) && refreshLPMStats(stats) &&
refreshFPStats(stats));
if (!isAlpmEnabled_) {
*stats->hw_table_stats_stale_ref() |= !(refreshLPMOnlyStats(stats));
}
updateBcmStateChangeStats(delta, stats);
}
} // namespace facebook::fboss
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Console
#include "System/Console.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Console::InternalCancelHandler);
DEFINE_IL2CPP_ARG_TYPE(::System::Console::InternalCancelHandler*, "System", "Console/InternalCancelHandler");
// Type namespace: System
namespace System {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: System.Console/System.InternalCancelHandler
// [TokenAttribute] Offset: FFFFFFFF
class Console::InternalCancelHandler : public ::System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x13A7E30
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static Console::InternalCancelHandler* New_ctor(::Il2CppObject* object, ::System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Console::InternalCancelHandler::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<Console::InternalCancelHandler*, creationType>(object, method)));
}
// public System.Void Invoke()
// Offset: 0x13A7E40
void Invoke();
// public System.IAsyncResult BeginInvoke(System.AsyncCallback callback, System.Object object)
// Offset: 0x13A804C
::System::IAsyncResult* BeginInvoke(::System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Void EndInvoke(System.IAsyncResult result)
// Offset: 0x13A8078
void EndInvoke(::System::IAsyncResult* result);
}; // System.Console/System.InternalCancelHandler
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Console::InternalCancelHandler::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Console::InternalCancelHandler::Invoke
// Il2CppName: Invoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Console::InternalCancelHandler::*)()>(&System::Console::InternalCancelHandler::Invoke)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Console::InternalCancelHandler*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Console::InternalCancelHandler::BeginInvoke
// Il2CppName: BeginInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::IAsyncResult* (System::Console::InternalCancelHandler::*)(::System::AsyncCallback*, ::Il2CppObject*)>(&System::Console::InternalCancelHandler::BeginInvoke)> {
static const MethodInfo* get() {
static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg;
static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Console::InternalCancelHandler*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{callback, object});
}
};
// Writing MetadataGetter for method: System::Console::InternalCancelHandler::EndInvoke
// Il2CppName: EndInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Console::InternalCancelHandler::*)(::System::IAsyncResult*)>(&System::Console::InternalCancelHandler::EndInvoke)> {
static const MethodInfo* get() {
static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Console::InternalCancelHandler*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result});
}
};
|
/* Copyright 2019 The TensorFlow Authors. 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.
==============================================================================*/
// This file defines helpers useful when creating or manipulating lhlo/hlo.
#include "mlir-hlo/utils/convert_op_folder.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/TypeUtilities.h"
namespace mlir {
namespace hlo {
mlir::ElementsAttr ConvertElementsAttr(const mlir::ElementsAttr& elements,
mlir::Type new_type) {
auto old_type = getElementTypeOrSelf(elements);
size_t bit_width = new_type.isBF16() ? 64 : new_type.getIntOrFloatBitWidth();
if (old_type.isa<mlir::FloatType>()) {
// mapValues always takes a function returning APInt, even when the output
// is actually float.
using func_type = mlir::APInt(const llvm::APFloat&);
if (auto newFloatType = new_type.dyn_cast<mlir::FloatType>()) {
// Float -> Float
return elements.mapValues(
new_type, llvm::function_ref<func_type>(
[&newFloatType](const llvm::APFloat& floatVal) {
llvm::APFloat newDouble(
mlir::FloatAttr::getValueAsDouble(floatVal));
bool loses_info = false;
newDouble.convert(newFloatType.getFloatSemantics(),
llvm::APFloat::rmNearestTiesToEven,
&loses_info);
return newDouble.bitcastToAPInt();
}));
}
// Float -> Int
return elements.mapValues(
new_type, llvm::function_ref<func_type>(
[&bit_width](const llvm::APFloat& floatVal) {
return llvm::APInt(
bit_width,
mlir::FloatAttr::getValueAsDouble(floatVal));
}));
}
// old_type is Integer
// mapValues always takes a function returning APInt, even when the output
// is actually float.
using func_type = llvm::APInt(const llvm::APInt&);
// TODO(hinsu): Correctly handle unsigned element types.
bool is_bool = old_type.isInteger(1);
if (auto newFloatType = new_type.dyn_cast<mlir::FloatType>()) {
// Int -> Float
return elements.mapValues(
new_type, llvm::function_ref<func_type>([&newFloatType, &is_bool](
const llvm::APInt& intVal) {
int64_t val = is_bool ? intVal.getZExtValue() : intVal.getSExtValue();
llvm::APFloat newDouble(static_cast<double>(val));
bool loses_info = false;
newDouble.convert(newFloatType.getFloatSemantics(),
llvm::APFloat::rmNearestTiesToEven, &loses_info);
return newDouble.bitcastToAPInt();
}));
}
// new_type is Integer
// Int -> Int
return elements.mapValues(
new_type, llvm::function_ref<func_type>([&bit_width, &is_bool](
const llvm::APInt& intVal) {
int64_t val = is_bool ? intVal.getZExtValue() : intVal.getSExtValue();
return llvm::APInt(bit_width, val);
}));
}
} // namespace hlo
} // namespace mlir
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkQuadEdge.h"
namespace itk
{
// ---------------------------------------------------------------------
QuadEdge
::QuadEdge()
{
this->m_Onext = this;
this->m_Rot = ITK_NULLPTR;
}
// ---------------------------------------------------------------------
QuadEdge
::~QuadEdge()
{
this->m_Onext = ITK_NULLPTR;
this->m_Rot = ITK_NULLPTR;
}
// ---------------------------------------------------------------------
QuadEdge *
QuadEdge
::GetLnext()
{
#ifdef NDEBUG
return this->GetInvRot()->GetOnext()->GetRot();
#else
Self *p1 = this->GetInvRot();
if ( p1 == NULL )
{
return NULL;
}
Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
Self *p3 = p2->GetRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
const QuadEdge *
QuadEdge
::GetLnext() const
{
#ifdef NDEBUG
return this->GetInvRot()->GetOnext()->GetRot();
#else
const Self *p1 = this->GetInvRot();
if ( p1 == NULL )
{
return NULL;
}
const Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
const Self *p3 = p2->GetRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
QuadEdge *
QuadEdge
::GetRnext()
{
#ifdef NDEBUG
return this->GetRot()->GetOnext()->GetInvRot();
#else
Self *p1 = this->GetRot();
if ( p1 == NULL )
{
return NULL;
}
Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
Self *p3 = p2->GetInvRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
const QuadEdge *
QuadEdge
::GetRnext() const
{
#ifdef NDEBUG
return this->GetRot()->GetOnext()->GetInvRot();
#else
const Self *p1 = this->GetRot();
if ( p1 == NULL )
{
return NULL;
}
const Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
const Self *p3 = p2->GetInvRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
QuadEdge *
QuadEdge
::GetDnext()
{
#ifdef NDEBUG
return this->GetSym()->GetOnext()->GetSym();
#else
Self *p1 = this->GetSym();
if ( p1 == NULL )
{
return NULL;
}
Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
Self *p3 = p2->GetSym();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
const QuadEdge *
QuadEdge
::GetDnext() const
{
#ifdef NDEBUG
return this->GetSym()->GetOnext()->GetSym();
#else
const Self *p1 = this->GetSym();
if ( p1 == NULL )
{
return NULL;
}
const Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
const Self *p3 = p2->GetSym();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
QuadEdge *
QuadEdge
::GetOprev()
{
#ifdef NDEBUG
return this->GetRot()->GetOnext()->GetRot();
#else
Self *p1 = this->GetRot();
if ( p1 == NULL )
{
return NULL;
}
Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
Self *p3 = p2->GetRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
const QuadEdge *
QuadEdge
::GetOprev() const
{
#ifdef NDEBUG
return this->GetRot()->GetOnext()->GetRot();
#else
const Self *p1 = this->GetRot();
if ( p1 == NULL )
{
return NULL;
}
const Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
const Self *p3 = p2->GetRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
QuadEdge *
QuadEdge
::GetLprev()
{
#ifdef NDEBUG
return this->GetOnext()->GetSym();
#else
Self *p1 = this->GetOnext();
if ( p1 == NULL )
{
return NULL;
}
Self *p2 = p1->GetSym();
if ( p2 == NULL )
{
return NULL;
}
return p2;
#endif
}
// ---------------------------------------------------------------------
const QuadEdge *
QuadEdge
::GetLprev() const
{
#ifdef NDEBUG
return this->GetOnext()->GetSym();
#else
const Self *p1 = this->GetOnext();
if ( p1 == NULL )
{
return NULL;
}
const Self *p2 = p1->GetSym();
if ( p2 == NULL )
{
return NULL;
}
return p2;
#endif
}
// ---------------------------------------------------------------------
QuadEdge *
QuadEdge
::GetRprev()
{
#ifdef NDEBUG
return this->GetSym()->GetOnext();
#else
Self *p1 = this->GetSym();
if ( p1 == NULL )
{
return NULL;
}
Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
return p2;
#endif
}
// ---------------------------------------------------------------------
const QuadEdge *
QuadEdge
::GetRprev() const
{
#ifdef NDEBUG
return this->GetSym()->GetOnext();
#else
const Self *p1 = this->GetSym();
if ( p1 == NULL )
{
return NULL;
}
const Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
return p2;
#endif
}
// ---------------------------------------------------------------------
QuadEdge *
QuadEdge
::GetDprev()
{
#ifdef NDEBUG
return this->GetInvRot()->GetOnext()->GetInvRot();
#else
Self *p1 = this->GetInvRot();
if ( p1 == NULL )
{
return NULL;
}
Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
Self *p3 = p2->GetInvRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
// ---------------------------------------------------------------------
const QuadEdge *
QuadEdge
::GetDprev() const
{
#ifdef NDEBUG
return this->GetInvRot()->GetOnext()->GetInvRot();
#else
const Self *p1 = this->GetInvRot();
if ( p1 == NULL )
{
return NULL;
}
const Self *p2 = p1->GetOnext();
if ( p2 == NULL )
{
return NULL;
}
const Self *p3 = p2->GetInvRot();
if ( p3 == NULL )
{
return NULL;
}
return p3;
#endif
}
bool
QuadEdge
::IsEdgeInOnextRing(Self *testEdge) const
{
if ( !this->IsIsolated() )
{
ConstIterator it = this->BeginOnext();
while ( it != this->EndOnext() )
{
if ( it.Value() == ITK_NULLPTR )
{
return false;
}
if ( it.Value() == testEdge )
{
return true;
}
it++;
}
}
return false;
}
bool
QuadEdge
::IsLnextGivenSizeCyclic(const int size) const
{
const Self *iterated = this;
for ( int i = 0; i < size; i++ )
{
iterated = iterated->GetLnext();
if ( !iterated ) { return false; }
}
return ( this == iterated );
}
unsigned int
QuadEdge
::GetOrder() const
{
if ( !( this->IsIsolated() ) )
{
unsigned int order = 1; // count this edge
const Self * it = this->GetOnext();
while ( it && it != this )
{
order++;
it = it->GetOnext();
}
return order;
}
return 0;
}
} // end namespace itk
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// UNSUPPORTED: nvrtc
// <cuda/std/tuple>
// template <class F, class T> constexpr decltype(auto) apply(F &&, T &&)
// Test with different ref/ptr/cv qualified argument types.
#include <cuda/std/tuple>
// Array tests are disabled
// #include <cuda/std/array>
#include <cuda/std/utility>
#include <cuda/std/cassert>
#include "test_macros.h"
#include "type_id.h"
// cuda::std::array is explicitly allowed to be initialized with A a = { init-list };.
// Disable the missing braces warning for this reason.
#include "disable_missing_braces_warning.h"
template <typename T>
__host__ __device__
constexpr void unused(T &&) {}
__host__ __device__
constexpr int constexpr_sum_fn() { return 0; }
template <class ...Ints>
__host__ __device__
constexpr int constexpr_sum_fn(int x1, Ints... rest) { return x1 + constexpr_sum_fn(rest...); }
struct ConstexprSumT {
constexpr ConstexprSumT() = default;
template <class ...Ints>
__host__ __device__
constexpr int operator()(Ints... values) const {
return constexpr_sum_fn(values...);
}
};
__host__ __device__
void test_constexpr_evaluation()
{
constexpr ConstexprSumT sum_obj{};
{
using Tup = cuda::std::tuple<>;
using Fn = int(&)();
constexpr Tup t;
static_assert(cuda::std::apply(static_cast<Fn>(constexpr_sum_fn), t) == 0, "");
static_assert(cuda::std::apply(sum_obj, t) == 0, "");
}
{
using Tup = cuda::std::tuple<int>;
using Fn = int(&)(int);
constexpr Tup t(42);
static_assert(cuda::std::apply(static_cast<Fn>(constexpr_sum_fn), t) == 42, "");
static_assert(cuda::std::apply(sum_obj, t) == 42, "");
}
{
using Tup = cuda::std::tuple<int, long>;
using Fn = int(&)(int, int);
constexpr Tup t(42, 101);
static_assert(cuda::std::apply(static_cast<Fn>(constexpr_sum_fn), t) == 143, "");
static_assert(cuda::std::apply(sum_obj, t) == 143, "");
}
{
using Tup = cuda::std::pair<int, long>;
using Fn = int(&)(int, int);
constexpr Tup t(42, 101);
static_assert(cuda::std::apply(static_cast<Fn>(constexpr_sum_fn), t) == 143, "");
static_assert(cuda::std::apply(sum_obj, t) == 143, "");
}
{
using Tup = cuda::std::tuple<int, long, int>;
using Fn = int(&)(int, int, int);
constexpr Tup t(42, 101, -1);
static_assert(cuda::std::apply(static_cast<Fn>(constexpr_sum_fn), t) == 142, "");
static_assert(cuda::std::apply(sum_obj, t) == 142, "");
}
/* TODO: enable cuda::std::array
{
using Tup = cuda::std::array<int, 3>;
using Fn = int(&)(int, int, int);
constexpr Tup t = {42, 101, -1};
static_assert(cuda::std::apply(static_cast<Fn>(constexpr_sum_fn), t) == 142, "");
static_assert(cuda::std::apply(sum_obj, t) == 142, "");
}
*/
}
enum CallQuals {
CQ_None,
CQ_LValue,
CQ_ConstLValue,
CQ_RValue,
CQ_ConstRValue
};
template <class Tuple>
struct CallInfo {
CallQuals quals;
TypeID const* arg_types;
Tuple args;
template <class ...Args>
__host__ __device__
CallInfo(CallQuals q, Args&&... xargs)
: quals(q), arg_types(&makeArgumentID<Args&&...>()), args(cuda::std::forward<Args>(xargs)...)
{}
};
template <class ...Args>
__host__ __device__
inline CallInfo<decltype(cuda::std::forward_as_tuple(cuda::std::declval<Args>()...))>
makeCallInfo(CallQuals quals, Args&&... args) {
return {quals, cuda::std::forward<Args>(args)...};
}
struct TrackedCallable {
TrackedCallable() = default;
template <class ...Args>
__host__ __device__
auto operator()(Args&&... xargs) &
{ return makeCallInfo(CQ_LValue, cuda::std::forward<Args>(xargs)...); }
template <class ...Args>
__host__ __device__
auto operator()(Args&&... xargs) const&
{ return makeCallInfo(CQ_ConstLValue, cuda::std::forward<Args>(xargs)...); }
template <class ...Args>
__host__ __device__
auto operator()(Args&&... xargs) &&
{ return makeCallInfo(CQ_RValue, cuda::std::forward<Args>(xargs)...); }
template <class ...Args>
__host__ __device__
auto operator()(Args&&... xargs) const&&
{ return makeCallInfo(CQ_ConstRValue, cuda::std::forward<Args>(xargs)...); }
};
template <class ...ExpectArgs, class Tuple>
__host__ __device__
void check_apply_quals_and_types(Tuple&& t) {
TypeID const* const expect_args = &makeArgumentID<ExpectArgs...>();
TrackedCallable obj;
TrackedCallable const& cobj = obj;
{
auto ret = cuda::std::apply(obj, cuda::std::forward<Tuple>(t));
assert(ret.quals == CQ_LValue);
assert(ret.arg_types == expect_args);
assert(ret.args == t);
}
{
auto ret = cuda::std::apply(cobj, cuda::std::forward<Tuple>(t));
assert(ret.quals == CQ_ConstLValue);
assert(ret.arg_types == expect_args);
assert(ret.args == t);
}
{
auto ret = cuda::std::apply(cuda::std::move(obj), cuda::std::forward<Tuple>(t));
assert(ret.quals == CQ_RValue);
assert(ret.arg_types == expect_args);
assert(ret.args == t);
}
{
auto ret = cuda::std::apply(cuda::std::move(cobj), cuda::std::forward<Tuple>(t));
assert(ret.quals == CQ_ConstRValue);
assert(ret.arg_types == expect_args);
assert(ret.args == t);
}
}
__host__ __device__
void test_call_quals_and_arg_types()
{
using Tup = cuda::std::tuple<int, int const&, unsigned&&>;
const int x = 42;
unsigned y = 101;
Tup t(-1, x, cuda::std::move(y));
Tup const& ct = t;
check_apply_quals_and_types<int&, int const&, unsigned&>(t);
check_apply_quals_and_types<int const&, int const&, unsigned&>(ct);
check_apply_quals_and_types<int&&, int const&, unsigned&&>(cuda::std::move(t));
check_apply_quals_and_types<int const&&, int const&, unsigned&&>(cuda::std::move(ct));
}
struct NothrowMoveable {
NothrowMoveable() noexcept = default;
__host__ __device__ NothrowMoveable(NothrowMoveable const&) noexcept(false) {}
__host__ __device__ NothrowMoveable(NothrowMoveable&&) noexcept {}
};
template <bool IsNoexcept>
struct TestNoexceptCallable {
template <class ...Args>
__host__ __device__ NothrowMoveable operator()(Args...) const noexcept(IsNoexcept) { return {}; }
};
__host__ __device__
void test_noexcept()
{
TestNoexceptCallable<true> nec;
TestNoexceptCallable<false> tc;
{
// test that the functions noexcept-ness is propagated
using Tup = cuda::std::tuple<int, const char*, long>;
Tup t;
LIBCPP_ASSERT_NOEXCEPT(cuda::std::apply(nec, t));
ASSERT_NOT_NOEXCEPT(cuda::std::apply(tc, t));
unused(t);
}
{
// test that the noexcept-ness of the argument conversions is checked.
using Tup = cuda::std::tuple<NothrowMoveable, int>;
Tup t;
ASSERT_NOT_NOEXCEPT(cuda::std::apply(nec, t));
LIBCPP_ASSERT_NOEXCEPT(cuda::std::apply(nec, cuda::std::move(t)));
unused(t);
}
}
namespace ReturnTypeTest {
#ifdef __CUDA_ARCH__
__constant__ int my_int = 42;
#else
static int my_int = 42;
#endif
template <int N> struct index {};
__host__ __device__
void f(index<0>) {}
__host__ __device__
int f(index<1>) { return 0; }
__host__ __device__
int & f(index<2>) { return static_cast<int &>(my_int); }
__host__ __device__
int const & f(index<3>) { return static_cast<int const &>(my_int); }
__host__ __device__
int volatile & f(index<4>) { return static_cast<int volatile &>(my_int); }
__host__ __device__
int const volatile & f(index<5>) { return static_cast<int const volatile &>(my_int); }
__host__ __device__
int && f(index<6>) { return static_cast<int &&>(my_int); }
__host__ __device__
int const && f(index<7>) { return static_cast<int const &&>(my_int); }
__host__ __device__
int volatile && f(index<8>) { return static_cast<int volatile &&>(my_int); }
__host__ __device__
int const volatile && f(index<9>) { return static_cast<int const volatile &&>(my_int); }
__host__ __device__
int * f(index<10>) { return static_cast<int *>(&my_int); }
__host__ __device__
int const * f(index<11>) { return static_cast<int const *>(&my_int); }
__host__ __device__
int volatile * f(index<12>) { return static_cast<int volatile *>(&my_int); }
__host__ __device__
int const volatile * f(index<13>) { return static_cast<int const volatile *>(&my_int); }
template <int Func, class Expect>
__host__ __device__
void test()
{
using RawInvokeResult = decltype(f(index<Func>{}));
static_assert(cuda::std::is_same<RawInvokeResult, Expect>::value, "");
using FnType = RawInvokeResult (*) (index<Func>);
FnType fn = f;
cuda::std::tuple<index<Func>> t;
using InvokeResult = decltype(cuda::std::apply(fn, t));
static_assert(cuda::std::is_same<InvokeResult, Expect>::value, "");
unused(t); unused(fn);
}
} // end namespace ReturnTypeTest
__host__ __device__
void test_return_type()
{
using ReturnTypeTest::test;
test<0, void>();
test<1, int>();
test<2, int &>();
test<3, int const &>();
test<4, int volatile &>();
test<5, int const volatile &>();
test<6, int &&>();
test<7, int const &&>();
test<8, int volatile &&>();
test<9, int const volatile &&>();
test<10, int *>();
test<11, int const *>();
test<12, int volatile *>();
test<13, int const volatile *>();
}
int main(int, char**) {
test_constexpr_evaluation();
test_call_quals_and_arg_types();
test_return_type();
test_noexcept();
return 0;
}
|
#include "HCUBE_Defines.h"
#include "Experiments/HCUBE_ImageCompressionExperiment.h"
#define INPUT_PPM "waveNM_diff.ppm"
#define DIFF_PPM "waveNM_diff2.ppm"
#define OUTPUT_PPM "waveNM_output2.ppm"
#define FITNESS_THRESHOLD (9000)
namespace HCUBE
{
using namespace NEAT;
ImageCompressionExperiment::ImageCompressionExperiment(string _experimentName,int _threadID)
:
Experiment(_experimentName,_threadID),
numNodesX(256),
numNodesY(256)
{
smallest.r = smallest.g = smallest.b = 0;
biggest.r = biggest.g = biggest.b = 255;
ifstream infile(INPUT_PPM);
string line;
for(int a=0;a<4;a++)
{
//skip header
getline(infile,line);
}
for(int y=0;y<256;y++)
{
for(int x=0;x<256;x++)
{
infile >> rawimage[y][x].r >> rawimage[y][x].g >> rawimage[y][x].b;
smallest.r = min(smallest.r,rawimage[y][x].r);
smallest.g = min(smallest.g,rawimage[y][x].g);
smallest.b = min(smallest.b,rawimage[y][x].b);
biggest.r = max(biggest.r,rawimage[y][x].r);
biggest.g = max(biggest.g,rawimage[y][x].g);
biggest.b = max(biggest.b,rawimage[y][x].b);
}
}
spread.r = biggest.r-smallest.r;
spread.g = biggest.g-smallest.g;
spread.b = biggest.b-smallest.b;
//Normalize the image to the new scale
/*
for(int y=0;y<256;y++)
{
for(int x=0;x<256;x++)
{
rawimage[y][x].r -= smallest.r;
rawimage[y][x].g -= smallest.g;
rawimage[y][x].b -= smallest.b;
if(spread.r)
{
rawimage[y][x].r = (rawimage[y][x].r*255)/spread.r;
}
else
{
rawimage[y][x].r=0;
}
if(spread.g)
{
rawimage[y][x].g = (rawimage[y][x].g*255)/spread.g;
}
else
{
rawimage[y][x].g=0;
}
if(spread.b)
{
rawimage[y][x].b = (rawimage[y][x].b*255)/spread.b;
}
else
{
rawimage[y][x].b=0;
}
}
}
*/
}
GeneticPopulation* ImageCompressionExperiment::createInitialPopulation(int populationSize)
{
GeneticPopulation *population = new GeneticPopulation();
vector<GeneticNodeGene> genes;
genes.push_back(GeneticNodeGene("Bias","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("X","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("Y","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("Output_1R","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
genes.push_back(GeneticNodeGene("Output_1G","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
genes.push_back(GeneticNodeGene("Output_1B","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
//genes.push_back(GeneticNodeGene("Output_1A","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
//genes.push_back(GeneticNodeGene("Output_2R","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
//genes.push_back(GeneticNodeGene("Output_2G","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
//genes.push_back(GeneticNodeGene("Output_2B","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
//genes.push_back(GeneticNodeGene("Output_2A","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
#if DEBUG_ENABLE_BIASES
genes.push_back(GeneticNodeGene("Bias_b","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
genes.push_back(GeneticNodeGene("Bias_c","NetworkOutputNode",1,false,ACTIVATION_FUNCTION_SIGMOID));
#endif
for (int a=0;a<populationSize;a++)
{
shared_ptr<GeneticIndividual> individual(new GeneticIndividual(genes,true,1.0));
for (int b=0;b<0;b++)
{
individual->testMutate();
}
//individual->getNode("Output_2R")->setTopologyFrozen(true);
//individual->getNode("Output_2R")->setEnabled(false);
//individual->getNode("Output_2G")->setTopologyFrozen(true);
//individual->getNode("Output_2G")->setEnabled(false);
//individual->getNode("Output_2B")->setTopologyFrozen(true);
//individual->getNode("Output_2B")->setEnabled(false);
//individual->getNode("Output_2A")->setTopologyFrozen(true);
//individual->getNode("Output_2A")->setEnabled(false);
population->addIndividual(individual);
}
cout << "Finished creating population\n";
return population;
}
void ImageCompressionExperiment::populateSubstrate(
shared_ptr<NEAT::GeneticIndividual> individual
)
{
if (substrateIndividual==individual)
{
//Don't bother remaking the same substrate
return;
}
substrateIndividual=individual;
NEAT::FastNetwork<float> network = individual->spawnFastPhenotypeStack<float>();
double totalFitness = 0;
Pixel biggestSpread;
biggestSpread.r = biggestSpread.g = biggestSpread.b = 0;
for (int y=0;y<numNodesY;y++)
{
for (int x=0;x<numNodesX;x++)
{
/*Remap the nodes to the [-1,1] domain*/
float xnormal,ynormal;
if (numNodesX>1)
{
xnormal = -1.0 + (float(x)/(numNodesX-1))*2.0;
}
else
{
xnormal = 0.0;
}
if (numNodesY>1)
{
ynormal = -1.0 + (float(y)/(numNodesY-1))*2.0;
}
else
{
ynormal = 0.0;
}
network.reinitialize();
network.setValue("X",xnormal);
network.setValue("Y",ynormal);
if(network.hasNode("Bias"))
{
network.setValue("Bias",(float)0.3);
}
network.update();
{
float unsignedVal = (network.getValue("Output_1R")+1.0)/2.0;
tmpimage[y][x].r = smallest.r + unsignedVal*(spread.r);
}
{
float unsignedVal = (network.getValue("Output_1G")+1.0)/2.0;
tmpimage[y][x].g = smallest.g + unsignedVal*(spread.g);
}
{
float unsignedVal = (network.getValue("Output_1B")+1.0)/2.0;
tmpimage[y][x].b = smallest.b + unsignedVal*(spread.b);
}
//tmpimage[y][x].a = 128 + int(network.getValue("Output_1A")*128);
totalFitness += 256-abs(rawimage[y][x].r-tmpimage[y][x].r);
totalFitness += 256-abs(rawimage[y][x].g-tmpimage[y][x].g);
totalFitness += 256-abs(rawimage[y][x].b-tmpimage[y][x].b);
//totalFitness += 256-fabs(rawimage[y][x].a-tmpimage[y][x].a);
}
}
individual->setFitness(totalFitness/256.0/256.0/256.0/3.0*10000.0);
if(individual->getFitness()>FITNESS_THRESHOLD)
{
{
//Write out the PPM
ofstream outfile(OUTPUT_PPM);
outfile << "P3\n# CREATOR: The GIMP's PNM Filter Version 1.0\n256 256\n255\n";
for(int y=0;y<256;y++)
{
for(int x=0;x<256;x++)
{
#if 0
outfile
<< abs(rawimage[y][x].r-tmpimage[y][x].r) << "\n"
<< abs(rawimage[y][x].g-tmpimage[y][x].g) << "\n"
<< abs(rawimage[y][x].b-tmpimage[y][x].b) << "\n";
#else
outfile
<< (tmpimage[y][x].r) << "\n"
<< (tmpimage[y][x].g) << "\n"
<< (tmpimage[y][x].b) << "\n";
#endif
}
}
outfile.flush();
}
{
//Write out the PPM
ofstream outfile(DIFF_PPM);
outfile << "P3\n# CREATOR: The GIMP's PNM Filter Version 1.0\n256 256\n255\n";
for(int y=0;y<256;y++)
{
for(int x=0;x<256;x++)
{
#if 0
outfile
<< abs(rawimage[y][x].r-tmpimage[y][x].r) << "\n"
<< abs(rawimage[y][x].g-tmpimage[y][x].g) << "\n"
<< abs(rawimage[y][x].b-tmpimage[y][x].b) << "\n";
#else
outfile
<< (rawimage[y][x].r-tmpimage[y][x].r) << "\n"
<< (rawimage[y][x].g-tmpimage[y][x].g) << "\n"
<< (rawimage[y][x].b-tmpimage[y][x].b) << "\n";
#endif
}
}
outfile.flush();
}
exit(1);
}
}
void ImageCompressionExperiment::processGroup(shared_ptr<NEAT::GeneticGeneration> generation)
{
populateSubstrate(group[0]);
/*
if(generation->getGenerationNumber()==9)
{
cout << "LOCKING TOPOLOGY\n";
shared_ptr<NEAT::GeneticIndividual> individual = group[0];
//Lock the topology
for(int a=0;a<individual->getNodesCount();a++)
{
if(!iequals(individual->getNode(a)->getType(),"NetworkSensor"))
{
if(
!iequals(individual->getNode(a)->getType(),"NetworkOutputNode") ||
(
iequals(individual->getNode(a)->getName(),"Output_1R") ||
iequals(individual->getNode(a)->getName(),"Output_1G") ||
iequals(individual->getNode(a)->getName(),"Output_1B") //||
//iequals(individual->getNode(a)->getName(),"Output_1A")
)
)
{
//Freeze hidden nodes and select output nodes
individual->getNode(a)->setTopologyFrozen(true);
}
}
}
individual->getNode("Output_2R")->setTopologyFrozen(false);
individual->getNode("Output_2R")->setEnabled(true);
individual->getNode("Output_2G")->setTopologyFrozen(false);
individual->getNode("Output_2G")->setEnabled(true);
individual->getNode("Output_2B")->setTopologyFrozen(false);
individual->getNode("Output_2B")->setEnabled(true);
//individual->getNode("Output_2A")->setTopologyFrozen(false);
//individual->getNode("Output_2A")->setEnabled(true);
for(int a=0;a<individual->getLinksCount();a++)
{
individual->getLink(a)->setFixed(true);
}
}
*/
}
void ImageCompressionExperiment::processIndividualPostHoc(shared_ptr<NEAT::GeneticIndividual> individual)
{
populateSubstrate(individual);
{
//Write out the PPM
ofstream outfile(OUTPUT_PPM);
outfile << "P3\n# CREATOR: The GIMP's PNM Filter Version 1.0\n256 256\n255\n";
for(int y=0;y<256;y++)
{
for(int x=0;x<256;x++)
{
#if 0
outfile
<< abs(rawimage[y][x].r-tmpimage[y][x].r) << "\n"
<< abs(rawimage[y][x].g-tmpimage[y][x].g) << "\n"
<< abs(rawimage[y][x].b-tmpimage[y][x].b) << "\n";
#else
outfile
<< (tmpimage[y][x].r) << "\n"
<< (tmpimage[y][x].g) << "\n"
<< (tmpimage[y][x].b) << "\n";
#endif
}
}
outfile.flush();
}
{
//Write out the PPM
ofstream outfile(DIFF_PPM);
outfile << "P3\n# CREATOR: The GIMP's PNM Filter Version 1.0\n256 256\n255\n";
for(int y=0;y<256;y++)
{
for(int x=0;x<256;x++)
{
#if 0
outfile
<< abs(rawimage[y][x].r-tmpimage[y][x].r) << "\n"
<< abs(rawimage[y][x].g-tmpimage[y][x].g) << "\n"
<< abs(rawimage[y][x].b-tmpimage[y][x].b) << "\n";
#else
outfile
<< (rawimage[y][x].r-tmpimage[y][x].r) << "\n"
<< (rawimage[y][x].g-tmpimage[y][x].g) << "\n"
<< (rawimage[y][x].b-tmpimage[y][x].b) << "\n";
#endif
}
}
outfile.flush();
}
}
Experiment* ImageCompressionExperiment::clone()
{
ImageCompressionExperiment* experiment = new ImageCompressionExperiment(*this);
return experiment;
}
void ImageCompressionExperiment::resetGenerationData(shared_ptr<NEAT::GeneticGeneration> generation)
{
//generation->setUserData(new TicTacToeStats());
}
void ImageCompressionExperiment::addGenerationData(shared_ptr<NEAT::GeneticGeneration> generation,shared_ptr<NEAT::GeneticIndividual> individual)
{
//TicTacToeStats* ticTacToeStats = (TicTacToeStats*)generation->getUserData();
//if (individual->getUserData())
//(*ticTacToeStats) += *((TicTacToeStats*)individual->getUserData());
}
}
|
#include "fuelconsumption.h"
#include "ui_fuelconsumption.h"
#include<QDebug>
FuelConsumption::FuelConsumption() :
ui(new Ui::FuelConsumption)
{
ui->setupUi(this);
ui->readingDate->setDate(QDate::currentDate());
query.exec("SELECT SFOC, dailyCons FROM fuelConsumption WHERE date= (SELECT MAX(date) FROM fuelConsumption)");
query.next();
ui->SFOC1label->setText(query.value(0).toString());
ui->dailyClbl->setText(query.value(1).toString());
ui->SFOC1date->setDate(QDate::currentDate());
ui->dailyC1->setDate(QDate::currentDate());
//connect(ui->SFOC1date, SIGNAL(dateChanged(const QDate &date)), this, SLOT(SFOCdateChanged()));
query.exec("SELECT MAX(date) FROM fuelConsumption");
query.next();
max->setDate(query.value(0).toDate());
min->setDate(query.value(0).toDate().addMonths(-1));
qDebug()<< "FUEL CONS "<< query.value(0).toDateTime();
axisX-> setFormat("dd/MM");
axisX->setMax(query.value(0).toDateTime());
axisX->setMin(query.value(0).toDateTime().addMonths(-1));
// axisX->setTickCount(query.value(0).toDateTime().addMonths(-1).daysTo(query.value(0).toDateTime())+1);
axisX->setTitleText("Date");
diagram->addAxis(axisX, Qt::AlignBottom);
chView->setRenderHint(QPainter::Antialiasing);
chView->setChart(diagram);
QVBoxLayout* vlyt= new QVBoxLayout;
QHBoxLayout* hlyt= new QHBoxLayout;
hlyt->addWidget(min);
hlyt->addSpacing(650);
hlyt->addWidget(max);
vlyt->addWidget(chView);
vlyt->addLayout(hlyt);
wgt.setLayout(vlyt);
wgt.resize(1300, 370);
connect(ui->enterBt, SIGNAL(clicked()), this, SLOT(enterFuelReadings()));
// connect(ui->diagramBt, SIGNAL(clicked()), this, SLOT(diagramClicked()));
connect( min, &QDateEdit::dateChanged, this, &FuelConsumption::test);
connect(max, &QDateEdit::dateChanged, this, &FuelConsumption::maxDateChanged);
connect( this, &FuelConsumption::showSFOCDiagram, &FuelConsumption::showPatricDiagram);
connect( this, &FuelConsumption::showDailyConsDiagram, &FuelConsumption::showPatricDiagram);
}
FuelConsumption::~FuelConsumption()
{
delete ui;
}
void FuelConsumption::enterFuelReadings(){
QSqlQuery query;
query.exec("SELECT counter FROM fuelConsumption WHERE date= (SELECT MAX(date) FROM fuelConsumption)");
query.next();
int lastCounter=query.value(0).toInt();
int dailyCons= (ui->lineEditRead->text().toInt())- lastCounter;
query.exec("SELECT load FROM Temperatures WHERE date='"+ QDate::currentDate().toString("yyyy-MM-dd") +"' ");
query.next();
if(query.value(0).toInt()==0){
QMessageBox::warning(this,"Warning", "Load was not entried! \n To calculate SFOC enter Load");
}
else{
float SFOC= dailyCons*1000/24/query.value(0).toInt();
ui->SFOC1label->setText(QString::number(SFOC));
ui->dailyClbl->setText(QString::number(dailyCons));
query.exec("INSERT INTO fuelConsumption VALUES('"+ ui->readingDate->date().toString("dd-MM-yyyy") +"', "+ QString::number(ui->lineEditRead->text().toInt())+","+ QString::number(SFOC)+ ","+
""+ QString::number(dailyCons)+")");
}
}
void FuelConsumption::SFOCdateChanged(){
}
//void FuelConsumption::showDiagram(QString str)
void FuelConsumption::diagramClicked()
{
// emit showSFOCDiagram("SFOC");
}
void FuelConsumption::showPatricDiagram(QString str){
qDebug()<<"TESSSSSSSSSSSSSSSST";
nameOfVar.clear();
QSqlQuery query;
if(str=="dailyCons"){
axisY->setRange(2500, 4000);
axisY->setTitleText("Daily consumption");
}
else{
axisY->setRange(190, 250);
axisY->setTitleText(str);
}
diagram->removeSeries(SFOCseries);
SFOCseries->clear();
diagram->addAxis(axisY, Qt::AlignLeft);
query.exec("SELECT date,"+ str +" FROM fuelConsumption WHERE date>= DATEADD( month, -1, (SELECT MAX(date) FROM fuelConsumption)) and date < (SELECT MAX(date) FROM fuelConsumption) ");
int i=0;
while(query.next()){
QPoint p(query.value(0).toDateTime().toMSecsSinceEpoch(), query.value(1).toInt());
qDebug()<<p;
SFOCseries->append(p);
i++;
}
axisX->setTickCount(i);
diagram->addSeries(SFOCseries);
SFOCseries->attachAxis(axisY);
qDebug()<< SFOCseries;
wgt.show();
nameOfVar= str;
}
void FuelConsumption::on_SFOC1date_dateChanged(const QDate &date)
{
QSqlQuery query;
query.exec("SELECT SFOC FROM fuelConsumption WHERE date='"+ ui->SFOC1date->date().toString("yyyy-MM-dd") +"'");
query.next();
ui->SFOC1label->setText(query.value(0).toString());
}
void FuelConsumption::on_dailyC1_dateChanged(const QDate &date)
{
QSqlQuery query;
query.exec("SELECT dailyCons FROM fuelConsumption WHERE date='"+ ui->dailyC1->date().toString("yyyy-MM-dd") +"'");
query.next();
ui->dailyClbl->setText(query.value(0).toString());
}
void FuelConsumption::maxDateChanged(QDate date){
tickCount=0;
QDateTime d(date);
QSqlQuery query;
diagram->removeSeries(SFOCseries);
bool needToChangeAxis;
if(axisX->max().toMSecsSinceEpoch() > d.toMSecsSinceEpoch()){ //remove extra points
SFOCseries->clear();
query.exec("SELECT date, "+nameOfVar+" FROM fuelConsumption WHERE date>='"+ axisX->min().toString("yyyy-MM-dd") +"' and date<='"+ date.toString("yyyy-MM-dd") +"'");
while(query.next()){
tickCount++;
QPoint p(query.value(0).toDateTime().toSecsSinceEpoch(), query.value(1).toInt());
SFOCseries->append(p);
needToChangeAxis=1;
}
}
else{ // add extra points
SFOCseries->clear();
query.exec("SELECT date, "+nameOfVar+" FROM fuelConsumption WHERE date>='"+ axisX->min().toString("yyyy-MM-dd") +"' and date<='"+ date.toString("yyyy-MM-dd") +"'");
while(query.next()){
tickCount++;
QPoint p(query.value(0).toDateTime().toSecsSinceEpoch(), query.value(1).toInt());
SFOCseries->append(p);
}
needToChangeAxis=1;
// }
}
if(needToChangeAxis){
axisX->setMax(axisX->min().addDays(tickCount));
axisX->setTickCount(tickCount);
// axisX->setTickCount(abs(date.daysTo(axisX->min().date()))+1);
}
diagram->addSeries(SFOCseries);
SFOCseries->attachAxis(axisY);
}
void FuelConsumption::test(QDate date){
tickCount=0;
QDateTime d(date);
QSqlQuery query;
diagram->removeSeries(SFOCseries);
bool needToChangeAxis;
if(axisX->min().toMSecsSinceEpoch() < d.toMSecsSinceEpoch()){ //remove extra points
SFOCseries->clear();
query.exec("SELECT date, "+nameOfVar+" FROM fuelConsumption WHERE date>='"+ date.toString("yyyy-MM-dd") +"' and date<='"+ axisX->max().date().toString("yyyy-MM-dd") +"'");
while(query.next()){
tickCount++;
QPoint p(query.value(0).toDateTime().toSecsSinceEpoch(), query.value(1).toInt());
SFOCseries->append(p);
}
needToChangeAxis=1;
}
else{ // add extra points
SFOCseries->clear();
query.exec("SELECT date,"+nameOfVar+" FROM fuelConsumption WHERE date>='"+ date.toString("yyyy-MM-dd") +"' and date<='"+ axisX->max().date().toString("yyyy-MM-dd") +"'");
int y=0;
query.next();
while(query.next()){
tickCount++;
QPoint p(query.value(0).toDateTime().toSecsSinceEpoch(), query.value(1).toInt());
SFOCseries->append(p);
y++;
}
needToChangeAxis=1;
}
if(needToChangeAxis){
axisX->setMin(axisX->max().addDays(-tickCount));
axisX->setTickCount(tickCount);
}
diagram->addSeries(SFOCseries);
SFOCseries->attachAxis(axisY);
}
void FuelConsumption::on_diagramBt_clicked()
{
emit showSFOCDiagram("SFOC");
}
void FuelConsumption::on_pushButton_2_clicked(){
emit showDailyConsDiagram("dailyCons");
}
|
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "Nebula.h"
#include "VirtualNetworkPool.h"
#include <sstream>
VirtualNetworkPool::VirtualNetworkPool(SqliteDB * db,
const string& prefix,
int _default_size):
PoolSQL(db,VirtualNetwork::table),
mac_prefix(0),
default_size(_default_size)
{
istringstream iss;
size_t pos = 0;
int count = 0;
unsigned int tmp;
string mac = prefix;
while ( (pos = mac.find(':')) != string::npos )
{
mac.replace(pos,1," ");
count++;
}
if (count != 1)
{
Nebula::log("VNM",Log::ERROR,"Wrong MAC prefix format, using default");
mac_prefix = 1; //"00:01"
return;
}
iss.str(mac);
iss >> hex >> mac_prefix >> ws >> hex >> tmp >> ws;
mac_prefix <<= 8;
mac_prefix += tmp;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int VirtualNetworkPool::allocate (
int uid,
const string& stemplate,
int * oid)
{
VirtualNetwork * vn;
char * error_msg;
int rc;
ostringstream oss;
string name;
string bridge;
string str_type;
// Build a new Virtual Network object
vn = new VirtualNetwork(mac_prefix, default_size);
vn->uid = uid;
rc = vn->vn_template.parse(stemplate,&error_msg);
if ( rc != 0 )
{
oss << error_msg;
Nebula::log("VNM", Log::ERROR, oss);
free(error_msg);
return -1;
}
// Information about the VN needs to be extracted from the template
vn->get_template_attribute("TYPE",str_type);
if ( str_type == "RANGED")
{
vn->type = VirtualNetwork::RANGED;
}
else
{
vn->type = VirtualNetwork::FIXED;
}
vn->get_template_attribute("NAME",name);
vn->name = name;
vn->get_template_attribute("BRIDGE",bridge);
vn->bridge = bridge;
// Insert the VN in the pool so we have a valid OID
*oid = PoolSQL::allocate(vn);
if ( *oid == -1 )
{
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C"
{
static int select_name_cb(
void * _value,
int num,
char ** values,
char ** names)
{
int * oid;
oid = static_cast<int *>(_value);
if ( oid == 0 || values == 0 || values[0] == 0 )
{
return -1;
}
*oid = atoi(values[0]);
return 0;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
VirtualNetwork * VirtualNetworkPool::get(const string& name, bool lock)
{
ostringstream oss;
int oid;
int rc;
char * sql_name = sqlite3_mprintf("%q",name.c_str());
if ( sql_name == 0 )
{
return 0;
}
oss << "SELECT oid FROM " << VirtualNetwork::table << " WHERE name = '"
<< sql_name << "'";
rc = db->exec(oss, select_name_cb, (void *) (&oid));
sqlite3_free(sql_name);
if (rc != 0)
{
return 0;
}
return get(oid,lock);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
|
/*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code 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 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "../idlib/precompiled.h"
#pragma hdrstop
/*
=================================================================================
idCompressor_None
=================================================================================
*/
class idCompressor_None : public idCompressor {
public:
idCompressor_None();
void Init( idFile *f, bool compress, int wordLength );
void FinishCompress();
float GetCompressionRatio() const;
const char * GetName();
const char * GetFullPath();
int Read( void *outData, int outLength );
int Write( const void *inData, int inLength );
int Length();
ID_TIME_T Timestamp();
int Tell();
void ForceFlush();
void Flush();
int Seek( long offset, fsOrigin_t origin );
protected:
idFile * file;
bool compress;
};
/*
================
idCompressor_None::idCompressor_None
================
*/
idCompressor_None::idCompressor_None() {
file = NULL;
compress = true;
}
/*
================
idCompressor_None::Init
================
*/
void idCompressor_None::Init( idFile *f, bool compress, int wordLength ) {
this->file = f;
this->compress = compress;
}
/*
================
idCompressor_None::FinishCompress
================
*/
void idCompressor_None::FinishCompress() {
}
/*
================
idCompressor_None::GetCompressionRatio
================
*/
float idCompressor_None::GetCompressionRatio() const {
return 0.0f;
}
/*
================
idCompressor_None::GetName
================
*/
const char *idCompressor_None::GetName() {
if ( file ) {
return file->GetName();
} else {
return "";
}
}
/*
================
idCompressor_None::GetFullPath
================
*/
const char *idCompressor_None::GetFullPath() {
if ( file ) {
return file->GetFullPath();
} else {
return "";
}
}
/*
================
idCompressor_None::Write
================
*/
int idCompressor_None::Write( const void *inData, int inLength ) {
if ( compress == false || inLength <= 0 ) {
return 0;
}
return file->Write( inData, inLength );
}
/*
================
idCompressor_None::Read
================
*/
int idCompressor_None::Read( void *outData, int outLength ) {
if ( compress == true || outLength <= 0 ) {
return 0;
}
return file->Read( outData, outLength );
}
/*
================
idCompressor_None::Length
================
*/
int idCompressor_None::Length() {
if ( file ) {
return file->Length();
} else {
return 0;
}
}
/*
================
idCompressor_None::Timestamp
================
*/
ID_TIME_T idCompressor_None::Timestamp() {
if ( file ) {
return file->Timestamp();
} else {
return 0;
}
}
/*
================
idCompressor_None::Tell
================
*/
int idCompressor_None::Tell() {
if ( file ) {
return file->Tell();
} else {
return 0;
}
}
/*
================
idCompressor_None::ForceFlush
================
*/
void idCompressor_None::ForceFlush() {
if ( file ) {
file->ForceFlush();
}
}
/*
================
idCompressor_None::Flush
================
*/
void idCompressor_None::Flush() {
if ( file ) {
file->ForceFlush();
}
}
/*
================
idCompressor_None::Seek
================
*/
int idCompressor_None::Seek( long offset, fsOrigin_t origin ) {
common->Error( "cannot seek on idCompressor" );
return -1;
}
/*
=================================================================================
idCompressor_BitStream
Base class for bit stream compression.
=================================================================================
*/
class idCompressor_BitStream : public idCompressor_None {
public:
idCompressor_BitStream() {}
void Init( idFile *f, bool compress, int wordLength );
void FinishCompress();
float GetCompressionRatio() const;
int Write( const void *inData, int inLength );
int Read( void *outData, int outLength );
protected:
byte buffer[65536];
int wordLength;
int readTotalBytes;
int readLength;
int readByte;
int readBit;
const byte * readData;
int writeTotalBytes;
int writeLength;
int writeByte;
int writeBit;
byte * writeData;
protected:
void InitCompress( const void *inData, const int inLength );
void InitDecompress( void *outData, int outLength );
void WriteBits( int value, int numBits );
int ReadBits( int numBits );
void UnreadBits( int numBits );
int Compare( const byte *src1, int bitPtr1, const byte *src2, int bitPtr2, int maxBits ) const;
};
/*
================
idCompressor_BitStream::Init
================
*/
void idCompressor_BitStream::Init( idFile *f, bool compress, int wordLength ) {
assert( wordLength >= 1 && wordLength <= 32 );
this->file = f;
this->compress = compress;
this->wordLength = wordLength;
readTotalBytes = 0;
readLength = 0;
readByte = 0;
readBit = 0;
readData = NULL;
writeTotalBytes = 0;
writeLength = 0;
writeByte = 0;
writeBit = 0;
writeData = NULL;
}
/*
================
idCompressor_BitStream::InitCompress
================
*/
ID_INLINE void idCompressor_BitStream::InitCompress( const void *inData, const int inLength ) {
readLength = inLength;
readByte = 0;
readBit = 0;
readData = (const byte *) inData;
if ( !writeLength ) {
writeLength = sizeof( buffer );
writeByte = 0;
writeBit = 0;
writeData = buffer;
}
}
/*
================
idCompressor_BitStream::InitDecompress
================
*/
ID_INLINE void idCompressor_BitStream::InitDecompress( void *outData, int outLength ) {
if ( !readLength ) {
readLength = file->Read( buffer, sizeof( buffer ) );
readByte = 0;
readBit = 0;
readData = buffer;
}
writeLength = outLength;
writeByte = 0;
writeBit = 0;
writeData = (byte *) outData;
}
/*
================
idCompressor_BitStream::WriteBits
================
*/
void idCompressor_BitStream::WriteBits( int value, int numBits ) {
int put, fraction;
// Short circuit for writing single bytes at a time
if ( writeBit == 0 && numBits == 8 && writeByte < writeLength ) {
writeByte++;
writeTotalBytes++;
writeData[writeByte - 1] = value;
return;
}
while( numBits ) {
if ( writeBit == 0 ) {
if ( writeByte >= writeLength ) {
if ( writeData == buffer ) {
file->Write( buffer, writeByte );
writeByte = 0;
} else {
put = numBits;
writeBit = put & 7;
writeByte += ( put >> 3 ) + ( writeBit != 0 );
writeTotalBytes += ( put >> 3 ) + ( writeBit != 0 );
return;
}
}
writeData[writeByte] = 0;
writeByte++;
writeTotalBytes++;
}
put = 8 - writeBit;
if ( put > numBits ) {
put = numBits;
}
fraction = value & ( ( 1 << put ) - 1 );
writeData[writeByte - 1] |= fraction << writeBit;
numBits -= put;
value >>= put;
writeBit = ( writeBit + put ) & 7;
}
}
/*
================
idCompressor_BitStream::ReadBits
================
*/
int idCompressor_BitStream::ReadBits( int numBits ) {
int value, valueBits, get, fraction;
value = 0;
valueBits = 0;
// Short circuit for reading single bytes at a time
if ( readBit == 0 && numBits == 8 && readByte < readLength ) {
readByte++;
readTotalBytes++;
return readData[readByte - 1];
}
while ( valueBits < numBits ) {
if ( readBit == 0 ) {
if ( readByte >= readLength ) {
if ( readData == buffer ) {
readLength = file->Read( buffer, sizeof( buffer ) );
readByte = 0;
} else {
get = numBits - valueBits;
readBit = get & 7;
readByte += ( get >> 3 ) + ( readBit != 0 );
readTotalBytes += ( get >> 3 ) + ( readBit != 0 );
return value;
}
}
readByte++;
readTotalBytes++;
}
get = 8 - readBit;
if ( get > (numBits - valueBits) ) {
get = (numBits - valueBits);
}
fraction = readData[readByte - 1];
fraction >>= readBit;
fraction &= ( 1 << get ) - 1;
value |= fraction << valueBits;
valueBits += get;
readBit = ( readBit + get ) & 7;
}
return value;
}
/*
================
idCompressor_BitStream::UnreadBits
================
*/
void idCompressor_BitStream::UnreadBits( int numBits ) {
readByte -= ( numBits >> 3 );
readTotalBytes -= ( numBits >> 3 );
if ( readBit == 0 ) {
readBit = 8 - ( numBits & 7 );
} else {
readBit -= numBits & 7;
if ( readBit <= 0 ) {
readByte--;
readTotalBytes--;
readBit = ( readBit + 8 ) & 7;
}
}
if ( readByte < 0 ) {
readByte = 0;
readBit = 0;
}
}
/*
================
idCompressor_BitStream::Compare
================
*/
int idCompressor_BitStream::Compare( const byte *src1, int bitPtr1, const byte *src2, int bitPtr2, int maxBits ) const {
int i;
// If the two bit pointers are aligned then we can use a faster comparison
if ( ( bitPtr1 & 7 ) == (bitPtr2 & 7 ) && maxBits > 16 ) {
const byte *p1 = &src1[bitPtr1 >> 3];
const byte *p2 = &src2[bitPtr2 >> 3];
int bits = 0;
int bitsRemain = maxBits;
// Compare the first couple bits (if any)
if ( bitPtr1 & 7 ) {
for ( i = (bitPtr1 & 7); i < 8; i++, bits++ ) {
if ( ( ( *p1 >> i ) ^ ( *p2 >> i ) ) & 1 ) {
return bits;
}
bitsRemain--;
}
p1++;
p2++;
}
int remain = bitsRemain >> 3;
// Compare the middle bytes as ints
while ( remain >= 4 && (*(const int *)p1 == *(const int *)p2) ) {
p1 += 4;
p2 += 4;
remain -= 4;
bits += 32;
}
// Compare the remaining bytes
while ( remain > 0 && (*p1 == *p2) ) {
p1++;
p2++;
remain--;
bits += 8;
}
// Compare the last couple of bits (if any)
int finalBits = 8;
if ( remain == 0 ) {
finalBits = ( bitsRemain & 7 );
}
for ( i = 0; i < finalBits; i++, bits++ ) {
if ( ( ( *p1 >> i ) ^ ( *p2 >> i ) ) & 1 ) {
return bits;
}
}
assert(bits == maxBits);
return bits;
} else {
for ( i = 0; i < maxBits; i++ ) {
if ( ( ( src1[bitPtr1 >> 3] >> ( bitPtr1 & 7 ) ) ^ ( src2[bitPtr2 >> 3] >> ( bitPtr2 & 7 ) ) ) & 1 ) {
break;
}
bitPtr1++;
bitPtr2++;
}
return i;
}
}
/*
================
idCompressor_BitStream::Write
================
*/
int idCompressor_BitStream::Write( const void *inData, int inLength ) {
int i;
if ( compress == false || inLength <= 0 ) {
return 0;
}
InitCompress( inData, inLength );
for ( i = 0; i < inLength; i++ ) {
WriteBits( ReadBits( 8 ), 8 );
}
return i;
}
/*
================
idCompressor_BitStream::FinishCompress
================
*/
void idCompressor_BitStream::FinishCompress() {
if ( compress == false ) {
return;
}
if ( writeByte ) {
file->Write( buffer, writeByte );
}
writeLength = 0;
writeByte = 0;
writeBit = 0;
}
/*
================
idCompressor_BitStream::Read
================
*/
int idCompressor_BitStream::Read( void *outData, int outLength ) {
int i;
if ( compress == true || outLength <= 0 ) {
return 0;
}
InitDecompress( outData, outLength );
for ( i = 0; i < outLength && readLength >= 0; i++ ) {
WriteBits( ReadBits( 8 ), 8 );
}
return i;
}
/*
================
idCompressor_BitStream::GetCompressionRatio
================
*/
float idCompressor_BitStream::GetCompressionRatio() const {
if ( compress ) {
return ( readTotalBytes - writeTotalBytes ) * 100.0f / readTotalBytes;
} else {
return ( writeTotalBytes - readTotalBytes ) * 100.0f / writeTotalBytes;
}
}
/*
=================================================================================
idCompressor_RunLength
The following algorithm implements run length compression with an arbitrary
word size.
=================================================================================
*/
class idCompressor_RunLength : public idCompressor_BitStream {
public:
idCompressor_RunLength() {}
void Init( idFile *f, bool compress, int wordLength );
int Write( const void *inData, int inLength );
int Read( void *outData, int outLength );
private:
int runLengthCode;
};
/*
================
idCompressor_RunLength::Init
================
*/
void idCompressor_RunLength::Init( idFile *f, bool compress, int wordLength ) {
idCompressor_BitStream::Init( f, compress, wordLength );
runLengthCode = ( 1 << wordLength ) - 1;
}
/*
================
idCompressor_RunLength::Write
================
*/
int idCompressor_RunLength::Write( const void *inData, int inLength ) {
int bits, nextBits, count;
if ( compress == false || inLength <= 0 ) {
return 0;
}
InitCompress( inData, inLength );
while( readByte <= readLength ) {
count = 1;
bits = ReadBits( wordLength );
for ( nextBits = ReadBits( wordLength ); nextBits == bits; nextBits = ReadBits( wordLength ) ) {
count++;
if ( count >= ( 1 << wordLength ) ) {
if ( count >= ( 1 << wordLength ) + 3 || bits == runLengthCode ) {
break;
}
}
}
if ( nextBits != bits ) {
UnreadBits( wordLength );
}
if ( count > 3 || bits == runLengthCode ) {
WriteBits( runLengthCode, wordLength );
WriteBits( bits, wordLength );
if ( bits != runLengthCode ) {
count -= 3;
}
WriteBits( count - 1, wordLength );
} else {
while( count-- ) {
WriteBits( bits, wordLength );
}
}
}
return inLength;
}
/*
================
idCompressor_RunLength::Read
================
*/
int idCompressor_RunLength::Read( void *outData, int outLength ) {
int bits, count;
if ( compress == true || outLength <= 0 ) {
return 0;
}
InitDecompress( outData, outLength );
while( writeByte <= writeLength && readLength >= 0 ) {
bits = ReadBits( wordLength );
if ( bits == runLengthCode ) {
bits = ReadBits( wordLength );
count = ReadBits( wordLength ) + 1;
if ( bits != runLengthCode ) {
count += 3;
}
while( count-- ) {
WriteBits( bits, wordLength );
}
} else {
WriteBits( bits, wordLength );
}
}
return writeByte;
}
/*
=================================================================================
idCompressor_RunLength_ZeroBased
The following algorithm implements run length compression with an arbitrary
word size for data with a lot of zero bits.
=================================================================================
*/
class idCompressor_RunLength_ZeroBased : public idCompressor_BitStream {
public:
idCompressor_RunLength_ZeroBased() {}
int Write( const void *inData, int inLength );
int Read( void *outData, int outLength );
private:
};
/*
================
idCompressor_RunLength_ZeroBased::Write
================
*/
int idCompressor_RunLength_ZeroBased::Write( const void *inData, int inLength ) {
int bits, count;
if ( compress == false || inLength <= 0 ) {
return 0;
}
InitCompress( inData, inLength );
while( readByte <= readLength ) {
count = 0;
for ( bits = ReadBits( wordLength ); bits == 0 && count < ( 1 << wordLength ); bits = ReadBits( wordLength ) ) {
count++;
}
if ( count ) {
WriteBits( 0, wordLength );
WriteBits( count - 1, wordLength );
UnreadBits( wordLength );
} else {
WriteBits( bits, wordLength );
}
}
return inLength;
}
/*
================
idCompressor_RunLength_ZeroBased::Read
================
*/
int idCompressor_RunLength_ZeroBased::Read( void *outData, int outLength ) {
int bits, count;
if ( compress == true || outLength <= 0 ) {
return 0;
}
InitDecompress( outData, outLength );
while( writeByte <= writeLength && readLength >= 0 ) {
bits = ReadBits( wordLength );
if ( bits == 0 ) {
count = ReadBits( wordLength ) + 1;
while( count-- > 0 ) {
WriteBits( 0, wordLength );
}
} else {
WriteBits( bits, wordLength );
}
}
return writeByte;
}
/*
=================================================================================
idCompressor_Huffman
The following algorithm is based on the adaptive Huffman algorithm described
in Sayood's Data Compression book. The ranks are not actually stored, but
implicitly defined by the location of a node within a doubly-linked list
=================================================================================
*/
const int HMAX = 256; // Maximum symbol
const int NYT = HMAX; // NYT = Not Yet Transmitted
const int INTERNAL_NODE = HMAX + 1; // internal node
typedef struct nodetype {
struct nodetype *left, *right, *parent; // tree structure
struct nodetype *next, *prev; // doubly-linked list
struct nodetype **head; // highest ranked node in block
int weight;
int symbol;
} huffmanNode_t;
class idCompressor_Huffman : public idCompressor_None {
public:
idCompressor_Huffman() {}
void Init( idFile *f, bool compress, int wordLength );
void FinishCompress();
float GetCompressionRatio() const;
int Write( const void *inData, int inLength );
int Read( void *outData, int outLength );
private:
byte seq[65536];
int bloc;
int blocMax;
int blocIn;
int blocNode;
int blocPtrs;
int compressedSize;
int unCompressedSize;
huffmanNode_t * tree;
huffmanNode_t * lhead;
huffmanNode_t * ltail;
huffmanNode_t * loc[HMAX+1];
huffmanNode_t **freelist;
huffmanNode_t nodeList[768];
huffmanNode_t * nodePtrs[768];
private:
void AddRef( byte ch );
int Receive( huffmanNode_t *node, int *ch );
void Transmit( int ch, byte *fout );
void PutBit( int bit, byte *fout, int *offset );
int GetBit( byte *fout, int *offset );
void Add_bit( char bit, byte *fout );
int Get_bit();
huffmanNode_t **Get_ppnode();
void Free_ppnode( huffmanNode_t **ppnode );
void Swap( huffmanNode_t *node1, huffmanNode_t *node2 );
void Swaplist( huffmanNode_t *node1, huffmanNode_t *node2 );
void Increment( huffmanNode_t *node );
void Send( huffmanNode_t *node, huffmanNode_t *child, byte *fout );
};
/*
================
idCompressor_Huffman::Init
================
*/
void idCompressor_Huffman::Init( idFile *f, bool compress, int wordLength ) {
int i;
this->file = f;
this->compress = compress;
bloc = 0;
blocMax = 0;
blocIn = 0;
blocNode = 0;
blocPtrs = 0;
compressedSize = 0;
unCompressedSize = 0;
tree = NULL;
lhead = NULL;
ltail = NULL;
for( i = 0; i < (HMAX+1); i++ ) {
loc[i] = NULL;
}
freelist = NULL;
for( i = 0; i < 768; i++ ) {
memset( &nodeList[i], 0, sizeof(huffmanNode_t) );
nodePtrs[i] = NULL;
}
if ( compress ) {
// Add the NYT (not yet transmitted) node into the tree/list
tree = lhead = loc[NYT] = &nodeList[blocNode++];
tree->symbol = NYT;
tree->weight = 0;
lhead->next = lhead->prev = NULL;
tree->parent = tree->left = tree->right = NULL;
} else {
// Initialize the tree & list with the NYT node
tree = lhead = ltail = loc[NYT] = &nodeList[blocNode++];
tree->symbol = NYT;
tree->weight = 0;
lhead->next = lhead->prev = NULL;
tree->parent = tree->left = tree->right = NULL;
}
}
/*
================
idCompressor_Huffman::PutBit
================
*/
void idCompressor_Huffman::PutBit( int bit, byte *fout, int *offset) {
bloc = *offset;
if ( (bloc&7) == 0 ) {
fout[(bloc>>3)] = 0;
}
fout[(bloc>>3)] |= bit << (bloc&7);
bloc++;
*offset = bloc;
}
/*
================
idCompressor_Huffman::GetBit
================
*/
int idCompressor_Huffman::GetBit( byte *fin, int *offset) {
int t;
bloc = *offset;
t = (fin[(bloc>>3)] >> (bloc&7)) & 0x1;
bloc++;
*offset = bloc;
return t;
}
/*
================
idCompressor_Huffman::Add_bit
Add a bit to the output file (buffered)
================
*/
void idCompressor_Huffman::Add_bit( char bit, byte *fout ) {
if ( (bloc&7) == 0 ) {
fout[(bloc>>3)] = 0;
}
fout[(bloc>>3)] |= bit << (bloc&7);
bloc++;
}
/*
================
idCompressor_Huffman::Get_bit
Get one bit from the input file (buffered)
================
*/
int idCompressor_Huffman::Get_bit() {
int t;
int wh = bloc >> 3;
int whb = wh>> 16;
if ( whb != blocIn ) {
blocMax += file->Read( seq, sizeof( seq ) );
blocIn++;
}
wh &= 0xffff;
t = ( seq[wh] >> ( bloc & 7 ) ) & 0x1;
bloc++;
return t;
}
/*
================
idCompressor_Huffman::Get_ppnode
================
*/
huffmanNode_t **idCompressor_Huffman::Get_ppnode() {
huffmanNode_t **tppnode;
if ( !freelist ) {
return &nodePtrs[blocPtrs++];
} else {
tppnode = freelist;
freelist = (huffmanNode_t **)*tppnode;
return tppnode;
}
}
/*
================
idCompressor_Huffman::Free_ppnode
================
*/
void idCompressor_Huffman::Free_ppnode( huffmanNode_t **ppnode ) {
*ppnode = (huffmanNode_t *)freelist;
freelist = ppnode;
}
/*
================
idCompressor_Huffman::Swap
Swap the location of the given two nodes in the tree.
================
*/
void idCompressor_Huffman::Swap( huffmanNode_t *node1, huffmanNode_t *node2 ) {
huffmanNode_t *par1, *par2;
par1 = node1->parent;
par2 = node2->parent;
if ( par1 ) {
if ( par1->left == node1 ) {
par1->left = node2;
} else {
par1->right = node2;
}
} else {
tree = node2;
}
if ( par2 ) {
if ( par2->left == node2 ) {
par2->left = node1;
} else {
par2->right = node1;
}
} else {
tree = node1;
}
node1->parent = par2;
node2->parent = par1;
}
/*
================
idCompressor_Huffman::Swaplist
Swap the given two nodes in the linked list (update ranks)
================
*/
void idCompressor_Huffman::Swaplist( huffmanNode_t *node1, huffmanNode_t *node2 ) {
huffmanNode_t *par1;
par1 = node1->next;
node1->next = node2->next;
node2->next = par1;
par1 = node1->prev;
node1->prev = node2->prev;
node2->prev = par1;
if ( node1->next == node1 ) {
node1->next = node2;
}
if ( node2->next == node2 ) {
node2->next = node1;
}
if ( node1->next ) {
node1->next->prev = node1;
}
if ( node2->next ) {
node2->next->prev = node2;
}
if ( node1->prev ) {
node1->prev->next = node1;
}
if ( node2->prev ) {
node2->prev->next = node2;
}
}
/*
================
idCompressor_Huffman::Increment
================
*/
void idCompressor_Huffman::Increment( huffmanNode_t *node ) {
huffmanNode_t *lnode;
if ( !node ) {
return;
}
if ( node->next != NULL && node->next->weight == node->weight ) {
lnode = *node->head;
if ( lnode != node->parent ) {
Swap( lnode, node );
}
Swaplist( lnode, node );
}
if ( node->prev && node->prev->weight == node->weight ) {
*node->head = node->prev;
} else {
*node->head = NULL;
Free_ppnode( node->head );
}
node->weight++;
if ( node->next && node->next->weight == node->weight ) {
node->head = node->next->head;
} else {
node->head = Get_ppnode();
*node->head = node;
}
if ( node->parent ) {
Increment( node->parent );
if ( node->prev == node->parent ) {
Swaplist( node, node->parent );
if ( *node->head == node ) {
*node->head = node->parent;
}
}
}
}
/*
================
idCompressor_Huffman::AddRef
================
*/
void idCompressor_Huffman::AddRef( byte ch ) {
huffmanNode_t *tnode, *tnode2;
if ( loc[ch] == NULL ) { /* if this is the first transmission of this node */
tnode = &nodeList[blocNode++];
tnode2 = &nodeList[blocNode++];
tnode2->symbol = INTERNAL_NODE;
tnode2->weight = 1;
tnode2->next = lhead->next;
if ( lhead->next ) {
lhead->next->prev = tnode2;
if ( lhead->next->weight == 1 ) {
tnode2->head = lhead->next->head;
} else {
tnode2->head = Get_ppnode();
*tnode2->head = tnode2;
}
} else {
tnode2->head = Get_ppnode();
*tnode2->head = tnode2;
}
lhead->next = tnode2;
tnode2->prev = lhead;
tnode->symbol = ch;
tnode->weight = 1;
tnode->next = lhead->next;
if ( lhead->next ) {
lhead->next->prev = tnode;
if ( lhead->next->weight == 1 ) {
tnode->head = lhead->next->head;
} else {
/* this should never happen */
tnode->head = Get_ppnode();
*tnode->head = tnode2;
}
} else {
/* this should never happen */
tnode->head = Get_ppnode();
*tnode->head = tnode;
}
lhead->next = tnode;
tnode->prev = lhead;
tnode->left = tnode->right = NULL;
if ( lhead->parent ) {
if ( lhead->parent->left == lhead ) { /* lhead is guaranteed to by the NYT */
lhead->parent->left = tnode2;
} else {
lhead->parent->right = tnode2;
}
} else {
tree = tnode2;
}
tnode2->right = tnode;
tnode2->left = lhead;
tnode2->parent = lhead->parent;
lhead->parent = tnode->parent = tnode2;
loc[ch] = tnode;
Increment( tnode2->parent );
} else {
Increment( loc[ch] );
}
}
/*
================
idCompressor_Huffman::Receive
Get a symbol.
================
*/
int idCompressor_Huffman::Receive( huffmanNode_t *node, int *ch ) {
while ( node && node->symbol == INTERNAL_NODE ) {
if ( Get_bit() ) {
node = node->right;
} else {
node = node->left;
}
}
if ( !node ) {
return 0;
}
return (*ch = node->symbol);
}
/*
================
idCompressor_Huffman::Send
Send the prefix code for this node.
================
*/
void idCompressor_Huffman::Send( huffmanNode_t *node, huffmanNode_t *child, byte *fout ) {
if ( node->parent ) {
Send( node->parent, node, fout );
}
if ( child ) {
if ( node->right == child ) {
Add_bit( 1, fout );
} else {
Add_bit( 0, fout );
}
}
}
/*
================
idCompressor_Huffman::Transmit
Send a symbol.
================
*/
void idCompressor_Huffman::Transmit( int ch, byte *fout ) {
int i;
if ( loc[ch] == NULL ) {
/* huffmanNode_t hasn't been transmitted, send a NYT, then the symbol */
Transmit( NYT, fout );
for ( i = 7; i >= 0; i-- ) {
Add_bit( (char)((ch >> i) & 0x1), fout );
}
} else {
Send( loc[ch], NULL, fout );
}
}
/*
================
idCompressor_Huffman::Write
================
*/
int idCompressor_Huffman::Write( const void *inData, int inLength ) {
int i, ch;
if ( compress == false || inLength <= 0 ) {
return 0;
}
for ( i = 0; i < inLength; i++ ) {
ch = ((const byte *)inData)[i];
Transmit( ch, seq ); /* Transmit symbol */
AddRef( (byte)ch ); /* Do update */
int b = (bloc>>3);
if ( b > 32768 ) {
file->Write( seq, b );
seq[0] = seq[b];
bloc &= 7;
compressedSize += b;
}
}
unCompressedSize += i;
return i;
}
/*
================
idCompressor_Huffman::FinishCompress
================
*/
void idCompressor_Huffman::FinishCompress() {
if ( compress == false ) {
return;
}
bloc += 7;
int str = (bloc>>3);
if ( str ) {
file->Write( seq, str );
compressedSize += str;
}
}
/*
================
idCompressor_Huffman::Read
================
*/
int idCompressor_Huffman::Read( void *outData, int outLength ) {
int i, j, ch;
if ( compress == true || outLength <= 0 ) {
return 0;
}
if ( bloc == 0 ) {
blocMax = file->Read( seq, sizeof( seq ) );
blocIn = 0;
}
for ( i = 0; i < outLength; i++ ) {
ch = 0;
// don't overflow reading from the file
if ( ( bloc >> 3 ) > blocMax ) {
break;
}
Receive( tree, &ch ); /* Get a character */
if ( ch == NYT ) { /* We got a NYT, get the symbol associated with it */
ch = 0;
for ( j = 0; j < 8; j++ ) {
ch = ( ch << 1 ) + Get_bit();
}
}
((byte *)outData)[i] = ch; /* Write symbol */
AddRef( (byte) ch ); /* Increment node */
}
compressedSize = bloc >> 3;
unCompressedSize += i;
return i;
}
/*
================
idCompressor_Huffman::GetCompressionRatio
================
*/
float idCompressor_Huffman::GetCompressionRatio() const {
return ( unCompressedSize - compressedSize ) * 100.0f / unCompressedSize;
}
/*
=================================================================================
idCompressor_Arithmetic
The following algorithm is based on the Arithmetic Coding methods described
by Mark Nelson. The probability table is implicitly stored.
=================================================================================
*/
const int AC_WORD_LENGTH = 8;
const int AC_NUM_BITS = 16;
const int AC_MSB_SHIFT = 15;
const int AC_MSB2_SHIFT = 14;
const int AC_MSB_MASK = 0x8000;
const int AC_MSB2_MASK = 0x4000;
const int AC_HIGH_INIT = 0xffff;
const int AC_LOW_INIT = 0x0000;
class idCompressor_Arithmetic : public idCompressor_BitStream {
public:
idCompressor_Arithmetic() {}
void Init( idFile *f, bool compress, int wordLength );
void FinishCompress();
int Write( const void *inData, int inLength );
int Read( void *outData, int outLength );
private:
typedef struct acProbs_s {
unsigned int low;
unsigned int high;
} acProbs_t;
typedef struct acSymbol_s {
unsigned int low;
unsigned int high;
int position;
} acSymbol_t;
acProbs_t probabilities[1<<AC_WORD_LENGTH];
int symbolBuffer;
int symbolBit;
unsigned short low;
unsigned short high;
unsigned short code;
unsigned int underflowBits;
unsigned int scale;
private:
void InitProbabilities();
void UpdateProbabilities( acSymbol_t* symbol );
int ProbabilityForCount( unsigned int count );
void CharToSymbol( byte c, acSymbol_t* symbol );
void EncodeSymbol( acSymbol_t* symbol );
int SymbolFromCount( unsigned int count, acSymbol_t* symbol );
int GetCurrentCount();
void RemoveSymbolFromStream( acSymbol_t* symbol );
void PutBit( int bit );
int GetBit();
void WriteOverflowBits();
};
/*
================
idCompressor_Arithmetic::Init
================
*/
void idCompressor_Arithmetic::Init( idFile *f, bool compress, int wordLength ) {
idCompressor_BitStream::Init( f, compress, wordLength );
symbolBuffer = 0;
symbolBit = 0;
}
/*
================
idCompressor_Arithmetic::InitProbabilities
================
*/
void idCompressor_Arithmetic::InitProbabilities() {
high = AC_HIGH_INIT;
low = AC_LOW_INIT;
underflowBits = 0;
code = 0;
for( int i = 0; i < (1<<AC_WORD_LENGTH); i++ ) {
probabilities[ i ].low = i;
probabilities[ i ].high = i + 1;
}
scale = (1<<AC_WORD_LENGTH);
}
/*
================
idCompressor_Arithmetic::UpdateProbabilities
================
*/
void idCompressor_Arithmetic::UpdateProbabilities( acSymbol_t* symbol ) {
int i, x;
x = symbol->position;
probabilities[ x ].high++;
for( i = x + 1; i < (1<<AC_WORD_LENGTH); i++ ) {
probabilities[ i ].low++;
probabilities[ i ].high++;
}
scale++;
}
/*
================
idCompressor_Arithmetic::GetCurrentCount
================
*/
int idCompressor_Arithmetic::GetCurrentCount() {
return (unsigned int) ( ( ( ( (long) code - low ) + 1 ) * scale - 1 ) / ( ( (long) high - low ) + 1 ) );
}
/*
================
idCompressor_Arithmetic::ProbabilityForCount
================
*/
int idCompressor_Arithmetic::ProbabilityForCount( unsigned int count ) {
#if 1
int len, mid, offset, res;
len = (1<<AC_WORD_LENGTH);
mid = len;
offset = 0;
res = 0;
while( mid > 0 ) {
mid = len >> 1;
if ( count >= probabilities[offset+mid].high ) {
offset += mid;
len -= mid;
res = 1;
}
else if ( count < probabilities[offset+mid].low ) {
len -= mid;
res = 0;
} else {
return offset+mid;
}
}
return offset+res;
#else
int j;
for( j = 0; j < (1<<AC_WORD_LENGTH); j++ ) {
if ( count >= probabilities[ j ].low && count < probabilities[ j ].high ) {
return j;
}
}
assert( false );
return 0;
#endif
}
/*
================
idCompressor_Arithmetic::SymbolFromCount
================
*/
int idCompressor_Arithmetic::SymbolFromCount( unsigned int count, acSymbol_t* symbol ) {
int p = ProbabilityForCount( count );
symbol->low = probabilities[ p ].low;
symbol->high = probabilities[ p ].high;
symbol->position = p;
return p;
}
/*
================
idCompressor_Arithmetic::RemoveSymbolFromStream
================
*/
void idCompressor_Arithmetic::RemoveSymbolFromStream( acSymbol_t* symbol ) {
long range;
range = ( long )( high - low ) + 1;
high = low + ( unsigned short )( ( range * symbol->high ) / scale - 1 );
low = low + ( unsigned short )( ( range * symbol->low ) / scale );
while( true ) {
if ( ( high & AC_MSB_MASK ) == ( low & AC_MSB_MASK ) ) {
} else if( ( low & AC_MSB2_MASK ) == AC_MSB2_MASK && ( high & AC_MSB2_MASK ) == 0 ) {
code ^= AC_MSB2_MASK;
low &= AC_MSB2_MASK - 1;
high |= AC_MSB2_MASK;
} else {
UpdateProbabilities( symbol );
return;
}
low <<= 1;
high <<= 1;
high |= 1;
code <<= 1;
code |= ReadBits( 1 );
}
}
/*
================
idCompressor_Arithmetic::GetBit
================
*/
int idCompressor_Arithmetic::GetBit() {
int getbit;
if( symbolBit <= 0 ) {
// read a new symbol out
acSymbol_t symbol;
symbolBuffer = SymbolFromCount( GetCurrentCount(), &symbol );
RemoveSymbolFromStream( &symbol );
symbolBit = AC_WORD_LENGTH;
}
getbit = ( symbolBuffer >> ( AC_WORD_LENGTH - symbolBit ) ) & 1;
symbolBit--;
return getbit;
}
/*
================
idCompressor_Arithmetic::EncodeSymbol
================
*/
void idCompressor_Arithmetic::EncodeSymbol( acSymbol_t* symbol ) {
unsigned int range;
// rescale high and low for the new symbol.
range = ( high - low ) + 1;
high = low + ( unsigned short )(( range * symbol->high ) / scale - 1 );
low = low + ( unsigned short )(( range * symbol->low ) / scale );
while( true ) {
if ( ( high & AC_MSB_MASK ) == ( low & AC_MSB_MASK ) ) {
// the high digits of low and high have converged, and can be written to the stream
WriteBits( high >> AC_MSB_SHIFT, 1 );
while( underflowBits > 0 ) {
WriteBits( ~high >> AC_MSB_SHIFT, 1 );
underflowBits--;
}
} else if ( ( low & AC_MSB2_MASK ) && !( high & AC_MSB2_MASK ) ) {
// underflow is in danger of happening, 2nd digits are converging but 1st digits don't match
underflowBits += 1;
low &= AC_MSB2_MASK - 1;
high |= AC_MSB2_MASK;
} else {
UpdateProbabilities( symbol );
return;
}
low <<= 1;
high <<= 1;
high |= 1;
}
}
/*
================
idCompressor_Arithmetic::CharToSymbol
================
*/
void idCompressor_Arithmetic::CharToSymbol( byte c, acSymbol_t* symbol ) {
symbol->low = probabilities[ c ].low;
symbol->high = probabilities[ c ].high;
symbol->position = c;
}
/*
================
idCompressor_Arithmetic::PutBit
================
*/
void idCompressor_Arithmetic::PutBit( int putbit ) {
symbolBuffer |= ( putbit & 1 ) << symbolBit;
symbolBit++;
if( symbolBit >= AC_WORD_LENGTH ) {
acSymbol_t symbol;
CharToSymbol( symbolBuffer, &symbol );
EncodeSymbol( &symbol );
symbolBit = 0;
symbolBuffer = 0;
}
}
/*
================
idCompressor_Arithmetic::WriteOverflowBits
================
*/
void idCompressor_Arithmetic::WriteOverflowBits() {
WriteBits( low >> AC_MSB2_SHIFT, 1 );
underflowBits++;
while( underflowBits-- > 0 ) {
WriteBits( ~low >> AC_MSB2_SHIFT, 1 );
}
}
/*
================
idCompressor_Arithmetic::Write
================
*/
int idCompressor_Arithmetic::Write( const void *inData, int inLength ) {
int i, j;
if ( compress == false || inLength <= 0 ) {
return 0;
}
InitCompress( inData, inLength );
for( i = 0; i < inLength; i++ ) {
if ( ( readTotalBytes & ( ( 1 << 14 ) - 1 ) ) == 0 ) {
if ( readTotalBytes ) {
WriteOverflowBits();
WriteBits( 0, 15 );
while( writeBit ) {
WriteBits( 0, 1 );
}
WriteBits( 255, 8 );
}
InitProbabilities();
}
for ( j = 0; j < 8; j++ ) {
PutBit( ReadBits( 1 ) );
}
}
return inLength;
}
/*
================
idCompressor_Arithmetic::FinishCompress
================
*/
void idCompressor_Arithmetic::FinishCompress() {
if ( compress == false ) {
return;
}
WriteOverflowBits();
idCompressor_BitStream::FinishCompress();
}
/*
================
idCompressor_Arithmetic::Read
================
*/
int idCompressor_Arithmetic::Read( void *outData, int outLength ) {
int i, j;
if ( compress == true || outLength <= 0 ) {
return 0;
}
InitDecompress( outData, outLength );
for( i = 0; i < outLength && readLength >= 0; i++ ) {
if ( ( writeTotalBytes & ( ( 1 << 14 ) - 1 ) ) == 0 ) {
if ( writeTotalBytes ) {
while( readBit ) {
ReadBits( 1 );
}
while( ReadBits( 8 ) == 0 && readLength > 0 ) {
}
}
InitProbabilities();
for ( j = 0; j < AC_NUM_BITS; j++ ) {
code <<= 1;
code |= ReadBits( 1 );
}
}
for ( j = 0; j < 8; j++ ) {
WriteBits( GetBit(), 1 );
}
}
return i;
}
/*
=================================================================================
idCompressor_LZSS
In 1977 Abraham Lempel and Jacob Ziv presented a dictionary based scheme for
text compression called LZ77. For any new text LZ77 outputs an offset/length
pair to previously seen text and the next new byte after the previously seen
text.
In 1982 James Storer and Thomas Szymanski presented a modification on the work
of Lempel and Ziv called LZSS. LZ77 always outputs an offset/length pair, even
if a match is only one byte long. An offset/length pair usually takes more than
a single byte to store and the compression is not optimal for small match sizes.
LZSS uses a bit flag which tells whether the following data is a literal (byte)
or an offset/length pair.
The following algorithm is an implementation of LZSS with arbitrary word size.
=================================================================================
*/
const int LZSS_BLOCK_SIZE = 65535;
const int LZSS_HASH_BITS = 10;
const int LZSS_HASH_SIZE = ( 1 << LZSS_HASH_BITS );
const int LZSS_HASH_MASK = ( 1 << LZSS_HASH_BITS ) - 1;
const int LZSS_OFFSET_BITS = 11;
const int LZSS_LENGTH_BITS = 5;
class idCompressor_LZSS : public idCompressor_BitStream {
public:
idCompressor_LZSS() {}
void Init( idFile *f, bool compress, int wordLength );
void FinishCompress();
int Write( const void *inData, int inLength );
int Read( void *outData, int outLength );
protected:
int offsetBits;
int lengthBits;
int minMatchWords;
byte block[LZSS_BLOCK_SIZE];
int blockSize;
int blockIndex;
int hashTable[LZSS_HASH_SIZE];
int hashNext[LZSS_BLOCK_SIZE * 8];
protected:
bool FindMatch( int startWord, int startValue, int &wordOffset, int &numWords );
void AddToHash( int index, int hash );
int GetWordFromBlock( int wordOffset ) const;
virtual void CompressBlock();
virtual void DecompressBlock();
};
/*
================
idCompressor_LZSS::Init
================
*/
void idCompressor_LZSS::Init( idFile *f, bool compress, int wordLength ) {
idCompressor_BitStream::Init( f, compress, wordLength );
offsetBits = LZSS_OFFSET_BITS;
lengthBits = LZSS_LENGTH_BITS;
minMatchWords = ( offsetBits + lengthBits + wordLength ) / wordLength;
blockSize = 0;
blockIndex = 0;
}
/*
================
idCompressor_LZSS::FindMatch
================
*/
bool idCompressor_LZSS::FindMatch( int startWord, int startValue, int &wordOffset, int &numWords ) {
int i, n, hash, bottom, maxBits;
wordOffset = startWord;
numWords = minMatchWords - 1;
bottom = Max( 0, startWord - ( ( 1 << offsetBits ) - 1 ) );
maxBits = ( blockSize << 3 ) - startWord * wordLength;
hash = startValue & LZSS_HASH_MASK;
for ( i = hashTable[hash]; i >= bottom; i = hashNext[i] ) {
n = Compare( block, i * wordLength, block, startWord * wordLength, Min( maxBits, ( startWord - i ) * wordLength ) );
if ( n > numWords * wordLength ) {
numWords = n / wordLength;
wordOffset = i;
if ( numWords > ( ( 1 << lengthBits ) - 1 + minMatchWords ) - 1 ) {
numWords = ( ( 1 << lengthBits ) - 1 + minMatchWords ) - 1;
break;
}
}
}
return ( numWords >= minMatchWords );
}
/*
================
idCompressor_LZSS::AddToHash
================
*/
void idCompressor_LZSS::AddToHash( int index, int hash ) {
hashNext[index] = hashTable[hash];
hashTable[hash] = index;
}
/*
================
idCompressor_LZSS::GetWordFromBlock
================
*/
int idCompressor_LZSS::GetWordFromBlock( int wordOffset ) const {
int blockBit, blockByte, value, valueBits, get, fraction;
blockBit = ( wordOffset * wordLength ) & 7;
blockByte = ( wordOffset * wordLength ) >> 3;
if ( blockBit != 0 ) {
blockByte++;
}
value = 0;
valueBits = 0;
while ( valueBits < wordLength ) {
if ( blockBit == 0 ) {
if ( blockByte >= LZSS_BLOCK_SIZE ) {
return value;
}
blockByte++;
}
get = 8 - blockBit;
if ( get > (wordLength - valueBits) ) {
get = (wordLength - valueBits);
}
fraction = block[blockByte - 1];
fraction >>= blockBit;
fraction &= ( 1 << get ) - 1;
value |= fraction << valueBits;
valueBits += get;
blockBit = ( blockBit + get ) & 7;
}
return value;
}
/*
================
idCompressor_LZSS::CompressBlock
================
*/
void idCompressor_LZSS::CompressBlock() {
int i, startWord, startValue, wordOffset, numWords;
InitCompress( block, blockSize );
memset( hashTable, -1, sizeof( hashTable ) );
memset( hashNext, -1, sizeof( hashNext ) );
startWord = 0;
while( readByte < readLength ) {
startValue = ReadBits( wordLength );
if ( FindMatch( startWord, startValue, wordOffset, numWords ) ) {
WriteBits( 1, 1 );
WriteBits( startWord - wordOffset, offsetBits );
WriteBits( numWords - minMatchWords, lengthBits );
UnreadBits( wordLength );
for ( i = 0; i < numWords; i++ ) {
startValue = ReadBits( wordLength );
AddToHash( startWord, startValue & LZSS_HASH_MASK );
startWord++;
}
} else {
WriteBits( 0, 1 );
WriteBits( startValue, wordLength );
AddToHash( startWord, startValue & LZSS_HASH_MASK );
startWord++;
}
}
blockSize = 0;
}
/*
================
idCompressor_LZSS::DecompressBlock
================
*/
void idCompressor_LZSS::DecompressBlock() {
int i, offset, startWord, numWords;
InitDecompress( block, LZSS_BLOCK_SIZE );
startWord = 0;
while( writeByte < writeLength && readLength >= 0 ) {
if ( ReadBits( 1 ) ) {
offset = startWord - ReadBits( offsetBits );
numWords = ReadBits( lengthBits ) + minMatchWords;
for ( i = 0; i < numWords; i++ ) {
WriteBits( GetWordFromBlock( offset + i ), wordLength );
startWord++;
}
} else {
WriteBits( ReadBits( wordLength ), wordLength );
startWord++;
}
}
blockSize = Min( writeByte, LZSS_BLOCK_SIZE );
}
/*
================
idCompressor_LZSS::Write
================
*/
int idCompressor_LZSS::Write( const void *inData, int inLength ) {
int i, n;
if ( compress == false || inLength <= 0 ) {
return 0;
}
for ( n = i = 0; i < inLength; i += n ) {
n = LZSS_BLOCK_SIZE - blockSize;
if ( inLength - i >= n ) {
memcpy( block + blockSize, ((const byte *)inData) + i, n );
blockSize = LZSS_BLOCK_SIZE;
CompressBlock();
blockSize = 0;
} else {
memcpy( block + blockSize, ((const byte *)inData) + i, inLength - i );
n = inLength - i;
blockSize += n;
}
}
return inLength;
}
/*
================
idCompressor_LZSS::FinishCompress
================
*/
void idCompressor_LZSS::FinishCompress() {
if ( compress == false ) {
return;
}
if ( blockSize ) {
CompressBlock();
}
idCompressor_BitStream::FinishCompress();
}
/*
================
idCompressor_LZSS::Read
================
*/
int idCompressor_LZSS::Read( void *outData, int outLength ) {
int i, n;
if ( compress == true || outLength <= 0 ) {
return 0;
}
if ( !blockSize ) {
DecompressBlock();
}
for ( n = i = 0; i < outLength; i += n ) {
if ( !blockSize ) {
return i;
}
n = blockSize - blockIndex;
if ( outLength - i >= n ) {
memcpy( ((byte *)outData) + i, block + blockIndex, n );
DecompressBlock();
blockIndex = 0;
} else {
memcpy( ((byte *)outData) + i, block + blockIndex, outLength - i );
n = outLength - i;
blockIndex += n;
}
}
return outLength;
}
/*
=================================================================================
idCompressor_LZSS_WordAligned
Outputs word aligned compressed data.
=================================================================================
*/
class idCompressor_LZSS_WordAligned : public idCompressor_LZSS {
public:
idCompressor_LZSS_WordAligned() {}
void Init( idFile *f, bool compress, int wordLength );
private:
virtual void CompressBlock();
virtual void DecompressBlock();
};
/*
================
idCompressor_LZSS_WordAligned::Init
================
*/
void idCompressor_LZSS_WordAligned::Init( idFile *f, bool compress, int wordLength ) {
idCompressor_LZSS::Init( f, compress, wordLength );
offsetBits = 2 * wordLength;
lengthBits = wordLength;
minMatchWords = ( offsetBits + lengthBits + wordLength ) / wordLength;
blockSize = 0;
blockIndex = 0;
}
/*
================
idCompressor_LZSS_WordAligned::CompressBlock
================
*/
void idCompressor_LZSS_WordAligned::CompressBlock() {
int i, startWord, startValue, wordOffset, numWords;
InitCompress( block, blockSize );
memset( hashTable, -1, sizeof( hashTable ) );
memset( hashNext, -1, sizeof( hashNext ) );
startWord = 0;
while( readByte < readLength ) {
startValue = ReadBits( wordLength );
if ( FindMatch( startWord, startValue, wordOffset, numWords ) ) {
WriteBits( numWords - ( minMatchWords - 1 ), lengthBits );
WriteBits( startWord - wordOffset, offsetBits );
UnreadBits( wordLength );
for ( i = 0; i < numWords; i++ ) {
startValue = ReadBits( wordLength );
AddToHash( startWord, startValue & LZSS_HASH_MASK );
startWord++;
}
} else {
WriteBits( 0, lengthBits );
WriteBits( startValue, wordLength );
AddToHash( startWord, startValue & LZSS_HASH_MASK );
startWord++;
}
}
blockSize = 0;
}
/*
================
idCompressor_LZSS_WordAligned::DecompressBlock
================
*/
void idCompressor_LZSS_WordAligned::DecompressBlock() {
int i, offset, startWord, numWords;
InitDecompress( block, LZSS_BLOCK_SIZE );
startWord = 0;
while( writeByte < writeLength && readLength >= 0 ) {
numWords = ReadBits( lengthBits );
if ( numWords ) {
numWords += ( minMatchWords - 1 );
offset = startWord - ReadBits( offsetBits );
for ( i = 0; i < numWords; i++ ) {
WriteBits( GetWordFromBlock( offset + i ), wordLength );
startWord++;
}
} else {
WriteBits( ReadBits( wordLength ), wordLength );
startWord++;
}
}
blockSize = Min( writeByte, LZSS_BLOCK_SIZE );
}
/*
=================================================================================
idCompressor_LZW
http://www.unisys.com/about__unisys/lzw
http://www.dogma.net/markn/articles/lzw/lzw.htm
http://www.cs.cf.ac.uk/Dave/Multimedia/node214.html
http://www.cs.duke.edu/csed/curious/compression/lzw.html
http://oldwww.rasip.fer.hr/research/compress/algorithms/fund/lz/lzw.html
This is the same compression scheme used by GIF with the exception that
the EOI and clear codes are not explicitly stored. Instead EOI happens
when the input stream runs dry and CC happens when the table gets to big.
This is a derivation of LZ78, but the dictionary starts with all single
character values so only code words are output. It is similar in theory
to LZ77, but instead of using the previous X bytes as a lookup table, a table
is built as the stream is read. The compressor and decompressor use the
same formula, so the tables should be exactly alike. The only catch is the
decompressor is always one step behind the compressor and may get a code not
yet in the table. In this case, it is easy to determine what the next code
is going to be (it will be the previous string plus the first byte of the
previous string).
The dictionary can be any size, but 12 bits seems to produce best results for
most sample data. The code size is variable. It starts with the minimum
number of bits required to store the dictionary and automatically increases
as the dictionary gets bigger (it starts at 9 bits and grows to 10 bits when
item 512 is added, 11 bits when 1024 is added, etc...) once the the dictionary
is filled (4096 items for a 12 bit dictionary), the whole thing is cleared and
the process starts over again.
The compressor increases the bit size after it adds the item, while the
decompressor does before it adds the item. The difference is subtle, but
it's because decompressor being one step behind. Otherwise, the decompressor
would read 512 with only 9 bits.
If "Hello" is in the dictionary, then "Hell", "Hel", "He" and "H" will be too.
We use this to our advantage by storing the index of the previous code, and
the value of the last character. This means when we traverse through the
dictionary, we get the characters in reverse.
Dictionary entries 0-255 are always going to have the values 0-255
=================================================================================
*/
class idCompressor_LZW : public idCompressor_BitStream {
public:
idCompressor_LZW() {}
void Init( idFile *f, bool compress, int wordLength );
void FinishCompress();
int Write( const void *inData, int inLength );
int Read( void *outData, int outLength );
protected:
int AddToDict( int w, int k );
int Lookup( int w, int k );
bool BumpBits();
int WriteChain( int code );
void DecompressBlock();
static const int LZW_BLOCK_SIZE = 32767;
static const int LZW_START_BITS = 9;
static const int LZW_FIRST_CODE = (1 << (LZW_START_BITS-1));
static const int LZW_DICT_BITS = 12;
static const int LZW_DICT_SIZE = 1 << LZW_DICT_BITS;
// Dictionary data
struct {
int k;
int w;
} dictionary[LZW_DICT_SIZE];
idHashIndex index;
int nextCode;
int codeBits;
// Block data
byte block[LZW_BLOCK_SIZE];
int blockSize;
int blockIndex;
// Used by the compressor
int w;
// Used by the decompressor
int oldCode;
};
/*
================
idCompressor_LZW::Init
================
*/
void idCompressor_LZW::Init( idFile *f, bool compress, int wordLength ) {
idCompressor_BitStream::Init( f, compress, wordLength );
for ( int i=0; i<LZW_FIRST_CODE; i++ ) {
dictionary[i].k = i;
dictionary[i].w = -1;
}
index.Clear();
nextCode = LZW_FIRST_CODE;
codeBits = LZW_START_BITS;
blockSize = 0;
blockIndex = 0;
w = -1;
oldCode = -1;
}
/*
================
idCompressor_LZW::Read
================
*/
int idCompressor_LZW::Read( void *outData, int outLength ) {
int i, n;
if ( compress == true || outLength <= 0 ) {
return 0;
}
if ( !blockSize ) {
DecompressBlock();
}
for ( n = i = 0; i < outLength; i += n ) {
if ( !blockSize ) {
return i;
}
n = blockSize - blockIndex;
if ( outLength - i >= n ) {
memcpy( ((byte *)outData) + i, block + blockIndex, n );
DecompressBlock();
blockIndex = 0;
} else {
memcpy( ((byte *)outData) + i, block + blockIndex, outLength - i );
n = outLength - i;
blockIndex += n;
}
}
return outLength;
}
/*
================
idCompressor_LZW::Lookup
================
*/
int idCompressor_LZW::Lookup( int w, int k ) {
int j;
if ( w == -1 ) {
return k;
} else {
for ( j = index.First( w ^ k ); j >= 0 ; j = index.Next( j ) ) {
if ( dictionary[ j ].k == k && dictionary[ j ].w == w ) {
return j;
}
}
}
return -1;
}
/*
================
idCompressor_LZW::AddToDict
================
*/
int idCompressor_LZW::AddToDict( int w, int k ) {
dictionary[ nextCode ].k = k;
dictionary[ nextCode ].w = w;
index.Add( w ^ k, nextCode );
return nextCode++;
}
/*
================
idCompressor_LZW::BumpBits
Possibly increments codeBits
Returns true if the dictionary was cleared
================
*/
bool idCompressor_LZW::BumpBits() {
if ( nextCode == ( 1 << codeBits ) ) {
codeBits ++;
if ( codeBits > LZW_DICT_BITS ) {
nextCode = LZW_FIRST_CODE;
codeBits = LZW_START_BITS;
index.Clear();
return true;
}
}
return false;
}
/*
================
idCompressor_LZW::FinishCompress
================
*/
void idCompressor_LZW::FinishCompress() {
WriteBits( w, codeBits );
idCompressor_BitStream::FinishCompress();
}
/*
================
idCompressor_LZW::Write
================
*/
int idCompressor_LZW::Write( const void *inData, int inLength ) {
int i;
InitCompress( inData, inLength );
for ( i = 0; i < inLength; i++ ) {
int k = ReadBits( 8 );
int code = Lookup(w, k);
if ( code >= 0 ) {
w = code;
} else {
WriteBits( w, codeBits );
if ( !BumpBits() ) {
AddToDict( w, k );
}
w = k;
}
}
return inLength;
}
/*
================
idCompressor_LZW::WriteChain
The chain is stored backwards, so we have to write it to a buffer then output the buffer in reverse
================
*/
int idCompressor_LZW::WriteChain( int code ) {
byte chain[LZW_DICT_SIZE];
int firstChar = 0;
int i = 0;
do {
assert( i < LZW_DICT_SIZE-1 && code >= 0 );
chain[i++] = dictionary[code].k;
code = dictionary[code].w;
} while ( code >= 0 );
firstChar = chain[--i];
for ( ; i >= 0; i-- ) {
WriteBits( chain[i], 8 );
}
return firstChar;
}
/*
================
idCompressor_LZW::DecompressBlock
================
*/
void idCompressor_LZW::DecompressBlock() {
int code, firstChar;
InitDecompress( block, LZW_BLOCK_SIZE );
while( writeByte < writeLength - LZW_DICT_SIZE && readLength > 0 ) {
assert( codeBits <= LZW_DICT_BITS );
code = ReadBits( codeBits );
if ( readLength == 0 ) {
break;
}
if ( oldCode == -1 ) {
assert( code < 256 );
WriteBits( code, 8 );
oldCode = code;
firstChar = code;
continue;
}
if ( code >= nextCode ) {
assert( code == nextCode );
firstChar = WriteChain( oldCode );
WriteBits( firstChar, 8 );
} else {
firstChar = WriteChain( code );
}
AddToDict( oldCode, firstChar );
if ( BumpBits() ) {
oldCode = -1;
} else {
oldCode = code;
}
}
blockSize = Min( writeByte, LZW_BLOCK_SIZE );
}
/*
=================================================================================
idCompressor
=================================================================================
*/
/*
================
idCompressor::AllocNoCompression
================
*/
idCompressor * idCompressor::AllocNoCompression() {
return new (TAG_IDFILE) idCompressor_None();
}
/*
================
idCompressor::AllocBitStream
================
*/
idCompressor * idCompressor::AllocBitStream() {
return new (TAG_IDFILE) idCompressor_BitStream();
}
/*
================
idCompressor::AllocRunLength
================
*/
idCompressor * idCompressor::AllocRunLength() {
return new (TAG_IDFILE) idCompressor_RunLength();
}
/*
================
idCompressor::AllocRunLength_ZeroBased
================
*/
idCompressor * idCompressor::AllocRunLength_ZeroBased() {
return new (TAG_IDFILE) idCompressor_RunLength_ZeroBased();
}
/*
================
idCompressor::AllocHuffman
================
*/
idCompressor * idCompressor::AllocHuffman() {
return new (TAG_IDFILE) idCompressor_Huffman();
}
/*
================
idCompressor::AllocArithmetic
================
*/
idCompressor * idCompressor::AllocArithmetic() {
return new (TAG_IDFILE) idCompressor_Arithmetic();
}
/*
================
idCompressor::AllocLZSS
================
*/
idCompressor * idCompressor::AllocLZSS() {
return new (TAG_IDFILE) idCompressor_LZSS();
}
/*
================
idCompressor::AllocLZSS_WordAligned
================
*/
idCompressor * idCompressor::AllocLZSS_WordAligned() {
return new (TAG_IDFILE) idCompressor_LZSS_WordAligned();
}
/*
================
idCompressor::AllocLZW
================
*/
idCompressor * idCompressor::AllocLZW() {
return new (TAG_IDFILE) idCompressor_LZW();
}
|
/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include <iostream>
#include <memory>
#include "echo_interpreter.hpp"
#include "xeus/xkernel.hpp"
#include "xeus/xkernel_configuration.hpp"
int main(int argc, char* argv[])
{
std::string file_name = (argc == 1) ? "connection.json" : argv[2];
xeus::xconfiguration config = xeus::load_configuration(file_name);
using interpreter_ptr = std::unique_ptr<echo_kernel::echo_interpreter>;
interpreter_ptr interpreter = interpreter_ptr(new echo_kernel::echo_interpreter());
xeus::xkernel kernel(config, xeus::get_user_name(), std::move(interpreter));
std::cout << "starting kernel" << std::endl;
kernel.start();
return 0;
}
|
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb_python/pyconnection.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include <utility>
#include "arrow_array_stream.hpp"
#include "duckdb.hpp"
#include "duckdb_python/pybind_wrapper.hpp"
namespace duckdb {
struct DuckDBPyRelation;
struct DuckDBPyResult;
class RegisteredObject {
public:
explicit RegisteredObject(py::object obj_p) : obj(move(obj_p)) {
}
virtual ~RegisteredObject() {
obj = py::none();
}
py::object obj;
};
class RegisteredArrow : public RegisteredObject {
public:
RegisteredArrow(unique_ptr<PythonTableArrowArrayStreamFactory> arrow_factory_p, py::object obj_p)
: RegisteredObject(std::move(obj_p)), arrow_factory(move(arrow_factory_p)) {};
unique_ptr<PythonTableArrowArrayStreamFactory> arrow_factory;
};
struct DuckDBPyConnection {
public:
shared_ptr<DuckDB> database;
unique_ptr<Connection> connection;
unordered_map<string, unique_ptr<RegisteredObject>> registered_objects;
unique_ptr<DuckDBPyResult> result;
vector<shared_ptr<DuckDBPyConnection>> cursors;
public:
static void Initialize(py::handle &m);
static void Cleanup();
static DuckDBPyConnection *DefaultConnection();
DuckDBPyConnection *ExecuteMany(const string &query, py::object params = py::list());
DuckDBPyConnection *Execute(const string &query, py::object params = py::list(), bool many = false);
DuckDBPyConnection *Append(const string &name, py::object value);
DuckDBPyConnection *RegisterDF(const string &name, py::object value);
unique_ptr<DuckDBPyRelation> FromQuery(const string &query, const string &alias = "query_relation");
DuckDBPyConnection *RegisterArrow(const string &name, py::object &value, const idx_t rows_per_tuple = 100000);
unique_ptr<DuckDBPyRelation> Table(const string &tname);
unique_ptr<DuckDBPyRelation> Values(py::object params = py::list());
unique_ptr<DuckDBPyRelation> View(const string &vname);
unique_ptr<DuckDBPyRelation> TableFunction(const string &fname, py::object params = py::list());
unique_ptr<DuckDBPyRelation> FromDF(py::object value);
unique_ptr<DuckDBPyRelation> FromCsvAuto(const string &filename);
unique_ptr<DuckDBPyRelation> FromParquet(const string &filename);
unique_ptr<DuckDBPyRelation> FromArrowTable(py::object &table, const idx_t rows_per_tuple = 1000000);
DuckDBPyConnection *UnregisterPythonObject(const string &name);
DuckDBPyConnection *Begin();
DuckDBPyConnection *Commit();
DuckDBPyConnection *Rollback();
py::object GetAttr(const py::str &key);
void Close();
// cursor() is stupid
shared_ptr<DuckDBPyConnection> Cursor();
// these should be functions on the result but well
py::object FetchOne();
py::list FetchAll();
py::dict FetchNumpy();
py::object FetchDF();
py::object FetchDFChunk(const idx_t vectors_per_chunk = 1) const;
py::object FetchArrow();
static shared_ptr<DuckDBPyConnection> Connect(const string &database, bool read_only, const py::dict &config);
static vector<Value> TransformPythonParamList(py::handle params);
private:
//! Default connection to an in-memory database
static shared_ptr<DuckDBPyConnection> default_connection;
};
} // namespace duckdb
|
/**
* Copyright 2021 Scott Brauer
*
* 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 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.
*/
/**
* @file AdminControlAgent.hpp
* @author Scott Brauer
* @date 05-03-2021
*/
#ifndef OFFCENTER_COMMON_FRAMEWORK_ADMIN_ADMINCONTROLAGENT_HPP_
#define OFFCENTER_COMMON_FRAMEWORK_ADMIN_ADMINCONTROLAGENT_HPP_
namespace offcenter {
namespace common {
namespace framework {
namespace admin {
/**
*
*/
class AdminControlAgent
{
public:
AdminControlAgent();
virtual ~AdminControlAgent();
};
} /* namespace admin */
} /* namespace framework */
} /* namespace common */
} /* namespace offcenter */
#endif /* OFFCENTER_COMMON_FRAMEWORK_ADMIN_ADMINCONTROLAGENT_HPP_ */
|
/*******************************************************************************
* Copyright 2016-2018 Intel Corporation
*
* 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 <assert.h>
#include "mkldnn.h"
#include "c_types_map.hpp"
#include "type_helpers.hpp"
#include "utils.hpp"
using namespace mkldnn::impl;
using namespace mkldnn::impl::utils;
using namespace mkldnn::impl::status;
using namespace mkldnn::impl::prop_kind;
using namespace mkldnn::impl::alg_kind;
using namespace mkldnn::impl::types;
namespace {
status_t eltwise_desc_init(eltwise_desc_t *eltwise_desc, prop_kind_t prop_kind,
alg_kind_t alg_kind, const memory_desc_t *data_desc,
const memory_desc_t *diff_data_desc, float alpha, float beta) {
bool args_ok = true
&& !any_null(eltwise_desc, data_desc)
&& one_of(prop_kind, forward_training, forward_inference,
backward_data)
&& one_of(alg_kind, eltwise_relu, eltwise_tanh, eltwise_elu,
eltwise_square, eltwise_abs, eltwise_sqrt, eltwise_linear,
eltwise_bounded_relu, eltwise_soft_relu, eltwise_logistic)
&& IMPLICATION(prop_kind == backward_data, diff_data_desc != nullptr);
if (!args_ok) return invalid_arguments;
auto ed = eltwise_desc_t();
ed.primitive_kind = primitive_kind::eltwise;
ed.prop_kind = prop_kind;
ed.alg_kind = alg_kind;
ed.data_desc = *data_desc;
ed.diff_data_desc =
(ed.prop_kind == backward_data) ? *diff_data_desc : zero_md();
ed.alpha = alpha;
ed.beta = beta;
ed.negative_slope = ed.alpha;
bool consistency = true
&& IMPLICATION(ed.prop_kind == backward_data,
array_cmp(ed.diff_data_desc.dims, ed.data_desc.dims,
ed.diff_data_desc.ndims));
if (!consistency) return invalid_arguments;
*eltwise_desc = ed;
return success;
}
}
status_t mkldnn_eltwise_forward_desc_init(eltwise_desc_t *eltwise_desc,
prop_kind_t prop_kind, alg_kind_t alg_kind,
const memory_desc_t *data_desc, float alpha, float beta) {
if (!one_of(prop_kind, forward_training, forward_inference))
return invalid_arguments;
return eltwise_desc_init(eltwise_desc, prop_kind, alg_kind, data_desc,
nullptr, alpha, beta);
}
status_t mkldnn_eltwise_backward_desc_init(eltwise_desc_t *eltwise_desc,
alg_kind_t alg_kind, const memory_desc_t *diff_data_desc,
const memory_desc_t *data_desc, float alpha, float beta) {
return eltwise_desc_init(eltwise_desc, backward_data, alg_kind, data_desc,
diff_data_desc, alpha, beta);
}
status_t mkldnn_relu_forward_desc_init(eltwise_desc_t *relu_desc,
prop_kind_t prop_kind, const memory_desc_t *data_desc,
float negative_slope) {
return mkldnn_eltwise_forward_desc_init(relu_desc, prop_kind, eltwise_relu,
data_desc, negative_slope, 0.);
}
status_t mkldnn_relu_backward_desc_init(eltwise_desc_t *relu_desc,
const memory_desc_t *diff_data_desc, const memory_desc_t *data_desc,
float negative_slope) {
return mkldnn_eltwise_backward_desc_init(relu_desc, eltwise_relu,
diff_data_desc, data_desc, negative_slope, 0.);
}
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81a.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-81a.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Copy a fixed string into data
* Sinks: snprintf
* GoodSink: snprintf with "%s" as the third argument and data as the fourth
* BadSink : snprintf with data as the third argument
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
namespace CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
const CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81_base& baseObject = CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81_bad();
baseObject.action(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
/* FIX: Use a fixed string that does not contain a format specifier */
strcpy(data, "fixedstringtest");
const CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81_base& baseObject = CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81_goodG2B();
baseObject.action(data);
}
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
const CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81_base& baseObject = CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81_goodB2G();
baseObject.action(data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE134_Uncontrolled_Format_String__char_listen_socket_snprintf_81; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
#pragma GCC optimize("O3")
#pragma GCC target("sse4")
#include <bits/stdc++.h>
using namespace std;
#define deb(x) cout << #x << " is " << x << "\n"
#define int long long
#define mod 1000000007
#define PI acos(-1)
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
template <typename T>
using max_heap = priority_queue<T>;
template <typename... T>
void read(T &... args) {
((cin >> args), ...);
}
template <typename... T>
void write(T &&... args) {
((cout << args), ...);
}
template <typename T>
void readContainer(T &t) {
for (auto &e : t) read(e);
}
template <typename T>
void writeContainer(T &t) {
for (const auto &e : t) write(e, " ");
write("\n");
}
void solve(int tc) {
string s;
read(s);
for (const auto &ch : s) {
if (ch == '1')
write('9');
else
write('1');
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int tc = 1;
// read(tc);
for (int curr = 1; curr <= tc; curr++) solve(curr);
return 0;
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include "engine/physics/physics.hpp"
#include "engine/window_context_handler.hpp"
struct Renderer
{
PhysicSolver& solver;
sf::VertexArray va;
explicit
Renderer(PhysicSolver& s)
: solver(s)
, va(sf::Lines)
{}
void updateVA()
{
const uint32_t links_count = to<uint32_t>(solver.constraints.size());
va.resize(2 * links_count);
for (uint32_t i(0); i<links_count; ++i) {
LinkConstraint& current_link = solver.constraints.data[i];
va[2 * i ].position = current_link.particle_1->position;
va[2 * i + 1].position = current_link.particle_2->position;
}
}
void render(RenderContext& context)
{
updateVA();
context.draw(va);
}
};
|
/*
Delete Node in a Linked List
============================
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.
It is guaranteed that the node to be deleted is not a tail node in the list.
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Example 3:
Input: head = [1,2,3,4], node = 3
Output: [1,2,4]
Example 4:
Input: head = [0,1], node = 0
Output: [1]
Example 5:
Input: head = [-3,5,-99], node = -3
Output: [5,-99]
Constraints:
The number of the nodes in the given list is in the range [2, 1000].
-1000 <= Node.val <= 1000
The value of each node in the list is unique.
The node to be deleted is in the list and is not a tail node
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
void deleteNode(ListNode *node)
{
node->val = node->next->val;
node->next = node->next->next;
}
};
|
// Copyright (C) 2020-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include <seal/seal.h>
#include <iostream>
#include <random>
#include <vector>
#include "gflags/gflags.h"
#include "include/data_loader.hpp"
#include "include/logger.hpp"
#include "include/lr_helper.hpp"
#include "include/lrhe.hpp"
#include "include/timer.hpp"
DEFINE_string(
data, "lrtest_mid",
"Dataset name to test. Files should have preset name conventions. "
"Refer to the datasets folder for more information.");
DEFINE_bool(compare, false,
"Compare the HE logistic regression inference results with "
"non-HE results.");
DEFINE_int32(poly_modulus_degree, 8192,
"Set polynomial modulus for CKKS context. Determines the batch "
"size and security level, thus recommended size is 4096-16384. "
"Must be a power of 2, with the range of [1024, 32768]");
DEFINE_bool(data_plain, false, "Run with the data as plaintext.");
DEFINE_bool(model_plain, false, "Run with the model as plaintext.");
DEFINE_bool(linear_regression, false,
"Calculate linear regression instead of logistic regression.");
DEFINE_int32(security_level, 0, "Security level. One of [0, 128, 192, 256].");
DEFINE_string(coeff_modulus, "60,45,45,45,45,60",
"Coefficient modulus (list of primes). The bit-lengths of the "
"primes to be generated.");
DEFINE_int32(batch_size, 0,
"Batch size. 0 = automatic (poly_modulus_degree / 2). Max = "
"poly_modulus_degree / 2.");
DEFINE_int32(scale, 45, "Scaling parameter defining precision.");
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
std::string fn_dataset(FLAGS_data);
if (FLAGS_poly_modulus_degree < 1024 || FLAGS_poly_modulus_degree > 32768 ||
(FLAGS_poly_modulus_degree & (FLAGS_poly_modulus_degree - 1)) != 0)
throw std::invalid_argument(
"poly_modulus_degree must be power of 2 and within [1024, 32768] "
"range.");
if (FLAGS_batch_size < 0 || FLAGS_batch_size > FLAGS_poly_modulus_degree / 2)
throw std::invalid_argument(
"batch_size must be between 0 and poly_modulus_degree / 2.");
seal::sec_level_type sec_level;
switch (FLAGS_security_level) {
case 0:
sec_level = seal::sec_level_type::none;
break;
case 128:
sec_level = seal::sec_level_type::tc128;
break;
case 192:
sec_level = seal::sec_level_type::tc192;
break;
case 256:
sec_level = seal::sec_level_type::tc256;
break;
default:
LOG<Info>("ERROR: Security level must be one of [0, 128, 192, 256].");
return EXIT_FAILURE;
}
std::vector<int> coeff_modulus;
std::stringstream ss(FLAGS_coeff_modulus);
for (int i; ss >> i;) {
coeff_modulus.push_back(i);
if (ss.peek() == ',') ss.ignore();
}
kernel::LRHEKernel kernel(FLAGS_poly_modulus_degree, coeff_modulus,
1UL << FLAGS_scale, true, true, sec_level);
if (FLAGS_data_plain && FLAGS_model_plain) {
LOG<Info>("ERROR: Either model or data (or both) must be encrypted.");
return EXIT_FAILURE;
}
std::unique_ptr<lrhe::LRHE> lrhe;
if (FLAGS_linear_regression)
lrhe = std::make_unique<lrhe::LinearRegressionHE>(
kernel, !FLAGS_data_plain, !FLAGS_model_plain, FLAGS_batch_size);
else
lrhe = std::make_unique<lrhe::LogisticRegressionHE>(
kernel, !FLAGS_data_plain, !FLAGS_model_plain, FLAGS_batch_size);
// load eval data for inference
LOG<Info>("Loading EVAL dataset");
auto t_started = intel::timer::now();
std::vector<std::vector<double>> rawdata_eval =
dataLoader(fn_dataset, DataMode::EVAL);
std::vector<std::vector<double>> evalData;
std::vector<double> evalTarget;
// Split data and target from rawdata
splitData(rawdata_eval, evalData, evalTarget);
size_t n_inputs = evalData.size();
size_t n_weights = evalData[0].size();
LOG<Info>("Loading EVAL dataset complete",
"Elapsed(s):", intel::timer::delta(t_started));
LOG<Info>("Input data size:", "(samples)", n_inputs, " (features)",
n_weights);
// load pretrained weights and bias
LOG<Info>("Loading Model");
t_started = intel::timer::now();
std::vector<double> pretrained_weightsbias = weightsLoaderCSV(fn_dataset);
std::vector<double> pretrained_weights;
double pretrained_bias;
// split bias and weights from pretrained model
splitWeights(pretrained_weightsbias, pretrained_weights, pretrained_bias);
LOG<Info>("Loading Model complete",
"Elapsed(s):", intel::timer::delta(t_started));
lrhe->load_weight(pretrained_weights, pretrained_bias);
// perform inference with test data
auto lrhe_evalout = lrhe->inference(evalData);
// evaluate result and get accuracy and f1 score
auto eval = lrhelper::get_evalmetrics(evalTarget, lrhe_evalout);
LOG<Info>("HE inference result - accuracy: ", eval["acc"]);
if (FLAGS_compare) { // If compare==true, compare with non-HE inference
// result
// Get cleartext inference results
auto lrcleartext_evalout =
lrhelper::test(evalData, pretrained_weights, pretrained_bias,
!FLAGS_linear_regression, FLAGS_linear_regression);
// Count mismatch
int mismatch_ct = 0;
for (size_t j = 0; j < n_inputs; ++j) {
if (lrhe_evalout[j] != lrcleartext_evalout[j]) {
mismatch_ct++;
}
}
if (mismatch_ct > 0) {
LOG<Info>("Mismatch count with cleartext LR:", mismatch_ct, "/",
n_inputs);
} else {
LOG<Info>("All match!");
}
}
return 0;
}
|
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const double EPS = 1e-9;
const int INF = 0x7f7f7f7f;
const double PI=acos(-1.0);
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define MP(x, y) make_pair(x, y)
#define PB(x) push_back(x)
#define rep(i,n) for(int i = 1 ; i<=(n) ; i++)
#define repI(i,n) for(int i = 0 ; i<(n) ; i++)
#define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++)
#define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--)
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define ALL(p) p.begin(),p.end()
#define ALLR(p) p.rbegin(),p.rend()
#define SET(p) memset(p, -1, sizeof(p))
#define CLR(p) memset(p, 0, sizeof(p))
#define MEM(p, v) memset(p, v, sizeof(p))
#define getI(a) scanf("%d", &a)
#define getII(a,b) scanf("%d%d", &a, &b)
#define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c)
#define getL(a) scanf("%lld",&a)
#define getLL(a,b) scanf("%lld%lld",&a,&b)
#define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c)
#define getC(n) scanf("%c",&n)
#define getF(n) scanf("%lf",&n)
#define getS(n) scanf("%s",n)
#define bitCheck(N,in) ((bool)(N&(1<<(in))))
#define bitOff(N,in) (N&(~(1<<(in))))
#define bitOn(N,in) (N|(1<<(in)))
#define bitFlip(a,k) (a^(1<<(k)))
#define bitCount(a) __builtin_popcount(a)
#define bitCountLL(a) __builtin_popcountll(a)
#define bitLeftMost(a) (63-__builtin_clzll((a)))
#define bitRightMost(a) (__builtin_ctzll(a))
#define iseq(a,b) (fabs(a-b)<EPS)
#define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end())
#define vi vector < int >
#define vii vector < vector < int > >
#define pii pair< int, int >
#define ff first
#define ss second
#define ll long long
#define ull unsigned long long
#define POPCOUNT __builtin_popcount
#define POPCOUNTLL __builtin_popcountll
#define RIGHTMOST __builtin_ctzll
#define LEFTMOST(x) (63-__builtin_clzll((x)))
template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); }
template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); }
#define dipta00
#ifdef dipta007
#define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;}
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define debug(args...) /// Just strip off all debug tokens
#define trace(...) ///yeeeee
#endif
struct debugger{
template<typename T> debugger& operator , (const T& v){
cerr<<v<<" ";
return *this;
}
}dbg;
///****************** template ends here ****************
// g++ -g -O2 -std=gnu++11 A.cpp
// ./a.out
int main() {
#ifdef dipta007
//READ("in.txt");
//WRITE("out.txt");
#endif // dipta007
ios_base::sync_with_stdio(0);cin.tie(0);
unsigned ll k, d, t;
while( cin >> k >> d >> t )
{
ll td = d;
if(k > d)
{
ll kk = k/d;
d = (kk+1)*d;
}
ll on = k; /// 1st k minz on
ll off = d - k ; /// baki asher age off
ll mod = d; /// period
ll ranna = on * 2LL + off; /// ranna joto tuku hoise
ll totRanna = 2LL * t; /// total ranna er poriman
ll kk = totRanna / ranna;
long double ans = kk * mod; /// ja ranna hoer hoise
// trace(on, off, mod, ranna, totRanna, kk, ans);
ll baki = totRanna % ranna; /// baki ki thake
kk = min(baki/2, on);
baki -= kk*2LL;
ans += kk;
if(kk < on && baki)
{
ans += 0.5;
}
else if(baki)
{
ans += baki;
}
cout << setprecision(10) << fixed << ans << endl;
}
return 0;
}
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "shared_test_classes/single_layer/lstm_cell.hpp"
namespace LayerTestsDefinitions {
TEST_P(LSTMCellTest, CompareWithRefs) {
Run();
};
} // namespace LayerTestsDefinitions
|
//
// basic_deadline_timer.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_BASIC_DEADLINE_TIMER_HPP
#define BOOST_ASIO_BASIC_DEADLINE_TIMER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \
|| defined(GENERATING_DOCUMENTATION)
#include <cstddef>
#include <boost/asio/basic_io_object.hpp>
#include <boost/asio/detail/handler_type_requirements.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/time_traits.hpp>
#if defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
# include <boost/asio/deadline_timer_service.hpp>
#else // defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
# include <boost/asio/detail/deadline_timer_service.hpp>
# define BOOST_ASIO_SVC_T detail::deadline_timer_service<TimeTraits>
#endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
/// Provides waitable timer functionality.
/**
* The basic_deadline_timer class template provides the ability to perform a
* blocking or asynchronous wait for a timer to expire.
*
* A deadline timer is always in one of two states: "expired" or "not expired".
* If the wait() or async_wait() function is called on an expired timer, the
* wait operation will complete immediately.
*
* Most applications will use the boost::asio::deadline_timer typedef.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Unsafe.
*
* @par Examples
* Performing a blocking wait:
* @code
* // Construct a timer without setting an expiry time.
* boost::asio::deadline_timer timer(io_context);
*
* // Set an expiry time relative to now.
* timer.expires_from_now(boost::posix_time::seconds(5));
*
* // Wait for the timer to expire.
* timer.wait();
* @endcode
*
* @par
* Performing an asynchronous wait:
* @code
* void handler(const boost::system::error_code& error)
* {
* if (!error)
* {
* // Timer expired.
* }
* }
*
* ...
*
* // Construct a timer with an absolute expiry time.
* boost::asio::deadline_timer timer(io_context,
* boost::posix_time::time_from_string("2005-12-07 23:59:59.000"));
*
* // Start an asynchronous wait.
* timer.async_wait(handler);
* @endcode
*
* @par Changing an active deadline_timer's expiry time
*
* Changing the expiry time of a timer while there are pending asynchronous
* waits causes those wait operations to be cancelled. To ensure that the action
* associated with the timer is performed only once, use something like this:
* used:
*
* @code
* void on_some_event()
* {
* if (my_timer.expires_from_now(seconds(5)) > 0)
* {
* // We managed to cancel the timer. Start new asynchronous wait.
* my_timer.async_wait(on_timeout);
* }
* else
* {
* // Too late, timer has already expired!
* }
* }
*
* void on_timeout(const boost::system::error_code& e)
* {
* if (e != boost::asio::error::operation_aborted)
* {
* // Timer was not cancelled, take necessary action.
* }
* }
* @endcode
*
* @li The boost::asio::basic_deadline_timer::expires_from_now() function
* cancels any pending asynchronous waits, and returns the number of
* asynchronous waits that were cancelled. If it returns 0 then you were too
* late and the wait handler has already been executed, or will soon be
* executed. If it returns 1 then the wait handler was successfully cancelled.
*
* @li If a wait handler is cancelled, the boost::system::error_code passed to
* it contains the value boost::asio::error::operation_aborted.
*/
template <typename Time,
typename TimeTraits = boost::asio::time_traits<Time>
BOOST_ASIO_SVC_TPARAM_DEF2(= deadline_timer_service<Time, TimeTraits>)>
class basic_deadline_timer
: BOOST_ASIO_SVC_ACCESS basic_io_object<BOOST_ASIO_SVC_T>
{
public:
/// The type of the executor associated with the object.
typedef io_context::executor_type executor_type;
/// The time traits type.
typedef TimeTraits traits_type;
/// The time type.
typedef typename traits_type::time_type time_type;
/// The duration type.
typedef typename traits_type::duration_type duration_type;
/// Constructor.
/**
* This constructor creates a timer without setting an expiry time. The
* expires_at() or expires_from_now() functions must be called to set an
* expiry time before the timer can be waited on.
*
* @param io_context The io_context object that the timer will use to dispatch
* handlers for any asynchronous operations performed on the timer.
*/
explicit basic_deadline_timer(boost::asio::io_context& io_context)
: basic_io_object<BOOST_ASIO_SVC_T>(io_context)
{
}
/// Constructor to set a particular expiry time as an absolute time.
/**
* This constructor creates a timer and sets the expiry time.
*
* @param io_context The io_context object that the timer will use to dispatch
* handlers for any asynchronous operations performed on the timer.
*
* @param expiry_time The expiry time to be used for the timer, expressed
* as an absolute time.
*/
basic_deadline_timer(boost::asio::io_context& io_context,
const time_type& expiry_time)
: basic_io_object<BOOST_ASIO_SVC_T>(io_context)
{
boost::system::error_code ec;
this->get_service().expires_at(this->get_implementation(), expiry_time, ec);
boost::asio::detail::throw_error(ec, "expires_at");
}
/// Constructor to set a particular expiry time relative to now.
/**
* This constructor creates a timer and sets the expiry time.
*
* @param io_context The io_context object that the timer will use to dispatch
* handlers for any asynchronous operations performed on the timer.
*
* @param expiry_time The expiry time to be used for the timer, relative to
* now.
*/
basic_deadline_timer(boost::asio::io_context& io_context,
const duration_type& expiry_time)
: basic_io_object<BOOST_ASIO_SVC_T>(io_context)
{
boost::system::error_code ec;
this->get_service().expires_from_now(
this->get_implementation(), expiry_time, ec);
boost::asio::detail::throw_error(ec, "expires_from_now");
}
#if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move-construct a basic_deadline_timer from another.
/**
* This constructor moves a timer from one object to another.
*
* @param other The other basic_deadline_timer object from which the move will
* occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_deadline_timer(io_context&) constructor.
*/
basic_deadline_timer(basic_deadline_timer&& other)
: basic_io_object<BOOST_ASIO_SVC_T>(std::move(other))
{
}
/// Move-assign a basic_deadline_timer from another.
/**
* This assignment operator moves a timer from one object to another. Cancels
* any outstanding asynchronous operations associated with the target object.
*
* @param other The other basic_deadline_timer object from which the move will
* occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_deadline_timer(io_context&) constructor.
*/
basic_deadline_timer& operator=(basic_deadline_timer&& other)
{
basic_io_object<BOOST_ASIO_SVC_T>::operator=(std::move(other));
return *this;
}
#endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Destroys the timer.
/**
* This function destroys the timer, cancelling any outstanding asynchronous
* wait operations associated with the timer as if by calling @c cancel.
*/
~basic_deadline_timer()
{
}
#if defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
// These functions are provided by basic_io_object<>.
#else // defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
#if !defined(BOOST_ASIO_NO_DEPRECATED)
/// (Deprecated: Use get_executor().) Get the io_context associated with the
/// object.
/**
* This function may be used to obtain the io_context object that the I/O
* object uses to dispatch handlers for asynchronous operations.
*
* @return A reference to the io_context object that the I/O object will use
* to dispatch handlers. Ownership is not transferred to the caller.
*/
boost::asio::io_context& get_io_context()
{
return basic_io_object<BOOST_ASIO_SVC_T>::get_io_context();
}
/// (Deprecated: Use get_executor().) Get the io_context associated with the
/// object.
/**
* This function may be used to obtain the io_context object that the I/O
* object uses to dispatch handlers for asynchronous operations.
*
* @return A reference to the io_context object that the I/O object will use
* to dispatch handlers. Ownership is not transferred to the caller.
*/
boost::asio::io_context& get_io_service()
{
return basic_io_object<BOOST_ASIO_SVC_T>::get_io_service();
}
#endif // !defined(BOOST_ASIO_NO_DEPRECATED)
/// Get the executor associated with the object.
executor_type get_executor() BOOST_ASIO_NOEXCEPT
{
return basic_io_object<BOOST_ASIO_SVC_T>::get_executor();
}
#endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
/// Cancel any asynchronous operations that are waiting on the timer.
/**
* This function forces the completion of any pending asynchronous wait
* operations against the timer. The handler for each cancelled operation will
* be invoked with the boost::asio::error::operation_aborted error code.
*
* Cancelling the timer does not change the expiry time.
*
* @return The number of asynchronous operations that were cancelled.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note If the timer has already expired when cancel() is called, then the
* handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t cancel()
{
boost::system::error_code ec;
std::size_t s = this->get_service().cancel(this->get_implementation(), ec);
boost::asio::detail::throw_error(ec, "cancel");
return s;
}
/// Cancel any asynchronous operations that are waiting on the timer.
/**
* This function forces the completion of any pending asynchronous wait
* operations against the timer. The handler for each cancelled operation will
* be invoked with the boost::asio::error::operation_aborted error code.
*
* Cancelling the timer does not change the expiry time.
*
* @param ec Set to indicate what error occurred, if any.
*
* @return The number of asynchronous operations that were cancelled.
*
* @note If the timer has already expired when cancel() is called, then the
* handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t cancel(boost::system::error_code& ec)
{
return this->get_service().cancel(this->get_implementation(), ec);
}
/// Cancels one asynchronous operation that is waiting on the timer.
/**
* This function forces the completion of one pending asynchronous wait
* operation against the timer. Handlers are cancelled in FIFO order. The
* handler for the cancelled operation will be invoked with the
* boost::asio::error::operation_aborted error code.
*
* Cancelling the timer does not change the expiry time.
*
* @return The number of asynchronous operations that were cancelled. That is,
* either 0 or 1.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note If the timer has already expired when cancel_one() is called, then
* the handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t cancel_one()
{
boost::system::error_code ec;
std::size_t s = this->get_service().cancel_one(
this->get_implementation(), ec);
boost::asio::detail::throw_error(ec, "cancel_one");
return s;
}
/// Cancels one asynchronous operation that is waiting on the timer.
/**
* This function forces the completion of one pending asynchronous wait
* operation against the timer. Handlers are cancelled in FIFO order. The
* handler for the cancelled operation will be invoked with the
* boost::asio::error::operation_aborted error code.
*
* Cancelling the timer does not change the expiry time.
*
* @param ec Set to indicate what error occurred, if any.
*
* @return The number of asynchronous operations that were cancelled. That is,
* either 0 or 1.
*
* @note If the timer has already expired when cancel_one() is called, then
* the handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t cancel_one(boost::system::error_code& ec)
{
return this->get_service().cancel_one(this->get_implementation(), ec);
}
/// Get the timer's expiry time as an absolute time.
/**
* This function may be used to obtain the timer's current expiry time.
* Whether the timer has expired or not does not affect this value.
*/
time_type expires_at() const
{
return this->get_service().expires_at(this->get_implementation());
}
/// Set the timer's expiry time as an absolute time.
/**
* This function sets the expiry time. Any pending asynchronous wait
* operations will be cancelled. The handler for each cancelled operation will
* be invoked with the boost::asio::error::operation_aborted error code.
*
* @param expiry_time The expiry time to be used for the timer.
*
* @return The number of asynchronous operations that were cancelled.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note If the timer has already expired when expires_at() is called, then
* the handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t expires_at(const time_type& expiry_time)
{
boost::system::error_code ec;
std::size_t s = this->get_service().expires_at(
this->get_implementation(), expiry_time, ec);
boost::asio::detail::throw_error(ec, "expires_at");
return s;
}
/// Set the timer's expiry time as an absolute time.
/**
* This function sets the expiry time. Any pending asynchronous wait
* operations will be cancelled. The handler for each cancelled operation will
* be invoked with the boost::asio::error::operation_aborted error code.
*
* @param expiry_time The expiry time to be used for the timer.
*
* @param ec Set to indicate what error occurred, if any.
*
* @return The number of asynchronous operations that were cancelled.
*
* @note If the timer has already expired when expires_at() is called, then
* the handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t expires_at(const time_type& expiry_time,
boost::system::error_code& ec)
{
return this->get_service().expires_at(
this->get_implementation(), expiry_time, ec);
}
/// Get the timer's expiry time relative to now.
/**
* This function may be used to obtain the timer's current expiry time.
* Whether the timer has expired or not does not affect this value.
*/
duration_type expires_from_now() const
{
return this->get_service().expires_from_now(this->get_implementation());
}
/// Set the timer's expiry time relative to now.
/**
* This function sets the expiry time. Any pending asynchronous wait
* operations will be cancelled. The handler for each cancelled operation will
* be invoked with the boost::asio::error::operation_aborted error code.
*
* @param expiry_time The expiry time to be used for the timer.
*
* @return The number of asynchronous operations that were cancelled.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note If the timer has already expired when expires_from_now() is called,
* then the handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t expires_from_now(const duration_type& expiry_time)
{
boost::system::error_code ec;
std::size_t s = this->get_service().expires_from_now(
this->get_implementation(), expiry_time, ec);
boost::asio::detail::throw_error(ec, "expires_from_now");
return s;
}
/// Set the timer's expiry time relative to now.
/**
* This function sets the expiry time. Any pending asynchronous wait
* operations will be cancelled. The handler for each cancelled operation will
* be invoked with the boost::asio::error::operation_aborted error code.
*
* @param expiry_time The expiry time to be used for the timer.
*
* @param ec Set to indicate what error occurred, if any.
*
* @return The number of asynchronous operations that were cancelled.
*
* @note If the timer has already expired when expires_from_now() is called,
* then the handlers for asynchronous wait operations will:
*
* @li have already been invoked; or
*
* @li have been queued for invocation in the near future.
*
* These handlers can no longer be cancelled, and therefore are passed an
* error code that indicates the successful completion of the wait operation.
*/
std::size_t expires_from_now(const duration_type& expiry_time,
boost::system::error_code& ec)
{
return this->get_service().expires_from_now(
this->get_implementation(), expiry_time, ec);
}
/// Perform a blocking wait on the timer.
/**
* This function is used to wait for the timer to expire. This function
* blocks and does not return until the timer has expired.
*
* @throws boost::system::system_error Thrown on failure.
*/
void wait()
{
boost::system::error_code ec;
this->get_service().wait(this->get_implementation(), ec);
boost::asio::detail::throw_error(ec, "wait");
}
/// Perform a blocking wait on the timer.
/**
* This function is used to wait for the timer to expire. This function
* blocks and does not return until the timer has expired.
*
* @param ec Set to indicate what error occurred, if any.
*/
void wait(boost::system::error_code& ec)
{
this->get_service().wait(this->get_implementation(), ec);
}
/// Start an asynchronous wait on the timer.
/**
* This function may be used to initiate an asynchronous wait against the
* timer. It always returns immediately.
*
* For each call to async_wait(), the supplied handler will be called exactly
* once. The handler will be called when:
*
* @li The timer has expired.
*
* @li The timer was cancelled, in which case the handler is passed the error
* code boost::asio::error::operation_aborted.
*
* @param handler The handler to be called when the timer expires. Copies
* will be made of the handler as required. The function signature of the
* handler must be:
* @code void handler(
* const boost::system::error_code& error // Result of operation.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. Invocation
* of the handler will be performed in a manner equivalent to using
* boost::asio::io_context::post().
*/
template <typename WaitHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(WaitHandler,
void (boost::system::error_code))
async_wait(BOOST_ASIO_MOVE_ARG(WaitHandler) handler)
{
// If you get an error on the following line it means that your handler does
// not meet the documented type requirements for a WaitHandler.
BOOST_ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check;
#if defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
return this->get_service().async_wait(this->get_implementation(),
BOOST_ASIO_MOVE_CAST(WaitHandler)(handler));
#else // defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
async_completion<WaitHandler,
void (boost::system::error_code)> init(handler);
this->get_service().async_wait(this->get_implementation(),
init.completion_handler);
return init.result.get();
#endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
}
};
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#if !defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
# undef BOOST_ASIO_SVC_T
#endif // !defined(BOOST_ASIO_ENABLE_OLD_SERVICES)
#endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME)
// || defined(GENERATING_DOCUMENTATION)
#endif // BOOST_ASIO_BASIC_DEADLINE_TIMER_HPP
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.