<commit_before>/*

Copyright (c) 2007, Arvid Norberg
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 the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/xml_parse.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>

using boost::bind;
using namespace libtorrent;

address_v4 lsd::lsd_multicast_address;
udp::endpoint lsd::lsd_multicast_endpoint;

lsd::lsd(io_service& ios, address const& listen_interface
	, peer_callback_t const& cb)
	: m_callback(cb)
	, m_retry_count(0)
	, m_socket(ios)
	, m_broadcast_timer(ios)
	, m_disabled(false)
{
	// Bittorrent Local discovery multicast address and port
	lsd_multicast_address = address_v4::from_string("239.192.152.143");
	lsd_multicast_endpoint = udp::endpoint(lsd_multicast_address, 6771);

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
	assert(lsd_multicast_address.is_multicast());
	rebind(listen_interface);
}

lsd::~lsd() {}

void lsd::rebind(address const& listen_interface)
{
	address_v4 local_ip;
	if (listen_interface.is_v4() && listen_interface != address_v4::from_string("0.0.0.0"))
	{
		local_ip = listen_interface.to_v4();
	}
	else
	{
		// make a best guess of the interface we're using and its IP
		udp::resolver r(m_socket.io_service());
		udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0"));
		for (;i != udp::resolver_iterator(); ++i)
		{
			if (i->endpoint().address().is_v4()) break;
		}

		if (i == udp::resolver_iterator())
		{
	#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
			m_log << "local host name did not resolve to an IPv4 address. "
				"disabling local service discovery" << std::endl;
	#endif
			m_disabled = true;
			return;
		}

		local_ip = i->endpoint().address().to_v4();
	}

	try
	{
		// the local interface hasn't changed
		if (m_socket.is_open()
			&& m_socket.local_endpoint().address() == local_ip)
			return;

		m_socket.close();

		using namespace asio::ip::multicast;

		m_socket.open(udp::v4());
		m_socket.set_option(datagram_socket::reuse_address(true));
		m_socket.bind(udp::endpoint(local_ip, 6771));

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << "local ip: " << local_ip << std::endl;
#endif

		m_socket.set_option(join_group(lsd_multicast_address));
		m_socket.set_option(outbound_interface(address_v4()));
		m_socket.set_option(enable_loopback(false));
		m_socket.set_option(hops(255));
	}
	catch (std::exception& e)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << "socket multicast error " << e.what()
			<< ". disabling local service discovery" << std::endl;
#endif
		m_disabled = true;
		return;
	}
	m_disabled = false;

	setup_receive();
}

void lsd::announce(sha1_hash const& ih, int listen_port)
{
	if (m_disabled) return;

	std::stringstream btsearch;
	btsearch << "BT-SEARCH * HTTP/1.1\r\n"
		"Host: 239.192.152.143:6771\r\n"
		"Port: " << listen_port << "\r\n"
		"Infohash: " << ih << "\r\n"
		"\r\n\r\n";
	std::string const& msg = btsearch.str();

	m_retry_count = 0;
	asio::error_code ec;
	m_socket.send_to(asio::buffer(msg.c_str(), msg.size() - 1)
		, lsd_multicast_endpoint, ec);
	if (ec)
	{
		m_disabled = true;
		return;
	}

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}

void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
	if (e) return;

	m_socket.send_to(asio::buffer(msg, msg.size() - 1)
		, lsd_multicast_endpoint);

	++m_retry_count;
	if (m_retry_count >= 5)
		return;

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}
catch (std::exception&)
{}

void lsd::on_announce(asio::error_code const& e
	, std::size_t bytes_transferred)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " <== on_announce" << std::endl;
#endif
	using namespace libtorrent::detail;
	if (e) return;

	char* p = m_receive_buffer;
	char* end = m_receive_buffer + bytes_transferred;
	char* line = std::find(p, end, '\n');
	for (char* i = p; i < line; ++i) *i = std::tolower(*i);
	if (line == end || std::strcmp("bt-search", p))
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " <== Got incorrect method in announce" << std::string(p, line) << std::endl;
#endif
		setup_receive();
		return;
	}
	p = line + 1;
	int port = 0;
	sha1_hash ih(0);
	while (p != end)
	{
		line = std::find(p, end, '\n');
		if (line == end) break;
		*line = 0;
		for (char* i = p; i < line; ++i) *i = std::tolower(*i);
		if (!strcmp(p, "port:"))
		{
			port = atoi(p + 5);
		}
		else if (!strcmp(p, "infohash:"))
		{
			ih = boost::lexical_cast<sha1_hash>(p + 9);
		}
		p = line + 1;
	}

	if (!ih.is_all_zeros() && port != 0)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " <== Got incoming local announce " << m_remote.address()
			<< ":" << port << " ih: " << ih << std::endl;
#endif
		// we got an announce, pass it on through the callback
		try { m_callback(tcp::endpoint(m_remote.address(), port), ih); }
		catch (std::exception&) {}
	}
	setup_receive();
}

void lsd::setup_receive() try
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " *** setup_receive" << std::endl;
#endif
	assert(m_socket.is_open());
	m_socket.async_receive_from(asio::buffer(m_receive_buffer
		, sizeof(m_receive_buffer)), m_remote, bind(&lsd::on_announce, this, _1, _2));
}
catch (std::exception&)
{}

void lsd::close()
{
	m_socket.close();
}

<commit_msg>fixed typo in last check in<commit_after>/*

Copyright (c) 2007, Arvid Norberg
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 the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/xml_parse.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>

using boost::bind;
using namespace libtorrent;

address_v4 lsd::lsd_multicast_address;
udp::endpoint lsd::lsd_multicast_endpoint;

lsd::lsd(io_service& ios, address const& listen_interface
	, peer_callback_t const& cb)
	: m_callback(cb)
	, m_retry_count(0)
	, m_socket(ios)
	, m_broadcast_timer(ios)
	, m_disabled(false)
{
	// Bittorrent Local discovery multicast address and port
	lsd_multicast_address = address_v4::from_string("239.192.152.143");
	lsd_multicast_endpoint = udp::endpoint(lsd_multicast_address, 6771);

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
	assert(lsd_multicast_address.is_multicast());
	rebind(listen_interface);
}

lsd::~lsd() {}

void lsd::rebind(address const& listen_interface)
{
	address_v4 local_ip;
	if (listen_interface.is_v4() && listen_interface != address_v4::from_string("0.0.0.0"))
	{
		local_ip = listen_interface.to_v4();
	}
	else
	{
		// make a best guess of the interface we're using and its IP
		udp::resolver r(m_socket.io_service());
		udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0"));
		for (;i != udp::resolver_iterator(); ++i)
		{
			if (i->endpoint().address().is_v4()) break;
		}

		if (i == udp::resolver_iterator())
		{
	#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
			m_log << "local host name did not resolve to an IPv4 address. "
				"disabling local service discovery" << std::endl;
	#endif
			m_disabled = true;
			return;
		}

		local_ip = i->endpoint().address().to_v4();
	}

	try
	{
		// the local interface hasn't changed
		if (m_socket.is_open()
			&& m_socket.local_endpoint().address() == local_ip)
			return;

		m_socket.close();

		using namespace asio::ip::multicast;

		m_socket.open(udp::v4());
		m_socket.set_option(datagram_socket::reuse_address(true));
		m_socket.bind(udp::endpoint(local_ip, 6771));

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << "local ip: " << local_ip << std::endl;
#endif

		m_socket.set_option(join_group(lsd_multicast_address));
		m_socket.set_option(outbound_interface(address_v4()));
		m_socket.set_option(enable_loopback(false));
		m_socket.set_option(hops(255));
	}
	catch (std::exception& e)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << "socket multicast error " << e.what()
			<< ". disabling local service discovery" << std::endl;
#endif
		m_disabled = true;
		return;
	}
	m_disabled = false;

	setup_receive();
}

void lsd::announce(sha1_hash const& ih, int listen_port)
{
	if (m_disabled) return;

	std::stringstream btsearch;
	btsearch << "BT-SEARCH * HTTP/1.1\r\n"
		"Host: 239.192.152.143:6771\r\n"
		"Port: " << listen_port << "\r\n"
		"Infohash: " << ih << "\r\n"
		"\r\n\r\n";
	std::string const& msg = btsearch.str();

	m_retry_count = 0;
	asio::error_code ec;
	m_socket.send_to(asio::buffer(msg.c_str(), msg.size() - 1)
		, lsd_multicast_endpoint, 0, ec);
	if (ec)
	{
		m_disabled = true;
		return;
	}

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}

void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
	if (e) return;

	m_socket.send_to(asio::buffer(msg, msg.size() - 1)
		, lsd_multicast_endpoint);

	++m_retry_count;
	if (m_retry_count >= 5)
		return;

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg));
}
catch (std::exception&)
{}

void lsd::on_announce(asio::error_code const& e
	, std::size_t bytes_transferred)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " <== on_announce" << std::endl;
#endif
	using namespace libtorrent::detail;
	if (e) return;

	char* p = m_receive_buffer;
	char* end = m_receive_buffer + bytes_transferred;
	char* line = std::find(p, end, '\n');
	for (char* i = p; i < line; ++i) *i = std::tolower(*i);
	if (line == end || std::strcmp("bt-search", p))
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " <== Got incorrect method in announce" << std::string(p, line) << std::endl;
#endif
		setup_receive();
		return;
	}
	p = line + 1;
	int port = 0;
	sha1_hash ih(0);
	while (p != end)
	{
		line = std::find(p, end, '\n');
		if (line == end) break;
		*line = 0;
		for (char* i = p; i < line; ++i) *i = std::tolower(*i);
		if (!strcmp(p, "port:"))
		{
			port = atoi(p + 5);
		}
		else if (!strcmp(p, "infohash:"))
		{
			ih = boost::lexical_cast<sha1_hash>(p + 9);
		}
		p = line + 1;
	}

	if (!ih.is_all_zeros() && port != 0)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " <== Got incoming local announce " << m_remote.address()
			<< ":" << port << " ih: " << ih << std::endl;
#endif
		// we got an announce, pass it on through the callback
		try { m_callback(tcp::endpoint(m_remote.address(), port), ih); }
		catch (std::exception&) {}
	}
	setup_receive();
}

void lsd::setup_receive() try
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " *** setup_receive" << std::endl;
#endif
	assert(m_socket.is_open());
	m_socket.async_receive_from(asio::buffer(m_receive_buffer
		, sizeof(m_receive_buffer)), m_remote, bind(&lsd::on_announce, this, _1, _2));
}
catch (std::exception&)
{}

void lsd::close()
{
	m_socket.close();
}

<|endoftext|>


<commit_before>#include <node.h>
#include <nan.h>
#include <openssl/obj_mac.h>

#include "eckey.h"

using namespace v8;

void InitCurves(Handle<Object> exports) {
	Local<Object> obj = Object::New();
	obj->Set(NanNew<String>("secp112r1"), NanNew<Number>(NID_secp112r1));
	obj->Set(NanNew<String>("secp112r2"), NanNew<Number>(NID_secp112r2));
	obj->Set(NanNew<String>("secp128r1"), NanNew<Number>(NID_secp128r1));
	obj->Set(NanNew<String>("secp128r2"), NanNew<Number>(NID_secp128r2));
	obj->Set(NanNew<String>("secp160k1"), NanNew<Number>(NID_secp160k1));
	obj->Set(NanNew<String>("secp160r1"), NanNew<Number>(NID_secp160r1));
	obj->Set(NanNew<String>("secp160r2"), NanNew<Number>(NID_secp160r2));
	obj->Set(NanNew<String>("secp192r1"), NanNew<Number>(NID_X9_62_prime192v1));
	obj->Set(NanNew<String>("secp192k1"), NanNew<Number>(NID_secp192k1));
	obj->Set(NanNew<String>("secp224k1"), NanNew<Number>(NID_secp224k1));
	obj->Set(NanNew<String>("secp224r1"), NanNew<Number>(NID_secp224r1));
	obj->Set(NanNew<String>("secp256r1"), NanNew<Number>(NID_X9_62_prime256v1));
	obj->Set(NanNew<String>("secp256k1"), NanNew<Number>(NID_secp256k1));
	obj->Set(NanNew<String>("secp384r1"), NanNew<Number>(NID_secp384r1));
	obj->Set(NanNew<String>("secp521r1"), NanNew<Number>(NID_secp521r1));
	obj->Set(NanNew<String>("sect113r1"), NanNew<Number>(NID_sect113r1));
	obj->Set(NanNew<String>("sect113r2"), NanNew<Number>(NID_sect113r2));
	obj->Set(NanNew<String>("sect131r1"), NanNew<Number>(NID_sect131r1));
	obj->Set(NanNew<String>("sect131r2"), NanNew<Number>(NID_sect131r2));
	obj->Set(NanNew<String>("sect163k1"), NanNew<Number>(NID_sect163k1));
	obj->Set(NanNew<String>("sect163r1"), NanNew<Number>(NID_sect163r1));
	obj->Set(NanNew<String>("sect163r2"), NanNew<Number>(NID_sect163r2));
	obj->Set(NanNew<String>("sect193r1"), NanNew<Number>(NID_sect193r1));
	obj->Set(NanNew<String>("sect193r2"), NanNew<Number>(NID_sect193r2));
	obj->Set(NanNew<String>("sect233k1"), NanNew<Number>(NID_sect233k1));
	obj->Set(NanNew<String>("sect233r1"), NanNew<Number>(NID_sect233r1));
	obj->Set(NanNew<String>("sect239k1"), NanNew<Number>(NID_sect239k1));
	obj->Set(NanNew<String>("sect283k1"), NanNew<Number>(NID_sect283k1));
	obj->Set(NanNew<String>("sect283r1"), NanNew<Number>(NID_sect283r1));
	obj->Set(NanNew<String>("sect409k1"), NanNew<Number>(NID_sect409k1));
	obj->Set(NanNew<String>("sect409r1"), NanNew<Number>(NID_sect409r1));
	obj->Set(NanNew<String>("sect571k1"), NanNew<Number>(NID_sect571k1));
	obj->Set(NanNew<String>("sect571r1"), NanNew<Number>(NID_sect571r1));

	// Intimidated? Can't go wrong with NIST recommended curves

	obj->Set(NanNew<String>("nistp192"), NanNew<Number>(NID_X9_62_prime192v1));
	obj->Set(NanNew<String>("nistp224"), NanNew<Number>(NID_secp224r1));
	obj->Set(NanNew<String>("nistp256"), NanNew<Number>(NID_X9_62_prime256v1));
	obj->Set(NanNew<String>("nistp384"), NanNew<Number>(NID_secp384r1));
	obj->Set(NanNew<String>("nistp521"), NanNew<Number>(NID_secp521r1));

	exports->Set(NanNew<String>("ECCurves"), obj);
}

void InitModule(Handle<Object> exports) {
	ECKey::Init(exports);
	InitCurves(exports);
}

NODE_MODULE(native, InitModule)
<commit_msg>Use NanNew<Object> for Object::New<commit_after>#include <node.h>
#include <nan.h>
#include <openssl/obj_mac.h>

#include "eckey.h"

using namespace v8;

void InitCurves(Handle<Object> exports) {
	Local<Object> obj = NanNew<Object>();
	obj->Set(NanNew<String>("secp112r1"), NanNew<Number>(NID_secp112r1));
	obj->Set(NanNew<String>("secp112r2"), NanNew<Number>(NID_secp112r2));
	obj->Set(NanNew<String>("secp128r1"), NanNew<Number>(NID_secp128r1));
	obj->Set(NanNew<String>("secp128r2"), NanNew<Number>(NID_secp128r2));
	obj->Set(NanNew<String>("secp160k1"), NanNew<Number>(NID_secp160k1));
	obj->Set(NanNew<String>("secp160r1"), NanNew<Number>(NID_secp160r1));
	obj->Set(NanNew<String>("secp160r2"), NanNew<Number>(NID_secp160r2));
	obj->Set(NanNew<String>("secp192r1"), NanNew<Number>(NID_X9_62_prime192v1));
	obj->Set(NanNew<String>("secp192k1"), NanNew<Number>(NID_secp192k1));
	obj->Set(NanNew<String>("secp224k1"), NanNew<Number>(NID_secp224k1));
	obj->Set(NanNew<String>("secp224r1"), NanNew<Number>(NID_secp224r1));
	obj->Set(NanNew<String>("secp256r1"), NanNew<Number>(NID_X9_62_prime256v1));
	obj->Set(NanNew<String>("secp256k1"), NanNew<Number>(NID_secp256k1));
	obj->Set(NanNew<String>("secp384r1"), NanNew<Number>(NID_secp384r1));
	obj->Set(NanNew<String>("secp521r1"), NanNew<Number>(NID_secp521r1));
	obj->Set(NanNew<String>("sect113r1"), NanNew<Number>(NID_sect113r1));
	obj->Set(NanNew<String>("sect113r2"), NanNew<Number>(NID_sect113r2));
	obj->Set(NanNew<String>("sect131r1"), NanNew<Number>(NID_sect131r1));
	obj->Set(NanNew<String>("sect131r2"), NanNew<Number>(NID_sect131r2));
	obj->Set(NanNew<String>("sect163k1"), NanNew<Number>(NID_sect163k1));
	obj->Set(NanNew<String>("sect163r1"), NanNew<Number>(NID_sect163r1));
	obj->Set(NanNew<String>("sect163r2"), NanNew<Number>(NID_sect163r2));
	obj->Set(NanNew<String>("sect193r1"), NanNew<Number>(NID_sect193r1));
	obj->Set(NanNew<String>("sect193r2"), NanNew<Number>(NID_sect193r2));
	obj->Set(NanNew<String>("sect233k1"), NanNew<Number>(NID_sect233k1));
	obj->Set(NanNew<String>("sect233r1"), NanNew<Number>(NID_sect233r1));
	obj->Set(NanNew<String>("sect239k1"), NanNew<Number>(NID_sect239k1));
	obj->Set(NanNew<String>("sect283k1"), NanNew<Number>(NID_sect283k1));
	obj->Set(NanNew<String>("sect283r1"), NanNew<Number>(NID_sect283r1));
	obj->Set(NanNew<String>("sect409k1"), NanNew<Number>(NID_sect409k1));
	obj->Set(NanNew<String>("sect409r1"), NanNew<Number>(NID_sect409r1));
	obj->Set(NanNew<String>("sect571k1"), NanNew<Number>(NID_sect571k1));
	obj->Set(NanNew<String>("sect571r1"), NanNew<Number>(NID_sect571r1));

	// Intimidated? Can't go wrong with NIST recommended curves

	obj->Set(NanNew<String>("nistp192"), NanNew<Number>(NID_X9_62_prime192v1));
	obj->Set(NanNew<String>("nistp224"), NanNew<Number>(NID_secp224r1));
	obj->Set(NanNew<String>("nistp256"), NanNew<Number>(NID_X9_62_prime256v1));
	obj->Set(NanNew<String>("nistp384"), NanNew<Number>(NID_secp384r1));
	obj->Set(NanNew<String>("nistp521"), NanNew<Number>(NID_secp521r1));

	exports->Set(NanNew<String>("ECCurves"), obj);
}

void InitModule(Handle<Object> exports) {
	ECKey::Init(exports);
	InitCurves(exports);
}

NODE_MODULE(native, InitModule)
<|endoftext|>


<commit_before>/**
 * @file main.cc
 * @author Rafal Slota
 * @copyright (C) 2016 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef linux
/* For pread()/pwrite()/utimensat() */
#define _XOPEN_SOURCE 700
#endif

