<commit_before>/*

Copyright (c) 2006, 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.

*/

#ifndef TORRENT_SESSION_HPP_INCLUDED
#define TORRENT_SESSION_HPP_INCLUDED

#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <list>
#include <deque>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/limits.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/thread.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/config.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session_status.hpp"
#include "libtorrent/version.hpp"
#include "libtorrent/fingerprint.hpp"

#include "libtorrent/storage.hpp"

#ifdef _MSC_VER
#	include <eh.h>
#endif

namespace libtorrent
{
	struct torrent_plugin;
	class torrent;
	class ip_filter;
	class port_filter;
	class connection_queue;

	namespace fs = boost::filesystem;

	namespace aux
	{
		// workaround for microsofts
		// hardware exceptions that makes
		// it hard to debug stuff
#ifdef _MSC_VER
		struct eh_initializer
		{
			eh_initializer()
			{
				::_set_se_translator(straight_to_debugger);
			}

			static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
			{ throw; }
		};
#else
		struct eh_initializer {};
#endif
		struct session_impl;

		struct filesystem_init
		{
			filesystem_init();
		};

	}

	class TORRENT_EXPORT session_proxy
	{
		friend class session;
	public:
		session_proxy() {}
	private:
		session_proxy(boost::shared_ptr<aux::session_impl> impl)
			: m_impl(impl) {}
		boost::shared_ptr<aux::session_impl> m_impl;
	};

	class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer
	{
	public:

		session(fingerprint const& print = fingerprint("LT"
			, LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0));
		session(
			fingerprint const& print
			, std::pair<int, int> listen_port_range
			, char const* listen_interface = "0.0.0.0");

		~session();

		// returns a list of all torrents in this session
		std::vector<torrent_handle> get_torrents() const;

		// returns an invalid handle in case the torrent doesn't exist
		torrent_handle find_torrent(sha1_hash const& info_hash) const;

		// all torrent_handles must be destructed before the session is destructed!
		torrent_handle add_torrent(
			torrent_info const& ti
			, fs::path const& save_path
			, entry const& resume_data = entry()
			, bool compact_mode = true
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor);

		torrent_handle add_torrent(
			char const* tracker_url
			, sha1_hash const& info_hash
			, char const* name
			, fs::path const& save_path
			, entry const& resume_data = entry()
			, bool compact_mode = true
			, bool paused = true
			, storage_constructor_type sc = default_storage_constructor);

		session_proxy abort() { return session_proxy(m_impl); }

		session_status status() const;

#ifndef TORRENT_DISABLE_DHT
		void start_dht(entry const& startup_state = entry());
		void stop_dht();
		void set_dht_settings(dht_settings const& settings);
		entry dht_state() const;
		void add_dht_node(std::pair<std::string, int> const& node);
		void add_dht_router(std::pair<std::string, int> const& node);
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
		void set_pe_settings(pe_settings const& settings);
		pe_settings const& get_pe_settings() const;
#endif

#ifndef TORRENT_DISABLE_EXTENSIONS
		void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*)> ext);
#endif

		void set_ip_filter(ip_filter const& f);
		void set_port_filter(port_filter const& f);
		void set_peer_id(peer_id const& pid);
		void set_key(int key);
		peer_id id() const;

		bool is_listening() const;

		// if the listen port failed in some way
		// you can retry to listen on another port-
		// range with this function. If the listener
		// succeeded and is currently listening,
		// a call to this function will shut down the
		// listen port and reopen it using these new
		// properties (the given interface and port range).
		// As usual, if the interface is left as 0
		// this function will return false on failure.
		// If it fails, it will also generate alerts describing
		// the error. It will return true on success.
		bool listen_on(
			std::pair<int, int> const& port_range
			, const char* net_interface = 0);

		// returns the port we ended up listening on
		unsigned short listen_port() const;

		// Get the number of uploads.
		int num_uploads() const;

		// Get the number of connections. This number also contains the
		// number of half open connections.
		int num_connections() const;

		void remove_torrent(const torrent_handle& h);

		void set_settings(session_settings const& s);
		session_settings const& settings();

		void set_peer_proxy(proxy_settings const& s);
		void set_web_seed_proxy(proxy_settings const& s);
		void set_tracker_proxy(proxy_settings const& s);

		proxy_settings const& peer_proxy() const;
		proxy_settings const& web_seed_proxy() const;
		proxy_settings const& tracker_proxy() const;

#ifndef TORRENT_DISABLE_DHT
		void set_dht_proxy(proxy_settings const& s);
		proxy_settings const& dht_proxy() const;
#endif

		int upload_rate_limit() const;
		int download_rate_limit() const;

		void set_upload_rate_limit(int bytes_per_second);
		void set_download_rate_limit(int bytes_per_second);
		void set_max_uploads(int limit);
		void set_max_connections(int limit);
		void set_max_half_open_connections(int limit);

		std::auto_ptr<alert> pop_alert();
		void set_severity_level(alert::severity_t s);

		connection_queue& get_connection_queue();

		// starts/stops UPnP, NATPMP or LSD port mappers
		// they are stopped by default
		void start_lsd();
		void start_natpmp();
		void start_upnp();

		void stop_lsd();
		void stop_natpmp();
		void stop_upnp();

	private:

		// just a way to initialize boost.filesystem
		// before the session_impl is created
		aux::filesystem_init m_dummy;

		// data shared between the main thread
		// and the working thread
		boost::shared_ptr<aux::session_impl> m_impl;
	};

}

#endif // TORRENT_SESSION_HPP_INCLUDED

<commit_msg>fixed default value for paused<commit_after>/*

Copyright (c) 2006, 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.

*/

#ifndef TORRENT_SESSION_HPP_INCLUDED
#define TORRENT_SESSION_HPP_INCLUDED

#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <list>
#include <deque>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/limits.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/thread.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/config.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session_status.hpp"
#include "libtorrent/version.hpp"
#include "libtorrent/fingerprint.hpp"

#include "libtorrent/storage.hpp"

#ifdef _MSC_VER
#	include <eh.h>
#endif

namespace libtorrent
{
	struct torrent_plugin;
	class torrent;
	class ip_filter;
	class port_filter;
	class connection_queue;

	namespace fs = boost::filesystem;

	namespace aux
	{
		// workaround for microsofts
		// hardware exceptions that makes
		// it hard to debug stuff
#ifdef _MSC_VER
		struct eh_initializer
		{
			eh_initializer()
			{
				::_set_se_translator(straight_to_debugger);
			}

			static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
			{ throw; }
		};
#else
		struct eh_initializer {};
#endif
		struct session_impl;

		struct filesystem_init
		{
			filesystem_init();
		};

	}

	class TORRENT_EXPORT session_proxy
	{
		friend class session;
	public:
		session_proxy() {}
	private:
		session_proxy(boost::shared_ptr<aux::session_impl> impl)
			: m_impl(impl) {}
		boost::shared_ptr<aux::session_impl> m_impl;
	};

	class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer
	{
	public:

		session(fingerprint const& print = fingerprint("LT"
			, LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0));
		session(
			fingerprint const& print
			, std::pair<int, int> listen_port_range
			, char const* listen_interface = "0.0.0.0");

		~session();

		// returns a list of all torrents in this session
		std::vector<torrent_handle> get_torrents() const;

		// returns an invalid handle in case the torrent doesn't exist
		torrent_handle find_torrent(sha1_hash const& info_hash) const;

		// all torrent_handles must be destructed before the session is destructed!
		torrent_handle add_torrent(
			torrent_info const& ti
			, fs::path const& save_path
			, entry const& resume_data = entry()
			, bool compact_mode = true
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor);

		torrent_handle add_torrent(
			char const* tracker_url
			, sha1_hash const& info_hash
			, char const* name
			, fs::path const& save_path
			, entry const& resume_data = entry()
			, bool compact_mode = true
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor);

		session_proxy abort() { return session_proxy(m_impl); }

		session_status status() const;

#ifndef TORRENT_DISABLE_DHT
		void start_dht(entry const& startup_state = entry());
		void stop_dht();
		void set_dht_settings(dht_settings const& settings);
		entry dht_state() const;
		void add_dht_node(std::pair<std::string, int> const& node);
		void add_dht_router(std::pair<std::string, int> const& node);
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
		void set_pe_settings(pe_settings const& settings);
		pe_settings const& get_pe_settings() const;
#endif

#ifndef TORRENT_DISABLE_EXTENSIONS
		void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*)> ext);
#endif

		void set_ip_filter(ip_filter const& f);
		void set_port_filter(port_filter const& f);
		void set_peer_id(peer_id const& pid);
		void set_key(int key);
		peer_id id() const;

		bool is_listening() const;

		// if the listen port failed in some way
		// you can retry to listen on another port-
		// range with this function. If the listener
		// succeeded and is currently listening,
		// a call to this function will shut down the
		// listen port and reopen it using these new
		// properties (the given interface and port range).
		// As usual, if the interface is left as 0
		// this function will return false on failure.
		// If it fails, it will also generate alerts describing
		// the error. It will return true on success.
		bool listen_on(
			std::pair<int, int> const& port_range
			, const char* net_interface = 0);

		// returns the port we ended up listening on
		unsigned short listen_port() const;

		// Get the number of uploads.
		int num_uploads() const;

		// Get the number of connections. This number also contains the
		// number of half open connections.
		int num_connections() const;

		void remove_torrent(const torrent_handle& h);

		void set_settings(session_settings const& s);
		session_settings const& settings();

		void set_peer_proxy(proxy_settings const& s);
		void set_web_seed_proxy(proxy_settings const& s);
		void set_tracker_proxy(proxy_settings const& s);

		proxy_settings const& peer_proxy() const;
		proxy_settings const& web_seed_proxy() const;
		proxy_settings const& tracker_proxy() const;

#ifndef TORRENT_DISABLE_DHT
		void set_dht_proxy(proxy_settings const& s);
		proxy_settings const& dht_proxy() const;
#endif

		int upload_rate_limit() const;
		int download_rate_limit() const;

		void set_upload_rate_limit(int bytes_per_second);
		void set_download_rate_limit(int bytes_per_second);
		void set_max_uploads(int limit);
		void set_max_connections(int limit);
		void set_max_half_open_connections(int limit);

		std::auto_ptr<alert> pop_alert();
		void set_severity_level(alert::severity_t s);

		connection_queue& get_connection_queue();

		// starts/stops UPnP, NATPMP or LSD port mappers
		// they are stopped by default
		void start_lsd();
		void start_natpmp();
		void start_upnp();

		void stop_lsd();
		void stop_natpmp();
		void stop_upnp();

	private:

		// just a way to initialize boost.filesystem
		// before the session_impl is created
		aux::filesystem_init m_dummy;

		// data shared between the main thread
		// and the working thread
		boost::shared_ptr<aux::session_impl> m_impl;
	};

}

