text:
#ifndef ASYNC_STATE_HPP
#define ASYNC_STATE_HPP

#include "bind_allocator.hpp"

#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/async_result.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/executor_work_guard.hpp>
#include <boost/scope_exit.hpp>
#include <memory>

namespace async_utils {
namespace asio = boost::asio;

template <typename CompletionHandlerSignature, typename CompletionToken, typename Executor, typename StateData>
class async_state;

// Container of the state data associated with asychronous operations.
// It holds the final operation completion handler, an executor to be used as a default if the final completion handler
// doesn't have any associated with it and any other state data used by the implementation of the asychronous operation.
// The memory used to hold the state is managed using the allocator associated with the completion handler.
template <typename CompletionHandlerSignature, typename CompletionToken, typename Executor, typename StateData>
class async_state {

    struct state_holder;

  public:
    // Completion type.
    using completion_type = asio::async_completion<CompletionToken, CompletionHandlerSignature>;
    // Completion handler type generated from CompletionHandlerSignature.
    using completion_handler_type = typename completion_type::completion_handler_type;
    // Default allocator if none associated with the completion handler.
    using default_allocator = std::allocator<void>;
    // The allocator associated with the completion handler.
    using completion_handler_allocator_type = asio::associated_allocator_t<completion_handler_type, default_allocator>;

    // Constructor.
    //
    // It creates a state object from a completion handler, default executor and arguments to construct the state data.
    template <class... Args>
    explicit async_state(completion_handler_type &&completion_handler, Executor const &executor, Args &&... args)
        : m_state{async_state::make_state(std::move(completion_handler), executor, std::forward<Args>(args)...)} {}

    async_state(async_state const &) = delete;
    async_state(async_state &&) noexcept = default;
    async_state &operator=(async_state const &) = delete;
    async_state &operator=(async_state &&) noexcept = default;
    ~async_state() = default;

    // Checks if there is any state set.
    bool has_data() const noexcept { return m_state != nullptr; }

    // Returns a pointer to the owned state data.
    StateData *get_data() const {
        BOOST_ASSERT(m_state);
        return m_state.get();
    }

    // Object returned by wrap() that allows adapting a (lambda) function object to be a proper completion handler.
    // This object insures that state object can be safely moved when building the lambda intermediary completion
    // handler.
    class wrapper {
      public:
        explicit wrapper(state_holder *state) : m_state{state} {}
        template <typename F> decltype(auto) operator()(F &&f) const {
            // The final completion handler should not have been called yet.
            BOOST_ASSERT(m_state);
            BOOST_ASSERT(m_state->io_work.owns_work());
            auto allocator = asio::get_associated_allocator(m_state->completion_handler, default_allocator{});
            auto executor = asio::get_associated_executor(m_state->completion_handler, m_state->executor);
            return asio::bind_executor(executor, bind_allocator(std::move(allocator), std::forward<F>(f)));
        }

      private:
        state_holder *m_state;
    };

    // Returns an object referring this state object that can be used to wrap intermediary (lambda) completion handlers.
    // After calling this method, the state object can be safely moved when building a lambda intermediary completion
    // handler.
    wrapper wrap() { return wrapper{m_state.get()}; }

    // Invokes the final completion handler with the given arguments.
    // This should be called at most once.
    // The state and associated state data is deallocated before calling the handler.
    template <class... Args> void invoke(Args &&... args) {
        BOOST_ASSERT(m_state);
        auto completion_handler = std::move(m_state->completion_handler);
        m_state.reset();
        std::invoke(completion_handler, std::forward<Args>(args)...);
    }

  private:
    struct state_holder_base {
        state_holder_base(completion_handler_type &&completion_handler, Executor const &executor)
            : completion_handler(std::move(completion_handler)),
              executor(executor), io_work{asio::make_work_guard(executor)} {}

        completion_handler_type completion_handler;
        Executor executor;
        asio::executor_work_guard<Executor> io_work;
    };

    struct state_holder : public state_holder_base, public StateData {
        template <class... Args>
        state_holder(completion_handler_type &&completion_handler, Executor const &executor, Args &&... args)
            : state_holder_base(std::move(completion_handler), executor), StateData(std::forward<Args>(args)...) {}
    };

    using state_allocator_type =
        typename std::allocator_traits<completion_handler_allocator_type>::template rebind_alloc<state_holder>;
    using state_allocator_traits = std::allocator_traits<state_allocator_type>;

    struct state_deleter {
        explicit state_deleter(state_allocator_type const &a) : m_allocator(a) {}
        using pointer = typename state_allocator_traits::pointer;
        void operator()(pointer p) const {
            state_allocator_type a(m_allocator);
            state_allocator_traits::destroy(a, std::addressof(*p));
            state_allocator_traits::deallocate(a, p, 1);
        }

      private:
        state_allocator_type m_allocator;
    };
    using state_holder_ptr = std::unique_ptr<state_holder, state_deleter>;

    template <class... Args>
    static state_holder_ptr make_state(completion_handler_type &&completion_handler, Executor const &executor,
                                       Args &&... args);

    state_holder_ptr m_state;
};

template <typename CompletionHandlerSignature, typename CompletionToken, typename Executor, typename StateData>
template <class... Args>
auto async_state<CompletionHandlerSignature, CompletionToken, Executor, StateData>::make_state(
    completion_handler_type &&completion_handler, Executor const &executor, Args &&... args) -> state_holder_ptr {

    static_assert(!std::is_array<StateData>::value);
    state_allocator_type state_allocator{asio::get_associated_allocator(completion_handler, default_allocator{})};
    auto p = state_allocator_traits::allocate(state_allocator, 1);
    bool commit = false;
    BOOST_SCOPE_EXIT_ALL(&) {
        if (!commit) {
            state_allocator_traits::deallocate(state_allocator, p, 1);
            p = nullptr;
        }
    };
    state_allocator_traits::construct(state_allocator, std::addressof(*p), std::move(completion_handler), executor,
                                      std::forward<Args>(args)...);
    BOOST_SCOPE_EXIT_ALL(&) {
        if (!commit) {
            state_allocator_traits::destroy(state_allocator, std::addressof(*p));
        }
    };

    state_holder_ptr state{p, state_deleter(state_allocator)};
    commit = true;
    return state;
}

} // namespace async_utils

#endif

max_stars_repo_name: sorf/cpp-playground

max_issues_repo_name: sorf/cpp-playground

max_forks_repo_name: sorf/cpp-playground


text:
//
//   Copyright 2014 QuarksLab
//
//   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 "binmap/log.hpp"
#include "binmap/collectors/pe/decoder.hpp"

#include <fstream>
#include <boost/filesystem.hpp>

class PECollector : public Collector {
  std::ifstream _stream;
  PEDecoder* _pe;
  boost::filesystem::path _path;
public:
  PECollector();
  ~PECollector();
  bool initialize(boost::filesystem::path const &input_file);
  void operator()(std::set<boost::filesystem::path> &deps);
  void operator()(MetadataInfo &mi);
};

PECollector::PECollector() : _pe(0) {
}

bool PECollector::initialize(boost::filesystem::path const &path) {
    if (boost::filesystem::is_symlink(path))
      return false;
    _path = path;
    _stream.open(path.string().c_str(), std::ios_base::binary);
    PeDosHeader dos;
    if(!_stream.read(reinterpret_cast<char*>(&dos), sizeof(dos)) || !dos.is_valid())
      return false;

    _stream.seekg(0);
    if(!(_pe = PeDecoderFactory(_stream, true)))
      return false;
    if(! _pe->is_compatible())
        return false;
    return true;
}

PECollector::~PECollector() {
  if(_pe) delete _pe;
}

void PECollector::operator()(std::set<boost::filesystem::path> &deps) {
  _pe->get_imports(_path, deps);
}

void PECollector::operator()(MetadataInfo &mi) {
		// collect exported functions
	std::vector<std::string> exports;
	std::vector<std::string> imported_symbols;
	std::vector<std::string> imported_symbols2;
	logging::log(logging::info) << "Symbols of : " << _path << std::endl;
	_pe->get_exports(_path, exports);

	_pe->get_imported_symbols(_path, imported_symbols);

	_pe->get_delay_imports(_path, imported_symbols2);

	mi.add_imported_symbols(imported_symbols.begin(), imported_symbols.end());
	mi.add_imported_symbols(imported_symbols2.begin(), imported_symbols2.end());
	mi.add_exported_symbols(exports.begin(), exports.end());

	//collect hardening features
	_pe->extract_hardening_features(mi);
}

// static collector
static Collector::Register registry(&make_collector<PECollector>);

ext: cpp


text:
#include "InputFileOperator.h"
#include "CommandLineHandlers/SingleCommandLineHandler.h"
#include "NumberOperator.h"
#include <boost/algorithm/string/trim.hpp>

USING_NAMESPACE(std);
USING_NAMESPACE(clu);

class ConsolidateAverage : public NumberOperator
{
public:
	ConsolidateAverage(int window_size) : m_size(window_size), m_data(0.0), m_count(0)
	{
	}

	virtual bool OnNumberRead(double number)
	{
		m_data = m_data + number;
		if (m_count == m_size) {
			m_OutputHandler->OutputDouble(m_data / m_count);
			m_count = 0;
			m_data = 0;
		}
		else {
			m_count++;
		}
		return true;
	}

	virtual void OnEnd()
	{
		m_data = 0.0;
		m_count = 0;
	}

protected:
	double m_data;
	int m_size;
	int m_count;
};

REGISTER_SINGLE_INTEGER("consolidate", ConsolidateAverage)->SetHelp("Consolidate - Average Out of groups of numbers");