#include "asio.hpp"
#include "auth/authException.h"
#include "auth/authManager.h"
#include "communication/exception.h"
#include "context.h"
#include "fsOperations.h"
#include "fslogic/composite.h"
#include "fuseOperations.h"
#include "helpers/init.h"
#include "logging.h"
#include "messages/configuration.h"
#include "messages/getConfiguration.h"
#include "messages/handshakeResponse.h"
#include "monitoring/monitoring.h"
#include "monitoring/monitoringConfiguration.h"
#include "options/options.h"
#include "scheduler.h"
#include "scopeExit.h"
#include "version.h"

#include <folly/Singleton.h>
#include <fuse/fuse_lowlevel.h>
#include <fuse/fuse_opt.h>

#include <sys/mount.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <exception>
#include <future>
#include <iostream>
#include <memory>
#include <random>
#include <regex>
#include <string>

#if !defined(NDEBUG)
/**
 * We have to expose FLAGS_vmodule variable here, as it is not declared
 * publicly by Glog library.
 */
DECLARE_string(vmodule);
#endif

using namespace one;
using namespace one::client;
using namespace one::monitoring;

void startLogging(
    const char *programName, std::shared_ptr<options::Options> options)
{
    try {
        boost::filesystem::create_directories(options->getLogDirPath());
    }
    catch (const boost::filesystem::filesystem_error &e) {
        std::cerr << "Failed to create log directory: '" << e.what()
                  << "'. Aborting..." << std::endl;
    }

    FLAGS_minloglevel = 0;
    FLAGS_logtostderr = false;
    FLAGS_stderrthreshold = options->getDebug() ? 0 : 2;
    FLAGS_log_dir = options->getLogDirPath().c_str();
    FLAGS_stop_logging_if_full_disk = true;
#if !defined(NDEBUG)
    FLAGS_v = options->getVerboseLogLevel();
    FLAGS_vmodule = options->getVerboseLogFilter()
        ? options->getVerboseLogFilter().get()
        : "*";
#endif
    google::InitGoogleLogging(programName);

    if (options->getProviderHost())
        LOG(INFO) << "Connecting to Oneprovider: "
                  << options->getProviderHost().get();
    LOG(INFO) << "Forced direct io: " << options->isDirectIOForced();
    LOG(INFO) << "Forced proxy io: " << options->isDirectIOForced();
    LOG(INFO) << "Verify service certificate: " << options->isInsecure();
    LOG(INFO) << "File read events disabled: "
              << options->areFileReadEventsDisabled();
    LOG(INFO) << "Is IO buffered: " << options->isIOBuffered();
    LOG(INFO) << "Oneprovider connection timeout [s]: "
              << options->getProviderTimeout().count();
    LOG(INFO) << "Is monitoring enabled: " << options->isMonitoringEnabled();
    if (options->getMonitoringType())
        LOG(INFO) << "Monitoring type: " << options->getMonitoringType().get();
    LOG(INFO) << "Is monitoring level basic: "
              << options->isMonitoringLevelBasic();
    LOG(INFO) << "Is monitoring level full: "
              << options->isMonitoringLevelFull();
    if (options->getMonitoringGraphiteUrl())
        LOG(INFO) << "Graphite URL: "
                  << options->getMonitoringGraphiteUrl().get();
    if (options->getMonitoringGraphiteNamespacePrefix())
        LOG(INFO) << "Graphite URL: "
                  << options->getMonitoringGraphiteNamespacePrefix().get();
    LOG(INFO) << "Mountpoint: " << options->getMountpoint();
}