#endif // TORRENT_SESSION_HPP_INCLUDED

<|endoftext|>


<commit_before>/*

Copyright (c) 2006, 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.

*/

#ifndef TORRENT_SESSION_HPP_INCLUDED
#define TORRENT_SESSION_HPP_INCLUDED

#include <algorithm>
#include <vector>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/limits.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/config.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/session_status.hpp"
#include "libtorrent/version.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/disk_io_thread.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/alert.hpp" // alert::error_notification
#include "libtorrent/add_torrent_params.hpp"

#include "libtorrent/storage.hpp"
#include <boost/preprocessor/cat.hpp>

#ifdef _MSC_VER
#	include <eh.h>
#endif

namespace libtorrent
{
	struct torrent_plugin;
	class torrent;
	class ip_filter;
	class port_filter;
	class connection_queue;
	class natpmp;
	class upnp;
	class alert;

	// this is used to create linker errors when trying to link to
	// a library with a conflicting build configuration than the application
#ifdef TORRENT_DEBUG
#define G _release
#else
#define G _debug
#endif

#ifdef TORRENT_USE_OPENSSL
#define S _ssl
#else
#define S _nossl
#endif

#ifdef TORRENT_DISABLE_DHT
#define D _nodht
#else
#define D _dht
#endif

#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
#define P _nopoolalloc
#else
#define P _poolalloc
#endif

#define TORRENT_LINK_TEST_PREFIX libtorrent_build_config
#define TORRENT_LINK_TEST_NAME BOOST_PP_CAT(TORRENT_LINK_TEST_PREFIX, BOOST_PP_CAT(P, BOOST_PP_CAT(D, BOOST_PP_CAT(S, G))))
#undef P
#undef D
#undef S
#undef G

	inline void test_link()
	{
		extern void TORRENT_LINK_TEST_NAME();
		TORRENT_LINK_TEST_NAME();
	}

	session_settings min_memory_usage();
	session_settings high_performance_seed();

	namespace aux
	{
		// workaround for microsofts
		// hardware exceptions that makes
		// it hard to debug stuff
#ifdef _MSC_VER
		struct eh_initializer
		{
			eh_initializer()
			{
				::_set_se_translator(straight_to_debugger);
			}

			static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
			{ throw; }
		};
#else
		struct eh_initializer {};
#endif
		struct session_impl;
	}

	class TORRENT_EXPORT session_proxy
	{
		friend class session;
	public:
		session_proxy() {}
	private:
		session_proxy(boost::shared_ptr<aux::session_impl> impl)
			: m_impl(impl) {}
		boost::shared_ptr<aux::session_impl> m_impl;
	};

	class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer
	{
	public:

		session(fingerprint const& print = fingerprint("LT"
			, LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0)
			, int flags = start_default_features | add_default_plugins
			, int alert_mask = alert::error_notification
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
			, std::string logpath = "."
#endif
				);
		session(
			fingerprint const& print
			, std::pair<int, int> listen_port_range
			, char const* listen_interface = "0.0.0.0"
			, int flags = start_default_features | add_default_plugins
			, int alert_mask = alert::error_notification
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
			, std::string logpath = "."
#endif
			);

		~session();

		void save_state(entry& e) const;
		void load_state(lazy_entry const& e);

		// returns a list of all torrents in this session
		std::vector<torrent_handle> get_torrents() const;

		io_service& get_io_service();

		// returns an invalid handle in case the torrent doesn't exist
		torrent_handle find_torrent(sha1_hash const& info_hash) const;

		// all torrent_handles must be destructed before the session is destructed!
#ifndef BOOST_NO_EXCEPTIONS
		torrent_handle add_torrent(add_torrent_params const& params);
#endif
		torrent_handle add_torrent(add_torrent_params const& params, error_code& ec);

#ifndef TORRENT_NO_DEPRECATE
		// deprecated in 0.14
		TORRENT_DEPRECATED_PREFIX
		torrent_handle add_torrent(
			torrent_info const& ti
			, std::string const& save_path
			, entry const& resume_data = entry()
			, storage_mode_t storage_mode = storage_mode_sparse
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor) TORRENT_DEPRECATED;

		// deprecated in 0.14
		TORRENT_DEPRECATED_PREFIX
		torrent_handle add_torrent(
			boost::intrusive_ptr<torrent_info> ti
			, std::string const& save_path
			, entry const& resume_data = entry()
			, storage_mode_t storage_mode = storage_mode_sparse
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor
			, void* userdata = 0) TORRENT_DEPRECATED;

		// deprecated in 0.14
		TORRENT_DEPRECATED_PREFIX
		torrent_handle add_torrent(
			char const* tracker_url
			, sha1_hash const& info_hash
			, char const* name
			, std::string const& save_path
			, entry const& resume_data = entry()
			, storage_mode_t storage_mode = storage_mode_sparse
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor
			, void* userdata = 0) TORRENT_DEPRECATED;
#endif

		session_proxy abort() { return session_proxy(m_impl); }

		void pause();
		void resume();
		bool is_paused() const;

		session_status status() const;
		cache_status get_cache_status() const;

		void get_cache_info(sha1_hash const& ih
			, std::vector<cached_piece_info>& ret) const;

#ifndef TORRENT_DISABLE_DHT
		void start_dht(entry const& startup_state = entry());
		void stop_dht();
		void set_dht_settings(dht_settings const& settings);
		entry dht_state() const;
		void add_dht_node(std::pair<std::string, int> const& node);
		void add_dht_router(std::pair<std::string, int> const& node);
		bool is_dht_running() const;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
		void set_pe_settings(pe_settings const& settings);
		pe_settings const& get_pe_settings() const;
#endif

#ifndef TORRENT_DISABLE_EXTENSIONS
		void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext);
#endif

#ifndef TORRENT_DISABLE_GEO_IP
		int as_for_ip(address const& addr);
		bool load_asnum_db(char const* file);
		bool load_country_db(char const* file);
#if TORRENT_USE_WSTRING
		bool load_country_db(wchar_t const* file);
		bool load_asnum_db(wchar_t const* file);
#endif
#endif

		void load_state(entry const& ses_state);
		entry state() const;

		void set_ip_filter(ip_filter const& f);
		ip_filter const& get_ip_filter() const;

		void set_port_filter(port_filter const& f);
		void set_peer_id(peer_id const& pid);
		void set_key(int key);
		peer_id id() const;

		bool is_listening() const;

		// if the listen port failed in some way
		// you can retry to listen on another port-
		// range with this function. If the listener
		// succeeded and is currently listening,
		// a call to this function will shut down the
		// listen port and reopen it using these new
		// properties (the given interface and port range).
		// As usual, if the interface is left as 0
		// this function will return false on failure.
		// If it fails, it will also generate alerts describing
		// the error. It will return true on success.
		bool listen_on(
			std::pair<int, int> const& port_range
			, const char* net_interface = 0);

		// returns the port we ended up listening on
		unsigned short listen_port() const;

		// Get the number of uploads.
		int num_uploads() const;

		// Get the number of connections. This number also contains the
		// number of half open connections.
		int num_connections() const;

		enum options_t
		{
			none = 0,
			delete_files = 1
		};

		enum session_flags_t
		{
			add_default_plugins = 1,
			start_default_features = 2
		};

		void remove_torrent(const torrent_handle& h, int options = none);

		void set_settings(session_settings const& s);
		session_settings const& settings();

		void set_peer_proxy(proxy_settings const& s);
		void set_web_seed_proxy(proxy_settings const& s);
		void set_tracker_proxy(proxy_settings const& s);

		proxy_settings const& peer_proxy() const;
		proxy_settings const& web_seed_proxy() const;
		proxy_settings const& tracker_proxy() const;

#ifndef TORRENT_DISABLE_DHT
		void set_dht_proxy(proxy_settings const& s);
		proxy_settings const& dht_proxy() const;
#endif

#if TORRENT_USE_I2P
		void set_i2p_proxy(proxy_settings const& s);
		proxy_settings const& i2p_proxy() const;
#endif

		int upload_rate_limit() const;
		int download_rate_limit() const;
		int local_upload_rate_limit() const;
		int local_download_rate_limit() const;
		int max_half_open_connections() const;

		void set_local_upload_rate_limit(int bytes_per_second);
		void set_local_download_rate_limit(int bytes_per_second);
		void set_upload_rate_limit(int bytes_per_second);
		void set_download_rate_limit(int bytes_per_second);
		void set_max_uploads(int limit);
		void set_max_connections(int limit);
		void set_max_half_open_connections(int limit);

		int max_connections() const;
		int max_uploads() const;

		std::auto_ptr<alert> pop_alert();
#ifndef TORRENT_NO_DEPRECATE
		TORRENT_DEPRECATED_PREFIX
		void set_severity_level(alert::severity_t s) TORRENT_DEPRECATED;
#endif
		void set_alert_mask(int m);
		size_t set_alert_queue_size_limit(size_t queue_size_limit_);

		alert const* wait_for_alert(time_duration max_wait);
		void set_alert_dispatch(boost::function<void(alert const&)> const& fun);

		connection_queue& get_connection_queue();

		// starts/stops UPnP, NATPMP or LSD port mappers
		// they are stopped by default
		void start_lsd();
		natpmp* start_natpmp();
		upnp* start_upnp();

		void stop_lsd();
		void stop_natpmp();
		void stop_upnp();

	private:

		// data shared between the main thread
		// and the working thread
		boost::shared_ptr<aux::session_impl> m_impl;
	};

}

#endif // TORRENT_SESSION_HPP_INCLUDED

<commit_msg>disable exception-only functions when exceptions are disabled<commit_after>/*

Copyright (c) 2006, 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.

*/

#ifndef TORRENT_SESSION_HPP_INCLUDED
#define TORRENT_SESSION_HPP_INCLUDED

#include <algorithm>
#include <vector>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/limits.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/config.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/session_status.hpp"
#include "libtorrent/version.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/disk_io_thread.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/alert.hpp" // alert::error_notification
#include "libtorrent/add_torrent_params.hpp"

#include "libtorrent/storage.hpp"
#include <boost/preprocessor/cat.hpp>

#ifdef _MSC_VER
#	include <eh.h>
#endif

namespace libtorrent
{
	struct torrent_plugin;
	class torrent;
	class ip_filter;
	class port_filter;
	class connection_queue;
	class natpmp;
	class upnp;
	class alert;