max_stars_repo_name: ShaiRoitman/clu

max_issues_repo_name: ShaiRoitman/clu

max_forks_repo_name: ShaiRoitman/clu


text:
/* vim: set tabstop=4 : */
#pragma once

#include <terark/stdtypes.hpp>
#include <terark/valvec.hpp>
#include <boost/noncopyable.hpp>

namespace terark { namespace cow_mman {

static const size_t AlignSize = 4;
enum ConcurrentLevel : char {
    NoWriteReadOnly,     // 0
    SingleThreadStrict,  // 1
    SingleThreadShared,  // 2, iterator with token will keep valid
    OneWriteMultiRead,   // 3
    MultiWriteMultiRead, // 4
};
enum TokenUpdatePolicy {
    UpdateNow,  // 0
    UpdateLazy, // 1
};
class TERARK_DLL_EXPORT TokenList;

struct TERARK_DLL_EXPORT TokenLink : private boost::noncopyable {
    TokenLink*    m_prev;
    TokenLink*    m_next;
    uint64_t      m_age;
};
class TERARK_DLL_EXPORT TokenBase : protected TokenLink {
    friend class cow_mman;
protected:
    class CowMemPool* m_main;
    class TokenList* m_sub;
    void*          m_value;
public:
    virtual ~TokenBase();
    virtual bool update(TokenUpdatePolicy) = 0;
    inline  bool update_lazy() { return update(UpdateLazy); }
    inline  bool update_now() { return update(UpdateNow); }
    class TokenList* sub()  const { return m_sub; }
    class CowMemPool* main() const { return m_main; }
    const void* value() const { return m_value; }
    template<class T>
    T value_of() const {
    //  assert(sizeof(T) == sub()->get_valsize());
        assert(NULL != m_value);
        assert(size_t(m_value) % AlignSize == 0);
        if (sizeof(T) == AlignSize)
            return   aligned_load<T>(m_value);
        else
            return unaligned_load<T>(m_value);
    }
    template<class T>
    T& mutable_value_of() const {
    //  assert(sizeof(T) == sub()->get_valsize());
        assert(NULL != m_value);
        assert(size_t(m_value) % AlignSize == 0);
        return *reinterpret_cast<T*>(m_value);
    }
};
class TERARK_DLL_EXPORT ReaderToken : public TokenBase {
protected:
    void update_list(ConcurrentLevel, class TokenList*);
public:
    ReaderToken();
    explicit ReaderToken(TokenList* sub);
    virtual ~ReaderToken();
    void attach(TokenList* sub);
    void detach();
    bool update(TokenUpdatePolicy) override;
};
class TERARK_DLL_EXPORT WriterToken : public TokenBase {
    friend class CowMemPool;
    void update_list(TokenList* sub);
protected:
    virtual bool init_value(void* valptr, size_t valsize);
public:
    explicit WriterToken(TokenList* sub);
    virtual ~WriterToken();
    bool update(TokenUpdatePolicy) override;
};
struct MemStat {
    valvec<size_t> fastbin;
    size_t used_size;
    size_t capacity;
    size_t frag_size; // = fast + huge
    size_t huge_size;
    size_t huge_cnt;
};

}} // namespace terark::cow_mmap

ext: hpp

max_stars_repo_name: rockeet/terark-zip

max_issues_repo_name: rockeet/terark-zip

max_forks_repo_name: rockeet/terark-zip


text:
#include <boost/bind.hpp>

#include "ipc.hpp"
#include "../../utility/common.hpp"
#include "../../utility/easylogging++.h"
#include "../../utility/folly/ScopeGuard.h"

#include "utility/ipc/io_service/gen/combined_headers"

#include "http_session.hpp"

using myio::StreamServer;
using myipc::GenericIpcChannel;

namespace msgs = myipc::ioservice::messages;
using msgs::type;

using std::shared_ptr;

#define _LOG_PREFIX(inst) << "ipcserv= " << (inst)->objId() << ": "

/* "inst" stands for instance, as in, instance of a class */
#define vloginst(level, inst) VLOG(level) _LOG_PREFIX(inst)
#define vlogself(level) vloginst(level, this)

#define dvloginst(level, inst) DVLOG(level) _LOG_PREFIX(inst)
#define dvlogself(level) dvloginst(level, this)

#define loginst(level, inst) LOG(level) _LOG_PREFIX(inst)
#define logself(level) loginst(level, this)

/* send the msg at the END OF CURRENT SCOPE */
#define BEGIN_BUILD_MSG_AND_SEND_AT_END(TYPE, bufbuilder, ipc_ch)       \
    auto const __type = msgs::type_ ## TYPE;                            \
    VLOG(2) << "begin building msg type: " << msgs::EnumNametype(__type); \
    msgs::TYPE ## MsgBuilder msgbuilder(bufbuilder);                    \
    SCOPE_EXIT {                                                        \
        auto msg = msgbuilder.Finish();                                 \
        bufbuilder.Finish(msg);                                         \
        VLOG(2) << "send msg";                                          \
        ipc_ch->sendMsg(                                                \
            __type, bufbuilder.GetSize(),                               \
            bufbuilder.GetBufferPointer());                             \
    }

IPCServer::IPCServer(struct event_base* evbase,
                     StreamServer::UniquePtr streamserver,
                     const NetConfig* netconf)
    : evbase_(evbase)
    , stream_server_(std::move(streamserver))
    , netconf_(netconf)
{
    stream_server_->set_observer(this);
    vlogself(2) << "tell stream server to start accepting";
    stream_server_->start_accepting();
}

void
IPCServer::send_ReceivedResponse(const int& routing_id,
                                 const int& req_id,
                                 const uint64_t& first_byte_time_ms)
{
    vlogself(2) << "begin, req_id: " << req_id
                << " first_byte_time_ms: " << first_byte_time_ms;

    CHECK(inMap(client_ipc_channels_, routing_id));
    auto ipc_ch = client_ipc_channels_[routing_id].get();
    CHECK_NOTNULL(ipc_ch);
    {
        flatbuffers::FlatBufferBuilder bufbuilder;
        BEGIN_BUILD_MSG_AND_SEND_AT_END(ReceivedResponse, bufbuilder, ipc_ch);

        msgbuilder.add_req_id(req_id);
        msgbuilder.add_first_byte_time_ms(first_byte_time_ms);
    }

    vlogself(2) << "done";
}

void
IPCServer::send_DataReceived(const int& routing_id,
                             const int& req_id,
                             const int& len)
{
    vlogself(2) << "begin, req_id: " << req_id
                << " len: " << len;

    CHECK(inMap(client_ipc_channels_, routing_id));
    auto ipc_ch = client_ipc_channels_[routing_id].get();
    CHECK_NOTNULL(ipc_ch);
    {
        flatbuffers::FlatBufferBuilder bufbuilder;
        BEGIN_BUILD_MSG_AND_SEND_AT_END(DataReceived, bufbuilder, ipc_ch);

        msgbuilder.add_req_id(req_id);
        msgbuilder.add_length(len);
    }

    vlogself(2) << "done";
}

void
IPCServer::send_RequestComplete(const int& routing_id,
                                const int& req_id,
                                const bool& success)
{
    vlogself(2) << "begin, req_id: " << req_id
                << " success: " << success;

    CHECK(inMap(client_ipc_channels_, routing_id));
    auto ipc_ch = client_ipc_channels_[routing_id].get();
    CHECK_NOTNULL(ipc_ch);
    {
        flatbuffers::FlatBufferBuilder bufbuilder;
        BEGIN_BUILD_MSG_AND_SEND_AT_END(RequestComplete, bufbuilder, ipc_ch);

        msgbuilder.add_req_id(req_id);
        msgbuilder.add_success(success);
    }

    vlogself(2) << "done";
}

void
IPCServer::_handle_RequestResource(const int& routing_id,
                                   const msgs::RequestResourceMsg* msg)
{
    hsessions_[routing_id]->handle_RequestResource(
        msg->req_id(), msg->webkit_resInstNum(),
        msg->host()->c_str(), msg->port(),
        msg->req_total_size(), msg->resp_meta_size(), msg->resp_body_size());
}

void
IPCServer::_handle_ResetSession(const int& routing_id,
                                const msgs::ResetSessionMsg*)
{
    hsessions_[routing_id]->handle_ResetSession();
}

void
IPCServer::onAccepted(StreamServer*, StreamChannel::UniquePtr channel) noexcept
{
    _setup_client(std::move(channel));
}

void
IPCServer::_setup_client(StreamChannel::UniquePtr channel)
{
    vlogself(2) << "ipc server got new client";

    GenericIpcChannel::UniquePtr ch(
        new GenericIpcChannel(
            evbase_,
            std::move(channel),
            boost::bind(&IPCServer::_on_msg_recv, this, _1, _2, _3, _4),
            boost::bind(&IPCServer::_on_called, this, _1, _2, _3, _4, _5),
            boost::bind(&IPCServer::_on_channel_status, this, _1, _2)));

    // use the id of the generic msg channel, not the stream channel,
    // as the routing id
    const auto routing_id = ch->objId();

    auto ret = client_ipc_channels_.insert(make_pair(routing_id, std::move(ch)));
    CHECK(ret.second); // insist it was newly inserted

    // for now each client will get its own session
    shared_ptr<HttpNetworkSession> hsess(
        new HttpNetworkSession(evbase_, this, routing_id, netconf_),
        [](HttpNetworkSession* s) { s->destroy(); });
    DCHECK_NOTNULL(hsess.get());

    auto ret2 = hsessions_.insert(make_pair(routing_id, hsess));
    CHECK(ret2.second); // insist it was newly inserted
}