int startPerformanceMonitoring(std::shared_ptr<options::Options> options)
{
    if (options->isMonitoringEnabled()) {
        if (options->getMonitoringType().get() == "graphite") {
            if (!options->getMonitoringGraphiteUrl()) {
                std::cerr << "Graphite URL not specified - use option "
                             "--graphite-url."
                          << std::endl;
                return EXIT_FAILURE;
            }

            auto config = std::make_shared<GraphiteMonitoringConfiguration>();
            try {
                config->fromGraphiteURL(
                    options->getMonitoringGraphiteUrl().get());
            }
            catch (std::invalid_argument &e) {
                std::cerr << "Graphite configuration error: " << e.what()
                          << std::endl;
            }
            if (options->getMonitoringGraphiteNamespacePrefix()) {
                config->namespacePrefix =
                    options->getMonitoringGraphiteNamespacePrefix().get();
            }
            config->reportingPeriod = options->getMonitoringReportingPeriod();
            if (options->isMonitoringLevelFull()) {
                config->reportingLevel = cppmetrics::core::ReportingLevel::Full;
            }
            else {
                config->reportingLevel =
                    cppmetrics::core::ReportingLevel::Basic;
            }

            LOG(INFO) << "Starting Graphite performance monitoring to host: "
                      << config->graphiteHostname;

            // Configure and start monitoring threads
            helpers::configureMonitoring(config, true);

            // Initialize the command line option counter values
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.scheduler_thread_count",
                options->getSchedulerThreadCount());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.communicator_thread_count",
                options->getCommunicatorThreadCount());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.storage_helper_thread_count",
                options->getStorageHelperThreadCount());
            ONE_METRIC_COUNTER_SET("comp.oneclient.mod.options.buffer_"
                                   "scheduler_helper_thread_count",
                options->getBufferSchedulerThreadCount());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.read_buffer_min_size",
                options->getReadBufferMinSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.read_buffer_max_size",
                options->getReadBufferMaxSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.write_buffer_min_size",
                options->getWriteBufferMinSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.write_buffer_max_size",
                options->getWriteBufferMaxSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.read_buffer_prefetch_duration",
                options->getReadBufferPrefetchDuration().count());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.write_buffer_flush_delay",
                options->getWriteBufferFlushDelay().count());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.metadata_cache_size",
                options->getMetadataCacheSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.monitoring_reporting_period",
                options->getMonitoringReportingPeriod());
        }
        else {
            std::cerr << "Unsupported performance monitoring reporter: "
                      << options->getMonitoringType().get() << std::endl;
            return EXIT_FAILURE;
        }
    }

    return EXIT_SUCCESS;
}

std::string generateSessionId()
{
    std::random_device rd;
    std::default_random_engine randomEngine{rd()};
    std::uniform_int_distribution<unsigned long long> sessionIdDistribution;
    return std::to_string(sessionIdDistribution(randomEngine));
}

std::shared_ptr<communication::Communicator> handshake(
    const std::string &sessionId,
    std::shared_ptr<auth::AuthManager> authManager,
    std::shared_ptr<Context> context)
{
    auto handshakeHandler = [&](messages::HandshakeResponse msg) {
        if (msg.isMacaroonError()) {
            authManager->cleanup();
        }
        return msg.status();
    };

    auto testCommunicatorTuple = authManager->createCommunicator(
        1, sessionId, ONECLIENT_VERSION, handshakeHandler);
    auto testCommunicator =
        std::get<std::shared_ptr<communication::Communicator>>(
            testCommunicatorTuple);

    testCommunicator->setScheduler(context->scheduler());
    testCommunicator->connect();
    communication::wait(
        std::get<folly::Future<folly::Unit>>(testCommunicatorTuple),
        context->options()->getProviderTimeout());

    return testCommunicator;
}

std::shared_ptr<options::Options> getOptions(int argc, char *argv[])
{
    auto options = std::make_shared<options::Options>();
    try {
        options->parse(argc, argv);
        return options;
    }
    catch (const boost::program_options::error &e) {
        std::cerr << std::regex_replace(e.what(), std::regex("--"), "") << "\n"
                  << "See '" << argv[0] << " --help'." << std::endl;
        exit(EXIT_FAILURE);
    }
}

std::shared_ptr<auth::AuthManager> getAuthManager(
    std::shared_ptr<Context> context)
{
    try {
        auto options = context->options();
        return std::make_shared<auth::MacaroonAuthManager>(context,
            options->getProviderHost().get(), options->getProviderPort(),
            !options->isInsecure(), options->getProviderTimeout());
    }
    catch (auth::AuthException &e) {
        std::cerr << "Authentication error: '" << e.what() << "'. Aborting..."
                  << std::endl;
        exit(EXIT_FAILURE);
    }
}

std::shared_ptr<messages::Configuration> getConfiguration(
    const std::string &sessionId,
    std::shared_ptr<auth::AuthManager> authManager,
    std::shared_ptr<Context> context)
{
    auto options = context->options();
    std::cout << "Connecting to provider '" << options->getProviderHost().get()
              << ":" << options->getProviderPort() << "' using session ID: '"
              << sessionId << "'..." << std::endl;

    try {
        auto communicator =
            handshake(sessionId, std::move(authManager), std::move(context));

        std::cout << "Getting configuration..." << std::endl;

        auto future = communicator->communicate<messages::Configuration>(
            messages::GetConfiguration{});
        auto configuration =
            communication::wait(future, options->getProviderTimeout());
        return std::make_shared<messages::Configuration>(
            std::move(configuration));
    }
    catch (const std::exception &e) {
        std::cerr << "Connection error: '" << e.what() << "'. Aborting..."
                  << std::endl;
        exit(EXIT_FAILURE);
    }
}