	// this is used to create linker errors when trying to link to
	// a library with a conflicting build configuration than the application
#ifdef TORRENT_DEBUG
#define G _release
#else
#define G _debug
#endif

#ifdef TORRENT_USE_OPENSSL
#define S _ssl
#else
#define S _nossl
#endif

#ifdef TORRENT_DISABLE_DHT
#define D _nodht
#else
#define D _dht
#endif

#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
#define P _nopoolalloc
#else
#define P _poolalloc
#endif

#define TORRENT_LINK_TEST_PREFIX libtorrent_build_config
#define TORRENT_LINK_TEST_NAME BOOST_PP_CAT(TORRENT_LINK_TEST_PREFIX, BOOST_PP_CAT(P, BOOST_PP_CAT(D, BOOST_PP_CAT(S, G))))
#undef P
#undef D
#undef S
#undef G

	inline void test_link()
	{
		extern void TORRENT_LINK_TEST_NAME();
		TORRENT_LINK_TEST_NAME();
	}

	session_settings min_memory_usage();
	session_settings high_performance_seed();

	namespace aux
	{
		// workaround for microsofts
		// hardware exceptions that makes
		// it hard to debug stuff
#ifdef _MSC_VER
		struct eh_initializer
		{
			eh_initializer()
			{
				::_set_se_translator(straight_to_debugger);
			}

			static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
			{ throw; }
		};
#else
		struct eh_initializer {};
#endif
		struct session_impl;
	}

	class TORRENT_EXPORT session_proxy
	{
		friend class session;
	public:
		session_proxy() {}
	private:
		session_proxy(boost::shared_ptr<aux::session_impl> impl)
			: m_impl(impl) {}
		boost::shared_ptr<aux::session_impl> m_impl;
	};

	class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer
	{
	public:

		session(fingerprint const& print = fingerprint("LT"
			, LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0)
			, int flags = start_default_features | add_default_plugins
			, int alert_mask = alert::error_notification
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
			, std::string logpath = "."
#endif
				);
		session(
			fingerprint const& print
			, std::pair<int, int> listen_port_range
			, char const* listen_interface = "0.0.0.0"
			, int flags = start_default_features | add_default_plugins
			, int alert_mask = alert::error_notification
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
			, std::string logpath = "."
#endif
			);

		~session();

		void save_state(entry& e) const;
		void load_state(lazy_entry const& e);

		// returns a list of all torrents in this session
		std::vector<torrent_handle> get_torrents() const;

		io_service& get_io_service();

		// returns an invalid handle in case the torrent doesn't exist
		torrent_handle find_torrent(sha1_hash const& info_hash) const;

		// all torrent_handles must be destructed before the session is destructed!
#ifndef BOOST_NO_EXCEPTIONS
		torrent_handle add_torrent(add_torrent_params const& params);
#endif
		torrent_handle add_torrent(add_torrent_params const& params, error_code& ec);

#ifndef BOOST_NO_EXCEPTIONS
#ifndef TORRENT_NO_DEPRECATE
		// deprecated in 0.14
		TORRENT_DEPRECATED_PREFIX
		torrent_handle add_torrent(
			torrent_info const& ti
			, std::string const& save_path
			, entry const& resume_data = entry()
			, storage_mode_t storage_mode = storage_mode_sparse
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor) TORRENT_DEPRECATED;

		// deprecated in 0.14
		TORRENT_DEPRECATED_PREFIX
		torrent_handle add_torrent(
			boost::intrusive_ptr<torrent_info> ti
			, std::string const& save_path
			, entry const& resume_data = entry()
			, storage_mode_t storage_mode = storage_mode_sparse
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor
			, void* userdata = 0) TORRENT_DEPRECATED;

		// deprecated in 0.14
		TORRENT_DEPRECATED_PREFIX
		torrent_handle add_torrent(
			char const* tracker_url
			, sha1_hash const& info_hash
			, char const* name
			, std::string const& save_path
			, entry const& resume_data = entry()
			, storage_mode_t storage_mode = storage_mode_sparse
			, bool paused = false
			, storage_constructor_type sc = default_storage_constructor
			, void* userdata = 0) TORRENT_DEPRECATED;
#endif
#endif

		session_proxy abort() { return session_proxy(m_impl); }

		void pause();
		void resume();
		bool is_paused() const;

		session_status status() const;
		cache_status get_cache_status() const;

		void get_cache_info(sha1_hash const& ih
			, std::vector<cached_piece_info>& ret) const;

#ifndef TORRENT_DISABLE_DHT
		void start_dht(entry const& startup_state = entry());
		void stop_dht();
		void set_dht_settings(dht_settings const& settings);
		entry dht_state() const;
		void add_dht_node(std::pair<std::string, int> const& node);
		void add_dht_router(std::pair<std::string, int> const& node);
		bool is_dht_running() const;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
		void set_pe_settings(pe_settings const& settings);
		pe_settings const& get_pe_settings() const;
#endif

#ifndef TORRENT_DISABLE_EXTENSIONS
		void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext);
#endif

#ifndef TORRENT_DISABLE_GEO_IP
		int as_for_ip(address const& addr);
		bool load_asnum_db(char const* file);
		bool load_country_db(char const* file);
#if TORRENT_USE_WSTRING
		bool load_country_db(wchar_t const* file);
		bool load_asnum_db(wchar_t const* file);
#endif
#endif

		void load_state(entry const& ses_state);
		entry state() const;

		void set_ip_filter(ip_filter const& f);
		ip_filter const& get_ip_filter() const;

		void set_port_filter(port_filter const& f);
		void set_peer_id(peer_id const& pid);
		void set_key(int key);
		peer_id id() const;

		bool is_listening() const;

		// if the listen port failed in some way
		// you can retry to listen on another port-
		// range with this function. If the listener
		// succeeded and is currently listening,
		// a call to this function will shut down the
		// listen port and reopen it using these new
		// properties (the given interface and port range).
		// As usual, if the interface is left as 0
		// this function will return false on failure.
		// If it fails, it will also generate alerts describing
		// the error. It will return true on success.
		bool listen_on(
			std::pair<int, int> const& port_range
			, const char* net_interface = 0);

		// returns the port we ended up listening on
		unsigned short listen_port() const;

		// Get the number of uploads.
		int num_uploads() const;

		// Get the number of connections. This number also contains the
		// number of half open connections.
		int num_connections() const;

		enum options_t
		{
			none = 0,
			delete_files = 1
		};

		enum session_flags_t
		{
			add_default_plugins = 1,
			start_default_features = 2
		};

		void remove_torrent(const torrent_handle& h, int options = none);

		void set_settings(session_settings const& s);
		session_settings const& settings();

		void set_peer_proxy(proxy_settings const& s);
		void set_web_seed_proxy(proxy_settings const& s);
		void set_tracker_proxy(proxy_settings const& s);

		proxy_settings const& peer_proxy() const;
		proxy_settings const& web_seed_proxy() const;
		proxy_settings const& tracker_proxy() const;

#ifndef TORRENT_DISABLE_DHT
		void set_dht_proxy(proxy_settings const& s);
		proxy_settings const& dht_proxy() const;
#endif

#if TORRENT_USE_I2P
		void set_i2p_proxy(proxy_settings const& s);
		proxy_settings const& i2p_proxy() const;
#endif

		int upload_rate_limit() const;
		int download_rate_limit() const;
		int local_upload_rate_limit() const;
		int local_download_rate_limit() const;
		int max_half_open_connections() const;

		void set_local_upload_rate_limit(int bytes_per_second);
		void set_local_download_rate_limit(int bytes_per_second);
		void set_upload_rate_limit(int bytes_per_second);
		void set_download_rate_limit(int bytes_per_second);
		void set_max_uploads(int limit);
		void set_max_connections(int limit);
		void set_max_half_open_connections(int limit);

		int max_connections() const;
		int max_uploads() const;

		std::auto_ptr<alert> pop_alert();
#ifndef TORRENT_NO_DEPRECATE
		TORRENT_DEPRECATED_PREFIX
		void set_severity_level(alert::severity_t s) TORRENT_DEPRECATED;
#endif
		void set_alert_mask(int m);
		size_t set_alert_queue_size_limit(size_t queue_size_limit_);

		alert const* wait_for_alert(time_duration max_wait);
		void set_alert_dispatch(boost::function<void(alert const&)> const& fun);

		connection_queue& get_connection_queue();

		// starts/stops UPnP, NATPMP or LSD port mappers
		// they are stopped by default
		void start_lsd();
		natpmp* start_natpmp();
		upnp* start_upnp();

		void stop_lsd();
		void stop_natpmp();
		void stop_upnp();

	private:

		// data shared between the main thread
		// and the working thread
		boost::shared_ptr<aux::session_impl> m_impl;
	};

}

#endif // TORRENT_SESSION_HPP_INCLUDED

<|endoftext|>


<commit_before>/*
	Copyright (c) 2016 nshcat

	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.
*/

#pragma once

#include <string>

#include "log_target.hxx"
#include "log_entry.hxx"

namespace lg
{
	class network_target
		: public log_target
	{
		using handle_type = void*;

		public:
			network_target(severity_level p_lvl, const ::std::string& p_host, const ::std::string& p_port);
			~network_target();

			network_target(const network_target&) = delete;
			network_target(network_target&&) = default;

			network_target& operator=(const network_target&) = delete;
			network_target& operator=(network_target&&) = default;

		public:
			virtual void write(const log_entry& entry) override;

		private:
			auto connect() -> void;

		private:
			::std::string m_Host;
			::std::string m_Port;
			handle_type m_InternalData{nullptr};
	};
}
<commit_msg>Added protocol info to network_target header file.<commit_after>/*
	Copyright (c) 2016 nshcat

	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.
*/

/*	PROTOCOL:
 *
 *	[u32]	Length of message string
 *	[u64]	Timestamp (time_t)
 *	[u32] 	Level
 *	[u32] 	Is Bare? (0x1 or 0x0)
 *	N*[u8]	String payload
 */

#pragma once

#include <string>

#include "log_target.hxx"
#include "log_entry.hxx"

namespace lg
{
	class network_target
		: public log_target
	{
		using handle_type = void*;

		public:
			network_target(severity_level p_lvl, const ::std::string& p_host, const ::std::string& p_port);
			~network_target();

			network_target(const network_target&) = delete;
			network_target(network_target&&) = default;

			network_target& operator=(const network_target&) = delete;
			network_target& operator=(network_target&&) = default;

		public:
			virtual void write(const log_entry& entry) override;

		private:
			auto connect() -> void;

		private:
			::std::string m_Host;
			::std::string m_Port;
			handle_type m_InternalData{nullptr};
	};
}
<|endoftext|>


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

using namespace std;

DataType::DataType(Type type) {
	this->type = type;
	this->length = 0;
}

DataType::DataType(DataType::Type type, int length) {
	this->type = type;
	this->length = length;
}