#define IPC_MSG_HANDLER(TYPE)                                           \
    case msgs::type_ ## TYPE: {                                         \
        _handle_ ## TYPE(routing_id, msgs::Get ## TYPE ## Msg(buf));   \
    }                                                                   \
    break;

void
IPCServer::_on_msg_recv(GenericIpcChannel* channel, uint8_t type,
                        uint16_t len, const uint8_t* buf)
{
    const auto routing_id = channel->objId();

    vlogself(2) << "recv'ed msg type= " << msgs::EnumNametype((msgs::type)type)
                << ", len= " << len << ", from channel= " << routing_id;

    switch (type) {

        IPC_MSG_HANDLER(RequestResource)
        IPC_MSG_HANDLER(ResetSession)

    default:
        logself(FATAL) << "invalid IPC message type " << type;
        break;
    }

}

void
IPCServer::_on_called(GenericIpcChannel*, uint32_t id, uint8_t type,
                        uint16_t len, const uint8_t* buf)
{
    logself(FATAL) << "to do";
}

void
IPCServer::_on_channel_status(GenericIpcChannel* ch,
                              GenericIpcChannel::ChannelStatus status)
{
    const auto routing_id = ch->objId();
    vlogself(2) << "ipc client stream " << ch << " closed";
    _remove_route(routing_id);
}

void
IPCServer::_remove_route(const uint32_t& routing_id)
{
    client_ipc_channels_.erase(routing_id);
    hsessions_.erase(routing_id);
}

void
IPCServer::onAcceptError(StreamServer*, int errorcode) noexcept
{
    logself(WARNING) << "IPC server has accept error: " << strerror(errorcode);
}

max_stars_repo_name: cauthu/shadow-browser-plugin

max_issues_repo_name: cauthu/shadow-browser-plugin

max_forks_repo_name: cauthu/shadow-browser-plugin


text:
#include <array>
#include "vc_shell.h"
#include <string>
#include <iostream>
#include <vector>
#include <cstdio>
#include <array>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <sstream>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string.hpp>

#define SSTR( x ) static_cast< std::ostringstream & >( \
        ( std::ostringstream() << std::dec << x ) ).str()

VC_Shell::VC_Shell(){

}
VC_Shell::VC_Shell(std::string executable){
    currentExecutable = executable;
    command_extras ="XX";
}
void VC_Shell::spawn_client_request(std::string result){
    bool extra =false;
     std::cout<<"[*] before if stmt test "<<result<<"\n";
     result= boost::replace_all_copy(result, "\n", "");
    if(split(std::string(result),1).at(2)!="XX"){
        std::cout<<"[*] in if stmt test "<<result<<"\n";
        setCommandExtras(split(result,1).at(2));
        std::cout<<"[*] before if stmt test {"<<getCommandExtras()<<"}\n";
        extra = true;
    }
    else{
        setCommandExtras("");
    }
    std::cout<<"[*] in stmt test "<<result<<"\n";
    int value = atoi(split(result,1).at(0).c_str());
    std::string clientRequestCommand = getClientRequestCommand(value);
    std::cout<<"[*] request command {"<<clientRequestCommand<<"}\n";
    std::array<char, 128> buffer;
    std::string cl_result="";
    std::shared_ptr<FILE> pipe(popen(clientRequestCommand.c_str(), "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer.data(), 128, pipe.get()) != NULL){
            while(fgets(buffer.data(), 128, pipe.get()) != NULL){
              cl_result += buffer.data();
            }
        }
        cl_result= boost::replace_all_copy(cl_result, "\"", "");
        std::string command ="mosquitto_pub -h 192.168.0.80 -t vc_shell_gatekeeper_request_hook -m \"{"+cl_result+"}\"";
        remote_pub_shell(command);
        cl_result="";

    }
}
void VC_Shell::client_request_hook(std::string command){
        std::cout<<"[*] in subscriber client_request_hook remote listening on: "<<command<<"\n";
        std::array<char, 128> buffer;
        std::string result="";
        std::shared_ptr<FILE> pipe(popen(command.c_str(), "r"), pclose);
        if (!pipe) throw std::runtime_error("popen() failed!");
        while (!feof(pipe.get())) {
            if (fgets(buffer.data(), 128, pipe.get()) != NULL){
                    result += buffer.data();

            }
            std::cout<<result;
            result="";
        }
        system("killall mosquitto_sub");
        exit(0);
}
void VC_Shell::remote_master_sub_shell(std::string command){
        std::cout<<"[*] in subscriber remote listening on: "<<command<<"\n";
        std::array<char, 128> buffer;
        std::string result="";
        std::shared_ptr<FILE> pipe(popen(command.c_str(), "r"), pclose);
        if (!pipe) throw std::runtime_error("popen() failed!");
        while (!feof(pipe.get())) {
            if (fgets(buffer.data(), 128, pipe.get()) != NULL){
                    result += buffer.data();
                 std::cout<<result;
            }
        }
        system("killall mosquitto_sub");
        exit(0);
}
void VC_Shell::remote_sub_shell(std::string command){
        setRun(true);
        std::cout<<"[*] in subscriber remote listening on: "<<command<<std::endl;;
        std::array<char, 128> buffer;
        std::string result="";
        std::shared_ptr<FILE> pipe(popen(command.c_str(), "r"), pclose);
        if (!pipe) throw std::runtime_error("popen() failed!");
        while (!feof(pipe.get()) && getRun() ==true) {
            std::cout<<"[*] waiting for incoming messages\n";
            if (fgets(buffer.data(), 128, pipe.get()) != NULL){
                    result = buffer.data();
                if(result =="EXIT\n"){
                    setRun(false);
                    // just in case
                    break;
                }
                else{
                   std::cout<<"[*] incoming message "<<result<<"\n";
                   spawn_client_request(result);
                }
            }

        }
        system("killall mosquitto_sub");
        exit(0);
}
void VC_Shell::remote_master_shell(int ip_locator,bool isPup,int command_index, std::string extras){
    bool isExit =false;
    std::string current_ip ="";

    switch (ip_locator){
        case 1: current_ip = "192.168.0.150"; break;
        case 2: current_ip = "192.168.0.144"; break;
        case 3: current_ip = "192.168.0.129"; break;
        case 4: current_ip = "192.168.0.124"; break;
        case 5: current_ip = "192.168.0.80";  break;
    }
    if(isPup== true){
       std::string command ="";
       if(extras !=""){
         if(extras =="EXIT"){
            isExit =true;
         }
         setCommandExtras(extras);
       }
       if(isExit ==false){
         command="mosquitto_pub -h "+current_ip+ " -t vc_shell -m "+SSTR( command_index)+"::"+getCommandExtras();
       }
       else{
          command="mosquitto_pub -h "+current_ip+ " -t vc_shell -m "+getCommandExtras();
       }
       remote_pub_shell(command);
    }
    else{
        std::string command = "mosquitto_sub -h localhost -t vc_shell";
         remote_sub_shell(command);
    }
}
void VC_Shell::remote_pub_shell(std::string command){
        std::cout<<command<<"\n";
        std::string mqtt_pub_command = command;
        std::array<char, 128> buffer;
        std::string result="";
        std::shared_ptr<FILE> pipe(popen(mqtt_pub_command.c_str(), "r"), pclose);
        if (!pipe) throw std::runtime_error("popen() failed!");
        while (!feof(pipe.get())) {
            if (fgets(buffer.data(), 128, pipe.get()) != NULL){
                result += buffer.data();
                std::cout<<result<<"\n";
            }
        }
}


text:
// (c) Facebook, Inc. and its affiliates. Confidential and proprietary.

#include "fboss/lib/CommonFileUtils.h"
#include <boost/filesystem/operations.hpp>
#include "fboss/agent/SysError.h"

#include <fcntl.h>

namespace facebook::fboss {

bool removeFile(const std::string& filename) {
  int rv = unlink(filename.c_str());
  if (rv == 0) {
    // The file existed and we successfully removed it.
    return true;
  }
  if (errno == ENOENT) {
    // The file wasn't present.
    return false;
  }
  // Some other unexpected error.
  throw SysError(errno, "error while trying to remove file: ", filename);
}

int createFile(const std::string& filename) {
  mode_t mode = S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP;
  auto fd = open(filename.c_str(), O_RDWR | O_CREAT, mode);
  if (fd < 0) {
    // Some other unexpected error.
    throw SysError(errno, "error while trying to create file ", filename);
  }
  return fd;
}

void createDir(folly::StringPiece path) {
  try {
    boost::filesystem::create_directories(path.str());
  } catch (...) {
    throw SysError(errno, "failed to create directory \"", path, "\"");
  }
}
} // namespace facebook::fboss

max_stars_repo_name: nathanawmk/fboss

max_issues_repo_name: nathanawmk/fboss

max_forks_repo_name: nathanawmk/fboss


text:
/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright 2019 ScyllaDB
 */

#define __user /* empty */  // for xfs includes, below

#include <sys/syscall.h>
#include <dirent.h>
#include <linux/types.h> // for xfs, below
#include <sys/ioctl.h>
#include <xfs/linux.h>
#define min min    /* prevent xfs.h from defining min() as a macro */
#include <xfs/xfs.h>
#undef min
#include <boost/range/numeric.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <seastar/core/reactor.hh>
#include <seastar/core/file.hh>
#include <seastar/core/report_exception.hh>
#include <seastar/core/linux-aio.hh>
#include "core/file-impl.hh"
#include "core/syscall_result.hh"
#include "core/thread_pool.hh"
#include "core/uname.hh"