std::shared_ptr<communication::Communicator> getCommunicator(
    const std::string &sessionId,
    std::shared_ptr<auth::AuthManager> authManager,
    std::shared_ptr<Context> context)
{
    auto handshakeHandler = [](auto) { return std::error_code{}; };

    auto communicatorTuple = authManager->createCommunicator(
        context->options()->getCommunicatorThreadCount(), sessionId,
        ONECLIENT_VERSION, handshakeHandler);
    auto communicator = std::get<std::shared_ptr<communication::Communicator>>(
        communicatorTuple);

    communicator->setScheduler(context->scheduler());

    return communicator;
}

void unmountFuse(std::shared_ptr<options::Options> options)
{
    int status = 0, pid = fork();
    if (pid) {
        waitpid(pid, &status, 0);
    }
    else {
#if defined(__APPLE__)
        auto exec = "/usr/sbin/diskutil";
        execl(exec, exec, "unmount", options->getMountpoint().c_str(), NULL);
#else
        auto exec = "/bin/fusermount";
        execl(exec, exec, "-u", options->getMountpoint().c_str(), NULL);
#endif
    }
    if (status == 0) {
        std::cout << "Oneclient has been successfully unmounted." << std::endl;
    }
    exit(status);
}

int main(int argc, char *argv[])
{
    helpers::init();

    auto context = std::make_shared<Context>();
    auto options = getOptions(argc, argv);
    context->setOptions(options);

    if (options->getHelp()) {
        std::cout << options->formatHelp(argv[0]);
        return EXIT_SUCCESS;
    }
    if (options->getVersion()) {
        std::cout << "Oneclient: " << ONECLIENT_VERSION << "\n"
                  << "FUSE library: " << FUSE_MAJOR_VERSION << "."
                  << FUSE_MINOR_VERSION << std::endl;
        return EXIT_SUCCESS;
    }
    if (options->getUnmount()) {
        unmountFuse(options);
    }
    if (!options->getProviderHost()) {
        std::cerr << "the option 'host' is required but missing\n"
                  << "See '" << argv[0] << " --help'." << std::endl;
        return EXIT_FAILURE;
    }
    if (options->hasDeprecated()) {
        std::cout << options->formatDeprecated();
    }

    startLogging(argv[0], options);

    context->setScheduler(
        std::make_shared<Scheduler>(options->getSchedulerThreadCount()));

    auto authManager = getAuthManager(context);
    auto sessionId = generateSessionId();
    auto configuration = getConfiguration(sessionId, authManager, context);

    auto fuse_oper = fuseOperations();
    auto args = options->getFuseArgs(argv[0]);
    char *mountpoint;
    int multithreaded;
    int foreground;
    int res;

    res = fuse_parse_cmdline(&args, &mountpoint, &multithreaded, &foreground);
    if (res == -1)
        return EXIT_FAILURE;

    ScopeExit freeMountpoint{[=] { free(mountpoint); }};

    auto ch = fuse_mount(mountpoint, &args);
    if (!ch)
        return EXIT_FAILURE;

    ScopeExit unmountFuse{[=] { fuse_unmount(mountpoint, ch); }};

    res = fcntl(fuse_chan_fd(ch), F_SETFD, FD_CLOEXEC);
    if (res == -1)
        perror("WARNING: failed to set FD_CLOEXEC on fuse device");

    std::unique_ptr<fslogic::Composite> fsLogic;
    auto fuse =
        fuse_lowlevel_new(&args, &fuse_oper, sizeof(fuse_oper), &fsLogic);
    if (fuse == nullptr)
        return EXIT_FAILURE;

    ScopeExit destroyFuse{[=] { fuse_session_destroy(fuse); }, unmountFuse};

    fuse_set_signal_handlers(fuse);
    ScopeExit removeHandlers{[&] { fuse_remove_signal_handlers(fuse); }};

    fuse_session_add_chan(fuse, ch);
    ScopeExit removeChannel{[&] { fuse_session_remove_chan(ch); }};

    std::cout << "Oneclient has been successfully mounted in '"
              << options->getMountpoint().c_str() << "'." << std::endl;

    if (!foreground) {
        context->scheduler()->prepareForDaemonize();
        folly::SingletonVault::singleton()->destroyInstances();

        fuse_remove_signal_handlers(fuse);
        res = fuse_daemonize(foreground);

        if (res != -1)
            res = fuse_set_signal_handlers(fuse);

        if (res == -1)
            return EXIT_FAILURE;

        folly::SingletonVault::singleton()->reenableInstances();
        context->scheduler()->restartAfterDaemonize();
    }
    else {
        FLAGS_stderrthreshold = options->getDebug() ? 0 : 1;
    }

    if (startPerformanceMonitoring(options) != EXIT_SUCCESS)
        return EXIT_FAILURE;

    auto communicator = getCommunicator(sessionId, authManager, context);
    context->setCommunicator(communicator);
    communicator->connect();

    auto helpersCache = std::make_unique<cache::HelpersCache>(
        *communicator, *context->scheduler(), *options);

    const auto &rootUuid = configuration->rootUuid();
    fsLogic = std::make_unique<fslogic::Composite>(rootUuid, std::move(context),
        std::move(configuration), std::move(helpersCache),
        options->areFileReadEventsDisabled(), options->getMetadataCacheSize(),
        options->getProviderTimeout());

    res = multithreaded ? fuse_session_loop_mt(fuse) : fuse_session_loop(fuse);

    communicator->stop();
    return res == -1 ? EXIT_FAILURE : EXIT_SUCCESS;
}
<commit_msg>VFS-4116 Fixed metadata cache size initialization<commit_after>/**
 * @file main.cc
 * @author Rafal Slota
 * @copyright (C) 2016 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef linux
/* For pread()/pwrite()/utimensat() */
#define _XOPEN_SOURCE 700
#endif

#include "asio.hpp"
#include "auth/authException.h"
#include "auth/authManager.h"
#include "communication/exception.h"
#include "context.h"
#include "fsOperations.h"
#include "fslogic/composite.h"
#include "fuseOperations.h"
#include "helpers/init.h"
#include "logging.h"
#include "messages/configuration.h"
#include "messages/getConfiguration.h"
#include "messages/handshakeResponse.h"
#include "monitoring/monitoring.h"
#include "monitoring/monitoringConfiguration.h"
#include "options/options.h"
#include "scheduler.h"
#include "scopeExit.h"
#include "version.h"

#include <folly/Singleton.h>
#include <fuse/fuse_lowlevel.h>
#include <fuse/fuse_opt.h>

#include <sys/mount.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <exception>
#include <future>
#include <iostream>
#include <memory>
#include <random>
#include <regex>
#include <string>

#if !defined(NDEBUG)
/**
 * We have to expose FLAGS_vmodule variable here, as it is not declared
 * publicly by Glog library.
 */
DECLARE_string(vmodule);
#endif

using namespace one;
using namespace one::client;
using namespace one::monitoring;

void startLogging(
    const char *programName, std::shared_ptr<options::Options> options)
{
    try {
        boost::filesystem::create_directories(options->getLogDirPath());
    }
    catch (const boost::filesystem::filesystem_error &e) {
        std::cerr << "Failed to create log directory: '" << e.what()
                  << "'. Aborting..." << std::endl;
    }

    FLAGS_minloglevel = 0;
    FLAGS_logtostderr = false;
    FLAGS_stderrthreshold = options->getDebug() ? 0 : 2;
    FLAGS_log_dir = options->getLogDirPath().c_str();
    FLAGS_stop_logging_if_full_disk = true;
#if !defined(NDEBUG)
    FLAGS_v = options->getVerboseLogLevel();
    FLAGS_vmodule = options->getVerboseLogFilter()
        ? options->getVerboseLogFilter().get()
        : "*";
#endif
    google::InitGoogleLogging(programName);

    if (options->getProviderHost())
        LOG(INFO) << "Connecting to Oneprovider: "
                  << options->getProviderHost().get();
    LOG(INFO) << "Forced direct io: " << options->isDirectIOForced();
    LOG(INFO) << "Forced proxy io: " << options->isDirectIOForced();
    LOG(INFO) << "Verify service certificate: " << options->isInsecure();
    LOG(INFO) << "File read events disabled: "
              << options->areFileReadEventsDisabled();
    LOG(INFO) << "Is IO buffered: " << options->isIOBuffered();
    LOG(INFO) << "Oneprovider connection timeout [s]: "
              << options->getProviderTimeout().count();
    LOG(INFO) << "Is monitoring enabled: " << options->isMonitoringEnabled();
    if (options->getMonitoringType())
        LOG(INFO) << "Monitoring type: " << options->getMonitoringType().get();
    LOG(INFO) << "Is monitoring level basic: "
              << options->isMonitoringLevelBasic();
    LOG(INFO) << "Is monitoring level full: "
              << options->isMonitoringLevelFull();
    if (options->getMonitoringGraphiteUrl())
        LOG(INFO) << "Graphite URL: "
                  << options->getMonitoringGraphiteUrl().get();
    if (options->getMonitoringGraphiteNamespacePrefix())
        LOG(INFO) << "Graphite URL: "
                  << options->getMonitoringGraphiteNamespacePrefix().get();
    LOG(INFO) << "Mountpoint: " << options->getMountpoint();
}