//map<string, DataType::Type> DataType::str_to_type = {
//		{"int", DataType::INT},
//		{"float", DataType::FLOAT},
//		{"double", DataType::DOUBLE},
//		{"char", DataType::CHAR},
//};
//
//
//map<DataType::Type, string> reverse_map(map<string, DataType::Type> str_to_type) {
//	map<DataType::Type, string> reversed;
//	for (auto it = str_to_type.begin(); it != str_to_type.end(); ++it)
//		reversed[it->second] = it->first;
//	return reversed;
//};
//
//map<DataType::Type, string> DataType::type_to_str = {
//		{DataType::INT, "int32_t"},
//		{DataType::FLOAT, "float"},
//		{DataType::DOUBLE, "double"},
//		{DataType::CHAR, "char*"},
//};

//string DataType::convert_type_to_str(DataType::Type type) {
//	auto it = DataType::type_to_str.find(type);
//	if (it == DataType::type_to_str.end())
//		return nullptr;
//	return it->second;
//}

//DataType::Type DataType::convert_str_to_type(string str) {
//	auto it = DataType::str_to_type.find(str);
//	if (it == DataType::str_to_type.end()) {
//		return (DataType::Type) (-1);
//	}
//	return it->second;
//}

DataType::Type DataType::get_typecode() {
	return this->type;
}

int DataType::get_length() {
	return this->length;
}

int DataType::equals(DataType *that) {
	if (this->get_typecode() != that->get_typecode())
		return 0;

	if (this->get_typecode() == DataType::INT)
		return 1;

	if (this->get_typecode() == DataType::DOUBLE)
		return 1;

	if (this->get_typecode() == DataType::FLOAT)
		return 1;

	if (this->get_typecode() == DataType::CHAR)
		return this->get_length() == that->get_length();

	return 0;
}

string DataType::str(string name) {
	if (this->get_typecode() == DataType::INT)
		return "int32_t " + name;

	if (this->get_typecode() == DataType::DOUBLE)
		return "double " + name;

	if (this->get_typecode() == DataType::FLOAT)
		return "float " + name;

	if (this->get_typecode() == DataType::CHAR) {
		string s("char " + name + "[" + to_string(this->get_length()) + "]");
		return s;
	}

	return "";
}

string DataType::str_out(string name) {
	if (this->get_typecode() == DataType::INT)
		return "int32_t " + name;

	if (this->get_typecode() == DataType::DOUBLE)
		return "double " + name;

	if (this->get_typecode() == DataType::FLOAT)
		return "float " + name;

	if (this->get_typecode() == DataType::CHAR) {
		string s("char " + name + "[" + to_string(this->get_length()+1) + "]");
		return s;
	}

	return "";
}

string DataType::signature(string name) {
	if (this->get_typecode() == DataType::INT)
		return "int32_t " + name;

	if (this->get_typecode() == DataType::DOUBLE)
		return "double " + name;

	if (this->get_typecode() == DataType::FLOAT)
		return "float " + name;

	if (this->get_typecode() == DataType::CHAR) {
		return "const char* " + name;
	}

	return "";
}

string DataType::get_format_specifier() {
	if (this->get_typecode() == DataType::INT)
		return "%d";

	if (this->get_typecode() == DataType::DOUBLE)
		return "%f";

	if (this->get_typecode() == DataType::FLOAT)
		return "%f";

	if (this->get_typecode() == DataType::CHAR) {
		return "\\\"%s\\\"";
	}

	return "";
}

string DataType::scan_expr(string column_name) {
	if (this->get_typecode() == DataType::INT)
		return "sscanf(token, \"%d\", &(arg->" + column_name + "));";

	if (this->get_typecode() == DataType::DOUBLE)
		return "sscanf(token, \"%lf\", &(arg->" + column_name + "));";

	if (this->get_typecode() == DataType::FLOAT)
		return "sscanf(token, \"%f\", &(arg->" + column_name + "));";

	if (this->get_typecode() == DataType::CHAR) {
		return "memcpy(arg->" + column_name + ", token + sizeof(char), strlen(token)-2);";
	}

	return "";
}

string DataType::init_expr(string column_name) {
	if (this->get_typecode() == DataType::INT)
		return "new->" + column_name + " = 0;";

	if (this->get_typecode() == DataType::DOUBLE)
		return "new->" + column_name + " = 0.0;";

	if (this->get_typecode() == DataType::FLOAT)
		return "new->" + column_name + " = 0.0;";

	if (this->get_typecode() == DataType::CHAR) {
		return "memset(new->" + column_name + ", 0, " + to_string(this->get_length()) + ");";
	}

	return "";
}

string DataType::select_expr(std::string param, std::string column) {
	if (this->get_typecode() == DataType::INT)
		return "inserted->" + param + " = page.items[i]->" + column + ";";

	if (this->get_typecode() == DataType::DOUBLE)
		return "inserted->" + param + " = page.items[i]->" + column + ";";

	if (this->get_typecode() == DataType::FLOAT)
		return "inserted->" + param + " = page.items[i]->" + column + ";";

	if (this->get_typecode() == DataType::CHAR) {
		return "memcpy(inserted->" + column + ", page.items[i]." + param + ", " + to_string(this->get_length()) +
				"); inserted->" + column + "[" + to_string(this->get_length()) + "] = '\\0';";
	}

	return "";
}

string DataType::compare_less_expr(string s1, string col1, string s2, string col2) {
	if (this->get_typecode() == DataType::INT)
		return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::DOUBLE)
		return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::FLOAT)
		return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::CHAR) {
		return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") < 0";
	}

	return "";
}

string DataType::compare_greater_expr(string s1, string col1, string s2, string col2) {
	if (this->get_typecode() == DataType::INT)
		return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::DOUBLE)
		return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::FLOAT)
		return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::CHAR) {
		return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") > 0";
	}

	return "";
}<commit_msg>generation 5<commit_after>#include "DataType.h"
#include <iostream>

using namespace std;

DataType::DataType(Type type) {
	this->type = type;
	this->length = 0;
}

DataType::DataType(DataType::Type type, int length) {
	this->type = type;
	this->length = length;
}

//map<string, DataType::Type> DataType::str_to_type = {
//		{"int", DataType::INT},
//		{"float", DataType::FLOAT},
//		{"double", DataType::DOUBLE},
//		{"char", DataType::CHAR},
//};
//
//
//map<DataType::Type, string> reverse_map(map<string, DataType::Type> str_to_type) {
//	map<DataType::Type, string> reversed;
//	for (auto it = str_to_type.begin(); it != str_to_type.end(); ++it)
//		reversed[it->second] = it->first;
//	return reversed;
//};
//
//map<DataType::Type, string> DataType::type_to_str = {
//		{DataType::INT, "int32_t"},
//		{DataType::FLOAT, "float"},
//		{DataType::DOUBLE, "double"},
//		{DataType::CHAR, "char*"},
//};

//string DataType::convert_type_to_str(DataType::Type type) {
//	auto it = DataType::type_to_str.find(type);
//	if (it == DataType::type_to_str.end())
//		return nullptr;
//	return it->second;
//}

//DataType::Type DataType::convert_str_to_type(string str) {
//	auto it = DataType::str_to_type.find(str);
//	if (it == DataType::str_to_type.end()) {
//		return (DataType::Type) (-1);
//	}
//	return it->second;
//}

DataType::Type DataType::get_typecode() {
	return this->type;
}

int DataType::get_length() {
	return this->length;
}

int DataType::equals(DataType *that) {
	if (this->get_typecode() != that->get_typecode())
		return 0;

	if (this->get_typecode() == DataType::INT)
		return 1;

	if (this->get_typecode() == DataType::DOUBLE)
		return 1;

	if (this->get_typecode() == DataType::FLOAT)
		return 1;

	if (this->get_typecode() == DataType::CHAR)
		return this->get_length() == that->get_length();

	return 0;
}

string DataType::str(string name) {
	if (this->get_typecode() == DataType::INT)
		return "int32_t " + name;

	if (this->get_typecode() == DataType::DOUBLE)
		return "double " + name;

	if (this->get_typecode() == DataType::FLOAT)
		return "float " + name;

	if (this->get_typecode() == DataType::CHAR) {
		string s("char " + name + "[" + to_string(this->get_length()) + "]");
		return s;
	}

	return "";
}

string DataType::str_out(string name) {
	if (this->get_typecode() == DataType::INT)
		return "int32_t " + name;

	if (this->get_typecode() == DataType::DOUBLE)
		return "double " + name;

	if (this->get_typecode() == DataType::FLOAT)
		return "float " + name;

	if (this->get_typecode() == DataType::CHAR) {
		string s("char " + name + "[" + to_string(this->get_length()+1) + "]");
		return s;
	}

	return "";
}

string DataType::signature(string name) {
	if (this->get_typecode() == DataType::INT)
		return "int32_t " + name;

	if (this->get_typecode() == DataType::DOUBLE)
		return "double " + name;

	if (this->get_typecode() == DataType::FLOAT)
		return "float " + name;

	if (this->get_typecode() == DataType::CHAR) {
		return "const char* " + name;
	}

	return "";
}

string DataType::get_format_specifier() {
	if (this->get_typecode() == DataType::INT)
		return "%d";

	if (this->get_typecode() == DataType::DOUBLE)
		return "%f";

	if (this->get_typecode() == DataType::FLOAT)
		return "%f";

	if (this->get_typecode() == DataType::CHAR) {
		return "\\\"%s\\\"";
	}

	return "";
}

string DataType::scan_expr(string column_name) {
	if (this->get_typecode() == DataType::INT)
		return "sscanf(token, \"%d\", &(arg->" + column_name + "));";

	if (this->get_typecode() == DataType::DOUBLE)
		return "sscanf(token, \"%lf\", &(arg->" + column_name + "));";

	if (this->get_typecode() == DataType::FLOAT)
		return "sscanf(token, \"%f\", &(arg->" + column_name + "));";

	if (this->get_typecode() == DataType::CHAR) {
		return "memcpy(arg->" + column_name + ", token + sizeof(char), strlen(token)-2);";
	}

	return "";
}

string DataType::init_expr(string column_name) {
	if (this->get_typecode() == DataType::INT)
		return "new->" + column_name + " = 0;";

	if (this->get_typecode() == DataType::DOUBLE)
		return "new->" + column_name + " = 0.0;";

	if (this->get_typecode() == DataType::FLOAT)
		return "new->" + column_name + " = 0.0;";

	if (this->get_typecode() == DataType::CHAR) {
		return "memset(new->" + column_name + ", 0, " + to_string(this->get_length()) + ");";
	}

	return "";
}