namespace seastar {

static_assert(std::is_nothrow_copy_constructible_v<io_priority_class>);
static_assert(std::is_nothrow_move_constructible_v<io_priority_class>);

using namespace internal;
using namespace internal::linux_abi;

file_handle::file_handle(const file_handle& x)
        : _impl(x._impl ? x._impl->clone() : std::unique_ptr<file_handle_impl>()) {
}

file_handle::file_handle(file_handle&& x) noexcept = default;

file_handle&
file_handle::operator=(const file_handle& x) {
    return operator=(file_handle(x));
}

file_handle&
file_handle::operator=(file_handle&&) noexcept = default;

file
file_handle::to_file() const & {
    return file_handle(*this).to_file();
}

file
file_handle::to_file() && {
    return file(std::move(*_impl).to_file());
}

posix_file_impl::posix_file_impl(int fd, open_flags f, file_open_options options, dev_t device_id)
        : _device_id(device_id)
        , _io_queue(&(engine().get_io_queue(_device_id)))
        , _open_flags(f)
        , _fd(fd)
{
    query_dma_alignment();
}

posix_file_impl::~posix_file_impl() {
    if (_refcount && _refcount->fetch_add(-1, std::memory_order_relaxed) != 1) {
        return;
    }
    delete _refcount;
    if (_fd != -1) {
        // Note: close() can be a blocking operation on NFS
        ::close(_fd);
    }
}

void
posix_file_impl::query_dma_alignment() {
    dioattr da;
    auto r = ioctl(_fd, XFS_IOC_DIOINFO, &da);
    if (r == 0) {
        _memory_dma_alignment = da.d_mem;
        _disk_read_dma_alignment = da.d_miniosz;
        // xfs wants at least the block size for writes
        // FIXME: really read the block size
        _disk_write_dma_alignment = std::max<unsigned>(da.d_miniosz, 4096);
    }
}

std::unique_ptr<seastar::file_handle_impl>
posix_file_impl::dup() {
    if (!_refcount) {
        _refcount = new std::atomic<unsigned>(1u);
    }
    auto ret = std::make_unique<posix_file_handle_impl>(_fd, _open_flags, _refcount, _device_id);
    _refcount->fetch_add(1, std::memory_order_relaxed);
    return ret;
}

posix_file_impl::posix_file_impl(int fd, open_flags f, std::atomic<unsigned>* refcount, dev_t device_id)
        : _refcount(refcount)
        , _device_id(device_id)
        , _io_queue(&(engine().get_io_queue(_device_id)))
        , _open_flags(f)
        , _fd(fd) {
}

future<>
posix_file_impl::flush(void) noexcept {
    if ((_open_flags & open_flags::dsync) != open_flags{}) {
        return make_ready_future<>();
    }
    return engine().fdatasync(_fd);
}

future<struct stat>
posix_file_impl::stat() noexcept {
    return engine().fstat(_fd);
}

future<>
posix_file_impl::truncate(uint64_t length) noexcept {
    return engine()._thread_pool->submit<syscall_result<int>>([this, length] {
        return wrap_syscall<int>(::ftruncate(_fd, length));
    }).then([] (syscall_result<int> sr) {
        sr.throw_if_error();
        return make_ready_future<>();
    });
}

future<>
posix_file_impl::discard(uint64_t offset, uint64_t length) noexcept {
    return engine()._thread_pool->submit<syscall_result<int>>([this, offset, length] () mutable {
        return wrap_syscall<int>(::fallocate(_fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE,
            offset, length));
    }).then([] (syscall_result<int> sr) {
        sr.throw_if_error();
        return make_ready_future<>();
    });
}

future<>
posix_file_impl::allocate(uint64_t position, uint64_t length) noexcept {
#ifdef FALLOC_FL_ZERO_RANGE
    // FALLOC_FL_ZERO_RANGE is fairly new, so don't fail if it's not supported.
    static bool supported = true;
    if (!supported) {
        return make_ready_future<>();
    }
    return engine()._thread_pool->submit<syscall_result<int>>([this, position, length] () mutable {
        auto ret = ::fallocate(_fd, FALLOC_FL_ZERO_RANGE|FALLOC_FL_KEEP_SIZE, position, length);
        if (ret == -1 && errno == EOPNOTSUPP) {
            ret = 0;
            supported = false; // Racy, but harmless.  At most we issue an extra call or two.
        }
        return wrap_syscall<int>(ret);
    }).then([] (syscall_result<int> sr) {
        sr.throw_if_error();
        return make_ready_future<>();
    });
#else
    return make_ready_future<>();
#endif
}

future<uint64_t>
posix_file_impl::size() noexcept {
    auto r = ::lseek(_fd, 0, SEEK_END);
    if (r == -1) {
        return make_exception_future<uint64_t>(std::system_error(errno, std::system_category()));
    }
    return make_ready_future<uint64_t>(r);
}

future<>
posix_file_impl::close() noexcept {
    if (_fd == -1) {
        seastar_logger.warn("double close() detected, contact support");
        return make_ready_future<>();
    }
    auto fd = _fd;
    _fd = -1;  // Prevent a concurrent close (which is illegal) from closing another file's fd
    if (_refcount && _refcount->fetch_add(-1, std::memory_order_relaxed) != 1) {
        _refcount = nullptr;
        return make_ready_future<>();
    }
    delete _refcount;
    _refcount = nullptr;
    auto closed = [fd] () noexcept {
        try {
            return engine()._thread_pool->submit<syscall_result<int>>([fd] {
                return wrap_syscall<int>(::close(fd));
            });
        } catch (...) {
            report_exception("Running ::close() in reactor thread, submission failed with exception", std::current_exception());
            return make_ready_future<syscall_result<int>>(wrap_syscall<int>(::close(fd)));
        }
    }();
    return closed.then([] (syscall_result<int> sr) {
        sr.throw_if_error();
    });
}

future<uint64_t>
blockdev_file_impl::size(void) noexcept {
    return engine()._thread_pool->submit<syscall_result_extra<size_t>>([this] {
        uint64_t size;
        int ret = ::ioctl(_fd, BLKGETSIZE64, &size);
        return wrap_syscall(ret, size);
    }).then([] (syscall_result_extra<uint64_t> ret) {
        ret.throw_if_error();
        return make_ready_future<uint64_t>(ret.extra);
    });
}

subscription<directory_entry>
posix_file_impl::list_directory(std::function<future<> (directory_entry de)> next) {
    static constexpr size_t buffer_size = 8192;
    struct work {
        stream<directory_entry> s;
        unsigned current = 0;
        unsigned total = 0;
        bool eof = false;
        int error = 0;
        char buffer[buffer_size];
    };

    // While it would be natural to use fdopendir()/readdir(),
    // our syscall thread pool doesn't support malloc(), which is
    // required for this to work.  So resort to using getdents()
    // instead.

    // From getdents(2):
    struct linux_dirent64 {
        ino64_t        d_ino;    /* 64-bit inode number */
        off64_t        d_off;    /* 64-bit offset to next structure */
        unsigned short d_reclen; /* Size of this dirent */
        unsigned char  d_type;   /* File type */
        char           d_name[]; /* Filename (null-terminated) */
    };

    auto w = make_lw_shared<work>();
    auto ret = w->s.listen(std::move(next));
    // List the directory asynchronously in the background.
    // Caller synchronizes using the returned subscription.
    (void)w->s.started().then([w, this] {
        auto eofcond = [w] { return w->eof; };
        return do_until(eofcond, [w, this] {
            if (w->current == w->total) {
                return engine()._thread_pool->submit<syscall_result<long>>([w , this] () {
                    auto ret = ::syscall(__NR_getdents64, _fd, reinterpret_cast<linux_dirent64*>(w->buffer), buffer_size);
                    return wrap_syscall(ret);
                }).then([w] (syscall_result<long> ret) {
                    ret.throw_if_error();
                    if (ret.result == 0) {
                        w->eof = true;
                    } else {
                        w->current = 0;
                        w->total = ret.result;
                    }
                });
            }
            auto start = w->buffer + w->current;
            auto de = reinterpret_cast<linux_dirent64*>(start);
            std::optional<directory_entry_type> type;
            switch (de->d_type) {
            case DT_BLK:
                type = directory_entry_type::block_device;
                break;
            case DT_CHR:
                type = directory_entry_type::char_device;
                break;
            case DT_DIR:
                type = directory_entry_type::directory;
                break;
            case DT_FIFO:
                type = directory_entry_type::fifo;
                break;
            case DT_REG:
                type = directory_entry_type::regular;
                break;
            case DT_LNK:
                type = directory_entry_type::link;
                break;
            case DT_SOCK:
                type = directory_entry_type::socket;
                break;
            default:
                // unknown, ignore
                ;
            }
            w->current += de->d_reclen;
            sstring name = de->d_name;
            if (name == "." || name == "..") {
                return make_ready_future<>();
            }
            return w->s.produce({std::move(name), type});
        });
    }).then([w] {
        w->s.close();
    }).handle_exception([] (std::exception_ptr ignored) {});
    return ret;
}

future<size_t>
posix_file_impl::write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& io_priority_class) noexcept {
    auto req = internal::io_request::make_write(_fd, pos, buffer, len);
    return engine().submit_io_write(_io_queue, io_priority_class, len, std::move(req));
}