int startPerformanceMonitoring(std::shared_ptr<options::Options> options)
{
    if (options->isMonitoringEnabled()) {
        if (options->getMonitoringType().get() == "graphite") {
            if (!options->getMonitoringGraphiteUrl()) {
                std::cerr << "Graphite URL not specified - use option "
                             "--graphite-url."
                          << std::endl;
                return EXIT_FAILURE;
            }

            auto config = std::make_shared<GraphiteMonitoringConfiguration>();
            try {
                config->fromGraphiteURL(
                    options->getMonitoringGraphiteUrl().get());
            }
            catch (std::invalid_argument &e) {
                std::cerr << "Graphite configuration error: " << e.what()
                          << std::endl;
            }
            if (options->getMonitoringGraphiteNamespacePrefix()) {
                config->namespacePrefix =
                    options->getMonitoringGraphiteNamespacePrefix().get();
            }
            config->reportingPeriod = options->getMonitoringReportingPeriod();
            if (options->isMonitoringLevelFull()) {
                config->reportingLevel = cppmetrics::core::ReportingLevel::Full;
            }
            else {
                config->reportingLevel =
                    cppmetrics::core::ReportingLevel::Basic;
            }

            LOG(INFO) << "Starting Graphite performance monitoring to host: "
                      << config->graphiteHostname;

            // Configure and start monitoring threads
            helpers::configureMonitoring(config, true);

            // Initialize the command line option counter values
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.scheduler_thread_count",
                options->getSchedulerThreadCount());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.communicator_thread_count",
                options->getCommunicatorThreadCount());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.storage_helper_thread_count",
                options->getStorageHelperThreadCount());
            ONE_METRIC_COUNTER_SET("comp.oneclient.mod.options.buffer_"
                                   "scheduler_helper_thread_count",
                options->getBufferSchedulerThreadCount());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.read_buffer_min_size",
                options->getReadBufferMinSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.read_buffer_max_size",
                options->getReadBufferMaxSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.write_buffer_min_size",
                options->getWriteBufferMinSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.write_buffer_max_size",
                options->getWriteBufferMaxSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.read_buffer_prefetch_duration",
                options->getReadBufferPrefetchDuration().count());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.write_buffer_flush_delay",
                options->getWriteBufferFlushDelay().count());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.metadata_cache_size",
                options->getMetadataCacheSize());
            ONE_METRIC_COUNTER_SET(
                "comp.oneclient.mod.options.monitoring_reporting_period",
                options->getMonitoringReportingPeriod());
        }
        else {
            std::cerr << "Unsupported performance monitoring reporter: "
                      << options->getMonitoringType().get() << std::endl;
            return EXIT_FAILURE;
        }
    }

    return EXIT_SUCCESS;
}

std::string generateSessionId()
{
    std::random_device rd;
    std::default_random_engine randomEngine{rd()};
    std::uniform_int_distribution<unsigned long long> sessionIdDistribution;
    return std::to_string(sessionIdDistribution(randomEngine));
}

std::shared_ptr<communication::Communicator> handshake(
    const std::string &sessionId,
    std::shared_ptr<auth::AuthManager> authManager,
    std::shared_ptr<Context> context)
{
    auto handshakeHandler = [&](messages::HandshakeResponse msg) {
        if (msg.isMacaroonError()) {
            authManager->cleanup();
        }
        return msg.status();
    };

    auto testCommunicatorTuple = authManager->createCommunicator(
        1, sessionId, ONECLIENT_VERSION, handshakeHandler);
    auto testCommunicator =
        std::get<std::shared_ptr<communication::Communicator>>(
            testCommunicatorTuple);

    testCommunicator->setScheduler(context->scheduler());
    testCommunicator->connect();
    communication::wait(
        std::get<folly::Future<folly::Unit>>(testCommunicatorTuple),
        context->options()->getProviderTimeout());

    return testCommunicator;
}

std::shared_ptr<options::Options> getOptions(int argc, char *argv[])
{
    auto options = std::make_shared<options::Options>();
    try {
        options->parse(argc, argv);
        return options;
    }
    catch (const boost::program_options::error &e) {
        std::cerr << std::regex_replace(e.what(), std::regex("--"), "") << "\n"
                  << "See '" << argv[0] << " --help'." << std::endl;
        exit(EXIT_FAILURE);
    }
}

std::shared_ptr<auth::AuthManager> getAuthManager(
    std::shared_ptr<Context> context)
{
    try {
        auto options = context->options();
        return std::make_shared<auth::MacaroonAuthManager>(context,
            options->getProviderHost().get(), options->getProviderPort(),
            !options->isInsecure(), options->getProviderTimeout());
    }
    catch (auth::AuthException &e) {
        std::cerr << "Authentication error: '" << e.what() << "'. Aborting..."
                  << std::endl;
        exit(EXIT_FAILURE);
    }
}

std::shared_ptr<messages::Configuration> getConfiguration(
    const std::string &sessionId,
    std::shared_ptr<auth::AuthManager> authManager,
    std::shared_ptr<Context> context)
{
    auto options = context->options();
    std::cout << "Connecting to provider '" << options->getProviderHost().get()
              << ":" << options->getProviderPort() << "' using session ID: '"
              << sessionId << "'..." << std::endl;

    try {
        auto communicator =
            handshake(sessionId, std::move(authManager), std::move(context));

        std::cout << "Getting configuration..." << std::endl;

        auto future = communicator->communicate<messages::Configuration>(
            messages::GetConfiguration{});
        auto configuration =
            communication::wait(future, options->getProviderTimeout());
        return std::make_shared<messages::Configuration>(
            std::move(configuration));
    }
    catch (const std::exception &e) {
        std::cerr << "Connection error: '" << e.what() << "'. Aborting..."
                  << std::endl;
        exit(EXIT_FAILURE);
    }
}

std::shared_ptr<communication::Communicator> getCommunicator(
    const std::string &sessionId,
    std::shared_ptr<auth::AuthManager> authManager,
    std::shared_ptr<Context> context)
{
    auto handshakeHandler = [](auto) { return std::error_code{}; };

    auto communicatorTuple = authManager->createCommunicator(
        context->options()->getCommunicatorThreadCount(), sessionId,
        ONECLIENT_VERSION, handshakeHandler);
    auto communicator = std::get<std::shared_ptr<communication::Communicator>>(
        communicatorTuple);

    communicator->setScheduler(context->scheduler());

    return communicator;
}

void unmountFuse(std::shared_ptr<options::Options> options)
{
    int status = 0, pid = fork();
    if (pid) {
        waitpid(pid, &status, 0);
    }
    else {
#if defined(__APPLE__)
        auto exec = "/usr/sbin/diskutil";
        execl(exec, exec, "unmount", options->getMountpoint().c_str(), NULL);
#else
        auto exec = "/bin/fusermount";
        execl(exec, exec, "-u", options->getMountpoint().c_str(), NULL);
#endif
    }
    if (status == 0) {
        std::cout << "Oneclient has been successfully unmounted." << std::endl;
    }
    exit(status);
}