string DataType::select_expr(std::string param, std::string column) {
	if (this->get_typecode() == DataType::INT)
		return "inserted->" + param + " = page.items[i]." + column + ";";

	if (this->get_typecode() == DataType::DOUBLE)
		return "inserted->" + param + " = page.items[i]." + column + ";";

	if (this->get_typecode() == DataType::FLOAT)
		return "inserted->" + param + " = page.items[i]." + column + ";";

	if (this->get_typecode() == DataType::CHAR) {
		return "memcpy(inserted->" + column + ", page.items[i]." + param + ", " + to_string(this->get_length()) +
				"); inserted->" + column + "[" + to_string(this->get_length()) + "] = '\\0';";
	}

	return "";
}

string DataType::compare_less_expr(string s1, string col1, string s2, string col2) {
	if (this->get_typecode() == DataType::INT)
		return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::DOUBLE)
		return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::FLOAT)
		return "(" + s1 + "->" + col1 + " < " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::CHAR) {
		return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") < 0";
	}

	return "";
}

string DataType::compare_greater_expr(string s1, string col1, string s2, string col2) {
	if (this->get_typecode() == DataType::INT)
		return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::DOUBLE)
		return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::FLOAT)
		return "(" + s1 + "->" + col1 + " > " + s2 + "->" + col2 + ")";

	if (this->get_typecode() == DataType::CHAR) {
		return "strncmp(" + s1 + "->" + col1 + ", " + s2 + "->" + col2 + ", " + to_string(this->get_length()) + ") > 0";
	}

	return "";
}<|endoftext|>


<commit_before>#ifndef SQUALL__EVENT_BUFFER_HXX
#define SQUALL__EVENT_BUFFER_HXX

#include <vector>
#include <algorithm>
#include "NonCopyable.hxx"
#include "PlatformLoop.hxx"
#include "PlatformWatcher.hxx"

#ifdef HAVE_UNISTD_H
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#endif // HAVE_UNISTD_H

using std::placeholders::_1;

namespace squall {

/* Event-driven I/O buffer. */
class EventBuffer : public IoWatcher, NonCopyable {
    using watcher = IoWatcher;

    template <typename T>
    friend class Dispatcher;

  public:
    /** Buffer block size */
    size_t blockSize() noexcept {
        return block_size;
    }

    /** Maximum buffer size */
    size_t bufferSize() noexcept {
        return buffer_size;
    }

    /** Incomming buffer size */
    size_t incomingSize() noexcept {
        return in.size();
    }

    /** Outcomming buffer size */
    size_t outcomingSize() noexcept {
        return out.size();
    }

    /* Returns `Event::Read` or `Event::Write` if there is waiting a buffer events. otherwise 0.  */
    int pendingEvent() {
        return pending_event;
    }

    /* Destructor */
    ~EventBuffer() {}

    /** Sets up a buffer for watching receiver events */
    int setup_receiver(size_t threshold) {
        return setup_buffer(Event::Read, threshold, std::vector<char>());
    }

    /** Sets up a buffer for watching receiver events */
    int setup_receiver(const std::vector<char>& delimiter, size_t threshold = 0) {
        return setup_buffer(Event::Read, threshold, delimiter);
    }

    /** Sets up a buffer for watching transmiter events */
    int setup_transmiter(size_t threshold = 0) {
        return setup_buffer(Event::Write, threshold, std::vector<char>());
    }

    /**
     * Read bytes from incoming buffer how much is there, but not more `size`.
     * If `size == 0` tries to read bytes block defined with used threshold
     * and/or delimiter.
     */
    std::vector<char> read(size_t size = 0) {
        std::vector<char> result;
        size = (size < in.size()) ? size : in.size();
        if (pending_event == Event::Read) {
            size = ((size == 0) && (threshold < in.size())) ? threshold : size;
            cancel();
        }
        if (size > 0) {
            std::copy(in.begin(), in.begin() + size, std::back_inserter(result));
            in.erase(in.begin(), in.begin() + size);
            watcher::setup(fd(), mode() | Event::Read);
        }
        return result;
    }

    /** Writes data to the outcoming buffer. Returns number of written bytes. */
    size_t write(std::vector<char> data) {
        if (pending_event == Event::Write)
            cancel();
        auto size = (data.size() < buffer_size - out.size()) ? data.size() : buffer_size - out.size();
        std::copy(data.begin(), data.begin() + size, std::back_inserter(out));
        watcher::setup(fd(), mode() | Event::Write);
        return size;
    }

    /* Cancels a buffer event watching */
    bool cancel() {
        if (pending_event) {
            threshold = 0;
            delimiter.clear();
            pending_event = 0;
            return true;
        }
        return false;
    }

protected:
    /* Constructor */
    EventBuffer(OnEvent&& on_event, const std::shared_ptr<PlatformLoop>& sp_loop, int fd,
                size_t block_size = 0, size_t buffer_size = 0)
        : IoWatcher(std::bind(&EventBuffer::event_handler, this, _1), sp_loop),
          on_event(std::forward<OnEvent>(on_event)), block_size(block_size), buffer_size(buffer_size) {
        watcher::setup(fd, static_cast<int>(Event::Read));
        adjust_buffer_size();
    }

    /* Return true if is buffer watcher */
    virtual bool is_buffer() noexcept {
        return true;
    }

#ifndef _POSIX_VERSION
public:
    /** Returns last error code. */
    virtual int lastErrno() noexcept {
        return last_errno;
    };

  protected:
    virtual bool set_non_block(int fd);
    virtual std::pair<size_t, int> write_block(char* buff, size_t block_size) = 0;
    virtual std::pair<size_t, int> read_block(const char* buff, size_t block_size) = 0;

#else
public:
    /** Returns last error code. */
    virtual int lastErrno() noexcept {
        return last_errno >= 0 ? last_errno : EIO;
    };

  protected:
    /* Sets non block */
    virtual bool set_non_block() {
        auto flags = fcntl(fd(), F_GETFL, 0);
        flags = (flags == -1) ? 0 : flags;
        if (fcntl(fd(), F_SETFL, flags | O_NONBLOCK) == -1)
            last_errno = errno;
        return (last_errno == 0);
    }

    /* Reads block of bytes from device. */
    std::pair<size_t, int> read_block(char* buff, size_t block_size) {
        auto size = ::read(fd(), buff, block_size);
        if (size > 0)
            return std::make_pair(size, 0);
        else if (size == 0)
            return std::make_pair(0, ECONNRESET);
        else if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
            return std::make_pair(0, 0);
        else
            return std::make_pair(0, errno);
    }

    /* Write block of bytes to device. */
    std::pair<size_t, int> write_block(const char* buff, size_t block_size) {
        auto size = ::write(fd(), buff, block_size);
        if (size >= 0)
            return std::make_pair(size, 0);
        else if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
            return std::make_pair(0, 0);
        else
            return std::make_pair(0, errno);
    }
#endif

  private:
    OnEvent on_event;
    int last_errno = 0;
    std::vector<char> in;
    std::vector<char> out;
    int pending_event = 0;
    std::vector<char> delimiter;
    size_t block_size, buffer_size, threshold;

    using watcher::setup;

    int setup_buffer(int pending_event_, size_t threshold_, const std::vector<char>& delimiter_) {
        cancel();
        if (pending_event_ == Event::Read)
            threshold = threshold_ < buffer_size ? threshold_ : buffer_size;
        else if (pending_event_ == Event::Write)
            threshold = threshold_ < (buffer_size - block_size) ? threshold_ : (buffer_size - block_size);
        else {
            return 0;
        }
        delimiter = delimiter_;
        if (!delimiter.empty() && (threshold == 0))
            threshold = buffer_size;
        pending_event = pending_event_;
        threshold = threshold > 0 ? threshold : 0;
        auto early_events = check_buffer_task();
        if (early_events == 0) {
            watcher::setup(fd(), mode() | pending_event);
            return -1;
        } else
            return early_events;
    }

    int check_buffer_task() {
        int result = 0;
        if (pending_event == Event::Read) {
            if (delimiter.size() > 0) {
                auto found = std::search(in.begin(), in.end(), delimiter.begin(), delimiter.end());
                if (found == in.end()) {
                    if (threshold <= incomingSize())
                        // delimiter not found but max_size
                        result = Event::Error;
                } else
                    // delimiter found; move threshold
                    threshold = std::distance(in.begin(), found) + delimiter.size();
            }
            if (threshold <= incomingSize())
                result |= Event::Read;
        } else if (pending_event == Event::Write) {
            if (out.size() <= threshold)
                result = Event::Write;
        }
        return result;
    }

    void adjust_buffer_size() {
        block_size = (block_size > 1024) ? block_size : 1024;
        block_size += (block_size % 1024) ? 1024 : 0;
        block_size = (block_size / 1024) * 1024;
        buffer_size = (buffer_size > 1024 * 4) ? buffer_size : 1024 * 4;
        buffer_size = (buffer_size / block_size) * block_size;
        threshold = 0;
    }

    void event_handler(int revents) {
        if (revents & Event::Error)
            last_errno = -1;
        else {
            size_t from = 0;
            size_t size = 0;
            last_errno = 0;
            if (revents & Event::Read) {
                size = buffer_size - in.size();
                size = (size < block_size) ? size : block_size;
                if (size > 0) {
                    from = in.size();
                    in.resize(in.size() + size);
                    auto result = read_block(&(*(in.begin() + from)), size);
                    if (result.first > 0) {
                        if (result.first != size)
                            in.resize(in.size() - size + result.first);
                    } else
                        last_errno = result.second; // read error
                }
            }
            if (revents & Event::Write) {
                size = out.size() < block_size ? out.size() : block_size;
                if (size > 0) {
                    auto result = write_block(&(*out.begin()), size);
                    if (result.first > 0)
                        out.erase(out.begin(), out.begin() + result.first);
                    else
                        last_errno = result.second; // write error
                }
            }
        }
        // update I/O buffer mode
        if (last_errno == 0) {
            if ((revents & Event::Read) && (in.size() >= buffer_size))
                watcher::setup(fd(), mode() & Event::Write);
            if ((revents & Event::Write) && out.empty())
                watcher::setup(fd(), mode() & Event::Read);
        } else
            watcher::setup(fd(), 0);
        // generate buffer events
        if (pending_event) {
            auto buffer_events = check_buffer_task();
            if (buffer_events)
                on_event(buffer_events);
        }
    }
};
}
#endif // SQUALL__EVENT_BUFFER_HXX<commit_msg>fixes<commit_after>#ifndef SQUALL__EVENT_BUFFER_HXX
#define SQUALL__EVENT_BUFFER_HXX

#include <vector>
#include <algorithm>
#include "NonCopyable.hxx"
#include "PlatformLoop.hxx"
#include "PlatformWatcher.hxx"

#ifdef HAVE_UNISTD_H
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#endif // HAVE_UNISTD_H

using std::placeholders::_1;