future<size_t>
posix_file_impl::write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& io_priority_class) noexcept {
    auto len = internal::sanitize_iovecs(iov, _disk_write_dma_alignment);
    auto req = internal::io_request::make_writev(_fd, pos, iov);
    return engine().submit_io_write(_io_queue, io_priority_class, len, std::move(req)).finally([iov = std::move(iov)] () {});
}

future<size_t>
posix_file_impl::read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& io_priority_class) noexcept {
    auto req = internal::io_request::make_read(_fd, pos, buffer, len);
    return engine().submit_io_read(_io_queue, io_priority_class, len, std::move(req));
}

future<size_t>
posix_file_impl::read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& io_priority_class) noexcept {
    auto len = internal::sanitize_iovecs(iov, _disk_read_dma_alignment);
    auto req = internal::io_request::make_readv(_fd, pos, iov);
    return engine().submit_io_read(_io_queue, io_priority_class, len, std::move(req)).finally([iov = std::move(iov)] () {});
}

future<temporary_buffer<uint8_t>>
posix_file_impl::dma_read_bulk(uint64_t offset, size_t range_size, const io_priority_class& pc) noexcept {
    using tmp_buf_type = typename file::read_state<uint8_t>::tmp_buf_type;

  try {
    auto front = offset & (_disk_read_dma_alignment - 1);
    offset -= front;
    range_size += front;

    auto rstate = make_lw_shared<file::read_state<uint8_t>>(offset, front,
                                                       range_size,
                                                       _memory_dma_alignment,
                                                       _disk_read_dma_alignment);

    //
    // First, try to read directly into the buffer. Most of the reads will
    // end here.
    //
    auto read = read_dma(offset, rstate->buf.get_write(),
                         rstate->buf.size(), pc);

    return read.then([rstate, this, &pc] (size_t size) mutable {
        rstate->pos = size;

        //
        // If we haven't read all required data at once -
        // start read-copy sequence. We can't continue with direct reads
        // into the previously allocated buffer here since we have to ensure
        // the aligned read length and thus the aligned destination buffer
        // size.
        //
        // The copying will actually take place only if there was a HW glitch.
        // In EOF case or in case of a persistent I/O error the only overhead is
        // an extra allocation.
        //
        return do_until(
            [rstate] { return rstate->done(); },
            [rstate, this, &pc] () mutable {
            return read_maybe_eof(
                rstate->cur_offset(), rstate->left_to_read(), pc).then(
                    [rstate] (auto buf1) mutable {
                if (buf1.size()) {
                    rstate->append_new_data(buf1);
                } else {
                    rstate->eof = true;
                }

                return make_ready_future<>();
            });
        }).then([rstate] () mutable {
            //
            // If we are here we are promised to have read some bytes beyond
            // "front" so we may trim straight away.
            //
            rstate->trim_buf_before_ret();
            return make_ready_future<tmp_buf_type>(std::move(rstate->buf));
        });
    });
  } catch (...) {
      return make_exception_future<tmp_buf_type>(std::current_exception());
  }
}

future<temporary_buffer<uint8_t>>
posix_file_impl::read_maybe_eof(uint64_t pos, size_t len, const io_priority_class& pc) {
    //
    // We have to allocate a new aligned buffer to make sure we don't get
    // an EINVAL error due to unaligned destination buffer.
    //
    temporary_buffer<uint8_t> buf = temporary_buffer<uint8_t>::aligned(
               _memory_dma_alignment, align_up(len, size_t(_disk_read_dma_alignment)));

    // try to read a single bulk from the given position
    auto dst = buf.get_write();
    auto buf_size = buf.size();
    return read_dma(pos, dst, buf_size, pc).then_wrapped(
            [buf = std::move(buf)](future<size_t> f) mutable {
        try {
            size_t size = std::get<0>(f.get());

            buf.trim(size);

            return std::move(buf);
        } catch (std::system_error& e) {
            //
            // TODO: implement a non-trowing file_impl::dma_read() interface to
            //       avoid the exceptions throwing in a good flow completely.
            //       Otherwise for users that don't want to care about the
            //       underlying file size and preventing the attempts to read
            //       bytes beyond EOF there will always be at least one
            //       exception throwing at the file end for files with unaligned
            //       length.
            //
            if (e.code().value() == EINVAL) {
                buf.trim(0);
                return std::move(buf);
            } else {
                throw;
            }
        }
    });
}

blockdev_file_impl::blockdev_file_impl(int fd, open_flags f, file_open_options options, dev_t device_id)
        : posix_file_impl(fd, f, options, device_id) {
}

future<>
blockdev_file_impl::truncate(uint64_t length) noexcept {
    return make_ready_future<>();
}

future<>
blockdev_file_impl::discard(uint64_t offset, uint64_t length) noexcept {
    return engine()._thread_pool->submit<syscall_result<int>>([this, offset, length] () mutable {
        uint64_t range[2] { offset, length };
        return wrap_syscall<int>(::ioctl(_fd, BLKDISCARD, &range));
    }).then([] (syscall_result<int> sr) {
        sr.throw_if_error();
        return make_ready_future<>();
    });
}

future<>
blockdev_file_impl::allocate(uint64_t position, uint64_t length) noexcept {
    // nothing to do for block device
    return make_ready_future<>();
}

append_challenged_posix_file_impl::append_challenged_posix_file_impl(int fd, open_flags f, file_open_options options,
        unsigned max_size_changing_ops, bool fsync_is_exclusive, dev_t device_id)
        : posix_file_impl(fd, f, options, device_id)
        , _max_size_changing_ops(max_size_changing_ops)
        , _fsync_is_exclusive(fsync_is_exclusive) {
    auto r = ::lseek(fd, 0, SEEK_END);
    throw_system_error_on(r == -1);
    _committed_size = _logical_size = r;
    _sloppy_size = options.sloppy_size;
    auto hint = align_up<uint64_t>(options.sloppy_size_hint, _disk_write_dma_alignment);
    if (_sloppy_size && _committed_size < hint) {
        auto r = ::ftruncate(_fd, hint);
        // We can ignore errors, since it's just a hint.
        if (r != -1) {
            _committed_size = hint;
        }
    }
}

append_challenged_posix_file_impl::~append_challenged_posix_file_impl() {
    // If the file has not been closed we risk having running tasks
    // that will try to access freed memory.
    assert(_closing_state == state::closed);
}

bool
append_challenged_posix_file_impl::must_run_alone(const op& candidate) const noexcept {
    // checks if candidate is a non-write, size-changing operation.
    return (candidate.type == opcode::truncate)
            || (candidate.type == opcode::flush && (_fsync_is_exclusive || _sloppy_size));
}

bool
append_challenged_posix_file_impl::size_changing(const op& candidate) const noexcept {
    return (candidate.type == opcode::write && candidate.pos + candidate.len > _committed_size)
            || must_run_alone(candidate);
}

bool
append_challenged_posix_file_impl::may_dispatch(const op& candidate) const noexcept {
    if (size_changing(candidate)) {
        return !_current_size_changing_ops && !_current_non_size_changing_ops;
    } else {
        return !_current_size_changing_ops;
    }
}

void
append_challenged_posix_file_impl::dispatch(op& candidate) noexcept {
    unsigned* op_counter = size_changing(candidate)
            ? &_current_size_changing_ops : &_current_non_size_changing_ops;
    ++*op_counter;
    // FIXME: future is discarded
    (void)candidate.run().then([me = shared_from_this(), op_counter] {
        --*op_counter;
        me->process_queue();
    });
}

// If we have a bunch of size-extending writes in the queue,
// issue an ftruncate() extending the file size, so they can
// be issued concurrently.
void
append_challenged_posix_file_impl::optimize_queue() noexcept {
    if (_current_non_size_changing_ops || _current_size_changing_ops) {
        // Can't issue an ftruncate() if something is going on
        return;
    }
    auto speculative_size = _committed_size;
    unsigned n_appending_writes = 0;
    for (const auto& op : _q) {
        // stop calculating speculative size after a non-write, size-changing
        // operation is found to prevent an useless truncate from being issued.
        if (must_run_alone(op)) {
            break;
        }
        if (op.type == opcode::write && op.pos + op.len > _committed_size) {
            speculative_size = std::max(speculative_size, op.pos + op.len);
            ++n_appending_writes;
        }
    }
    if (n_appending_writes > _max_size_changing_ops
            || (n_appending_writes && _sloppy_size)) {
        if (_sloppy_size && speculative_size < 2 * _committed_size) {
            speculative_size = align_up<uint64_t>(2 * _committed_size, _disk_write_dma_alignment);
        }
        // We're all alone, so issuing the ftruncate() in the reactor
        // thread won't block us.
        //
        // Issuing it in the syscall thread is too slow; this can happen
        // every several ops, and the syscall thread latency can be very
        // high.
        auto r = ::ftruncate(_fd, speculative_size);
        if (r != -1) {
            _committed_size = speculative_size;
            // If we failed, the next write will pick it up.
        }
    }
}

void
append_challenged_posix_file_impl::process_queue() noexcept {
    optimize_queue();
    while (!_q.empty() && may_dispatch(_q.front())) {
        op candidate = std::move(_q.front());
        _q.pop_front();
        dispatch(candidate);
    }
    if (may_quit()) {
        _completed.set_value();
        _closing_state = state::closing; // prevents _completed to be signaled again in case of recursion
    }
}

void
append_challenged_posix_file_impl::enqueue_op(op&& op) {
    _q.push_back(std::move(op));
    process_queue();
}

bool
append_challenged_posix_file_impl::may_quit() const noexcept {
    return _closing_state == state::draining && _q.empty() && !_current_non_size_changing_ops &&
           !_current_size_changing_ops;
}