int main(int argc, char *argv[])
{
    helpers::init();

    auto context = std::make_shared<Context>();
    auto options = getOptions(argc, argv);
    context->setOptions(options);

    if (options->getHelp()) {
        std::cout << options->formatHelp(argv[0]);
        return EXIT_SUCCESS;
    }
    if (options->getVersion()) {
        std::cout << "Oneclient: " << ONECLIENT_VERSION << "\n"
                  << "FUSE library: " << FUSE_MAJOR_VERSION << "."
                  << FUSE_MINOR_VERSION << std::endl;
        return EXIT_SUCCESS;
    }
    if (options->getUnmount()) {
        unmountFuse(options);
    }
    if (!options->getProviderHost()) {
        std::cerr << "the option 'host' is required but missing\n"
                  << "See '" << argv[0] << " --help'." << std::endl;
        return EXIT_FAILURE;
    }
    if (options->hasDeprecated()) {
        std::cout << options->formatDeprecated();
    }

    startLogging(argv[0], options);

    context->setScheduler(
        std::make_shared<Scheduler>(options->getSchedulerThreadCount()));

    auto authManager = getAuthManager(context);
    auto sessionId = generateSessionId();
    auto configuration = getConfiguration(sessionId, authManager, context);

    auto fuse_oper = fuseOperations();
    auto args = options->getFuseArgs(argv[0]);
    char *mountpoint;
    int multithreaded;
    int foreground;
    int res;

    res = fuse_parse_cmdline(&args, &mountpoint, &multithreaded, &foreground);
    if (res == -1)
        return EXIT_FAILURE;

    ScopeExit freeMountpoint{[=] { free(mountpoint); }};

    auto ch = fuse_mount(mountpoint, &args);
    if (!ch)
        return EXIT_FAILURE;

    ScopeExit unmountFuse{[=] { fuse_unmount(mountpoint, ch); }};

    res = fcntl(fuse_chan_fd(ch), F_SETFD, FD_CLOEXEC);
    if (res == -1)
        perror("WARNING: failed to set FD_CLOEXEC on fuse device");

    std::unique_ptr<fslogic::Composite> fsLogic;
    auto fuse =
        fuse_lowlevel_new(&args, &fuse_oper, sizeof(fuse_oper), &fsLogic);
    if (fuse == nullptr)
        return EXIT_FAILURE;

    ScopeExit destroyFuse{[=] { fuse_session_destroy(fuse); }, unmountFuse};

    fuse_set_signal_handlers(fuse);
    ScopeExit removeHandlers{[&] { fuse_remove_signal_handlers(fuse); }};

    fuse_session_add_chan(fuse, ch);
    ScopeExit removeChannel{[&] { fuse_session_remove_chan(ch); }};

    std::cout << "Oneclient has been successfully mounted in '"
              << options->getMountpoint().c_str() << "'." << std::endl;

    if (!foreground) {
        context->scheduler()->prepareForDaemonize();
        folly::SingletonVault::singleton()->destroyInstances();

        fuse_remove_signal_handlers(fuse);
        res = fuse_daemonize(foreground);

        if (res != -1)
            res = fuse_set_signal_handlers(fuse);

        if (res == -1)
            return EXIT_FAILURE;

        folly::SingletonVault::singleton()->reenableInstances();
        context->scheduler()->restartAfterDaemonize();
    }
    else {
        FLAGS_stderrthreshold = options->getDebug() ? 0 : 1;
    }

    if (startPerformanceMonitoring(options) != EXIT_SUCCESS)
        return EXIT_FAILURE;

    auto communicator = getCommunicator(sessionId, authManager, context);
    context->setCommunicator(communicator);
    communicator->connect();

    auto helpersCache = std::make_unique<cache::HelpersCache>(
        *communicator, *context->scheduler(), *options);

    const auto &rootUuid = configuration->rootUuid();
    fsLogic = std::make_unique<fslogic::Composite>(rootUuid, std::move(context),
        std::move(configuration), std::move(helpersCache),
        options->getMetadataCacheSize(), options->areFileReadEventsDisabled(),
        options->getProviderTimeout());

    res = multithreaded ? fuse_session_loop_mt(fuse) : fuse_session_loop(fuse);

    communicator->stop();
    return res == -1 ? EXIT_FAILURE : EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "NTClient.h"

int main(int argc, char** argv) {
	return 0;
}<commit_msg>Makefile updates<commit_after>#include <iostream>
#include "NTClient.h"

int main(int argc, char** argv) {
	NTClient nclient = NTClient("asd4wderg", "123asd123"); // Throw-away account
	return 0;
}<|endoftext|>


<commit_before>//
// Copyright (C) Michael Yang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full
// license information.
//

#include "config.h"
#include "funny_pics.h"
#include "girl_pics.h"
#include "joke.h"
#include "message.h"
#include "quote.h"
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/program_options.hpp>
#include <csignal>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>

enum class bot_command : std::uint8_t {
    quote,
    joke,
    funny_pics,
    girl_pics,
    about
};

using namespace std::chrono_literals;
using bot_command_queue =
    boost::lockfree::spsc_queue<bot_command, boost::lockfree::capacity<100>>;

static std::atomic<bool> keep_running(true);

static std::unordered_map<std::int64_t, std::shared_ptr<bot_command_queue>>
    message_queue_map;

static std::mutex map_mutex;

static void signal_handler(int signal) { keep_running = false; }

static void consumer(std::int64_t chat_id,
                     std::shared_ptr<bot_command_queue> queue) {
    spdlog::get("logger")->info("ℹ thread is created for 💬<{}>",
                                chat_id);

    std::chrono::time_point<std::chrono::steady_clock> start;

    for (;;) {
        if (!queue->consume_all([&chat_id, &start](bot_command command) {
                switch (command) {
                case bot_command::quote: {
                    const auto quote = ohmyarch::get_quote();
                    if (quote)
                        ohmyarch::send_message(chat_id, quote->text() + " - " +
                                                            quote->author());

                    break;
                }
                case bot_command::joke: {
                    const auto joke = ohmyarch::get_joke();
                    if (joke)
                        ohmyarch::send_message(chat_id, joke.value());

                    break;
                }
                case bot_command::funny_pics: {
                    const auto funny_pics = ohmyarch::get_funny_pics();
                    if (funny_pics) {
                        for (const auto &pic_uri : funny_pics.value())
                            if (boost::ends_with(pic_uri, "gif"))
                                ohmyarch::send_document(chat_id, pic_uri);
                            else
                                ohmyarch::send_message(chat_id, pic_uri);
                    }

                    break;
                }
                case bot_command::girl_pics: {
                    const auto girl_pics = ohmyarch::get_girl_pics();
                    if (girl_pics) {
                        for (const auto &pic_uri : girl_pics.value())
                            if (boost::ends_with(pic_uri, "gif"))
                                ohmyarch::send_document(chat_id, pic_uri);
                            else
                                ohmyarch::send_message(chat_id, pic_uri);
                    }

                    break;
                }
                case bot_command::about: {
                    ohmyarch::send_message(
                        chat_id, "https://github.com/ohmyarch/ohmyarch_bot");

                    break;
                }
                }

                start = std::chrono::steady_clock::now();
            })) {
            if (std::chrono::duration<double>(std::chrono::steady_clock::now() -
                                              start)
                    .count() > 10.0) {
                break;
            } else {
                std::this_thread::yield();
                std::this_thread::sleep_for(100ms);
            }
        }
    }

    {
        std::lock_guard<std::mutex> guard(map_mutex);
        message_queue_map.erase(chat_id);
    }

    spdlog::get("logger")->info("ℹ thread is destroyed for 💬<{}>",
                                chat_id);
}

int main(int argc, char *argv[]) {
    std::string path_to_config;

    boost::program_options::options_description options("options");
    options.add_options()(
        "config", boost::program_options::value<std::string>(&path_to_config)
                      ->value_name("/path/to/config"),
        "specify a path to a custom config file")("help,h",
                                                  "print this text and exit");

    boost::program_options::variables_map map;

    try {
        boost::program_options::store(
            boost::program_options::parse_command_line(argc, argv, options),
            map);
    } catch (const boost::program_options::error &error) {
        std::cerr << "❌ " << error.what() << std::endl;

        return 1;
    }

    if (map.count("help") || map.empty()) {
        std::cout << options;

        return 0;
    }

    boost::program_options::notify(map);

    if (path_to_config.empty()) {
        std::cerr << "❌ option '--config' is missing" << std::endl;

        return 1;
    }

    std::ifstream config_file(path_to_config);
    if (!config_file) {
        std::cerr << "❌ config file opening failed" << std::endl;

        return 1;
    }

    nlohmann::json json;

    try {
        json << config_file;

        ohmyarch::api_uri =
            "https://api.telegram.org/bot" +
            json.at("token").get_ref<const nlohmann::json::string_t &>() + '/';
    } catch (const std::exception &error) {
        std::cerr << "❌ json: " << error.what() << std::endl;

        return 1;
    }

    const auto iterator_http_proxy = json.find("http_proxy");
    if (iterator_http_proxy != json.end())
        try {
            ohmyarch::client_config.set_proxy(web::web_proxy(
                iterator_http_proxy.value()
                    .get_ref<const nlohmann::json::string_t &>()));
        } catch (const std::exception &error) {
            std::cerr << "❌ set_proxy: " << error.what() << std::endl;

            return 1;
        }

    spdlog::set_async_mode(8192);

    try {
        std::vector<spdlog::sink_ptr> sinks{
            std::make_shared<spdlog::sinks::ansicolor_sink>(
                std::make_shared<spdlog::sinks::stdout_sink_mt>()),
            std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
                json.at("log_path"), "txt", 1024 * 1024 * 5, 0)};
        auto combined_logger = std::make_shared<spdlog::logger>(
            "logger", sinks.begin(), sinks.end());
        combined_logger->flush_on(spdlog::level::err);

        spdlog::register_logger(combined_logger);
    } catch (const std::exception &error) {
        std::cout << "❌ log failed: " << error.what() << std::endl;

        return 1;
    }

    std::signal(SIGINT, signal_handler);

    const auto bot_username = ohmyarch::get_me();
    if (!bot_username)
        return 1;

    const std::string &username = bot_username.value();

    const std::string quote_command = "/quote@" + username;
    const std::string joke_command = "/joke@" + username;
    const std::string funny_pics_command = "/funny_pics@" + username;
    const std::string girl_pics_command = "/girl_pics@" + username;
    const std::string about_command = "/about@" + username;

    spdlog::get("logger")->info("🤖 @{} is running 😉", username);
    spdlog::get("logger")->flush();

    while (keep_running) {
        const auto updates = ohmyarch::get_updates();
        if (updates)
            for (const auto &update : updates.value()) {
                const auto &message = update.message();
                if (message) {
                    const auto &entities = message->entities();
                    if (entities) {
                        const std::int64_t chat_id = message->chat().id();

                        std::u16string text =
                            utility::conversions::utf8_to_utf16(
                                message->text().value());

                        for (const auto &entity : entities.value())
                            if (entity.type() == "bot_command") {
                                bot_command command;

                                const std::string command_text =
                                    utility::conversions::utf16_to_utf8(
                                        text.substr(entity.offset(),
                                                    entity.length()));
                                if (command_text == "/quote" ||
                                    command_text == quote_command)
                                    command = bot_command::quote;
                                else if (command_text == "/joke" ||
                                         command_text == joke_command)
                                    command = bot_command::joke;
                                else if (command_text == "/funny_pics" ||
                                         command_text == funny_pics_command)
                                    command = bot_command::funny_pics;
                                else if (command_text == "/girl_pics" ||
                                         command_text == girl_pics_command)
                                    command = bot_command::girl_pics;
                                else if (command_text == "/about" ||
                                         command_text == about_command)
                                    command = bot_command::about;

                                std::unique_lock<std::mutex> lock(map_mutex);
                                const auto pair = message_queue_map.emplace(
                                    chat_id,
                                    std::make_shared<bot_command_queue>());
                                lock.unlock();

                                auto &queue = pair.first->second;
                                queue->push(command);
                                if (pair.second) {
                                    std::thread consumer_thread(consumer,
                                                                chat_id, queue);
                                    consumer_thread.detach();
                                }
                            }
                    }
                }
            }
    }

    spdlog::get("logger")->info("🤖 @{} stopped 😴", username);
}
<commit_msg>🐛 Fix a bug<commit_after>//
// Copyright (C) Michael Yang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full
// license information.
//