namespace squall {

/* Event-driven I/O buffer. */
class EventBuffer : public IoWatcher, NonCopyable {
    using watcher = IoWatcher;

    template <typename T>
    friend class Dispatcher;

  public:
    /** Buffer block size */
    size_t blockSize() noexcept {
        return block_size;
    }

    /** Maximum buffer size */
    size_t bufferSize() noexcept {
        return buffer_size;
    }

    /** Incomming buffer size */
    size_t incomingSize() noexcept {
        return in.size();
    }

    /** Outcomming buffer size */
    size_t outcomingSize() noexcept {
        return out.size();
    }

    /* Returns `Event::Read` or `Event::Write` if there is waiting a buffer events. otherwise 0.  */
    int pendingEvent() {
        return pending_event;
    }

    /* Destructor */
    ~EventBuffer() {}

    /** Sets up a buffer for watching receiver events */
    int setup_receiver(size_t threshold) {
        return setup_buffer(Event::Read, threshold, std::vector<char>());
    }

    /** Sets up a buffer for watching receiver events */
    int setup_receiver(const std::vector<char>& delimiter, size_t threshold = 0) {
        return setup_buffer(Event::Read, threshold, delimiter);
    }

    /** Sets up a buffer for watching transmiter events */
    int setup_transmiter(size_t threshold = 0) {
        return setup_buffer(Event::Write, threshold, std::vector<char>());
    }

    /**
     * Read bytes from incoming buffer how much is there, but not more `size`.
     * If `size == 0` tries to read bytes block defined with used threshold
     * and/or delimiter.
     */
    std::vector<char> read(size_t size = 0) {
        std::vector<char> result;
        size = (size < in.size()) ? size : in.size();
        if (pending_event == Event::Read) {
            size = ((size == 0) && (threshold < in.size())) ? threshold : size;
            cancel();
        }
        if (size > 0) {
            std::copy(in.begin(), in.begin() + size, std::back_inserter(result));
            in.erase(in.begin(), in.begin() + size);
            watcher::setup(fd(), mode() | Event::Read);
        }
        return result;
    }

    /** Writes data to the outcoming buffer. Returns number of written bytes. */
    size_t write(std::vector<char> data) {
        if (pending_event == Event::Write)
            cancel();
        auto size = (data.size() < buffer_size - out.size()) ? data.size() : buffer_size - out.size();
        std::copy(data.begin(), data.begin() + size, std::back_inserter(out));
        watcher::setup(fd(), mode() | Event::Write);
        return size;
    }

    /* Cancels a buffer event watching */
    bool cancel() {
        if (pending_event) {
            threshold = 0;
            delimiter.clear();
            pending_event = 0;
            return true;
        }
        return false;
    }

protected:
    /* Constructor */
    EventBuffer(OnEvent&& on_event, const std::shared_ptr<PlatformLoop>& sp_loop, int fd,
                size_t block_size = 0, size_t buffer_size = 0)
        : IoWatcher(std::bind(&EventBuffer::event_handler, this, _1), sp_loop),
          on_event(std::forward<OnEvent>(on_event)), block_size(block_size), buffer_size(buffer_size) {
        watcher::setup(fd, static_cast<int>(Event::Read));
        adjust_buffer_size();
        set_non_block(fd);
    }

    /* Return true if is buffer watcher */
    virtual bool is_buffer() noexcept {
        return true;
    }

#ifndef _POSIX_VERSION
public:
    /** Returns last error code. */
    virtual int lastErrno() noexcept {
        return last_errno;
    };

  protected:
    virtual bool set_non_block(int fd);
    virtual std::pair<size_t, int> write_block(char* buff, size_t block_size) = 0;
    virtual std::pair<size_t, int> read_block(const char* buff, size_t block_size) = 0;

#else
public:
    /** Returns last error code. */
    virtual int lastErrno() noexcept {
        return last_errno >= 0 ? last_errno : EIO;
    };

  protected:
    /* Sets non block */
    virtual bool set_non_block(int fd) {
        auto flags = fcntl(fd, F_GETFL, 0);
        flags = (flags == -1) ? 0 : flags;
        if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
            last_errno = errno;
        return (last_errno == 0);
    }

    /* Reads block of bytes from device. */
    std::pair<size_t, int> read_block(char* buff, size_t block_size) {
        auto size = ::read(fd(), buff, block_size);
        if (size > 0)
            return std::make_pair(size, 0);
        else if (size == 0)
            return std::make_pair(0, ECONNRESET);
        else if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
            return std::make_pair(0, 0);
        else
            return std::make_pair(0, errno);
    }

    /* Write block of bytes to device. */
    std::pair<size_t, int> write_block(const char* buff, size_t block_size) {
        auto size = ::write(fd(), buff, block_size);
        if (size >= 0)
            return std::make_pair(size, 0);
        else if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
            return std::make_pair(0, 0);
        else
            return std::make_pair(0, errno);
    }
#endif

  private:
    OnEvent on_event;
    int last_errno = 0;
    std::vector<char> in;
    std::vector<char> out;
    int pending_event = 0;
    std::vector<char> delimiter;
    size_t block_size, buffer_size, threshold;

    using watcher::setup;

    int setup_buffer(int pending_event_, size_t threshold_, const std::vector<char>& delimiter_) {
        cancel();
        if (pending_event_ == Event::Read)
            threshold = threshold_ < buffer_size ? threshold_ : buffer_size;
        else if (pending_event_ == Event::Write)
            threshold = threshold_ < (buffer_size - block_size) ? threshold_ : (buffer_size - block_size);
        else {
            return 0;
        }
        delimiter = delimiter_;
        if (!delimiter.empty() && (threshold == 0))
            threshold = buffer_size;
        pending_event = pending_event_;
        threshold = threshold > 0 ? threshold : 0;
        auto early_events = check_buffer_task();
        if (early_events == 0) {
            watcher::setup(fd(), mode() | pending_event);
            return -1;
        } else
            return early_events;
    }

    int check_buffer_task() {
        int result = 0;
        if (pending_event == Event::Read) {
            if (delimiter.size() > 0) {
                auto found = std::search(in.begin(), in.end(), delimiter.begin(), delimiter.end());
                if (found == in.end()) {
                    if (threshold <= incomingSize())
                        // delimiter not found but max_size
                        result = Event::Error;
                } else
                    // delimiter found; move threshold
                    threshold = std::distance(in.begin(), found) + delimiter.size();
            }
            if (threshold <= incomingSize())
                result |= Event::Read;
        } else if (pending_event == Event::Write) {
            if (out.size() <= threshold)
                result = Event::Write;
        }
        if ((result==0)&&(last_errno != 0))
            result = Event::Error;
        return result;
    }

    void adjust_buffer_size() {
        block_size = (block_size > 1024) ? block_size : 1024;
        block_size += (block_size % 1024) ? 1024 : 0;
        block_size = (block_size / 1024) * 1024;
        buffer_size = (buffer_size > 1024 * 4) ? buffer_size : 1024 * 4;
        buffer_size = (buffer_size / block_size) * block_size;
        threshold = 0;
    }

    void event_handler(int revents) {
        if (revents & Event::Error)
            last_errno = -1;
        else {
            size_t from = 0;
            size_t size = 0;
            last_errno = 0;
            if (revents & Event::Read) {
                size = buffer_size - in.size();
                size = (size < block_size) ? size : block_size;
                if (size > 0) {
                    from = in.size();
                    in.resize(in.size() + size);
                    auto result = read_block(&(*(in.begin() + from)), size);
                    if (result.first > 0) {
                        if (result.first != size)
                            in.resize(in.size() - size + result.first);
                    } else
                        last_errno = result.second; // read error
                }
            }
            if ((last_errno == 0) && (revents & Event::Write)) {
                size = out.size() < block_size ? out.size() : block_size;
                if (size > 0) {
                    auto result = write_block(&(*out.begin()), size);
                    if (result.first > 0)
                        out.erase(out.begin(), out.begin() + result.first);
                    else
                        last_errno = result.second; // write error
                }
            }
        }
        // update I/O buffer mode
        if (last_errno == 0) {
            if ((revents & Event::Read) && (in.size() >= buffer_size))
                watcher::setup(fd(), mode() & Event::Write);
            if ((revents & Event::Write) && out.empty())
                watcher::setup(fd(), mode() & Event::Read);
        } else
            watcher::setup(fd(), 0);
        // generate buffer events
        if (pending_event) {
            auto buffer_events = check_buffer_task();
            if (buffer_events)
                on_event(buffer_events);
        }
    }
};
}
#endif // SQUALL__EVENT_BUFFER_HXX<|endoftext|>


<commit_before>// Copyright (c) 2014-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL

#ifndef TAO_PEGTL_DEMANGLE_HPP
#define TAO_PEGTL_DEMANGLE_HPP

#include <ciso646>
#include <string_view>

#include "config.hpp"

#include "internal/dependent_true.hpp"

namespace TAO_PEGTL_NAMESPACE
{
#if defined( __clang__ )

#if defined( _LIBCPP_VERSION )

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __PRETTY_FUNCTION__;
      constexpr auto begin = sv.find( '=' );
      static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) );
      return sv.substr( begin + 2, sv.size() - begin - 3 );
   }

#else

   // When using libstdc++ with clang, std::string_view::find is not constexpr :(
   template< char C >
   constexpr const char* find( const char* p, std::size_t n ) noexcept
   {
      while( n ) {
         if( *p == C ) {
            return p;
         }
         ++p;
         --n;
      }
      return nullptr;
   }

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __PRETTY_FUNCTION__;
      constexpr auto begin = find< '=' >( sv.data(), sv.size() );
      static_assert( internal::dependent_true< T > && ( begin != nullptr ) );
      return { begin + 2, sv.data() + sv.size() - begin - 3 };
   }

#endif

#elif defined( __GNUC__ )

#if( __GNUC__ == 7 )

   // GCC 7 wrongly sometimes disallows __PRETTY_FUNCTION__ in constexpr functions,
   // therefore we drop the 'constexpr' and hope for the best.
   template< typename T >
   [[nodiscard]] std::string_view demangle() noexcept
   {
      const std::string_view sv = __PRETTY_FUNCTION__;
      const auto begin = sv.find( '=' );
      const auto tmp = sv.substr( begin + 2 );
      const auto end = tmp.rfind( ';' );
      return tmp.substr( 0, end );
   }

#elif( __GNUC__ == 9 ) && ( __GNUC_MINOR__ < 3 )

   // GCC 9.1 and 9.2 have a bug that leads to truncated __PRETTY_FUNCTION__ names,
   // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155
   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      // fallback: requires RTTI, no demangling
      return typeid( T ).name();
   }