void
append_challenged_posix_file_impl::commit_size(uint64_t size) noexcept {
    _committed_size = std::max(size, _committed_size);
    _logical_size = std::max(size, _logical_size);
}

future<size_t>
append_challenged_posix_file_impl::read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) noexcept {
    if (pos >= _logical_size) {
        // later() avoids tail recursion
        return later().then([] {
            return size_t(0);
        });
    }
    len = std::min(pos + len, align_up<uint64_t>(_logical_size, _disk_read_dma_alignment)) - pos;
    return enqueue<size_t>(
        opcode::read,
        pos,
        len,
        [this, pos, buffer, len, &pc] () mutable {
            return posix_file_impl::read_dma(pos, buffer, len, pc);
        }
    );
}

future<size_t>
append_challenged_posix_file_impl::read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept {
    if (pos >= _logical_size) {
        // later() avoids tail recursion
        return later().then([] {
            return size_t(0);
        });
    }
    size_t len = 0;
    auto i = iov.begin();
    while (i != iov.end() && pos + len + i->iov_len <= _logical_size) {
        len += i++->iov_len;
    }
    auto aligned_logical_size = align_up<uint64_t>(_logical_size, _disk_read_dma_alignment);
    if (i != iov.end()) {
        auto last_len = pos + len + i->iov_len - aligned_logical_size;
        if (last_len) {
            i++->iov_len = last_len;
        }
        iov.erase(i, iov.end());
    }
    return enqueue<size_t>(
        opcode::read,
        pos,
        len,
        [this, pos, iov = std::move(iov), &pc] () mutable {
            return posix_file_impl::read_dma(pos, std::move(iov), pc);
        }
    );
}

future<size_t>
append_challenged_posix_file_impl::write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) noexcept {
    return enqueue<size_t>(
        opcode::write,
        pos,
        len,
        [this, pos, buffer, len, &pc] {
            return posix_file_impl::write_dma(pos, buffer, len, pc).then([this, pos] (size_t ret) {
                commit_size(pos + ret);
                return make_ready_future<size_t>(ret);
            });
        }
    );
}

future<size_t>
append_challenged_posix_file_impl::write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept {
    auto len = boost::accumulate(iov | boost::adaptors::transformed(std::mem_fn(&iovec::iov_len)), size_t(0));
    return enqueue<size_t>(
        opcode::write,
        pos,
        len,
        [this, pos, iov = std::move(iov), &pc] () mutable {
            return posix_file_impl::write_dma(pos, std::move(iov), pc).then([this, pos] (size_t ret) {
                commit_size(pos + ret);
                return make_ready_future<size_t>(ret);
            });
        }
    );
}

future<>
append_challenged_posix_file_impl::flush() noexcept {
    if ((!_sloppy_size || _logical_size == _committed_size) && !_fsync_is_exclusive) {
        // FIXME: determine if flush can block concurrent reads or writes
        return posix_file_impl::flush();
    } else {
        return enqueue<>(
            opcode::flush,
            0,
            0,
            [this] () {
                if (_logical_size != _committed_size) {
                    // We're all alone, so can truncate in reactor thread
                    auto r = ::ftruncate(_fd, _logical_size);
                    if (r == -1) {
                        return make_exception_future<>(std::system_error(errno, std::system_category(), "flush"));
                    }
                    _committed_size = _logical_size;
                }
                return posix_file_impl::flush();
            }
        );
    }
}

future<struct stat>
append_challenged_posix_file_impl::stat() noexcept {
    // FIXME: can this conflict with anything?
    return posix_file_impl::stat().then([this] (struct stat stat) {
        stat.st_size = _logical_size;
        return stat;
    });
}

future<>
append_challenged_posix_file_impl::truncate(uint64_t length) noexcept {
    return enqueue<>(
        opcode::truncate,
        length,
        0,
        [this, length] () mutable {
            return posix_file_impl::truncate(length).then([this, length] () mutable {
                _committed_size = _logical_size = length;
            });
        }
    );
}

future<uint64_t>
append_challenged_posix_file_impl::size() noexcept {
    return make_ready_future<size_t>(_logical_size);
}

future<>
append_challenged_posix_file_impl::close() noexcept {
    // Caller should have drained all pending I/O
    _closing_state = state::draining;
    process_queue();
    return _completed.get_future().then([this] {
        if (_logical_size != _committed_size) {
            auto r = ::ftruncate(_fd, _logical_size);
            if (r != -1) {
                _committed_size = _logical_size;
            }
        }
        return posix_file_impl::close().finally([this] { _closing_state = state::closed; });
    });
}

posix_file_handle_impl::~posix_file_handle_impl() {
    if (_refcount && _refcount->fetch_add(-1, std::memory_order_relaxed) == 1) {
        ::close(_fd);
        delete _refcount;
    }
}

std::unique_ptr<seastar::file_handle_impl>
posix_file_handle_impl::clone() const {
    auto ret = std::make_unique<posix_file_handle_impl>(_fd, _open_flags, _refcount, _device_id);
    if (_refcount) {
        _refcount->fetch_add(1, std::memory_order_relaxed);
    }
    return ret;
}

shared_ptr<file_impl>
posix_file_handle_impl::to_file() && {
    auto ret = ::seastar::make_shared<posix_file_impl>(_fd, _open_flags, _refcount, _device_id);
    _fd = -1;
    _refcount = nullptr;
    return ret;
}

// Some kernels can append to xfs filesystems, some cannot; determine
// from kernel version.
static
unsigned
xfs_concurrency_from_kernel_version() {
    // try to see if this is a mainline kernel with xfs append fixed (3.15+)
    // or a RHEL kernel with the backported fix (3.10.0-325.el7+)
    if (kernel_uname().whitelisted({"3.15", "3.10.0-325.el7"})) {
            // Can append, but not concurrently
            return 1;
    }
    // Cannot append at all; need ftrucnate().
    return 0;
}

future<shared_ptr<file_impl>>
make_file_impl(int fd, file_open_options options, int flags) noexcept {
    return engine().fstat(fd).then([fd, options = std::move(options), flags] (struct stat st) mutable {
        auto r = ::ioctl(fd, BLKGETSIZE);
        auto st_dev = st.st_dev;

        if (r != -1) {
            return make_ready_future<shared_ptr<file_impl>>(make_shared<blockdev_file_impl>(fd, open_flags(flags), options, st_dev));
        } else {
            if ((flags & O_ACCMODE) == O_RDONLY || S_ISDIR(st.st_mode)) {
                return make_ready_future<shared_ptr<file_impl>>(make_shared<posix_file_impl>(fd, open_flags(flags), options, st_dev));
            }
            struct append_support {
                bool append_challenged;
                unsigned append_concurrency;
                bool fsync_is_exclusive;
            };
            static thread_local std::unordered_map<decltype(st_dev), append_support> s_fstype;
            future<> get_append_support = s_fstype.count(st_dev) ? make_ready_future<>() :
                engine().fstatfs(fd).then([st_dev] (struct statfs sfs) {
                    append_support as;
                    switch (sfs.f_type) {
                    case 0x58465342: /* XFS */
                        as.append_challenged = true;
                        static auto xc = xfs_concurrency_from_kernel_version();
                        as.append_concurrency = xc;
                        as.fsync_is_exclusive = true;
                        break;
                    case 0x6969: /* NFS */
                        as.append_challenged = false;
                        as.append_concurrency = 0;
                        as.fsync_is_exclusive = false;
                        break;
                    case 0xEF53: /* EXT4 */
                        as.append_challenged = true;
                        as.append_concurrency = 0;
                        as.fsync_is_exclusive = false;
                        break;
                    default:
                        as.append_challenged = true;
                        as.append_concurrency = 0;
                        as.fsync_is_exclusive = true;
                    }
                    s_fstype[st_dev] = as;
                });
            return get_append_support.then([st_dev, fd, flags, options = std::move(options)] () mutable {
                auto as = s_fstype[st_dev];
                if (!as.append_challenged) {
                    return make_ready_future<shared_ptr<file_impl>>(make_shared<posix_file_impl>(fd, open_flags(flags), std::move(options), st_dev));
                }
                return make_ready_future<shared_ptr<file_impl>>(make_shared<append_challenged_posix_file_impl>(fd, open_flags(flags), std::move(options), as.append_concurrency, as.fsync_is_exclusive, st_dev));
            });
        }
    });
}

file::file(seastar::file_handle&& handle) noexcept
        : _file_impl(std::move(std::move(handle).to_file()._file_impl)) {
}

future<uint64_t> file::size() const noexcept {
  try {
    return _file_impl->size();
  } catch (...) {
    return current_exception_as_future<uint64_t>();
  }
}

future<> file::close() noexcept {
    return do_with(shared_ptr<file_impl>(_file_impl), [](shared_ptr<file_impl>& f) {
        return f->close();
    });
}

subscription<directory_entry>
file::list_directory(std::function<future<>(directory_entry de)> next) {
    return _file_impl->list_directory(std::move(next));
}

future<temporary_buffer<uint8_t>>
file::dma_read_bulk_impl(uint64_t offset, size_t range_size, const io_priority_class& pc) noexcept {
  try {
    return _file_impl->dma_read_bulk(offset, range_size, pc);
  } catch (...) {
    return current_exception_as_future<temporary_buffer<uint8_t>>();
  }
}

future<> file::discard(uint64_t offset, uint64_t length) noexcept {
  try {
    return _file_impl->discard(offset, length);
  } catch (...) {
    return current_exception_as_future();
  }
}