#include "config.h"
#include "funny_pics.h"
#include "girl_pics.h"
#include "joke.h"
#include "message.h"
#include "quote.h"
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/program_options.hpp>
#include <csignal>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>

enum class bot_command : std::uint8_t {
    quote,
    joke,
    funny_pics,
    girl_pics,
    about
};

using namespace std::chrono_literals;
using bot_command_queue =
    boost::lockfree::spsc_queue<bot_command, boost::lockfree::capacity<100>>;

static std::atomic<bool> keep_running(true);

static std::unordered_map<std::int64_t, std::shared_ptr<bot_command_queue>>
    message_queue_map;

static std::mutex map_mutex;

static void signal_handler(int signal) { keep_running = false; }

static void consumer(std::int64_t chat_id,
                     std::shared_ptr<bot_command_queue> queue) {
    spdlog::get("logger")->info("ℹ thread is created for 💬<{}>",
                                chat_id);

    std::chrono::time_point<std::chrono::steady_clock> start;

    for (;;) {
        if (!queue->consume_all([&chat_id, &start](bot_command command) {
                switch (command) {
                case bot_command::quote: {
                    const auto quote = ohmyarch::get_quote();
                    if (quote)
                        ohmyarch::send_message(chat_id, quote->text() + " - " +
                                                            quote->author());

                    break;
                }
                case bot_command::joke: {
                    const auto joke = ohmyarch::get_joke();
                    if (joke)
                        ohmyarch::send_message(chat_id, joke.value());

                    break;
                }
                case bot_command::funny_pics: {
                    const auto funny_pics = ohmyarch::get_funny_pics();
                    if (funny_pics) {
                        for (const auto &pic_uri : funny_pics.value())
                            if (boost::ends_with(pic_uri, "gif"))
                                ohmyarch::send_document(chat_id, pic_uri);
                            else
                                ohmyarch::send_message(chat_id, pic_uri);
                    }

                    break;
                }
                case bot_command::girl_pics: {
                    const auto girl_pics = ohmyarch::get_girl_pics();
                    if (girl_pics) {
                        for (const auto &pic_uri : girl_pics.value())
                            if (boost::ends_with(pic_uri, "gif"))
                                ohmyarch::send_document(chat_id, pic_uri);
                            else
                                ohmyarch::send_message(chat_id, pic_uri);
                    }

                    break;
                }
                case bot_command::about: {
                    ohmyarch::send_message(
                        chat_id, "https://github.com/ohmyarch/ohmyarch_bot");

                    break;
                }
                }

                start = std::chrono::steady_clock::now();
            })) {
            if (std::chrono::duration<double>(std::chrono::steady_clock::now() -
                                              start)
                    .count() > 10.0) {
                break;
            } else {
                std::this_thread::yield();
                std::this_thread::sleep_for(100ms);
            }
        }
    }

    {
        std::lock_guard<std::mutex> guard(map_mutex);
        message_queue_map.erase(chat_id);
    }

    spdlog::get("logger")->info("ℹ thread is destroyed for 💬<{}>",
                                chat_id);
}

int main(int argc, char *argv[]) {
    std::string path_to_config;

    boost::program_options::options_description options("options");
    options.add_options()(
        "config", boost::program_options::value<std::string>(&path_to_config)
                      ->value_name("/path/to/config"),
        "specify a path to a custom config file")("help,h",
                                                  "print this text and exit");

    boost::program_options::variables_map map;

    try {
        boost::program_options::store(
            boost::program_options::parse_command_line(argc, argv, options),
            map);
    } catch (const boost::program_options::error &error) {
        std::cerr << "❌ " << error.what() << std::endl;

        return 1;
    }

    if (map.count("help") || map.empty()) {
        std::cout << options;

        return 0;
    }

    boost::program_options::notify(map);

    if (path_to_config.empty()) {
        std::cerr << "❌ option '--config' is missing" << std::endl;

        return 1;
    }

    std::ifstream config_file(path_to_config);
    if (!config_file) {
        std::cerr << "❌ config file opening failed" << std::endl;

        return 1;
    }

    nlohmann::json json;

    try {
        json << config_file;

        ohmyarch::api_uri =
            "https://api.telegram.org/bot" +
            json.at("token").get_ref<const nlohmann::json::string_t &>() + '/';
    } catch (const std::exception &error) {
        std::cerr << "❌ json: " << error.what() << std::endl;

        return 1;
    }

    const auto iterator_http_proxy = json.find("http_proxy");
    if (iterator_http_proxy != json.end())
        try {
            ohmyarch::client_config.set_proxy(web::web_proxy(
                iterator_http_proxy.value()
                    .get_ref<const nlohmann::json::string_t &>()));
        } catch (const std::exception &error) {
            std::cerr << "❌ set_proxy: " << error.what() << std::endl;

            return 1;
        }

    spdlog::set_async_mode(8192);

    try {
        std::vector<spdlog::sink_ptr> sinks{
            std::make_shared<spdlog::sinks::ansicolor_sink>(
                std::make_shared<spdlog::sinks::stdout_sink_mt>()),
            std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
                json.at("log_path"), "txt", 1024 * 1024 * 5, 0)};
        auto combined_logger = std::make_shared<spdlog::logger>(
            "logger", sinks.begin(), sinks.end());
        combined_logger->flush_on(spdlog::level::err);

        spdlog::register_logger(combined_logger);
    } catch (const std::exception &error) {
        std::cout << "❌ log failed: " << error.what() << std::endl;

        return 1;
    }

    std::signal(SIGINT, signal_handler);

    const auto bot_username = ohmyarch::get_me();
    if (!bot_username)
        return 1;

    const std::string &username = bot_username.value();

    const std::string quote_command = "/quote@" + username;
    const std::string joke_command = "/joke@" + username;
    const std::string funny_pics_command = "/funny_pics@" + username;
    const std::string girl_pics_command = "/girl_pics@" + username;
    const std::string about_command = "/about@" + username;

    spdlog::get("logger")->info("🤖 @{} is running 😉", username);
    spdlog::get("logger")->flush();

    while (keep_running) {
        const auto updates = ohmyarch::get_updates();
        if (updates)
            for (const auto &update : updates.value()) {
                const auto &message = update.message();
                if (message) {
                    const auto &entities = message->entities();
                    if (entities) {
                        const std::int64_t chat_id = message->chat().id();

                        std::u16string text =
                            utility::conversions::utf8_to_utf16(
                                message->text().value());

                        for (const auto &entity : entities.value())
                            if (entity.type() == "bot_command") {
                                std::experimental::optional<bot_command>
                                    command;

                                const std::string command_text =
                                    utility::conversions::utf16_to_utf8(
                                        text.substr(entity.offset(),
                                                    entity.length()));
                                if (command_text == "/quote" ||
                                    command_text == quote_command)
                                    command = bot_command::quote;
                                else if (command_text == "/joke" ||
                                         command_text == joke_command)
                                    command = bot_command::joke;
                                else if (command_text == "/funny_pics" ||
                                         command_text == funny_pics_command)
                                    command = bot_command::funny_pics;
                                else if (command_text == "/girl_pics" ||
                                         command_text == girl_pics_command)
                                    command = bot_command::girl_pics;
                                else if (command_text == "/about" ||
                                         command_text == about_command)
                                    command = bot_command::about;

                                if (command) {
                                    std::unique_lock<std::mutex> lock(
                                        map_mutex);
                                    const auto pair = message_queue_map.emplace(
                                        chat_id,
                                        std::make_shared<bot_command_queue>());
                                    lock.unlock();

                                    auto &queue = pair.first->second;
                                    queue->push(command.value());
                                    if (pair.second) {
                                        std::thread consumer_thread(
                                            consumer, chat_id, queue);
                                        consumer_thread.detach();
                                    }
                                }
                            }
                    }
                }
            }
    }

    spdlog::get("logger")->info("🤖 @{} stopped 😴", username);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011, Paul Tagliamonte <tag@pault.ag>
 *
 * 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 "NcursesTerminal.hh"
#include "Shibuya.hh"
#include "Exceptions.hh"
#include "BGFile.hh"

#include <iostream>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

NcursesTerminal * toDump = NULL;

void sighandle ( int signo ) {
	switch ( signo ) {
		case SIGUSR1:
			if ( ! toDump )
				return;

			for ( int iy = 0; iy < toDump->get_height(); ++iy ) {
				for ( int ix = 0; ix < toDump->get_width(); ++ix ) {
					int offset = ( toDump->get_width() * iy ) + ix;
					std::cerr << toDump->chars[offset].ch;
				}
				std::cerr << std::endl;
			}
			break;
		case SIGWINCH:
			/* Something's wrong with this... */
			uninit_screen();
			init_screen();
			update_screen();
			/* XXX: Handle background re-center */
			break;
		case SIGTERM:
			uninit_screen();
			exit(0);
			break;
		case SIGINT:
			toDump->sigint(); /* Fixme */
			break;
		default:
			break;
	}
}