#else

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __PRETTY_FUNCTION__;
      constexpr auto begin = sv.find( '=' );
      static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) );
      constexpr auto tmp = sv.substr( begin + 2 );
      constexpr auto end = tmp.rfind( ';' );
      static_assert( internal::dependen_true< T > && ( end != std::string_view::npos ) );
      return tmp.substr( 0, end );
   }

#endif

#elif defined( _MSC_VER )

#if( _MSC_VER < 1920 )

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      const std::string_view sv = __FUNCSIG__;
      const auto begin = sv.find( "demangle<" );
      const auto tmp = sv.substr( begin + 9 );
      const auto end = tmp.rfind( '>' );
      return tmp.substr( 0, end );
   }

#else

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __FUNCSIG__;
      constexpr auto begin = sv.find( "demangle<" );
      static_assert( internal::dependen_true< T > && ( begin != std::string_view::npos ) );
      constexpr auto tmp = sv.substr( begin + 9 );
      constexpr auto end = tmp.rfind( '>' );
      static_assert( internal::dependent_true< T > && ( end != std::string_view::npos ) );
      return tmp.substr( 0, end );
   }

#endif

#else

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      // fallback: requires RTTI, no demangling
      return typeid( T ).name();
   }

#endif

}  // namespace TAO_PEGTL_NAMESPACE

#endif
<commit_msg>Fix typo.<commit_after>// Copyright (c) 2014-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL

#ifndef TAO_PEGTL_DEMANGLE_HPP
#define TAO_PEGTL_DEMANGLE_HPP

#include <ciso646>
#include <string_view>

#include "config.hpp"

#include "internal/dependent_true.hpp"

namespace TAO_PEGTL_NAMESPACE
{
#if defined( __clang__ )

#if defined( _LIBCPP_VERSION )

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __PRETTY_FUNCTION__;
      constexpr auto begin = sv.find( '=' );
      static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) );
      return sv.substr( begin + 2, sv.size() - begin - 3 );
   }

#else

   // When using libstdc++ with clang, std::string_view::find is not constexpr :(
   template< char C >
   constexpr const char* find( const char* p, std::size_t n ) noexcept
   {
      while( n ) {
         if( *p == C ) {
            return p;
         }
         ++p;
         --n;
      }
      return nullptr;
   }

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __PRETTY_FUNCTION__;
      constexpr auto begin = find< '=' >( sv.data(), sv.size() );
      static_assert( internal::dependent_true< T > && ( begin != nullptr ) );
      return { begin + 2, sv.data() + sv.size() - begin - 3 };
   }

#endif

#elif defined( __GNUC__ )

#if( __GNUC__ == 7 )

   // GCC 7 wrongly sometimes disallows __PRETTY_FUNCTION__ in constexpr functions,
   // therefore we drop the 'constexpr' and hope for the best.
   template< typename T >
   [[nodiscard]] std::string_view demangle() noexcept
   {
      const std::string_view sv = __PRETTY_FUNCTION__;
      const auto begin = sv.find( '=' );
      const auto tmp = sv.substr( begin + 2 );
      const auto end = tmp.rfind( ';' );
      return tmp.substr( 0, end );
   }

#elif( __GNUC__ == 9 ) && ( __GNUC_MINOR__ < 3 )

   // GCC 9.1 and 9.2 have a bug that leads to truncated __PRETTY_FUNCTION__ names,
   // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155
   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      // fallback: requires RTTI, no demangling
      return typeid( T ).name();
   }

#else

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __PRETTY_FUNCTION__;
      constexpr auto begin = sv.find( '=' );
      static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) );
      constexpr auto tmp = sv.substr( begin + 2 );
      constexpr auto end = tmp.rfind( ';' );
      static_assert( internal::dependent_true< T > && ( end != std::string_view::npos ) );
      return tmp.substr( 0, end );
   }

#endif

#elif defined( _MSC_VER )

#if( _MSC_VER < 1920 )

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      const std::string_view sv = __FUNCSIG__;
      const auto begin = sv.find( "demangle<" );
      const auto tmp = sv.substr( begin + 9 );
      const auto end = tmp.rfind( '>' );
      return tmp.substr( 0, end );
   }

#else

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      constexpr std::string_view sv = __FUNCSIG__;
      constexpr auto begin = sv.find( "demangle<" );
      static_assert( internal::dependent_true< T > && ( begin != std::string_view::npos ) );
      constexpr auto tmp = sv.substr( begin + 9 );
      constexpr auto end = tmp.rfind( '>' );
      static_assert( internal::dependent_true< T > && ( end != std::string_view::npos ) );
      return tmp.substr( 0, end );
   }

#endif

#else

   template< typename T >
   [[nodiscard]] constexpr std::string_view demangle() noexcept
   {
      // fallback: requires RTTI, no demangling
      return typeid( T ).name();
   }

#endif

}  // namespace TAO_PEGTL_NAMESPACE

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2013, Cloudera, inc.

#include "util/net/socket.h"

#include <errno.h>
#include <glog/logging.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <string>

#include "util/errno.h"
#include "util/net/sockaddr.h"