future<> file::allocate(uint64_t position, uint64_t length) noexcept {
  try {
    return _file_impl->allocate(position, length);
  } catch (...) {
    return current_exception_as_future();
  }
}

future<> file::truncate(uint64_t length) noexcept {
  try {
    return _file_impl->truncate(length);
  } catch (...) {
    return current_exception_as_future();
  }
}

future<struct stat> file::stat() noexcept {
  try {
    return _file_impl->stat();
  } catch (...) {
    return current_exception_as_future<struct stat>();
  }
}

future<> file::flush() noexcept {
  try {
    return _file_impl->flush();
  } catch (...) {
    return current_exception_as_future();
  }
}

future<size_t> file::dma_write(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept {
  try {
    return _file_impl->write_dma(pos, std::move(iov), pc);
  } catch (...) {
    return current_exception_as_future<size_t>();
  }
}

future<size_t>
file::dma_write_impl(uint64_t pos, const uint8_t* buffer, size_t len, const io_priority_class& pc) noexcept {
  try {
    return _file_impl->write_dma(pos, buffer, len, pc);
  } catch (...) {
    return current_exception_as_future<size_t>();
  }
}

future<size_t> file::dma_read(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept {
  try {
    return _file_impl->read_dma(pos, std::move(iov), pc);
  } catch (...) {
    return current_exception_as_future<size_t>();
  }
}

future<temporary_buffer<uint8_t>>
file::dma_read_exactly_impl(uint64_t pos, size_t len, const io_priority_class& pc) noexcept {
    return dma_read<uint8_t>(pos, len, pc).then([len](auto buf) {
        if (buf.size() < len) {
            throw eof_error();
        }

        return buf;
    });
}

future<temporary_buffer<uint8_t>>
file::dma_read_impl(uint64_t pos, size_t len, const io_priority_class& pc) noexcept {
    return dma_read_bulk<uint8_t>(pos, len, pc).then([len](temporary_buffer<uint8_t> buf) {
        if (len < buf.size()) {
            buf.trim(len);
        }

        return buf;
    });
}

future<size_t>
file::dma_read_impl(uint64_t aligned_pos, uint8_t* aligned_buffer, size_t aligned_len, const io_priority_class& pc) noexcept {
  try {
    return _file_impl->read_dma(aligned_pos, aligned_buffer, aligned_len, pc);
  } catch (...) {
    return current_exception_as_future<size_t>();
  }
}

seastar::file_handle
file::dup() {
    return seastar::file_handle(_file_impl->dup());
}

file_impl* file_impl::get_file_impl(file& f) {
    return f._file_impl.get();
}

std::unique_ptr<seastar::file_handle_impl>
file_impl::dup() {
    throw std::runtime_error("this file type cannot be duplicated");
}

future<file> open_file_dma(sstring name, open_flags flags) noexcept {
    return engine().open_file_dma(std::move(name), flags, file_open_options());
}

future<file> open_file_dma(sstring name, open_flags flags, file_open_options options) noexcept {
    return engine().open_file_dma(std::move(name), flags, std::move(options));
}

future<file> open_directory(sstring name) noexcept {
    return engine().open_directory(std::move(name));
}

}

ext: cc


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file testDSF.cpp
 * @date June 25, 2010
 * @author nikai
 * @brief unit tests for DSF
 */

#include <iostream>
#include <boost/make_shared.hpp>
#include <boost/assign/std/list.hpp>
#include <boost/assign/std/set.hpp>
#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
#include <CppUnitLite/TestHarness.h>

#include <gtsam/base/DSFVector.h>

using namespace std;
using namespace gtsam;

/* ************************************************************************* */
TEST(DSFVectorVector, findSet) {
  DSFVector dsf(3);
  CHECK(dsf.findSet(0) != dsf.findSet(2));
}

/* ************************************************************************* */
TEST(DSFVectorVector, makeUnionInPlace) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,2);
  CHECK(dsf.findSet(0) == dsf.findSet(2));
}

/* ************************************************************************* */
TEST(DSFVectorVector, makeUnionInPlace2) {
  boost::shared_ptr<DSFVector::V> v = boost::make_shared<DSFVector::V>(5);
  std::vector<size_t> keys; keys += 1, 3;
  DSFVector dsf(v, keys);
  dsf.makeUnionInPlace(1,3);
  CHECK(dsf.findSet(1) == dsf.findSet(3));
}

/* ************************************************************************* */
TEST(DSFVector, makeUnion2) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(2,0);
  CHECK(dsf.findSet(0) == dsf.findSet(2));
}

/* ************************************************************************* */
TEST(DSFVector, makeUnion3) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  dsf.makeUnionInPlace(1,2);
  CHECK(dsf.findSet(0) == dsf.findSet(2));
}

/* ************************************************************************* */
TEST(DSFVector, sets) {
  DSFVector dsf(2);
  dsf.makeUnionInPlace(0,1);
  map<size_t, set<size_t> > sets = dsf.sets();
  LONGS_EQUAL(1, sets.size());

  set<size_t> expected; expected += 0, 1;
  CHECK(expected == sets[dsf.findSet(0)]);
}

/* ************************************************************************* */
TEST(DSFVector, arrays) {
  DSFVector dsf(2);
  dsf.makeUnionInPlace(0,1);
  map<size_t, vector<size_t> > arrays = dsf.arrays();
  LONGS_EQUAL(1, arrays.size());

  vector<size_t> expected; expected += 0, 1;
  CHECK(expected == arrays[dsf.findSet(0)]);
}

/* ************************************************************************* */
TEST(DSFVector, sets2) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  dsf.makeUnionInPlace(1,2);
  map<size_t, set<size_t> > sets = dsf.sets();
  LONGS_EQUAL(1, sets.size());

  set<size_t> expected; expected += 0, 1, 2;
  CHECK(expected == sets[dsf.findSet(0)]);
}

/* ************************************************************************* */
TEST(DSFVector, arrays2) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  dsf.makeUnionInPlace(1,2);
  map<size_t, vector<size_t> > arrays = dsf.arrays();
  LONGS_EQUAL(1, arrays.size());

  vector<size_t> expected; expected += 0, 1, 2;
  CHECK(expected == arrays[dsf.findSet(0)]);
}

/* ************************************************************************* */
TEST(DSFVector, sets3) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  map<size_t, set<size_t> > sets = dsf.sets();
  LONGS_EQUAL(2, sets.size());

  set<size_t> expected; expected += 0, 1;
  CHECK(expected == sets[dsf.findSet(0)]);
}

/* ************************************************************************* */
TEST(DSFVector, arrays3) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  map<size_t, vector<size_t> > arrays = dsf.arrays();
  LONGS_EQUAL(2, arrays.size());

  vector<size_t> expected; expected += 0, 1;
  CHECK(expected == arrays[dsf.findSet(0)]);
}

/* ************************************************************************* */
TEST(DSFVector, set) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  set<size_t> set = dsf.set(0);
  LONGS_EQUAL(2, set.size());

  std::set<size_t> expected; expected += 0, 1;
  CHECK(expected == set);
}

/* ************************************************************************* */
TEST(DSFVector, set2) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  dsf.makeUnionInPlace(1,2);
  set<size_t> set = dsf.set(0);
  LONGS_EQUAL(3, set.size());

  std::set<size_t> expected; expected += 0, 1, 2;
  CHECK(expected == set);
}