int main ( int argc, char ** argv ) {
	set_clog();    // XXX: This is ugly
	init_screen();

	NcursesTerminal nt( 80, 25, 3, 2 );
	nt.fork("/bin/bash");
	toDump          = &nt;

	signal( SIGUSR1, sighandle );
	signal( SIGTERM, sighandle );
	signal( SIGINT,  sighandle );
	signal( SIGWINCH, sighandle );

	try {
		while ( true ) {
			nt.poke();
			if ( nt.render() )
				update_screen();
			timeout(0);
			int ch = getch();

			if ( ch != ERR ) {
				if ( ch == 0x05 ) {
					/* 0x05 is ENQ - let's use it for our special sequence. */
					nt.resize( 100, 30 );
				} else {
					nt.type(ch);
				}
			} else {
				usleep( 2000 );
			}
		}
	} catch ( DeadChildException * e ) {
		delete e;
	}
	uninit_screen();
}
<commit_msg>ignoring ncurses kruft<commit_after>/*
 * Copyright (C) 2011, Paul Tagliamonte <tag@pault.ag>
 *
 * 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 "NcursesTerminal.hh"
#include "Shibuya.hh"
#include "Exceptions.hh"
#include "BGFile.hh"

#include <iostream>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

NcursesTerminal * toDump = NULL;

void sighandle ( int signo ) {
	switch ( signo ) {
		case SIGUSR1:
			if ( ! toDump )
				return;

			for ( int iy = 0; iy < toDump->get_height(); ++iy ) {
				for ( int ix = 0; ix < toDump->get_width(); ++ix ) {
					int offset = ( toDump->get_width() * iy ) + ix;
					std::cerr << toDump->chars[offset].ch;
				}
				std::cerr << std::endl;
			}
			break;
		case SIGWINCH:
			/* Something's wrong with this... */
			uninit_screen();
			init_screen();
			update_screen();
			/* XXX: Handle background re-center */
			break;
		case SIGTERM:
			uninit_screen();
			exit(0);
			break;
		case SIGINT:
			toDump->sigint(); /* Fixme */
			break;
		default:
			break;
	}
}

int main ( int argc, char ** argv ) {
	set_clog();    // XXX: This is ugly
	init_screen();

	NcursesTerminal nt( 80, 25, 3, 2 );
	nt.fork("/bin/bash");
	toDump          = &nt;

	signal( SIGUSR1, sighandle );
	signal( SIGTERM, sighandle );
	signal( SIGINT,  sighandle );
	signal( SIGWINCH, sighandle );

	try {
		while ( true ) {
			nt.poke();
			if ( nt.render() )
				update_screen();
			timeout(0);
			int ch = getch();

			if ( ch != ERR ) {
				if ( ch == 0x05 ) {
					/* 0x05 is ENQ - let's use it for our special sequence. */
					nt.resize( 100, 30 );
				} else if ( ch < 128 ) {
					nt.type(ch);
				}
			} else {
				usleep( 2000 );
			}
		}
	} catch ( DeadChildException * e ) {
		delete e;
	}
	uninit_screen();
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include <iostream>
#include <vector>

#include "yaml-cpp/yaml.h"
#include "scene/filters.h"
#include "data/tileData.h"
#include "scene/sceneLoader.h"
#include "scene/scene.h"
#include "scene/styleContext.h"

using namespace Tangram;
using YAML::Node;

using Context = StyleContext;

Context ctx;

Feature civic, bmw1, bike;

Filter load(const std::string& filterYaml) {
    Scene scene;
    YAML::Node node = YAML::Load(filterYaml);
    return SceneLoader::generateFilter(node["filter"], scene);
}

void init() {

    civic.props.clear();
    civic.props.add("name", "civic");
    civic.props.add("brand", "honda");
    civic.props.add("wheel",  4);
    civic.props.add("drive", "fwd");
    civic.props.add("type", "car");

    bmw1.props.clear();
    bmw1.props.add("name", "bmw320i");
    bmw1.props.add("brand", "bmw");
    bmw1.props.add("check", "false");
    bmw1.props.add("series", "3");
    bmw1.props.add("wheel", 4);
    bmw1.props.add("drive", "all");
    bmw1.props.add("type", "car");

    bike.props.clear();
    bike.props.add("name", "cb1100");
    bike.props.add("brand", "honda");
    bike.props.add("wheel", 2);
    bike.props.add("type", "bike");
    bike.props.add("series", "CB");
    bike.props.add("check", "available");

    ctx.setGlobal("$geometry", Value(1));
    ctx.setGlobal("$zoom", Value("false"));
}

//1. basic predicate
TEST_CASE( "yaml-filter-tests: basic predicate test", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { series: !!str 3}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//2. predicate with valueList
TEST_CASE( "yaml-filter-tests: predicate with valueList", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { name : [civic, bmw320i] }");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//3. range min
TEST_CASE( "yaml-filter-tests: range min", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {wheel : {min : 3}}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//4. range max
TEST_CASE( "yaml-filter-tests: range max", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {wheel : {max : 2}}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//5. range min max
TEST_CASE( "yaml-filter-tests: range min max", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {wheel : {min : 2, max : 5}}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

//6. any
TEST_CASE( "yaml-filter-tests: any", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {any : [{name : civic}, {name : bmw320i}]}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//7. all
TEST_CASE( "yaml-filter-tests: all", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {all : [ {name : civic}, {brand : honda}, {wheel: 4} ] }");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//8. none
TEST_CASE( "yaml-filter-tests: none", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {none : [{name : civic}, {name : bmw320i}]}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

//9. not
TEST_CASE( "yaml-filter-tests: not", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {not : {name : civic}}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

//10. basic predicate with context
TEST_CASE( "yaml-filter-tests: context filter", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {$geometry : 1}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: bogus filter", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {max: bogus}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean true filter as existence check", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { drive : true }");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean false filter as existence check", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { drive : false}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean true filter as existence check for keyword", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {$geometry : 1}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean false filter as existence check for keyword", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {$zoom : false}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}
<commit_msg>Add a test case for filtering with large integer values<commit_after>#include "catch.hpp"

#include <iostream>
#include <vector>

#include "yaml-cpp/yaml.h"
#include "scene/filters.h"
#include "data/tileData.h"
#include "scene/sceneLoader.h"
#include "scene/scene.h"
#include "scene/styleContext.h"

using namespace Tangram;
using YAML::Node;

using Context = StyleContext;

Context ctx;

Feature civic, bmw1, bike;

Filter load(const std::string& filterYaml) {
    Scene scene;
    YAML::Node node = YAML::Load(filterYaml);
    return SceneLoader::generateFilter(node["filter"], scene);
}

void init() {

    civic.props.clear();
    civic.props.add("name", "civic");
    civic.props.add("brand", "honda");
    civic.props.add("wheel",  4);
    civic.props.add("drive", "fwd");
    civic.props.add("type", "car");

    bmw1.props.clear();
    bmw1.props.add("name", "bmw320i");
    bmw1.props.add("brand", "bmw");
    bmw1.props.add("check", "false");
    bmw1.props.add("series", "3");
    bmw1.props.add("wheel", 4);
    bmw1.props.add("drive", "all");
    bmw1.props.add("type", "car");
    bmw1.props.add("serial", 4398046511104); // 2^42

    bike.props.clear();
    bike.props.add("name", "cb1100");
    bike.props.add("brand", "honda");
    bike.props.add("wheel", 2);
    bike.props.add("type", "bike");
    bike.props.add("series", "CB");
    bike.props.add("check", "available");
    bike.props.add("serial", 4398046511105); // 2^42 + 1

    ctx.setGlobal("$geometry", Value(1));
    ctx.setGlobal("$zoom", Value("false"));
}

//1. basic predicate
TEST_CASE( "yaml-filter-tests: basic predicate test", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { series: !!str 3}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//2. predicate with valueList
TEST_CASE( "yaml-filter-tests: predicate with valueList", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { name : [civic, bmw320i] }");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//3. range min
TEST_CASE( "yaml-filter-tests: range min", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {wheel : {min : 3}}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//4. range max
TEST_CASE( "yaml-filter-tests: range max", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {wheel : {max : 2}}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//5. range min max
TEST_CASE( "yaml-filter-tests: range min max", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {wheel : {min : 2, max : 5}}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

//6. any
TEST_CASE( "yaml-filter-tests: any", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {any : [{name : civic}, {name : bmw320i}]}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//7. all
TEST_CASE( "yaml-filter-tests: all", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {all : [ {name : civic}, {brand : honda}, {wheel: 4} ] }");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

//8. none
TEST_CASE( "yaml-filter-tests: none", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {none : [{name : civic}, {name : bmw320i}]}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

//9. not
TEST_CASE( "yaml-filter-tests: not", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {not : {name : civic}}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

//10. basic predicate with context
TEST_CASE( "yaml-filter-tests: context filter", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {$geometry : 1}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: bogus filter", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {max: bogus}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean true filter as existence check", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { drive : true }");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean false filter as existence check", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { drive : false}");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(!filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean true filter as existence check for keyword", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {$geometry : 1}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: boolean false filter as existence check for keyword", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: {$zoom : false}");

    REQUIRE(filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(filter.eval(bike, ctx));

}

TEST_CASE( "yaml-filter-tests: predicate with large integers", "[filters][core][yaml]") {
    init();
    Filter filter = load("filter: { serial : [4398046511104] }");

    REQUIRE(!filter.eval(civic, ctx));
    REQUIRE(filter.eval(bmw1, ctx));
    REQUIRE(!filter.eval(bike, ctx));

}<|endoftext|>