namespace kudu {

Socket::Socket()
  : fd_(-1) {
}

Socket::Socket(int fd)
  : fd_(fd) {
}

void Socket::Reset(int fd) {
  Close();
  fd_ = fd;
}

int Socket::Release() {
  int fd = fd_;
  fd_ = -1;
  return fd;
}

Socket::~Socket() {
  Close();
}

Status Socket::Close() {
  if (fd_ < 0)
    return Status::OK();
  int err, fd = fd_;
  fd_ = -1;
  if (::close(fd) < 0) {
    err = errno;
    return Status::NetworkError(std::string("close error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  fd = -1;
  return Status::OK();
}

Status Socket::Shutdown(bool shut_read, bool shut_write) {
  DCHECK_GE(fd_, 0);
  int flags = 0;
  if (shut_read && shut_write) {
    flags |= SHUT_RDWR;
  } else if (shut_read) {
    flags |= SHUT_RD;
  } else if (shut_write) {
    flags |= SHUT_WR;
  }
  if (::shutdown(fd_, flags) < 0) {
    int err = errno;
    return Status::NetworkError(std::string("shutdown error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  return Status::OK();
}

int Socket::GetFd() const {
  return fd_;
}

bool Socket::IsTemporarySocketError(int err) {
  return ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR));
}

#ifdef __linux

Status Socket::Init(int flags) {
  int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? SOCK_NONBLOCK : 0;
  Reset(::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC | nonblocking_flag, 0));
  if (fd_ < 0) {
    int err = errno;
    return Status::NetworkError(std::string("error opening socket: ") +
                                ErrnoToString(err), Slice(), err);
  }

  return Status::OK();
}

#else

#error This code has never been tested. Best of luck!

Status Socket::Init(int flags) {
  Reset(::socket(AF_INET, SOCK_STREAM, 0));
  if (fd_ < 0) {
    int err = errno;
    return Status::NetworkError(std::string("error opening socket: ") +
                                ErrnoToString(err), Slice(), err);
  }
  int curflags = fcntl(fd_, F_GETFL, 0);
  if (curflags == -1) {
    int err = errno;
    Reset(-1);
    return Status::NetworkError(std::string("fcntl(F_GETFL) error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? O_NONBLOCK : 0;
  if (fcntl(fd_, F_SETFL, curflags | nonblocking_flag | FD_CLOEXEC) == -1) {
    int err = errno;
    Reset(-1);
    return Status::NetworkError(std::string("fcntl(F_SETFL) error: ") +
                                ErrnoToString(err), Slice(), err);
  }

  // Disable SIGPIPE.
  RETURN_NOT_OK(DisableSigPipe());

  return Status::OK();
}

#endif

Status Socket::SetNoDelay(bool enabled) {
  int flag = enabled ? 1 : 0;
  if (setsockopt(fd_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag)) == -1) {
    int err = errno;
    return Status::NetworkError(std::string("failed to set TCP_NODELAY: ") +
                                ErrnoToString(err), Slice(), err);
  }
  return Status::OK();
}

Status Socket::BindAndListen(const Sockaddr &sockaddr,
                             int listenQueueSize) {
  int err;
  struct sockaddr_in addr = sockaddr.addr();

  DCHECK_GE(fd_, 0);
  if (bind(fd_, (struct sockaddr*) &addr, sizeof(addr))) {
    err = errno;
    return Status::NetworkError(
        StringPrintf("error binding socket to %s: %s",
            sockaddr.ToString().c_str(), ErrnoToString(err).c_str()),
        Slice(), err);
  }
  if (listen(fd_, listenQueueSize)) {
    err = errno;
    return Status::NetworkError(
        StringPrintf("error listening on %s: %s",
            sockaddr.ToString().c_str(), ErrnoToString(err).c_str()),
        Slice(), err);
  }
  return Status::OK();
}

Status Socket::GetSocketAddress(Sockaddr *cur_addr) {
  struct sockaddr_in sin;
  socklen_t len = sizeof(sin);
  DCHECK_GE(fd_, 0);
  if (getsockname(fd_, (struct sockaddr *)&sin, &len) == -1) {
    int err = errno;
    return Status::NetworkError(string("getsockname error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  *cur_addr = sin;
  return Status::OK();
}

Status Socket::Accept(Socket *new_conn, Sockaddr *remote, int flags) {
  struct sockaddr_in addr;
  socklen_t olen = sizeof(addr);
  int accept_flags = SOCK_CLOEXEC;
  if (flags & FLAG_NONBLOCKING) {
    accept_flags |= SOCK_NONBLOCK;
  }
  DCHECK_GE(fd_, 0);
  // TODO: add #ifdef accept4, etc.
  new_conn->Reset(::accept4(fd_, (struct sockaddr*)&addr,
                &olen, accept_flags));
  if (new_conn->GetFd() < 0) {
    int err = errno;
    return Status::NetworkError(std::string("accept4(2) error: ") +
                                ErrnoToString(err), Slice(), err);
  }

  *remote = addr;
  return Status::OK();
}

Status Socket::Connect(const Sockaddr &remote) {
  struct sockaddr_in addr;
  memcpy(&addr, &remote.addr(), sizeof(sockaddr_in));
  DCHECK_GE(fd_, 0);
  if (::connect(fd_, (const struct sockaddr*)&addr, sizeof(addr)) < 0) {
    int err = errno;
    return Status::NetworkError(std::string("connect(2) error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  return Status::OK();
}

Status Socket::GetSockError() {
  int val = 0, ret;
  socklen_t val_len = sizeof(val);
  DCHECK_GE(fd_, 0);
  ret = ::getsockopt(fd_, SOL_SOCKET, SO_ERROR, &val, &val_len);
  if (ret) {
    int err = errno;
    return Status::NetworkError(std::string("getsockopt(SO_ERROR) failed: ") +
                                ErrnoToString(err), Slice(), err);
  }
  if (val != 0) {
    return Status::NetworkError(ErrnoToString(val), Slice(), val);
  }
  return Status::OK();
}

Status Socket::Write(uint8_t *buf, int32_t amt, int32_t *nwritten) {
  if (amt <= 0) {
    return Status::NetworkError(
              StringPrintf("invalid send of %"PRId32" bytes",
                           amt), Slice(), EINVAL);
  }
  DCHECK_GE(fd_, 0);
  int res = ::write(fd_, buf, amt);
  if (res < 0) {
    int err = errno;
    return Status::NetworkError(std::string("write error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  *nwritten = res;
  return Status::OK();
}

Status Socket::Writev(const struct ::iovec *iov, int iov_len,
                      int32_t *nwritten) {
  if (PREDICT_FALSE(iov_len <= 0)) {
    return Status::NetworkError(
                StringPrintf("writev: invalid io vector length of %d",
                             iov_len),
                Slice(), EINVAL);
  }
  DCHECK_GE(fd_, 0);

  struct msghdr msg;
  memset(&msg, 0, sizeof(struct msghdr));
  msg.msg_iov = const_cast<iovec *>(iov);
  msg.msg_iovlen = iov_len;
  int res = sendmsg(fd_, &msg, MSG_NOSIGNAL);
  if (PREDICT_FALSE(res < 0)) {
    int err = errno;
    return Status::NetworkError(std::string("sendmsg error: ") +
                                ErrnoToString(err), Slice(), err);
  }

  *nwritten = res;
  return Status::OK();
}

Status Socket::Recv(uint8_t *buf, int32_t amt, int32_t *nread) {
  if (amt <= 0) {
    return Status::NetworkError(
          StringPrintf("invalid recv of %d bytes", amt), Slice(), EINVAL);
  }
  DCHECK_GE(fd_, 0);
  int res = ::recv(fd_, buf, amt, 0);
  if (res <= 0) {
    if (res == 0) {
      return Status::NetworkError("shut down by remote end", Slice(),
                                  ESHUTDOWN);
    }
    int err = errno;
    return Status::NetworkError(std::string("recv error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  *nread = res;
  return Status::OK();
}

} // namespace kudu
<commit_msg>socket: set SO_REUSEADDR when binding sockets<commit_after>// Copyright (c) 2013, Cloudera, inc.

#include "util/net/socket.h"

#include <errno.h>
#include <glog/logging.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <string>

#include "util/errno.h"
#include "util/net/sockaddr.h"

namespace kudu {

Socket::Socket()
  : fd_(-1) {
}

Socket::Socket(int fd)
  : fd_(fd) {
}

void Socket::Reset(int fd) {
  Close();
  fd_ = fd;
}

int Socket::Release() {
  int fd = fd_;
  fd_ = -1;
  return fd;
}

Socket::~Socket() {
  Close();
}

Status Socket::Close() {
  if (fd_ < 0)
    return Status::OK();
  int err, fd = fd_;
  fd_ = -1;
  if (::close(fd) < 0) {
    err = errno;
    return Status::NetworkError(std::string("close error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  fd = -1;
  return Status::OK();
}

Status Socket::Shutdown(bool shut_read, bool shut_write) {
  DCHECK_GE(fd_, 0);
  int flags = 0;
  if (shut_read && shut_write) {
    flags |= SHUT_RDWR;
  } else if (shut_read) {
    flags |= SHUT_RD;
  } else if (shut_write) {
    flags |= SHUT_WR;
  }
  if (::shutdown(fd_, flags) < 0) {
    int err = errno;
    return Status::NetworkError(std::string("shutdown error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  return Status::OK();
}

int Socket::GetFd() const {
  return fd_;
}

bool Socket::IsTemporarySocketError(int err) {
  return ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR));
}

#ifdef __linux

Status Socket::Init(int flags) {
  int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? SOCK_NONBLOCK : 0;
  Reset(::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC | nonblocking_flag, 0));
  if (fd_ < 0) {
    int err = errno;
    return Status::NetworkError(std::string("error opening socket: ") +
                                ErrnoToString(err), Slice(), err);
  }

  return Status::OK();
}

#else

#error This code has never been tested. Best of luck!

Status Socket::Init(int flags) {
  Reset(::socket(AF_INET, SOCK_STREAM, 0));
  if (fd_ < 0) {
    int err = errno;
    return Status::NetworkError(std::string("error opening socket: ") +
                                ErrnoToString(err), Slice(), err);
  }
  int curflags = fcntl(fd_, F_GETFL, 0);
  if (curflags == -1) {
    int err = errno;
    Reset(-1);
    return Status::NetworkError(std::string("fcntl(F_GETFL) error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  int nonblocking_flag = (flags & FLAG_NONBLOCKING) ? O_NONBLOCK : 0;
  if (fcntl(fd_, F_SETFL, curflags | nonblocking_flag | FD_CLOEXEC) == -1) {
    int err = errno;
    Reset(-1);
    return Status::NetworkError(std::string("fcntl(F_SETFL) error: ") +
                                ErrnoToString(err), Slice(), err);
  }

  // Disable SIGPIPE.
  RETURN_NOT_OK(DisableSigPipe());

  return Status::OK();
}

#endif

Status Socket::SetNoDelay(bool enabled) {
  int flag = enabled ? 1 : 0;
  if (setsockopt(fd_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag)) == -1) {
    int err = errno;
    return Status::NetworkError(std::string("failed to set TCP_NODELAY: ") +
                                ErrnoToString(err), Slice(), err);
  }
  return Status::OK();
}

Status Socket::BindAndListen(const Sockaddr &sockaddr,
                             int listenQueueSize) {
  int err;
  struct sockaddr_in addr = sockaddr.addr();

  int yes = 1;
  if (setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
    err = errno;
    return Status::NetworkError(std::string("failed to set SO_REUSEADDR: ") +
                                ErrnoToString(err), Slice(), err);
  }

  DCHECK_GE(fd_, 0);
  if (bind(fd_, (struct sockaddr*) &addr, sizeof(addr))) {
    err = errno;
    return Status::NetworkError(
        StringPrintf("error binding socket to %s: %s",
            sockaddr.ToString().c_str(), ErrnoToString(err).c_str()),
        Slice(), err);
  }
  if (listen(fd_, listenQueueSize)) {
    err = errno;
    return Status::NetworkError(
        StringPrintf("error listening on %s: %s",
            sockaddr.ToString().c_str(), ErrnoToString(err).c_str()),
        Slice(), err);
  }
  return Status::OK();
}

Status Socket::GetSocketAddress(Sockaddr *cur_addr) {
  struct sockaddr_in sin;
  socklen_t len = sizeof(sin);
  DCHECK_GE(fd_, 0);
  if (getsockname(fd_, (struct sockaddr *)&sin, &len) == -1) {
    int err = errno;
    return Status::NetworkError(string("getsockname error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  *cur_addr = sin;
  return Status::OK();
}

Status Socket::Accept(Socket *new_conn, Sockaddr *remote, int flags) {
  struct sockaddr_in addr;
  socklen_t olen = sizeof(addr);
  int accept_flags = SOCK_CLOEXEC;
  if (flags & FLAG_NONBLOCKING) {
    accept_flags |= SOCK_NONBLOCK;
  }
  DCHECK_GE(fd_, 0);
  // TODO: add #ifdef accept4, etc.
  new_conn->Reset(::accept4(fd_, (struct sockaddr*)&addr,
                &olen, accept_flags));
  if (new_conn->GetFd() < 0) {
    int err = errno;
    return Status::NetworkError(std::string("accept4(2) error: ") +
                                ErrnoToString(err), Slice(), err);
  }

  *remote = addr;
  return Status::OK();
}

Status Socket::Connect(const Sockaddr &remote) {
  struct sockaddr_in addr;
  memcpy(&addr, &remote.addr(), sizeof(sockaddr_in));
  DCHECK_GE(fd_, 0);
  if (::connect(fd_, (const struct sockaddr*)&addr, sizeof(addr)) < 0) {
    int err = errno;
    return Status::NetworkError(std::string("connect(2) error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  return Status::OK();
}

Status Socket::GetSockError() {
  int val = 0, ret;
  socklen_t val_len = sizeof(val);
  DCHECK_GE(fd_, 0);
  ret = ::getsockopt(fd_, SOL_SOCKET, SO_ERROR, &val, &val_len);
  if (ret) {
    int err = errno;
    return Status::NetworkError(std::string("getsockopt(SO_ERROR) failed: ") +
                                ErrnoToString(err), Slice(), err);
  }
  if (val != 0) {
    return Status::NetworkError(ErrnoToString(val), Slice(), val);
  }
  return Status::OK();
}

Status Socket::Write(uint8_t *buf, int32_t amt, int32_t *nwritten) {
  if (amt <= 0) {
    return Status::NetworkError(
              StringPrintf("invalid send of %"PRId32" bytes",
                           amt), Slice(), EINVAL);
  }
  DCHECK_GE(fd_, 0);
  int res = ::write(fd_, buf, amt);
  if (res < 0) {
    int err = errno;
    return Status::NetworkError(std::string("write error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  *nwritten = res;
  return Status::OK();
}

Status Socket::Writev(const struct ::iovec *iov, int iov_len,
                      int32_t *nwritten) {
  if (PREDICT_FALSE(iov_len <= 0)) {
    return Status::NetworkError(
                StringPrintf("writev: invalid io vector length of %d",
                             iov_len),
                Slice(), EINVAL);
  }
  DCHECK_GE(fd_, 0);

  struct msghdr msg;
  memset(&msg, 0, sizeof(struct msghdr));
  msg.msg_iov = const_cast<iovec *>(iov);
  msg.msg_iovlen = iov_len;
  int res = sendmsg(fd_, &msg, MSG_NOSIGNAL);
  if (PREDICT_FALSE(res < 0)) {
    int err = errno;
    return Status::NetworkError(std::string("sendmsg error: ") +
                                ErrnoToString(err), Slice(), err);
  }

  *nwritten = res;
  return Status::OK();
}

Status Socket::Recv(uint8_t *buf, int32_t amt, int32_t *nread) {
  if (amt <= 0) {
    return Status::NetworkError(
          StringPrintf("invalid recv of %d bytes", amt), Slice(), EINVAL);
  }
  DCHECK_GE(fd_, 0);
  int res = ::recv(fd_, buf, amt, 0);
  if (res <= 0) {
    if (res == 0) {
      return Status::NetworkError("shut down by remote end", Slice(),
                                  ESHUTDOWN);
    }
    int err = errno;
    return Status::NetworkError(std::string("recv error: ") +
                                ErrnoToString(err), Slice(), err);
  }
  *nread = res;
  return Status::OK();
}

} // namespace kudu
<|endoftext|>