/* ************************************************************************* */
TEST(DSFVector, isSingleton) {
  DSFVector dsf(3);
  dsf.makeUnionInPlace(0,1);
  CHECK(!dsf.isSingleton(0));
  CHECK(!dsf.isSingleton(1));
  CHECK( dsf.isSingleton(2));
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */

max_stars_repo_name: malcolmreynolds/GTSAM

max_issues_repo_name: malcolmreynolds/GTSAM

max_forks_repo_name: malcolmreynolds/GTSAM


text:
#include <kst_servoing.hpp>
#include <boost/asio.hpp>

/*****
 *
 * Some utility functions
 *
 ****/

// Format the double to string messages
FormatedDouble2String(double a, int dec)
{
	std::stringstream stream;
    stream << std::fixed << std::setprecision(dec) << a;
    std::string s = stream.str();
    return s;
}

// Parse received messages into double vector
std::vector<double> ParseString2DoubleVec(std::string s)
{
	std::vector<double> vec;
	std::string delimiter = "_";
	size_t pos = 0;
	while ((pos = s.find(delimiter)) != std::string::npos)
	{
	    vec.push_back(std::stod(s.substr(0, pos)));
	    s.erase(0, pos + delimiter.length());
	}
	return vec;
}

/*****
 *
 * KstServoing implementations
 *
 ****/

// Constructor
KstServoing::KstServoing(
	std::string robot_ip,
	boost::asio::io_context& io_context)
	:
	tcp_sock_(io_context)
{
	ip_ = robot_ip;
	tcp::endpoint remote_endpoint = tcp::endpoint(boost::asio::ip::address_v4::from_string(robot_ip), 30001);
}

// Send connection request to Sunrise Cabinet
void KstServoing::NetEstablishConnection()
{
	tcp_sock_.connect(remote_endpoint);

	boost::system::error_code error;

	// Msg is the tool transformation (may need to edit. leave it for now
	// currently just calculate from outside and send the command that only
	// regards to the end-effector of the robot)
	const std::string msg1 = "TFtrans_0.0_0.0_0.0_0.0_0.0_0.0\n";
	size_t lenmsgr1;

	// TODO: test if: successful connection when received
	// May need to add a pause (or better, check if can do a handshake type of ack)
	// Previously using ros sleep

	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
	lenmsgr1 = tcp_sock_.read_some(boost::asio::buffer(buf_));

}

// Send a point-to-point command, in joint space
void KstServoing::PTPJointSpace(std::vector<double> jpos , double relVel)
{
	try
	{
		boost::system::error_code error;

		const std::string msg1 = "jRelVel_" +
			boost::lexical_cast<std::string>(relVel) + "_\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
		size_t lenmsgr1 = tcp_sock_.read_some(boost::asio::buffer(buf_), error);

		const std::string msgjs = "jp_" +
			FormatedDouble2String(jpos[0], 5) + "_" +
			FormatedDouble2String(jpos[1], 5) + "_" +
			FormatedDouble2String(jpos[2], 5) + "_" +
			FormatedDouble2String(jpos[3], 5) + "_" +
			FormatedDouble2String(jpos[4], 5) + "_" +
			FormatedDouble2String(jpos[5], 5) + "_" +
			FormatedDouble2String(jpos[6], 5) + "_\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msgjs), error);
		size_t lenmsgrjs = tcp_sock_.read_some(boost::asio::buffer(buf_), error);

		const std::string msg2 = "doPTPinJS\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msg2), error);
		size_t lenmsgr2 = tcp_sock_.read_some(boost::asio::buffer(buf_), error);

		size_t lenmsgr3 = tcp_sock_.read_some(boost::asio::buffer(buf_), error);

	}
	catch(std::exception& e)
	{
		throw;
	}
}

// Send a point-to-point command, in end-effector, and the linear trajectory
void KstServoing::PTPLineEEF(std::vector<double> epos, double vel)
{// vel: mm/sec
	try
	{
		boost::system::error_code error;

		const std::string msg1 = "jRelVel_" +
			boost::lexical_cast<std::string>(vel) + "_\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
		size_t lenmsgr1 = tcp_sock_.read_some(boost::asio::buffer(buf_), error);

		const std::string msgjs = "cArtixanPosition_" +
			std::to_string(epos[0]) + "_" +
			std::to_string(epos[1]) + "_" +
			std::to_string(epos[2]) + "_" +
			std::to_string(epos[3]) + "_" +
			std::to_string(epos[4]) + "_" +
			std::to_string(epos[5]) + "_\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msgjs), error);
		size_t lenmsgrjs = tcp_sock_.read_some(boost::asio::buffer(buf_), error);

		const std::string msg2 = "doPTPinCS\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msg2), error);
		size_t lenmsgr2 = tcp_sock_.read_some(boost::asio::buffer(buf_), error);

		size_t lenmsgr3 = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
	}
	catch(std::exception& e)
	{
		throw;
	}
}

// Send a command to Sunrise Cabinet to start Direct Servo, in EEF
void KstServoing::ServoDirectCartesianStart()
{
	boost::system::error_code error;
	const std::string msg1 = "stDcEEf_\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
	size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
}

// Send a command to Sunrise Cabinet to start Direct Servo, in joint space
void KstServoing::ServoDirectJointStart()
{
	boost::system::error_code error;
	const std::string msg1 = "startDirectServoJoints\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
	size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
}

// Send a command to Sunrise Cabinet to start Smart Servo, in EEF
void KstServoing::ServoSmartCartesianStart()
{
	boost::system::error_code error;
	const std::string msg1 = "stSmtSEEf_\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
	size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
}

// Stop Smart/Direct Servo
void KstServoing::ServoStop()
{
	boost::system::error_code error;
	const std::string msg1 = "stopDirectServoJoints\n"; // the same to stop direct servo based on KST
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
	size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
}

// In servo mode, send joint positions
void KstServoing::ServoSendJoints(std::vector<double> jp)
{
	boost::system::error_code error;
	const std::string msg1 = "jf_"+
		FormatedDouble2String(jp[0], 5) + "_" +
		FormatedDouble2String(jp[1], 5) + "_" +
		FormatedDouble2String(jp[2], 5) + "_" +
		FormatedDouble2String(jp[3], 5) + "_" +
		FormatedDouble2String(jp[4], 5) + "_" +
		FormatedDouble2String(jp[5], 5) + "_" +
		FormatedDouble2String(jp[6], 5) + "_\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
}

// In servo mode, send joint positions and get feedback
std::vector<double> KstServoing::ServoSendJointsGetFeedback(std::vector<double> jp)
{
	boost::system::error_code error;
	const std::string msg1 = "jpJP_"+
		FormatedDouble2String(jp[0], 5) + "_" +
		FormatedDouble2String(jp[1], 5) + "_" +
		FormatedDouble2String(jp[2], 5) + "_" +
		FormatedDouble2String(jp[3], 5) + "_" +
		FormatedDouble2String(jp[4], 5) + "_" +
		FormatedDouble2String(jp[5], 5) + "_" +
		FormatedDouble2String(jp[6], 5) + "_\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);

	size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
	std::stringstream ssmsgr;
	std::string strmsgr;
	for(int i=0;i<lenmsgr;i++)
		ssmsgr << buf_[i];
	strmsgr = ssmsgr.str();

	// Joint position feedback
	std::vector<double> jpbk = ParseString2DoubleVec(strmsgr);

	return jpbk;
}

// In servo mode, send EEF position
void KstServoing::ServoSendEEF(std::vector<double> eef) // x y z rz ry rx
{
	boost::system::error_code error;
	const std::string msg1 = "DcSeCar_"+
		FormatedDouble2String(eef[0], 5) + "_" +
		FormatedDouble2String(eef[1], 5) + "_" +
		FormatedDouble2String(eef[2], 5) + "_" +
		FormatedDouble2String(eef[3], 5) + "_" +
		FormatedDouble2String(eef[4], 5) + "_" +
		FormatedDouble2String(eef[5], 5) + "_\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
}

// In servo mode, send EEF position and get feedback
std::vector<double> KstServoing::ServoSendEEFGetFeedback(std::vector<double> eef)  // x y z rz ry rx
{
	boost::system::error_code error;
	const std::string msg1 = "DcSeCarEEfP_"+
		FormatedDouble2String(eef[0], 5) + "_" +
		FormatedDouble2String(eef[1], 5) + "_" +
		FormatedDouble2String(eef[2], 5) + "_" +
		FormatedDouble2String(eef[3], 5) + "_" +
		FormatedDouble2String(eef[4], 5) + "_" +
		FormatedDouble2String(eef[5], 5) + "_\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);

	size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
	std::stringstream ssmsgr;
	std::string strmsgr;
	for(int i=0;i<lenmsgr;i++)
		ssmsgr << buf_[i];
	strmsgr = ssmsgr.str();

	std::vector<double> eefbk = ParseString2DoubleVec(strmsgr);

	return eefbk;
}

// Get current joint position
std::vector<double> KstServoing::GetJointPosition()
{
	std::string strmsgr;
	try
	{
		boost::system::error_code error;
		const std::string msg = "getJointsPositions\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msg), error);
		size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
		std::stringstream ssmsgr;
		for(int i=0;i<lenmsgr;i++)
			ssmsgr << buf_[i];
		ssmsgr << "_"; // this is for getting jpos only, because the kuka java side miss a _
		strmsgr = ssmsgr.str();
	}
	catch(std::exception& e)
	{
		throw;
	}
	std::vector<double> vec = ParseString2DoubleVec(strmsgr);
	// vector format: a1 a2 a3 a4 a5 a6 a7

	return vec;
}

// Get current EEF pose
std::vector<double> KstServoing::GetEEFPosition()
{
	std::string strmsgr;
	try
	{
		boost::system::error_code error;
		const std::string msg = "Eef_pos\n";
		boost::asio::write(tcp_sock_, boost::asio::buffer(msg), error);
		size_t lenmsgr = tcp_sock_.read_some(boost::asio::buffer(buf_), error);
		std::stringstream ssmsgr;
		for(int i=0;i<lenmsgr;i++)
			ssmsgr << buf_[i];
		strmsgr = ssmsgr.str();
	}
	catch(std::exception& e)
	{
		throw;
	}
	std::vector<double> vec = ParseString2DoubleVec(strmsgr);
	// vector format: x y z rz ry rx

	return vec;
}

// Turn of the connection
void KstServoing::NetTurnoffServer()
{
	boost::system::error_code error;
	const std::string msg1 = "end\n";
	boost::asio::write(tcp_sock_, boost::asio::buffer(msg1), error);
	tcp_sock_.close();
}

max_stars_repo_name: bingogome/ros-kuka-sunrise-toolbox

max_issues_repo_name: bingogome/ros-kuka-sunrise-toolbox

max_forks_repo_name: bingogome/ros-kuka-sunrise-toolbox


text:
//  (C) Copyright Edward Diener 2019
//  Use, modification and distribution are subject to 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).

#if !defined(BOOST_TTI_DETAIL_STATIC_FUNCTION_TAGS_HPP)
#define BOOST_TTI_DETAIL_STATIC_FUNCTION_TAGS_HPP

#include <boost/function_types/property_tags.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/or.hpp>

namespace boost
  {
  namespace tti
    {
    namespace detail
      {
      template
        <
        class BOOST_TTI_DETAIL_TP_TAG
        >
      struct static_function_tag :
        boost::mpl::not_
          <
          boost::mpl::or_
            <
            boost::function_types::has_const_property_tag<BOOST_TTI_DETAIL_TP_TAG>,
            boost::function_types::has_volatile_property_tag<BOOST_TTI_DETAIL_TP_TAG>
            >
          >
        {
        };
      }
    }
  }

#endif // BOOST_TTI_DETAIL_STATIC_FUNCTION_TAGS_HPP