net-cpp-2.0.0/0000775000175100017510000000000012553403521013441 5ustar tvosstvoss00000000000000net-cpp-2.0.0/CMakeLists.txt0000664000175100017510000000260012553403510016175 0ustar tvosstvoss00000000000000# Copyright © 2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authored by: Thomas Voss cmake_minimum_required(VERSION 2.8) project(net-cpp) find_package(Threads) include(GNUInstallDirs) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror -Wall -pedantic -Wextra -fvisibility=hidden") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Werror -Wall -fno-strict-aliasing -fvisibility=hidden -fvisibility-inlines-hidden -pedantic -Wextra") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--no-undefined") set(NET_CPP_VERSION_MAJOR 2) set(NET_CPP_VERSION_MINOR 0) set(NET_CPP_VERSION_PATCH 0) include(CTest) include_directories( include/ ) file(GLOB_RECURSE NET_CPP_INTERFACE_HEADERS include/*.h) add_subdirectory(doc) add_subdirectory(data) add_subdirectory(include) add_subdirectory(src) add_subdirectory(tests) net-cpp-2.0.0/symbols.map0000664000175100017510000000034512553403510015630 0ustar tvosstvoss00000000000000{ global: extern "C++" { core::*; typeinfo?for?core::*; typeinfo?name?for?core::*; VTT?for?core::*; virtual?thunk?to?core::*; vtable?for?core::*; std::hash*; }; local: extern "C++" { *; }; };net-cpp-2.0.0/src/0000775000175100017510000000000012553403521014230 5ustar tvosstvoss00000000000000net-cpp-2.0.0/src/CMakeLists.txt0000664000175100017510000000327312553403510016773 0ustar tvosstvoss00000000000000# Copyright © 2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authored by: Thomas Voss find_package(Boost COMPONENTS system serialization REQUIRED) find_package(CURL REQUIRED) include_directories(${Boost_INCLUDE_DIRS} ${CURL_INCLUDE_DIRS}) add_library( net-cpp SHARED ${NET_CPP_INTERFACE_HEADERS} core/location.cpp core/net/error.cpp core/net/uri.cpp core/net/http/client.cpp core/net/http/error.cpp core/net/http/header.cpp core/net/http/request.cpp core/net/http/status.cpp core/net/http/impl/curl/client.cpp core/net/http/impl/curl/easy.cpp core/net/http/impl/curl/multi.cpp core/net/http/impl/curl/shared.cpp ) target_link_libraries( net-cpp ${CMAKE_THREAD_LIBS_INIT} ${Boost_LIBRARIES} ${CURL_LIBRARIES} ) set(symbol_map "${CMAKE_SOURCE_DIR}/symbols.map") set_target_properties( net-cpp PROPERTIES LINK_FLAGS "${ldflags} -Wl,--version-script,${symbol_map}" LINK_DEPENDS ${symbol_map} VERSION ${NET_CPP_VERSION_MAJOR}.${NET_CPP_VERSION_MINOR}.${NET_CPP_VERSION_PATCH} SOVERSION ${NET_CPP_VERSION_MAJOR} ) install( TARGETS net-cpp LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ) net-cpp-2.0.0/src/core/0000775000175100017510000000000012553403521015160 5ustar tvosstvoss00000000000000net-cpp-2.0.0/src/core/net/0000775000175100017510000000000012553403521015746 5ustar tvosstvoss00000000000000net-cpp-2.0.0/src/core/net/http/0000775000175100017510000000000012553403521016725 5ustar tvosstvoss00000000000000net-cpp-2.0.0/src/core/net/http/client.cpp0000664000175100017510000000461412553403510020712 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include namespace net = core::net; namespace http = net::http; http::Client::Errors::HttpMethodNotSupported::HttpMethodNotSupported( http::Method method, const core::Location& loc) : http::Error("Http method not suppored", loc), method(method) { } std::shared_ptr http::Client::post_form( const http::Request::Configuration& configuration, const std::map& values) { std::stringstream ss; bool first{true}; for (const auto& pair : values) { ss << (first ? "" : "&") << url_escape(pair.first) << "=" << url_escape(pair.second); first = false; } return post(configuration, ss.str(), http::ContentType::x_www_form_urlencoded); } std::string http::Client::uri_to_string(const core::net::Uri& uri) const { std::ostringstream s; // Start with the host of the URI s << uri.host; // Append each of the components of the path for (const std::string& part : uri.path) { s << "/" << url_escape(part); } // Append the parameters bool first = true; for (const std::pair& query_parameter : uri.query_parameters) { if (first) { // The first parameter needs a ? s << "?"; first = false; } else { // The rest are separated with a & s << "&"; } // URL escape the parameters s << url_escape(query_parameter.first) << "=" << url_escape(query_parameter.second); } // We're done return s.str(); } net-cpp-2.0.0/src/core/net/http/request.cpp0000664000175100017510000000337112553403510021123 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include namespace http = core::net::http; http::Request::Errors::AlreadyActive::AlreadyActive(const core::Location& loc) : http::Error("Request is already active.", loc) { } const http::Request::ProgressHandler& http::Request::Handler::on_progress() const { return progress_handler; } http::Request::Handler& http::Request::Handler::on_progress(const http::Request::ProgressHandler& handler) { progress_handler = handler; return *this; } const http::Request::ResponseHandler& http::Request::Handler::on_response() const { return response_handler; } http::Request::Handler& http::Request::Handler::on_response(const http::Request::ResponseHandler& handler) { response_handler = handler; return *this; } const http::Request::ErrorHandler& http::Request::Handler::on_error() const { return error_handler; } http::Request::Handler& http::Request::Handler::on_error(const http::Request::ErrorHandler& handler) { error_handler = handler; return *this; } net-cpp-2.0.0/src/core/net/http/header.cpp0000664000175100017510000000435112553403510020662 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include namespace http = core::net::http; bool http::Header::has(const std::string& key, const std::string& value) const { auto it = fields.find(canonicalize_key(key)); if (it == fields.end()) return false; return it->second.count(value) > 0; } bool http::Header::has(const std::string& key) const { return fields.count(canonicalize_key(key)) > 0; } void http::Header::add(const std::string& key, const std::string& value) { fields[canonicalize_key(key)].insert(value); } void http::Header::remove(const std::string& key) { fields.erase(canonicalize_key(key)); } void http::Header::remove(const std::string& key, const std::string& value) { auto it = fields.find(canonicalize_key(key)); if (it != fields.end()) { it->second.erase(value); } } void http::Header::set(const std::string& key, const std::string& value) { fields[canonicalize_key(key)] = std::set{value}; } std::string http::Header::canonicalize_key(const std::string& key) { std::string result{key}; bool should_be_capitalized{true}; for (auto it = result.begin(), itE = result.end(); it != itE; ++it) { *it = should_be_capitalized ? std::toupper(*it) : std::tolower(*it); should_be_capitalized = *it == '-'; } return result; } void http::Header::enumerate(const std::function&)>& enumerator) const { for (const auto& pair : fields) enumerator(pair.first, pair.second); } net-cpp-2.0.0/src/core/net/http/status.cpp0000664000175100017510000000703612553403510020760 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include namespace http = core::net::http; std::ostream& http::operator<<(std::ostream& out, http::Status status) { static const std::map lut = { {http::Status::continue_, "continue_(100)"}, {http::Status::switching_protocols, "switching_protocols(101)"}, {http::Status::ok, "ok(200)"}, {http::Status::created, "created(201)"}, {http::Status::accepted, "accepted(202)"}, {http::Status::non_authorative_info, "non_authorative_info(203)"}, {http::Status::no_content, "no_content(204)"}, {http::Status::reset_content, "reset_content(205)"}, {http::Status::partial_content, "partial_content(206)"}, {http::Status::multiple_choices, "multiple_choices(300)"}, {http::Status::moved_permanently, "moved_permanently(301)"}, {http::Status::found, "found(302)"}, {http::Status::see_other, "see_other(303)"}, {http::Status::not_modified, "not_modified(304)"}, {http::Status::use_proxy, "use_proxy(305)"}, {http::Status::temporary_redirect, "temporary_redirect(307)"}, {http::Status::bad_request, "bad_request(400)"}, {http::Status::unauthorized, "unauthorized(401)"}, {http::Status::payment_required, "payment_required(402)"}, {http::Status::forbidden, "forbidden(403)"}, {http::Status::not_found, "not_found(404)"}, {http::Status::method_not_allowed, "method_not_allowed(405)"}, {http::Status::not_acceptable, "not_acceptable(406)"}, {http::Status::proxy_auth_required, "proxy_auth_required(407)"}, {http::Status::request_timeout, "request_timeout(408)"}, {http::Status::conflict, "conflict(409)"}, {http::Status::gone, "gone(410)"}, {http::Status::length_required, "length_required(411)"}, {http::Status::precondition_failed, "precondition_failed(412)"}, {http::Status::request_entity_too_large, "request_entity_too_large(413)"}, {http::Status::request_uri_too_long, "request_uri_too_long(414)"}, {http::Status::unsupported_media_type, "unsupported_media_type(415)"}, {http::Status::requested_range_not_satisfiable, "requested_range_not_satisfiable(416)"}, {http::Status::expectation_failed, "expectation_failed(417)"}, {http::Status::teapot, "teapot(418)"}, {http::Status::internal_server_error, "internal_server_error(500)"}, {http::Status::not_implemented, "not_implemented(501)"}, {http::Status::bad_gateway, "bad_gateway(502)"}, {http::Status::service_unavailable, "service_unavailable(503)"}, {http::Status::gateway_timeout, "gateway_timeout(504)"}, {http::Status::http_version_not_supported, "http_version_not_supported(505)"} }; return out << lut.at(status); } net-cpp-2.0.0/src/core/net/http/error.cpp0000664000175100017510000000161412553403510020562 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include namespace net = core::net; namespace http = core::net::http; http::Error::Error(const std::string& what, const core::Location& loc) : net::Error(what, loc) { } net-cpp-2.0.0/src/core/net/http/impl/0000775000175100017510000000000012553403521017666 5ustar tvosstvoss00000000000000net-cpp-2.0.0/src/core/net/http/impl/curl/0000775000175100017510000000000012553403521020633 5ustar tvosstvoss00000000000000net-cpp-2.0.0/src/core/net/http/impl/curl/curl.h0000664000175100017510000000157112553403510021753 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_IMPL_CURL_CURL_H_ #define CORE_NET_HTTP_IMPL_CURL_CURL_H_ #include "easy.h" #include "multi.h" #include "shared.h" #endif // CORE_NET_HTTP_IMPL_CURL_CURL_H_ net-cpp-2.0.0/src/core/net/http/impl/curl/multi.cpp0000664000175100017510000004261512553403510022477 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include "multi.h" #include "easy.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace acc = boost::accumulators; namespace easy = ::curl::easy; namespace multi = ::curl::multi; namespace { struct SynchronizedHandleStore { std::mutex guard; std::map handles; void add(easy::Handle easy) { std::lock_guard lg(guard); handles.insert(std::make_pair(easy.native(), easy)); } void remove(easy::Handle easy) { std::lock_guard lg(guard); handles.erase(easy.native()); } easy::Handle lookup_native(CURL* native) { std::lock_guard lg(guard); auto it = handles.find(native); if (it == handles.end()) throw std::runtime_error("SynchronizedHandleStore::lookup_native: No such handle."); return it->second; } }; template struct Holder { std::shared_ptr value; }; } std::ostream& multi::operator<<(std::ostream& out, multi::Code code) { switch (code) { case multi::Code::call_multi_perform: out << "curl::multi::Code::call_multi_perform"; break; case multi::Code::ok: out << "curl::multi::Code::ok"; break; case multi::Code::bad_handle: out << "curl::multi::Code::bad_handle"; break; case multi::Code::bad_easy_handle: out << "curl::multi::Code::easy_handle"; break; case multi::Code::out_of_memory: out << "curl::multi::Code::out_of_memory"; break; case multi::Code::internal_error: out << "curl::multi::Code::internal_error"; break; case multi::Code::bad_socket: out << "curl::multi::Code::bad_socket"; break; case multi::Code::unknown_option: out << "curl::multi::Code::unknown_option"; break; case multi::Code::added_already: out << "curl::multi::Code::added_already"; break; } return out; } multi::native::Handle multi::native::init() { return curl_multi_init(); } multi::Code multi::native::cleanup(multi::native::Handle handle) { return static_cast(curl_multi_cleanup(handle)); } multi::Code multi::native::assign(multi::native::Handle handle, multi::native::Socket socket, void* cookie) { return static_cast(curl_multi_assign(handle, socket, cookie)); } multi::Code multi::native::add_handle(multi::native::Handle m, easy::native::Handle e) { return static_cast(curl_multi_add_handle(m, e)); } multi::Code multi::native::remove_handle(multi::native::Handle m, easy::native::Handle e) { return static_cast(curl_multi_remove_handle(m, e)); } std::pair multi::native::read_info(multi::native::Handle handle) { int count{-1}; auto msg = curl_multi_info_read(handle, &count); return std::make_pair(msg, count); } std::pair multi::native::socket_action(multi::native::Handle handle, multi::native::Socket socket, int events) { int count{-1}; auto rc = static_cast( curl_multi_socket_action( handle, socket, events, &count)); return std::make_pair(rc, count); } struct multi::Handle::Private { void process_multi_info(); static int timer_callback( multi::native::Handle, long timeout_ms, void* cookie); struct Timeout { Timeout(boost::asio::io_service& dispatcher); void cancel(); void async_wait_for( const std::shared_ptr& context, const std::chrono::milliseconds& ms); struct Private : public std::enable_shared_from_this { Private(boost::asio::io_service& dispatcher); void cancel(); void async_wait_for( const std::weak_ptr& context, const std::chrono::milliseconds& ms); void handle_timeout(const std::shared_ptr& context); boost::asio::deadline_timer timer; }; std::shared_ptr d; }; static int socket_callback( easy::native::Handle, multi::native::Socket s, int action, void* cookie, void* socket_cookie); struct Socket { Socket(boost::asio::io_service& dispatcher, multi::native::Socket native); ~Socket(); void async_wait_for_readable(const std::weak_ptr& context); void async_wait_for_writeable(const std::weak_ptr& context); struct Private : public std::enable_shared_from_this { Private(boost::asio::io_service& dispatcher, multi::native::Socket native); ~Private(); void cancel(); void async_wait_for_readable(const std::weak_ptr& context); void async_wait_for_writeable(std::weak_ptr context); bool cancel_requested; boost::asio::posix::stream_descriptor sd; }; std::shared_ptr d; }; typedef acc::accumulator_set< double, acc::stats< acc::tag::min, acc::tag::max, acc::tag::mean, acc::tag::variance > > Accumulator; static void fill_from_accumulator(core::net::http::Client::Timings::Statistics& stats, const multi::Handle::Private::Accumulator& accu) { typedef core::net::http::Client::Timings::Seconds Seconds; stats.max = Seconds{acc::max(accu)}; stats.min = Seconds{acc::min(accu)}; stats.mean = Seconds{acc::mean(accu)}; stats.variance = Seconds{acc::variance(accu)}; } Private(); ~Private(); void update_timings(const easy::Handle::Timings& timings); multi::native::Handle handle; boost::asio::io_service dispatcher; boost::asio::io_service::work keep_alive; std::mutex guard; SynchronizedHandleStore handle_store; Timeout timeout; struct { Accumulator for_name_look_up{}; Accumulator for_connect{}; Accumulator for_app_connect{}; Accumulator for_pre_transfer{}; Accumulator for_start_transfer{}; Accumulator for_total{}; } accumulator; struct Holder { std::weak_ptr value; } holder; }; multi::Handle::Handle() : d(new Private()) { d->holder.value = d; set_option(Option::socket_function, Private::socket_callback); set_option(Option::socket_data, &d->holder); set_option(Option::timer_function, Private::timer_callback); set_option(Option::timer_data, &d->holder); set_option(Option::pipelining, easy::enable); } core::net::http::Client::Timings multi::Handle::timings() { core::net::http::Client::Timings result; Private::fill_from_accumulator(result.name_look_up, d->accumulator.for_name_look_up); Private::fill_from_accumulator(result.connect, d->accumulator.for_connect); Private::fill_from_accumulator(result.app_connect, d->accumulator.for_app_connect); Private::fill_from_accumulator(result.pre_transfer, d->accumulator.for_pre_transfer); Private::fill_from_accumulator(result.start_transfer, d->accumulator.for_start_transfer); Private::fill_from_accumulator(result.total, d->accumulator.for_total); return result; } void multi::Handle::run() { d->dispatcher.run(); } void multi::Handle::stop() { d->dispatcher.stop(); } void multi::Handle::add(easy::Handle easy) { std::lock_guard lg(d->guard); d->handle_store.add(easy); multi::throw_if_not( multi::native::add_handle( native(), easy.native())); } void multi::Handle::remove(easy::Handle easy) { d->handle_store.remove(easy); multi::throw_if_not( multi::native::remove_handle( native(), easy.native())); } curl::easy::Handle multi::Handle::easy_handle_from_native(easy::native::Handle native) { return d->handle_store.lookup_native(native); } multi::native::Handle multi::Handle::native() const { return d->handle; } void multi::Handle::Private::process_multi_info() { while (true) { multi::native::Message msg; int count; std::tie(msg, count) = multi::native::read_info(handle); if (!msg) break; if (msg->msg == CURLMSG_DONE) { auto native_easy = msg->easy_handle; auto rc = static_cast(msg->data.result); try { auto easy = handle_store.lookup_native(native_easy); update_timings(easy.timings()); easy.notify_finished(rc); handle_store.remove(easy); multi::native::remove_handle(handle, native_easy); } catch(...) { std::cout << "Something weird happened" << std::endl; } } } } multi::Handle::Private::Timeout::Timeout(boost::asio::io_service& dispatcher) : d(new Private(dispatcher)) { } void multi::Handle::Private::Timeout::cancel() { } void multi::Handle::Private::Timeout::async_wait_for(const std::shared_ptr& context, const std::chrono::milliseconds& ms) { d->async_wait_for(context, ms); } multi::Handle::Private::Timeout::Private::Private(boost::asio::io_service& dispatcher) : timer(dispatcher) { } void multi::Handle::Private::Timeout::Private::cancel() { timer.cancel(); } void multi::Handle::Private::Timeout::Private::async_wait_for(const std::weak_ptr& context, const std::chrono::milliseconds& ms) { if (ms.count() > 0) { std::weak_ptr self{shared_from_this()}; timer.expires_from_now(boost::posix_time::milliseconds{ms.count()}); timer.async_wait([self, context](const boost::system::error_code& ec) { if (ec) return; if (auto spc = context.lock()) { if (auto sp = self.lock()) { std::lock_guard lg(spc->guard); sp->handle_timeout(spc); } } }); } else if (ms.count() == 0) { auto sp = context.lock(); if (not sp) return; handle_timeout(sp); } } void multi::Handle::Private::Timeout::Private::handle_timeout(const std::shared_ptr& context) { auto result = multi::native::socket_action(context->handle, CURL_SOCKET_TIMEOUT, 0); multi::throw_if_not(result.first); context->process_multi_info(); } int multi::Handle::Private::timer_callback( multi::native::Handle, long timeout_ms, void* cookie) { if (timeout_ms < 0) return -1; auto holder = static_cast(cookie); if (!holder) return 0; auto thiz = holder->value.lock(); thiz->timeout.async_wait_for(thiz, std::chrono::milliseconds{timeout_ms}); return 0; } multi::Handle::Private::Socket::Socket(boost::asio::io_service& dispatcher, multi::native::Socket native) : d(new Private(dispatcher, native)) { } multi::Handle::Private::Socket::~Socket() { d->cancel(); } void multi::Handle::Private::Socket::async_wait_for_readable(const std::weak_ptr& context) { d->async_wait_for_readable(context); } void multi::Handle::Private::Socket::async_wait_for_writeable(const std::weak_ptr& context) { d->async_wait_for_writeable(context); } multi::Handle::Private::Socket::Socket::Private::Private(boost::asio::io_service& dispatcher, multi::native::Socket native) : cancel_requested(false), sd(dispatcher, static_cast(native)) { } multi::Handle::Private::Socket::Socket::Private::~Private() { sd.release(); } void multi::Handle::Private::Socket::Socket::Private::cancel() { cancel_requested = true; sd.release(); } void multi::Handle::Private::Socket::Socket::Private::async_wait_for_readable(const std::weak_ptr& context) { std::weak_ptr self{shared_from_this()}; sd.async_read_some(boost::asio::null_buffers{}, [self, context](const boost::system::error_code& ec, std::size_t) { if (ec == boost::asio::error::operation_aborted) return; if (auto sp = self.lock()) { if (sp->cancel_requested) return; if (auto spc = context.lock()) { std::lock_guard lg(spc->guard); int bitmask{0}; if (ec) bitmask = CURL_CSELECT_ERR; else bitmask = CURL_CSELECT_IN; auto result = multi::native::socket_action(spc->handle, sp->sd.native_handle(), bitmask); multi::throw_if_not(result.first); spc->process_multi_info(); if (result.second <= 0) spc->timeout.cancel(); // Restart sp->async_wait_for_readable(context); } } }); } void multi::Handle::Private::Socket::Socket::Private::async_wait_for_writeable( std::weak_ptr context) { std::weak_ptr self(shared_from_this()); sd.async_write_some(boost::asio::null_buffers{}, [self, context](const boost::system::error_code& ec, std::size_t) { if (ec == boost::asio::error::operation_aborted) return; if (auto sp = self.lock()) { if (sp->cancel_requested) return; if (auto spc = context.lock()) { std::lock_guard lg(spc->guard); int bitmask{0}; if (ec) bitmask = CURL_CSELECT_ERR; else bitmask = CURL_CSELECT_OUT; auto result = multi::native::socket_action(spc->handle, sp->sd.native_handle(), bitmask); multi::throw_if_not(result.first); spc->process_multi_info(); if (result.second <= 0) spc->timeout.cancel(); } // Restart sp->async_wait_for_writeable(context); } }); } int multi::Handle::Private::socket_callback( easy::native::Handle, multi::native::Socket s, int action, void* cookie, void* socket_cookie) { static const int doc_tells_we_must_return_0{0}; auto holder = static_cast(cookie); if (!holder) return doc_tells_we_must_return_0; auto thiz = holder->value.lock(); auto socket = static_cast(socket_cookie); if (!socket) { socket = new Socket{thiz->dispatcher, s}; multi::throw_if_not(multi::native::assign(thiz->handle, s, socket)); } switch (action) { case CURL_POLL_NONE: { break; } case CURL_POLL_IN: socket->async_wait_for_readable(thiz); break; case CURL_POLL_OUT: socket->async_wait_for_writeable(thiz); break; case CURL_POLL_INOUT: socket->async_wait_for_readable(thiz); socket->async_wait_for_writeable(thiz); break; case CURL_POLL_REMOVE: { multi::native::assign(thiz->handle, s, nullptr); delete socket; break; } } return doc_tells_we_must_return_0; } multi::Handle::Private::Private() : handle(multi::native::init()), keep_alive(dispatcher), timeout(dispatcher) { } multi::Handle::Private::~Private() { multi::native::cleanup(handle); } void multi::Handle::Private::update_timings(const easy::Handle::Timings& timings) { accumulator.for_name_look_up(timings.name_look_up.count()); accumulator.for_connect(timings.connect.count()); accumulator.for_app_connect(timings.app_connect.count()); accumulator.for_pre_transfer(timings.pre_transfer.count()); accumulator.for_start_transfer(timings.start_transfer.count()); accumulator.for_total(timings.total.count()); } net-cpp-2.0.0/src/core/net/http/impl/curl/easy.cpp0000664000175100017510000002756712553403510022317 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include "easy.h" #include "shared.h" #include #include #include #include #include #include #include #include namespace easy = ::curl::easy; namespace shared = ::curl::shared; namespace { struct Init { Init() { curl::easy::throw_if_not(curl::easy::native::global::init()); } ~Init() { curl::easy::native::global::cleanup(); } } init; } std::ostream& curl::operator<<(std::ostream& out, curl::Code code) { return out << curl_easy_strerror(static_cast(code)); } std::string curl::native::escape(const std::string& in) { auto escaped = curl_escape(in.c_str(), in.size()); std::string result{(escaped ? escaped : "")}; if (escaped) curl_free(escaped); return result; } ::curl::Code curl::easy::native::global::init() { return static_cast<::curl::Code>(curl_global_init(CURL_GLOBAL_DEFAULT)); } void curl::easy::native::global::cleanup() { curl_global_cleanup(); } std::string easy::print_error(curl::Code code) { return std::string{curl_easy_strerror(static_cast(code))}; } easy::native::Handle easy::native::init() { return curl_easy_init(); } void easy::native::cleanup(easy::native::Handle handle) { curl_easy_cleanup(handle); } ::curl::Code easy::native::perform(easy::native::Handle handle) { return static_cast(curl_easy_perform(handle)); } std::string easy::native::escape(easy::native::Handle handle, const std::string& in) { auto escaped = curl_easy_escape(handle, in.c_str(), in.size()); std::string result{(escaped ? escaped : "")}; if (escaped) curl_free(escaped); return result; } // URL unescapes the given input string. std::string easy::native::unescape(easy::native::Handle handle, const std::string& in) { int out_length{0}; auto escaped = curl_easy_unescape(handle, in.c_str(), in.size(), &out_length); std::string result; if (escaped) { result = std::string{escaped, static_cast(out_length)}; curl_free(escaped); } return result; } // Append a string to a string list ::curl::StringList* ::curl::native::append_string_to_list(::curl::StringList* in, const char* string) { return curl_slist_append(in, string); } // Frees the overall string list void ::curl::native::free_string_list(::curl::StringList* in) { curl_slist_free_all(in); } struct easy::Handle::Private { Private() : handle(easy::native::init(), [](easy::native::Handle handle) { easy::native::cleanup(handle); }), header_string_list(nullptr) { } ~Private() { if (header_string_list) ::curl::native::free_string_list(header_string_list); } std::shared_ptr handle; easy::Handle::OnFinished on_finished_cb; easy::Handle::OnProgress on_progress; easy::Handle::OnReadData on_read_data_cb; easy::Handle::OnWriteData on_write_data_cb; easy::Handle::OnWriteHeader on_write_header_cb; ::curl::StringList* header_string_list; char error[CURL_ERROR_SIZE]; }; int easy::Handle::progress_cb(void* data, double dltotal, double dlnow, double ultotal, double ulnow) { static const int continue_operation = 0; auto thiz = static_cast(data); if (thiz && thiz->on_progress) { return thiz->on_progress(data, dltotal, dlnow, ultotal, ulnow); } return continue_operation; } std::size_t easy::Handle::write_data_cb(char* data, size_t size, size_t nmemb, void* cookie) { static const std::size_t did_not_consume_any_data = 0; auto thiz = static_cast(cookie); if (thiz && thiz->on_write_data_cb) { return thiz->on_write_data_cb(data, size, nmemb); } return did_not_consume_any_data; } std::size_t easy::Handle::write_header_cb(void* data, size_t size, size_t nmemb, void* cookie) { static const std::size_t did_not_consume_any_data = 0; auto thiz = static_cast(cookie); if (thiz && thiz->on_write_header_cb) { return thiz->on_write_header_cb(data, size, nmemb); } return did_not_consume_any_data; } std::size_t easy::Handle::read_data_cb(void* data, std::size_t size, std::size_t nmemb, void *cookie) { static const std::size_t did_not_consume_any_data = 0; auto thiz = static_cast(cookie); if (thiz && thiz->on_read_data_cb) { return thiz->on_read_data_cb(data, size, nmemb); } return did_not_consume_any_data; } easy::Handle::HandleHasBeenAbandoned::HandleHasBeenAbandoned() : std::runtime_error("Handle has been abandoned.") { } easy::Handle::Handle() : d(new Private()) { set_option(Option::http_auth, CURLAUTH_ANY); set_option(Option::error_buffer, d->error); set_option(Option::ssl_engine_default, easy::enable); set_option(Option::no_signal, easy::enable); } void easy::Handle::release() { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; d.reset(); } easy::Handle::Timings easy::Handle::timings() { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; easy::Handle::Timings result; double value; get_option(::curl::Info::namelookup_time, &value); result.name_look_up = easy::Handle::Timings::Seconds{value}; get_option(::curl::Info::connect_time, &value); result.connect = easy::Handle::Timings::Seconds{value} - result.name_look_up; get_option(::curl::Info::pretransfer_time, &value); result.pre_transfer = easy::Handle::Timings::Seconds{value} - (result.connect + result.name_look_up); get_option(::curl::Info::starttransfer_time, &value); result.start_transfer = easy::Handle::Timings::Seconds{value} - (result.pre_transfer + result.connect + result.name_look_up); get_option(::curl::Info::total_time, &value); result.total = easy::Handle::Timings::Seconds{value}; get_option(::curl::Info::appconnect_time, &value); result.app_connect = easy::Handle::Timings::Seconds{value}; return result; } easy::Handle& easy::Handle::url(const char* url) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; set_option(Option::url, url); return *this; } easy::Handle& easy::Handle::user_agent(const char* user_agent) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; set_option(Option::user_agent, user_agent); return *this; } easy::Handle& easy::Handle::http_credentials(const std::string& username, const std::string& pwd) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; set_option(Option::username, username.c_str()); set_option(Option::password, pwd.c_str()); return *this; } easy::Handle& easy::Handle::on_finished(const easy::Handle::OnFinished& on_finished) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; d->on_finished_cb = on_finished; return *this; } easy::Handle& easy::Handle::on_progress(const easy::Handle::OnProgress& on_progress) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; set_option(Option::no_progress, curl::easy::disable); set_option(Option::progress_function, Handle::progress_cb); set_option(Option::progress_data, d.get()); d->on_progress = on_progress; return *this; } easy::Handle& easy::Handle::on_read_data(const easy::Handle::OnReadData& on_read_data, std::size_t size) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; set_option(Option::read_function, Handle::read_data_cb); set_option(Option::read_data, d.get()); set_option(Option::in_file_size, size); d->on_read_data_cb = on_read_data; return *this; } easy::Handle& easy::Handle::on_write_data(const easy::Handle::OnWriteData& on_new_data) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; set_option(Option::write_function, Handle::write_data_cb); set_option(Option::write_data, d.get()); d->on_write_data_cb = on_new_data; return *this; } easy::Handle& easy::Handle::on_write_header(const easy::Handle::OnWriteHeader& on_new_header) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; set_option(Option::header_function, Handle::write_header_cb); set_option(Option::header_data, d.get()); d->on_write_header_cb = on_new_header; return *this; } easy::Handle& easy::Handle::method(core::net::http::Method method) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; switch(method) { case core::net::http::Method::get: set_option(Option::http_get, enable); break; case core::net::http::Method::head: set_option(Option::http_get, disable); set_option(Option::http_put, disable); set_option(Option::http_post, disable); break; case core::net::http::Method::post: set_option(Option::http_post, enable); break; case core::net::http::Method::put: set_option(Option::http_put, enable); break; default: throw core::net::http::Client::Errors::HttpMethodNotSupported{method, CORE_FROM_HERE()}; } return *this; } easy::Handle& easy::Handle::post_data(const std::string& data, const std::string&) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; long content_length = data.size(); set_option(Option::post_field_size, content_length); set_option(Option::copy_postfields, data.c_str()); return *this; } easy::Handle& easy::Handle::header(const core::net::http::Header& header) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; static constexpr const char* separator = ": "; header.enumerate([this](const std::string& key, const std::set& values) { for (const auto& value : values) { std::stringstream ss; ss << key << separator << value; d->header_string_list = ::curl::native::append_string_to_list(d->header_string_list, ss.str().c_str()); } }); if (d->header_string_list) set_option(Option::http_header, d->header_string_list); return *this; } core::net::http::Status easy::Handle::status() { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; long result; get_option(curl::Info::response_code, &result); return static_cast(result); } easy::native::Handle easy::Handle::native() const { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; return d->handle.get(); } void easy::Handle::perform() { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; throw_if_not(easy::native::perform(native()), [this]() { return std::string{d->error};}); } // URL escapes the given input string. std::string easy::Handle::escape(const std::string& in) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; return easy::native::escape(native(), in); } // URL unescapes the given input string. std::string easy::Handle::unescape(const std::string& in) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; return easy::native::unescape(native(), in); } void easy::Handle::notify_finished(curl::Code code) { if (!d) throw easy::Handle::HandleHasBeenAbandoned{}; if (d->on_finished_cb) d->on_finished_cb(code); } std::string easy::Handle::error() const { return std::string{d->error}; } net-cpp-2.0.0/src/core/net/http/impl/curl/shared.h0000664000175100017510000000203112553403510022244 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_IMPL_CURL_SHARED_H_ #define CORE_NET_HTTP_IMPL_CURL_SHARED_H_ #include namespace curl { namespace shared { typedef void* Native; class Handle { public: Handle(); Native native() const; private: struct Private; std::shared_ptr d; }; } } #endif // CORE_NET_HTTP_IMPL_CURL_SHARED_H_ net-cpp-2.0.0/src/core/net/http/impl/curl/multi.h0000664000175100017510000001364112553403510022141 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_IMPL_CURL_MULTI_H_ #define CORE_NET_HTTP_IMPL_CURL_MULTI_H_ #include "easy.h" namespace curl { namespace multi { // Return codes for native curl multi functions. enum class Code { // Indicates to the app that curl_multi_perform should be called. call_multi_perform = CURLM_CALL_MULTI_PERFORM, // All good. ok = CURLM_OK, // A bad native curl multi handle has been passed. bad_handle = CURLM_BAD_HANDLE, // A bad native curl easy handle has been passed. bad_easy_handle = CURLM_BAD_EASY_HANDLE, // Out of memory. out_of_memory = CURLM_OUT_OF_MEMORY, // An internal libcurl bug occured. internal_error = CURLM_INTERNAL_ERROR, // The underlying socket went havoc. bad_socket = CURLM_BAD_SOCKET, // An unknown option has been passed to curl::multi::native::set. unknown_option = CURLM_UNKNOWN_OPTION, // The native curl easy handle is already known to the curl multi instance. added_already = CURLM_ADDED_ALREADY }; std::ostream& operator<<(std::ostream& out, Code code); // Known options that can be set on a curl multi instance. enum class Option { // Controls pipelining behavior for multiple connections. // Expects a long value, pass 1 for enabling, 0 for disabling. pipelining = CURLMOPT_PIPELINING, // Callback function for associating a socket with an alien event loop. socket_function = CURLMOPT_SOCKETFUNCTION, // Cookie passed to invocation of the socket callback function. socket_data = CURLMOPT_SOCKETDATA, // Callback function for associating a timeout with an alien event loop. timer_function = CURLMOPT_TIMERFUNCTION, // Cookie passed to an invocation of the timeout callback function. timer_data = CURLMOPT_TIMERDATA }; // Throws a std::runtime_error if the parameter to the function does match the // constant templated value. template inline void throw_if(Code code) { if (code == ref) { std::stringstream ss; ss << code; throw std::system_error(static_cast(code), std::generic_category(), ss.str()); } } // Throws a std::runtime_error if the parameter to the function does not match the // constant templated value. template inline void throw_if_not(Code code) { if (code != ref) { std::stringstream ss; ss << code; throw std::system_error(static_cast(code), std::generic_category(), ss.str()); } } // All curl native types and functions go here. namespace native { // A message as popped when reading off infos from a native Handle. typedef CURLMsg* Message; // An opaque handle to a curl multi instance. typedef CURLM* Handle; // Underlying type of a socket. typedef curl_socket_t Socket; // Creates a new curl multi instance. Returns a nullptr in case of issues. Handle init(); // Cleans up any resources associated with a curl multi instance. Code cleanup(Handle handle); // Sets an option on a native curl multi instance. template inline Code set(Handle handle, Option option, T value) { return static_cast(curl_multi_setopt(handle, static_cast(option), value)); } // Assigns the cookie to the socket in the underlying implementation. Code assign(Handle handle, Socket socket, void* cookie); // Adds a native curl easy handle to a curl multi instance. Code add_handle(Handle, curl::easy::native::Handle); // Removes a native curl easy handle from a curl multi instance. Code remove_handle(Handle, curl::easy::native::Handle); // Pops a message off a curl multi instance. std::pair read_info(Handle); // Reports socket/timeout activity to a curl multi.instance. std::pair socket_action(Handle handle, Socket socket, int events); } // Wrapper class for a native curl multi handle. class Handle { public: // Creates a new instance and initializes a new curl multi instance. Handle(); // Queries statistics about the timing information of the last transfers. core::net::http::Client::Timings timings(); // Executes the underlying dispatcher executing the curl multi instance. // Can be called multiple times for thread-pool use-cases. void run(); // Stops execution of the underlying dispatcher. // Only needs to be called once to be able to join all threads who are blocked in run(). void stop(); // Adds and schedules a new curl easy handle for execution. // Throws std::system_error in case of issues. void add(curl::easy::Handle easy); // Removes a previously added curl easy handle. // Throws std::system_error in case of issues. void remove(curl::easy::Handle easy); // Sets an option of the curl multi instance. // Throw std:: runtime_error in case of issues. template inline void set_option(Option option, T value) { throw_if_not(native::set(native(), option, value)); } // Resolves a given native easy handle to its wrapper. // Throws std::runtime_error if the native handle cannot be resolved. curl::easy::Handle easy_handle_from_native(curl::easy::native::Handle native); // Returns the native curl multi instance handle. native::Handle native() const; private: struct Private; std::shared_ptr d; }; } } #endif // CORE_NET_HTTP_IMPL_CURL_MULTI_H_ net-cpp-2.0.0/src/core/net/http/impl/curl/client.cpp0000664000175100017510000002257712553403510022630 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include "client.h" #include "curl.h" #include "request.h" #include #include #include #include #include #include namespace net = core::net; namespace http = core::net::http; namespace bai = boost::archive::iterators; namespace { const std::string BASE64_PADDING[] = { "", "==", "=" }; } http::impl::curl::Client::Client() { multi.set_option(::curl::multi::Option::pipelining, ::curl::easy::enable); } std::string http::impl::curl::Client::url_escape(const std::string& s) const { return ::curl::native::escape(s); } std::string http::impl::curl::Client::base64_encode(const std::string& s) const { std::stringstream os; // convert binary values to base64 characters typedef bai::base64_from_binary // retrieve 6 bit integers from a sequence of 8 bit bytes > base64_enc; std::copy(base64_enc(s.c_str()), base64_enc(s.c_str() + s.size()), std::ostream_iterator(os)); os << BASE64_PADDING[s.size() % 3]; return os.str(); } std::string http::impl::curl::Client::base64_decode(const std::string& s) const { std::stringstream os; typedef bai::transform_width, 8, 6> base64_dec; unsigned int size = s.size(); // Remove the padding characters // See: https://svn.boost.org/trac/boost/ticket/5629 if (size && s[size - 1] == '=') { --size; if (size && s[size - 1] == '=') { --size; } } if (size == 0) { return std::string(); } std::copy(base64_dec(s.data()), base64_dec(s.data() + size), std::ostream_iterator(os)); return os.str(); } core::net::http::Client::Timings http::impl::curl::Client::timings() { return multi.timings(); } void http::impl::curl::Client::run() { multi.run(); } void http::impl::curl::Client::stop() { multi.stop(); } std::shared_ptr http::impl::curl::Client::head_impl(const http::Request::Configuration& configuration) { ::curl::easy::Handle handle; handle.method(http::Method::head) .url(configuration.uri.c_str()) .header(configuration.header); //const long value = configuration.ssl.verify_host ? ::curl::easy::enable : ::curl::easy::disable; handle.set_option(::curl::Option::ssl_verify_host, configuration.ssl.verify_host ? ::curl::easy::enable_ssl_host_verification : ::curl::easy::disable); handle.set_option(::curl::Option::ssl_verify_peer, configuration.ssl.verify_peer ? ::curl::easy::enable : ::curl::easy::disable); if (configuration.authentication_handler.for_http) { auto credentials = configuration.authentication_handler.for_http(configuration.uri); handle.http_credentials(credentials.username, credentials.password); } return std::shared_ptr{new http::impl::curl::Request{multi, handle}}; } std::shared_ptr http::impl::curl::Client::get_impl(const http::Request::Configuration& configuration) { ::curl::easy::Handle handle; handle.method(http::Method::get) .url(configuration.uri.c_str()) .header(configuration.header); handle.set_option(::curl::Option::ssl_verify_host, configuration.ssl.verify_host ? ::curl::easy::enable_ssl_host_verification : ::curl::easy::disable); handle.set_option(::curl::Option::ssl_verify_peer, configuration.ssl.verify_peer ? ::curl::easy::enable : ::curl::easy::disable); if (configuration.authentication_handler.for_http) { auto credentials = configuration.authentication_handler.for_http(configuration.uri); handle.http_credentials(credentials.username, credentials.password); } return std::shared_ptr{new http::impl::curl::Request{multi, handle}}; } std::shared_ptr http::impl::curl::Client::post_impl( const Request::Configuration& configuration, const std::string& payload, const std::string& ct) { ::curl::easy::Handle handle; handle.method(http::Method::post) .url(configuration.uri.c_str()) .header(configuration.header) .post_data(payload.c_str(), ct); handle.set_option(::curl::Option::ssl_verify_host, configuration.ssl.verify_host ? ::curl::easy::enable_ssl_host_verification : ::curl::easy::disable); handle.set_option(::curl::Option::ssl_verify_peer, configuration.ssl.verify_peer ? ::curl::easy::enable : ::curl::easy::disable); if (configuration.authentication_handler.for_http) { auto credentials = configuration.authentication_handler.for_http(configuration.uri); handle.http_credentials(credentials.username, credentials.password); } return std::shared_ptr{new http::impl::curl::Request{multi, handle}}; } std::shared_ptr http::impl::curl::Client::put_impl( const Request::Configuration& configuration, std::istream& payload, std::size_t size) { ::curl::easy::Handle handle; handle.method(http::Method::put) .url(configuration.uri.c_str()) .header(configuration.header) .on_read_data([&payload, size](void* dest, std::size_t /*in_size*/, std::size_t /*nmemb*/) { auto result = payload.readsome(static_cast(dest), size); return result; }, size); handle.set_option(::curl::Option::ssl_verify_host, configuration.ssl.verify_host ? ::curl::easy::enable_ssl_host_verification : ::curl::easy::disable); handle.set_option(::curl::Option::ssl_verify_peer, configuration.ssl.verify_peer ? ::curl::easy::enable : ::curl::easy::disable); if (configuration.authentication_handler.for_http) { auto credentials = configuration.authentication_handler.for_http(configuration.uri); handle.http_credentials(credentials.username, credentials.password); } return std::shared_ptr{new http::impl::curl::Request{multi, handle}}; } std::shared_ptr http::impl::curl::Client::streaming_get(const http::Request::Configuration& configuration) { return get_impl(configuration); } std::shared_ptr http::impl::curl::Client::streaming_head(const http::Request::Configuration& configuration) { return head_impl(configuration); } std::shared_ptr http::impl::curl::Client::streaming_put(const http::Request::Configuration& configuration, std::istream& payload, std::size_t size) { return put_impl(configuration, payload, size); } std::shared_ptr http::impl::curl::Client::streaming_post(const http::Request::Configuration& configuration, const std::string& payload, const std::string& type) { return post_impl(configuration, payload, type); } std::shared_ptr http::impl::curl::Client::streaming_post_form(const http::Request::Configuration& configuration, const std::map& values) { std::stringstream ss; bool first{true}; for (const auto& pair : values) { ss << (first ? "" : "&") << url_escape(pair.first) << "=" << url_escape(pair.second); first = false; } return post_impl(configuration, ss.str(), http::ContentType::x_www_form_urlencoded); } std::shared_ptr http::impl::curl::Client::head(const http::Request::Configuration& configuration) { return head_impl(configuration); } std::shared_ptr http::impl::curl::Client::get(const http::Request::Configuration& configuration) { return get_impl(configuration); } std::shared_ptr http::impl::curl::Client::post( const Request::Configuration& configuration, const std::string& payload, const std::string& ct) { return post_impl(configuration, payload, ct); } std::shared_ptr http::impl::curl::Client::put( const Request::Configuration& configuration, std::istream& payload, std::size_t size) { return put_impl(configuration, payload, size); } std::shared_ptr http::make_client() { return std::make_shared(); } std::shared_ptr http::make_streaming_client() { return std::make_shared(); } net-cpp-2.0.0/src/core/net/http/impl/curl/request.h0000664000175100017510000002302512553403510022474 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_IMPL_CURL_REQUEST_H_ #define CORE_NET_HTTP_IMPL_CURL_REQUEST_H_ #include #include #include #include "client.h" #include "curl.h" #include #include #include #include #include namespace core { namespace net { namespace http { // A regex for parsing key,value pairs from an http header line. std::regex header_line{"\\s*(\\S*)\\s*:\\s*(\\S*)\\s*"}; namespace impl { namespace curl { // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html std::tuple parse_header_line(const char* line, std::size_t size) { std::cmatch matches; if (not std::regex_match(line, line + size, matches, http::header_line)) return std::make_tuple(std::string{}, std::string{}); return std::make_tuple(matches.str(0), matches.str(1)); } std::tuple handle_header_line(void* data, std::size_t size, std::size_t nmemb) { std::size_t length = size * nmemb; return std::tuple_cat(parse_header_line(static_cast(data), length), std::make_tuple(length)); } // Make sure that we switch the state back to idle whenever an instance // of StateGuard goes out of scope. struct StateGuard { StateGuard(std::atomic& state) : state(state) { state.store(core::net::http::Request::State::active); } ~StateGuard() { state.store(core::net::http::Request::State::done); } std::atomic& state; }; class Request : public core::net::http::StreamingRequest, public std::enable_shared_from_this { public: static std::shared_ptr create(::curl::multi::Handle multi, ::curl::easy::Handle easy) { return std::make_shared(multi, easy); } Request(::curl::multi::Handle multi, ::curl::easy::Handle easy) : atomic_state(core::net::http::Request::State::ready), multi(multi), easy(easy) { } State state() { return atomic_state.load(); } void set_timeout(const std::chrono::milliseconds& timeout) { if (atomic_state.load() != core::net::http::Request::State::ready) throw core::net::http::Request::Errors::AlreadyActive{CORE_FROM_HERE()}; // timeout.count() is a long long, but curl uses varargs and wants a long. // If timeout.count() overflows a long, we wait forever instead of roughly 24.8 days. auto count = timeout.count(); long adjusted_timeout = count <= std::numeric_limits::max() ? count : 0; easy.set_option(::curl::Option::timeout_ms, adjusted_timeout); } Response execute(const Request::ProgressHandler& ph) { return execute(ph, [](const std::string&){}); } Response execute(const Request::ProgressHandler& ph, const StreamingRequest::DataHandler& dh) { if (atomic_state.load() != core::net::http::Request::State::ready) throw core::net::http::Request::Errors::AlreadyActive{CORE_FROM_HERE()}; StateGuard sg{atomic_state}; Context context; if (ph) { easy.on_progress([&](void*, double dltotal, double dlnow, double ultotal, double ulnow) { Request::Progress progress; progress.download.total = dltotal; progress.download.current = dlnow; progress.upload.total = ultotal; progress.upload.current = ulnow; int result{-1}; switch(ph(progress)) { case Request::Progress::Next::abort_operation: result = 1; break; case Request::Progress::Next::continue_operation: result = 0; break; } return result; }); } easy.on_write_data( [&](char* data, std::size_t size, std::size_t nmemb) { // Report out to the data handler prior to accumulating data. dh(std::string{data, size * nmemb}); context.body.write(data, size * nmemb); return size * nmemb; }); easy.on_write_header( [&](void* data, std::size_t size, std::size_t nmemb) { static constexpr const std::size_t key_index{0}; static constexpr const std::size_t value_index{1}; static constexpr const std::size_t size_index{2}; auto kvs = handle_header_line(data, size, nmemb); if (not std::get(kvs).empty()) context.result.header.add(std::get(kvs), std::get(kvs)); return std::get(kvs); }); try { easy.perform(); } catch(const std::system_error& se) { throw core::net::http::Error(se.what(), CORE_FROM_HERE()); } context.result.status = easy.status(); context.result.body = context.body.str(); return context.result; } void async_execute(const Request::Handler& handler) { async_execute(handler, [](const std::string&){}); } void async_execute(const Request::Handler& handler, const StreamingRequest::DataHandler& dh) { if (atomic_state.load() != core::net::http::Request::State::ready) throw core::net::http::Request::Errors::AlreadyActive{CORE_FROM_HERE()}; auto sg = std::make_shared(atomic_state); auto context = std::make_shared(); auto thiz = shared_from_this(); easy.on_finished([thiz, handler, context](::curl::Code code) { if (code == ::curl::Code::ok) { context->result.status = thiz->easy.status(); context->result.body = context->body.str(); if (handler.on_response()) handler.on_response()(context->result); } else { if (handler.on_error()) { std::stringstream ss; ss << code; handler.on_error()(core::net::http::Error(ss.str(), CORE_FROM_HERE())); } } thiz->easy.release(); }); if (handler.on_progress()) { easy.on_progress([handler](void*, double dltotal, double dlnow, double ultotal, double ulnow) { Request::Progress progress; progress.download.total = dltotal; progress.download.current = dlnow; progress.upload.total = ultotal; progress.upload.current = ulnow; int result{-1}; switch(handler.on_progress()(progress)) { case Request::Progress::Next::abort_operation: result = 1; break; case Request::Progress::Next::continue_operation: result = 0; break; } return result; }); } easy.on_write_data( [context, dh](char* data, std::size_t size, std::size_t nmemb) { // Report out to the data handler prior to accumulating data. dh(std::string{data, size * nmemb}); context->body.write(data, size * nmemb); return size * nmemb; }); easy.on_write_header( [context](void* data, std::size_t size, std::size_t nmemb) { static constexpr const std::size_t key_index{0}; static constexpr const std::size_t value_index{1}; static constexpr const std::size_t size_index{2}; auto kvs = handle_header_line(data, size, nmemb); if (not std::get(kvs).empty()) context->result.header.add(std::get(kvs), std::get(kvs)); return std::get(kvs); }); multi.add(easy); } std::string url_escape(const std::string& s) { return easy.escape(s); } std::string url_unescape(const std::string& s) { return easy.unescape(s); } private: std::atomic atomic_state; ::curl::multi::Handle multi; ::curl::easy::Handle easy; struct Context { Response result; std::stringstream body; }; }; } } } } } #endif // CORE_NET_HTTP_IMPL_CURL_REQUEST_H_ net-cpp-2.0.0/src/core/net/http/impl/curl/shared.cpp0000664000175100017510000000310212553403510022577 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include "shared.h" #include namespace curl { namespace shared { static const curl_lock_data cookies = CURL_LOCK_DATA_COOKIE; static const curl_lock_data dns = CURL_LOCK_DATA_DNS; static const curl_lock_data ssl = CURL_LOCK_DATA_SSL_SESSION; namespace option { static const CURLSHoption share = CURLSHOPT_SHARE; } } } namespace shared = ::curl::shared; struct shared::Handle::Private { Private() : handle(curl_share_init()) { curl_share_setopt(handle, shared::option::share, shared::cookies); curl_share_setopt(handle, shared::option::share, shared::dns); curl_share_setopt(handle, shared::option::share, shared::ssl); } ~Private() { curl_share_cleanup(handle); } shared::Native handle; }; shared::Handle::Handle() : d(new Private()) { } shared::Native shared::Handle::native() const { return d->handle; } net-cpp-2.0.0/src/core/net/http/impl/curl/client.h0000664000175100017510000000617712553403510022273 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_IMPL_CURL_CLIENT_H_ #define CORE_NET_HTTP_IMPL_CURL_CLIENT_H_ #include #include "curl.h" #include "request.h" namespace core { namespace net { namespace http { namespace impl { namespace curl { class Client : public core::net::http::StreamingClient { public: Client(); // From core::net::http::Client std::string url_escape(const std::string& s) const; std::string base64_encode(const std::string& s) const override; std::string base64_decode(const std::string& s) const override; core::net::http::Client::Timings timings() override; void run() override; void stop() override; std::shared_ptr get(const Request::Configuration& configuration) override; std::shared_ptr head(const Request::Configuration& configuration) override; std::shared_ptr post(const Request::Configuration& configuration, const std::string&, const std::string&) override; std::shared_ptr put(const Request::Configuration& configuration, std::istream& payload, std::size_t size) override; std::shared_ptr streaming_get(const Request::Configuration& configuration) override; std::shared_ptr streaming_head(const Request::Configuration& configuration) override; std::shared_ptr streaming_put(const Request::Configuration& configuration, std::istream& payload, std::size_t size) override; std::shared_ptr streaming_post(const Request::Configuration& configuration, const std::string& payload, const std::string& type) override; std::shared_ptr streaming_post_form(const Request::Configuration& configuration, const std::map& values) override; private: std::shared_ptr get_impl(const Request::Configuration& configuration); std::shared_ptr head_impl(const Request::Configuration& configuration); std::shared_ptr post_impl(const Request::Configuration& configuration, const std::string&, const std::string&); std::shared_ptr put_impl(const Request::Configuration& configuration, std::istream& payload, std::size_t size); ::curl::multi::Handle multi; }; } } // Create an instance of a client implementation. std::shared_ptr make_client(); } } } #endif // CORE_NET_HTTP_IMPL_CURL_CLIENT_H_ net-cpp-2.0.0/src/core/net/http/impl/curl/easy.h0000664000175100017510000003177012553403510021753 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_IMPL_CURL_EASY_H_ #define CORE_NET_HTTP_IMPL_CURL_EASY_H_ #include #include #include #include #include "shared.h" #include #include #include #include #include namespace curl { typedef curl_slist StringList; enum class Code { ok = CURLE_OK, unsupported_protocol = CURLE_UNSUPPORTED_PROTOCOL, failed_init = CURLE_FAILED_INIT, url_malformat = CURLE_URL_MALFORMAT, not_built_in = CURLE_NOT_BUILT_IN, could_not_resolve_proxy = CURLE_COULDNT_RESOLVE_PROXY, could_not_resolve_host = CURLE_COULDNT_RESOLVE_HOST, could_not_connect = CURLE_COULDNT_CONNECT, remote_access_denied = CURLE_REMOTE_ACCESS_DENIED, quote_error = CURLE_QUOTE_ERROR, http_returned_error = CURLE_HTTP_RETURNED_ERROR, write_error = CURLE_WRITE_ERROR, upload_failed = CURLE_UPLOAD_FAILED, read_error = CURLE_READ_ERROR, out_of_memory = CURLE_OUT_OF_MEMORY, operation_timed_out = CURLE_OPERATION_TIMEDOUT, range_error = CURLE_RANGE_ERROR, http_post_error = CURLE_HTTP_POST_ERROR, ssl_connect_error = CURLE_SSL_CONNECT_ERROR, bad_download_resume = CURLE_BAD_DOWNLOAD_RESUME, function_not_found = CURLE_FUNCTION_NOT_FOUND, aborted_by_callback = CURLE_ABORTED_BY_CALLBACK, bad_function_argument = CURLE_BAD_FUNCTION_ARGUMENT, interface_failed = CURLE_INTERFACE_FAILED, too_many_redirects = CURLE_TOO_MANY_REDIRECTS, unknown_option = CURLE_UNKNOWN_OPTION, peer_failed_verification = CURLE_PEER_FAILED_VERIFICATION, ssl_engine_not_found = CURLE_SSL_ENGINE_NOTFOUND, ssl_engine_set_failed = CURLE_SSL_ENGINE_SETFAILED, send_error = CURLE_SEND_ERROR, receive_error = CURLE_RECV_ERROR, ssl_cert_problem = CURLE_SSL_CERTPROBLEM, ssl_cipher = CURLE_SSL_CIPHER, ssl_ca_cert = CURLE_SSL_CACERT, bad_content_encoding = CURLE_BAD_CONTENT_ENCODING, filesize_exceeded = CURLE_FILESIZE_EXCEEDED, send_fail_while_rewinding = CURLE_SEND_FAIL_REWIND, ssl_engine_init_failed = CURLE_SSL_ENGINE_INITFAILED, login_denied = CURLE_LOGIN_DENIED, remote_disk_full = CURLE_REMOTE_DISK_FULL, remote_file_exists = CURLE_REMOTE_FILE_EXISTS, conversion_failed = CURLE_CONV_FAILED, caller_must_register_conversion = CURLE_CONV_REQD, ssl_cacert_bad_file = CURLE_SSL_CACERT_BADFILE, remote_file_not_found = CURLE_REMOTE_FILE_NOT_FOUND, ssl_shutdown_failed = CURLE_SSL_SHUTDOWN_FAILED, again = CURLE_AGAIN, ssl_crl_bad_file = CURLE_SSL_CRL_BADFILE, ssl_issuer_error = CURLE_SSL_ISSUER_ERROR, chunk_failed = CURLE_CHUNK_FAILED, no_connection_available = CURLE_NO_CONNECTION_AVAILABLE }; std::ostream& operator<<(std::ostream& out, Code code); enum class Info { response_code = CURLINFO_RESPONSE_CODE, namelookup_time = CURLINFO_NAMELOOKUP_TIME, connect_time = CURLINFO_CONNECT_TIME, appconnect_time = CURLINFO_APPCONNECT_TIME, pretransfer_time = CURLINFO_PRETRANSFER_TIME, starttransfer_time = CURLINFO_STARTTRANSFER_TIME, total_time = CURLINFO_TOTAL_TIME }; enum class Option { error_buffer = CURLOPT_ERRORBUFFER, cache_dns_timeout = CURLOPT_DNS_CACHE_TIMEOUT, header_function = CURLOPT_HEADERFUNCTION, header_data = CURLOPT_HEADERDATA, progress_function = CURLOPT_PROGRESSFUNCTION, progress_data = CURLOPT_PROGRESSDATA, no_progress = CURLOPT_NOPROGRESS, write_function = CURLOPT_WRITEFUNCTION, write_data = CURLOPT_WRITEDATA, read_function = CURLOPT_READFUNCTION, read_data = CURLOPT_READDATA, url = CURLOPT_URL, user_agent = CURLOPT_USERAGENT, http_header = CURLOPT_HTTPHEADER, http_auth = CURLOPT_HTTPAUTH, http_get = CURLOPT_HTTPGET, http_post = CURLOPT_POST, http_put = CURLOPT_PUT, copy_postfields = CURLOPT_COPYPOSTFIELDS, post_field_size = CURLOPT_POSTFIELDSIZE, upload = CURLOPT_UPLOAD, in_file_size = CURLOPT_INFILESIZE, sharing = CURLOPT_SHARE, username = CURLOPT_USERNAME, password = CURLOPT_PASSWORD, no_signal = CURLOPT_NOSIGNAL, verbose = CURLOPT_VERBOSE, timeout_ms = CURLOPT_TIMEOUT_MS, ssl_engine_default = CURLOPT_SSLENGINE_DEFAULT, ssl_verify_peer = CURLOPT_SSL_VERIFYPEER, ssl_verify_host = CURLOPT_SSL_VERIFYHOST }; namespace native { // Global setup of curl. Code init(); // Cleanup all native curl resources. void cleanup(); // URL escapes the given input string. std::string escape(const std::string& in); // Append a string to a string list StringList* append_string_to_list(StringList* in, const char* string); // Frees the overall string list void free_string_list(StringList* in); } namespace easy { // Constant for disabling a feature on a curl easy instance. constexpr static const long disable = 0; // Constant for enabling a feature on a curl easy instance. constexpr static const long enable = 1; // Constant for enabling automatic SSL host verification. constexpr static const long enable_ssl_host_verification = 2; // Returns a human-readable description of the error code. std::string print_error(Code code); // Throws a std::runtime_error if the parameter to the function does match the // constant templated value. template inline void throw_if(Code code, const std::function& descriptor = std::function()) { if (code == ref) throw std::runtime_error(print_error(code) + (descriptor ? ": " + descriptor() : "")); } // Throws a std::runtime_error if the parameter to the function does not match the // constant templated value. template inline void throw_if_not(Code code, const std::function& descriptor = std::function()) { if (code != ref) throw std::runtime_error(print_error(code) + (descriptor ? ": " + descriptor() : "")); } // All curl native types and functions go here. namespace native { // Global init/cleanup namespace global { // Globally initializes curl. Code init(); // Globally cleans up everything curl. void cleanup(); } // An opaque handle to a curl easy instance. typedef CURL* Handle; // Creates and initializes a new native easy instance. Handle init(); // Releases and cleans up the resources of a native easy instance. void cleanup(Handle handle); // Executes the operation configured on the handle. ::curl::Code perform(Handle handle); // URL escapes the given input string. std::string escape(Handle handle, const std::string& in); // URL unescapes the given input string. std::string unescape(Handle handle, const std::string& in); // Sets an option on a native curl multi instance. template inline Code set(Handle handle, Option option, T value) { return static_cast(curl_easy_setopt(handle, static_cast(option), value)); } // Reads information off a native curl multi instance. template inline Code get(Handle handle, Info info, T value) { return static_cast(curl_easy_getinfo(handle, static_cast(info), value)); } } class Handle { public: struct HandleHasBeenAbandoned : public std::runtime_error { HandleHasBeenAbandoned(); }; struct Timings { typedef std::chrono::duration Seconds; // Time it took from the start until the name resolving was completed. Seconds name_look_up{Seconds::max()}; // Time it took from the finished name lookup until the connect to the remote host (or proxy) was completed. Seconds connect{Seconds::max()}; // Time it took from the connect until the SSL/SSH connect/handshake to the remote host was completed. Seconds app_connect{Seconds::max()}; // Time it took from app_connect until the file transfer is just about to begin. Seconds pre_transfer{Seconds::max()}; // Time it took from pre-transfer until the first byte is received by libcurl. Seconds start_transfer{Seconds::max()}; // Time in total that the previous transfer took. Seconds total{Seconds::max()}; }; // Function type that gets called to indicate that an operation finished. typedef std::function OnFinished; // Function type that gets called to report progress of an operation. typedef std::function OnProgress; // Function type that gets called whenever data should be read. typedef std::function OnReadData; // Function type that gets called whenever body/payload data should be written. typedef std::function OnWriteData; // Function type that gets called whenever header data should be written. typedef std::function OnWriteHeader; // Creates a new handle and initializes the underlying curl easy instance. Handle(); // Releases the handle and all underlying state. // Subsequent accesses to this instance will throw a // HandleHasBeenAbandoned exception. void release(); // Queries the timing information of the last execution from the native curl handle. Timings timings(); // Queries information from the instance. template inline void get_option(T option, U value) { throw_if_not(native::get(native(), option, value)); } // Sets an option on the instance. template inline void set_option(Option option, T value) { switch (option) { case Option::ssl_engine_default: throw_if_not(native::set(native(), option, value), []() { return "We failed to setup the default SSL engine for CURL.\n" "This likely hints towards a broken CURL implementation.\n" "Please make sure that all the build-dependencies of the software are installed.\n"; }); break; default: throw_if_not(native::set(native(), option, value), [this]() { return error(); }); break; } } // Adjusts the url that the instance should download. Handle& url(const char* url); // Adjusts the user agent that is passed in the request. Handle& user_agent(const char* user_agent); // Adjusts the credentials of the request. Handle& http_credentials(const std::string& username, const std::string& pwd); // Sets the OnFinished handler. Handle& on_finished(const OnFinished& on_finished); // Sets the OnProgress handler. Handle& on_progress(const OnProgress& on_progress); // Sets the OnReadData handler. Handle& on_read_data(const OnReadData& on_read_data, std::size_t size); // Sets the OnWriteData handler. Handle& on_write_data(const OnWriteData& on_new_data); // Sets the OnWriteHeader handler. Handle& on_write_header(const OnWriteHeader& on_new_header); // Sets the http method used by this instance. Handle& method(core::net::http::Method method); // Sets the data to be posted by this instance. Handle& post_data(const std::string& data, const std::string&); // Sets custom request headers Handle& header(const core::net::http::Header& header); // Queries the current status of this instance. core::net::http::Status status(); // Queries the native curl easy handle. native::Handle native() const; // Executes the operation associated with this handle. void perform(); // URL escapes the given input string. std::string escape(const std::string& in); // URL unescapes the given input string. std::string unescape(const std::string& in); // Notifies this instance that the operation finished with 'code'. void notify_finished(curl::Code code); private: static int progress_cb(void* data, double dltotal, double dlnow, double ultotal, double ulnow); static std::size_t read_data_cb(void* data, std::size_t size, std::size_t nmemb, void *cookie); static std::size_t write_data_cb(char* data, size_t size, size_t nmemb, void* cookie); static std::size_t write_header_cb(void* data, size_t size, size_t nmemb, void* cookie); // Returns the current error description. std::string error() const; struct Private; std::shared_ptr d; }; } } #endif // CORE_NET_HTTP_IMPL_CURL_EASY_H_ net-cpp-2.0.0/src/core/net/uri.cpp0000664000175100017510000000170512553403510017252 0ustar tvosstvoss00000000000000/* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Pete Woods */ #include namespace net = core::net; net::Uri net::make_uri (const net::Uri::Host& host, const net::Uri::Path& path, const net::Uri::QueryParameters& query_parameters) { return net::Uri{ host, path, query_parameters }; } net-cpp-2.0.0/src/core/net/error.cpp0000664000175100017510000000161212553403510017601 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include core::net::Error::Error(const std::string& what, const core::Location& loc) : std::runtime_error(loc.print_with_what(what).c_str()) { } net-cpp-2.0.0/src/core/location.cpp0000664000175100017510000000224412553403510017474 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include std::string core::Location::print_with_what(const std::string& what) const { std::stringstream ss; ss << file << "@" << line << " - " << function << ": " << what; return ss.str(); } core::Location core::from_here(const std::string& file, const std::string& function, std::size_t line) { core::Location result; result.file = file; result.function = function; result.line = line; return result; } net-cpp-2.0.0/tests/0000775000175100017510000000000012553403521014603 5ustar tvosstvoss00000000000000net-cpp-2.0.0/tests/CMakeLists.txt0000664000175100017510000000537312553403510017351 0ustar tvosstvoss00000000000000# Copyright © 2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authored by: Thomas Voss execute_process( COMMAND ${CMAKE_COMMAND} -E tar xf ${CMAKE_CURRENT_SOURCE_DIR}/httpbin.tar.bz2 WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/httpbin.h.in ${CMAKE_CURRENT_BINARY_DIR}/httpbin.h @ONLY ) find_package(PkgConfig) find_package(Threads) pkg_check_modules(JSON_CPP jsoncpp) pkg_check_modules(PROCESS_CPP process-cpp) # Build with system gmock and embedded gtest set (GMOCK_INCLUDE_DIR "/usr/include/gmock/include" CACHE PATH "gmock source include directory") set (GMOCK_SOURCE_DIR "/usr/src/gmock" CACHE PATH "gmock source directory") set (GTEST_INCLUDE_DIR "${GMOCK_SOURCE_DIR}/gtest/include" CACHE PATH "gtest source include directory") set (GMOCK_BOTH_LIBRARIES gmock gmock_main) add_subdirectory(${GMOCK_SOURCE_DIR} "${CMAKE_CURRENT_BINARY_DIR}/gmock") include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${GMOCK_INCLUDE_DIR} ${GTEST_INCLUDE_DIR} ${JSON_CPP_INCLUDE_DIRS} ${PROCESS_CPP_INCLUDE_DIRS} ) add_executable( header_test header_test.cpp ) add_executable( http_client_test http_client_test.cpp ) add_executable( http_streaming_client_test http_streaming_client_test.cpp ) add_executable( http_client_load_test http_client_load_test.cpp ) target_link_libraries( header_test net-cpp ${GMOCK_BOTH_LIBRARIES} ${JSON_CPP_LDFLAGS} ${PROCESS_CPP_LDFLAGS} ) target_link_libraries( http_client_test net-cpp ${GMOCK_BOTH_LIBRARIES} ${JSON_CPP_LDFLAGS} ${PROCESS_CPP_LDFLAGS} ) target_link_libraries( http_streaming_client_test net-cpp ${GMOCK_BOTH_LIBRARIES} ${JSON_CPP_LDFLAGS} ${PROCESS_CPP_LDFLAGS} ) target_link_libraries( http_client_load_test net-cpp ${GMOCK_BOTH_LIBRARIES} ${JSON_CPP_LDFLAGS} ${PROCESS_CPP_LDFLAGS} ) add_test(header_test ${CMAKE_CURRENT_BINARY_DIR}/header_test) add_test(http_client_test ${CMAKE_CURRENT_BINARY_DIR}/http_client_test) add_test(http_streaming_client_test ${CMAKE_CURRENT_BINARY_DIR}/http_streaming_client_test) add_test(http_client_load_test ${CMAKE_CURRENT_BINARY_DIR}/http_client_load_test) net-cpp-2.0.0/tests/httpbin.tar.bz20000664000175100017510000003602712553403510017465 0ustar tvosstvoss00000000000000BZh91AY&SYYٽ<z dp(`F}9Zu}ԏc4reXwٹG%;۾[η_mgr7o{l:9kRֻ{}__ϳjm>.kw;׾_#m>jk{s{>_}k{*.lwo<{o{}JiDA%?&f4=Fhhh%Mz5pHߊǬl?Dk'dCjWSo{N?9hǂTj>S'g;Q_x8AؚtXtL\~N E-r" eL*eL5=M3h Vnp@]kpʽ">V cm|8|P!cBE) 6Ou!)#NϐK+K.fBUit.,JTzjK]9:#0+aK*3K??2ƯM_Z95N}rFƴS @(ͭBLO5 "<̚b[u4q8)4&ŠgClΉ:Hk%9wp5pe'w>ף]؏BsG3H zqmJ0#N$ ּhR^%R?vM_z1LhkeKk/Nη,7 NބyT!yS:C5\5YN!\kZprQw/@ˮ4ne m$4tx&7/y8T"=$jc_O-F]#}7F֝H^z[ANj*}Y d _4w2awZI=!`=+5ڷ\^}CϧLz^&""z{|߲F~+MZߥx wx~l 9瞳H!w-PF(T$vn z.3qd.IŠORzws:a:hg͞OSUzh]\V G&YnunxUsM>sH]1`牗af~{܇PTf3ϵf #ܔxK4 xɺ\X@ׂӁFS6.kdIb\'d  i CU1XRRULշo'A7Ccu'ƣl[XuB.+:#񀿤|DKrLD.ao3m? ;^1Zb{✪$ꀔgHUJ|T %i~_9SW+<8v[Lb0yJF;!Lelb%|eٿ"ei&`F>V. @7ڈZN!uݵΏzx;W-TNۅ㰱B(`ṃCԄJ bTgsz,/QLZ=E*(Y*5Ԣ7 7fTy+JU| ʼ_"(G[:ed2E-;i@b΢Xo#va&,\A7G}]R V*YWAVA5z9E80(&9lpGtlI Sr:5> n΍ =]ܙ2-Zkc뇈.jY"e3x(13ߢ_P D1b1qȪ{%0ǿc3}?^WpUfaf r2I ;Ii_ɏGa{OoF.aݒγ6bF6;kf&iˢ:t5PW(dM)a="hSӗKS(bzw7pWt܎ f(?fV[HMdz;+Ok<Pl#ҋH1w8wche{Ug 2I5cd?a"DF1e yH@:<[2d8LJ8.V&`NF15~r^J`[*UBu[hq.84; |qm2(ĠYm0'aZ{ |b D* 61Yf )d)eC2f}Xawz݅i I߲y[ۘŒM"]b5FSluudmnW7/n)tⵤe:,!mВ(!$8N5*ǜ@J uB /%$<8u ]蔤dfFaHnrfԤvpykʈ_/gwWNx忇o̚Fp|yJJ,؟BC D*pQm[r܄yZiIp";#qU 󴄊jCȷ̥!A-bN/CMԧ)Qg`l{27n:Rp7 #b\3ޭ8;8ljþr=';ƓM"""5PZj2 tiڧ:Od}{?[hk9pQWsqQOi_s-ڦVG^B gn9m&6YƬ56}JݹxC;w/?9ȑ0zM 'Ef"p}*TƍԳ(nM-n},89 hC ǚW8|[3V[/T՗co1EOaif8ye) 3ԡ`:y@EŌo&nC{odd!"cF`(_W]>7ۂƽ(:Zt&‘Z`K-yOཉ^^xjbFYV__<r!c^2/pg% 2(:vXߦ)tz2~J9}6Sa gz&fY\OOUV1&w"*jkYПLf%UU[)ZZuY4T qc%)X)KY j ιDgBfeffxqy&fdU^7w~}hݺEֶyFc6l Mtξ]$E;%r TV4M8Za5V(C x!A!|_$S?&XNlz~*t<;oBDkTx$mM3;DK1Ǯz>qX*P~{0#qߗ( 'x:R,,tTّz/qo!B win)N6b~~  Ǡ{-! <%ٔo6^MWNlAlxح5Y6륏S+*`Ւ玻ΓfHmzߠ6UOXh=w&b1w.5S4S,[Qh(l}RB0p9 $au{ux6[oG/ĽB^ĚG6ghrYY#RXVR+{mX˽cWF>wPչQ߾'y-8so+m̥7FsWGPq<"Iq3#Tltk.]yAk4Ģle m(s؎I`ILl*Λ$I^_>f®U)SA-c&e#'K} EdJ$*IVI9EVIQ2>tf2xY~^#vI"t^ypܧf&KI2A U gL@DMEF 1\0= 1"U䈟>y4הfK>Gj??dugWmLgu[*?Nlr:a5Qy7 ?;_¯%T۶hj+["8b~!ېh CxS1Tb˂sr?d={8.@I1xEU(<`\054טnJ}YohnG,ԝ#0`B͕+GJ F8ٕC rJΩU{w<-=/|o _ӿ|[9Fҡ LS*@)!`,!5r{oAo]E&g{Pȹ=1=w}꨾{]xpFTqB˺Fls,xD={ ~2l.}:<$Q/웈 Ai[mY¨XnTzWQ3=h!&F0dCFV՜Md,eK@PqG+L5xG&Ģv@+v{EQO1x*\bڥY2D2Y>4t+?+BiB#Վd'Iy,BMNW G͕҆Ou9KƦ2_uF eps%F4_<x\&8 HlPi-jbG..2Xݶa8,v[:Ȍ-,CQ6/N :5m"D~Ewt#0[xi%ȃȺ!ScfPD0$qd"|QSޣ8D0;g\hAhwܳm~{mBYPS0E3O08]gء:{qgHhs9mEm}'X_ 0x܄n"lɶYQss(R ؙТ0Omvě;i4EְXYӡ~YA_8Bx g.MDOH :[yf>dL l*9Biz1lm*huHvĜT`LJ6p+{bFŁn=c`jkTS!i>fUEH - L+CZ)j NMU!KʫpF uXq1Ym!NhafLU4F]~ڎ1VU8 DSXƠcm6ٞшd} NW;8d"?k ef|JWoqzu!ס }هFdsb>>RMZH(AV@|_jg2Y\O)o8rL{Ż ;P--a(׳Dkm + Z¿VJJMo\`ivcK1^o=A\ EC0 Ey_*gj1\O4dtmR~4s[JFw>0@ a8[1uv(` hdGI~e`z5 7 (\~+d86r=⎩&F#QH/iN1􀷗%Z"9Ot7!KNKs OMgXSte^W,XIQJ{iH72 %ժT_`ظbE&ļI;;*#cH̼RzP"*'}LiYRv3;V ^-܅AxvA006& [ 51 Egh HFD"gI f+ŊkX#b`7w*0k8b-%S95qDu{nw?/ PCܿ#ze!RЯE%nUM(P+IǬ5iBhyG7L1 0R wbu|a13A`1.+yOKm(N ɉi5-s6O3\ `ﶓ#Ĕ|0甘~-{r;^ym\1m8b(!TӶnHe3rАiGr``GBJgk=L3(A) MiZ+Wy:I92B#ݺBqӚ_;22̓`ҫ#" DEPN)n<@HdDe !CXpܐ}MnǺ"6L=[A-4rVlf1Y,(J%$FCadA,/k9 Wo9jcM4+$覰CtPc2u$9@T X< Rvв׶T:hr!u6R *LHq\4I-vr9 ^i$h0!@zt"0:lTu<;p8dX"t]&s&elɻ 1.B5T 9 ]SdJ[xP墪S\JAR_ZyY:N "Ȁl} #}ϷikVn c@ԝ ̐SRM%Ef.RB̋<4-Be\U[ HN5&{Z!g%6q.m NVrgJnQۦ堒Q(VQ&Ei4%eVNJQ&Rpub1EAT (L-la G. ftc(A]FQ9I8W'fs+6|2`e*04^Y Wtخvii.C00c+zH~u>I`PfojfLߧpTi g+7R*4WJ[$)3vX"EA $Z ߾0-0؅RW!Ōtxՙ#5|BGs c; KF %ok濬_,5!8UPd҆@A"`Ў?u8ui THNԌ6~ԘԄF׃dABLUߞkrqտ9/PEGov65 . &;IB nUٛ{;SS0k+,Z6}HFA{/GR|NWG~3=jl- hT"ym`BaM HGǑH%AQ66ٽT} ,!o_9Y7bmQ599Q"ʍ]&ԑ5շ1:L}V8Bӂcp:,R /pO8e+ֺSü 6+Hr Ik+-.cҕj<`GAcjGcy dW$(a&ķL1TIy('A=)[?r?@E#zѝҍz8wetb,5n; { iwlV-c:!"10Ƴ / cB8l}b@F1)nL36 >2ʂ)"%Ʈ>IRRy E`2 qC;NdNN a*@` C >w}aF|{a t<К~w@σԔ%Eu*=l% 4T@,%IX ePk& R#%S{s3ER 62y][&IKt '~j̑.]kQrpe% yRA0\Fg/O7{CC!4SbM'GaYdR8!: ;rYG,)rt!]lÌ!$ƌ280uZWM슙4E5)(+qf/(* JKalLJBCCD{Yl3fl}dO0:%s? bieuIL>& ]2Fs[FzɄRu&).vRz%yFw_k+dٜEq93ǎE m0uB:@eDi$ H8d 2I$4|JJaGād{=1cW a\Dg"G,&( TRwk.*)kK뤟ǩ}3jiusy')f!)GT @V)SU%]~Ϝ` q-J#MA@!`|FOg/ŬyI @Bbhed;9Ek-}m7V#C61@w{47 %2)1w(mE_aOmÁ)SH&B̰( DDw,5d!un3=)XrV$4 T&e6EX<Ȧ48TL dm<:w#ƻo| E! : I.=|Il`,C|A$)|A9)m?f|Qy1hӏ^ `cg_dpJ9ȈbZ0tce+1d,T#20S B1+c`q ;Ɯ˜/6U͚r Q+C6ubԪ9ÓzRѾR^*E w+& J|* }cCfdoݼiT\ Q P'rgB d$HE.L[% &b0ߠ"8 Ά](A8&WPZ%%YH jtų"XN9:xуsv571(X&(24bbYX#/.񊢬[Kg`h. ɄeՠZKrU1AK ۱1~W3@Z*n`yfo`8"(QX{ a Bqn RP{[ *ueGTM@t\A@* VGs;4"1/ x*)PRaWds!( *FSIz Dh%$2dq;Q]ЦAm\6"1{0@aN#G4WtIZ{x m6 KtDM&Aⶓ[ (]Rx!G—tCa3S8S#?D|dDL-(4DzHy7qAݺnit ~#ԝ;^1f$z6TP0 eh zjc44[.SXI\ 15cyBIa솉 `R1t܈ GJ{^T ֚ܡAlG4mSmEw8LwME9 K-H!x:;- Hb0VPqS%пuXnZKA'՞!b䆓]'#Iv޲Qϑ!DGbx~'a4ULGSZ=;ܦ~p;HN+ 3эb0($͕⻅#1%T Bh^&oZ$M%4BDgUo.& D X!@.n&9+ml@hM(AT.i)i,UL,<: 3{%B]uMLNJV$dXh8yPj:Q@d)%>}i֪9nT?b0"# la,;m/ Ҷg%Gxp\saM 6\i 1\ iD&PS2K{&ERfW,t1㑘jhil `x0gM wsr`Sۮ#!}1L5teJk9'K8^ jRƮ=Y`F$EBuŷ pb*Y&Vґ(t`7R#YYV zQDj8ٚĆ nɣfР=qPSE\D_Ewnt < m)`D"~yGNP>m_MB4BSd>A%XI0BM.^zE+9hHh%} C4I4d3^ AՄkE5E=<0)T Fy!6W+5x>b0@XH3<% (+yEԦ)kD)4d@(Q BmX8bdHR=BQ@&{쥙@%\!BM"I9uzO] bgY(ؘi f$GҺ:2w!]1ܒ vS(oՐ$'"GqLKRZ(IE;vn,5VYG#ըtcrE,ݽBR,RFX`.wpk]pR S) Q)*<D2|aj4 يwmhlj,+ h?z*BߠpL :H mO&&LqWLSp;zLjq >[VF kv,\YGJ j`~y$*iА Ϣ*UW7Q5&+ mj>#"{~ؖ٩F&L"cN枮]^$L lmUa,-ppTHb02j*Јx)M7G[% C8"jP -º0 2ݜ䜱,b СL%??Ҥ1,"2 PF:6T_Wm? NPg܆l5%C93AI&[{h!KrU@KCe.0)aC<6**, 8Nm&o wwbUtYx":m>h-%cmLطewNH(t^kxTw;zpfgQgjϬ 02nmXtK*0$CDJ"zWF-Z ?'KOaI w}$9V}'şr>X>] =ie[,ו&w5P<_zW=oO kiFH0Fs#q(w$S net-cpp-2.0.0/tests/header_test.cpp0000664000175100017510000000545512553403510017605 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include namespace http = core::net::http; TEST(Header, canonicalizing_empty_string_does_not_throw) { std::string key{}; EXPECT_TRUE(key.empty()); auto result = http::Header::canonicalize_key(key); EXPECT_TRUE(result.empty()); } TEST(Header, canonicalizing_a_valid_key_works) { std::string key{"accept-encoding"}; auto result = http::Header::canonicalize_key(key); EXPECT_EQ("Accept-Encoding", result); } TEST(Header, canonicalizing_is_idempotent) { std::string key{"Accept-Encoding"}; auto result = http::Header::canonicalize_key(key); EXPECT_EQ("Accept-Encoding", result); } TEST(Header, canonicalizing_corrects_random_capitalization) { std::string key{"aCcEpT-eNcOdInG"}; auto result = http::Header::canonicalize_key(key); EXPECT_EQ("Accept-Encoding", result); } TEST(Header, adding_values_works_correctly) { http::Header header; header.add("Accept-Encoding", "utf8"); EXPECT_TRUE(header.has("Accept-Encoding")); EXPECT_TRUE(header.has("Accept-Encoding", "utf8")); header.add("Accept-Encoding", "utf16"); EXPECT_TRUE(header.has("Accept-Encoding", "utf8")); EXPECT_TRUE(header.has("Accept-Encoding", "utf16")); } TEST(Header, removing_values_works_correctly) { http::Header header; header.add("Accept-Encoding", "utf8"); EXPECT_TRUE(header.has("Accept-Encoding")); EXPECT_TRUE(header.has("Accept-Encoding", "utf8")); header.remove("Accept-Encoding", "utf8"); EXPECT_TRUE(header.has("Accept-Encoding")); EXPECT_FALSE(header.has("Accept-Encoding", "utf8")); header.remove("Accept-Encoding"); EXPECT_FALSE(header.has("Accept-Encoding")); } TEST(Header, setting_values_works_correctly) { http::Header header; header.add("Accept-Encoding", "utf8"); EXPECT_TRUE(header.has("Accept-Encoding")); EXPECT_TRUE(header.has("Accept-Encoding", "utf8")); header.set("Accept-Encoding", "utf16"); EXPECT_TRUE(header.has("Accept-Encoding")); EXPECT_FALSE(header.has("Accept-Encoding", "utf8")); EXPECT_TRUE(header.has("Accept-Encoding", "utf16")); } net-cpp-2.0.0/tests/http_streaming_client_test.cpp0000664000175100017510000004461612553403510022745 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include #include #include #include "httpbin.h" #include #include #include #include #include namespace http = core::net::http; namespace json = Json; namespace net = core::net; namespace { class MockDataHandler : public std::enable_shared_from_this { public: // We are enabling shared from this, thus forcing creation of // managed instances here. static std::shared_ptr create() { return std::shared_ptr(new MockDataHandler); } MOCK_METHOD1(on_new_data, void(const std::string&)); http::StreamingRequest::DataHandler to_data_handler() { auto thiz = shared_from_this(); return [thiz](const std::string& s) { thiz->on_new_data(s); }; } private: MockDataHandler() = default; }; auto default_progress_reporter = [](const http::Request::Progress& progress) { if (progress.download.current > 0. && progress.download.total > 0.) std::cout << "Download progress: " << progress.download.current / progress.download.total << std::endl; if (progress.upload.current > 0. && progress.upload.total > 0.) std::cout << "Upload progress: " << progress.upload.current / progress.upload.total << std::endl; return http::Request::Progress::Next::continue_operation; }; bool init() { static httpbin::Instance instance; return true; } static const bool is_initialized = init(); } TEST(StreamingStreamingHttpClient, head_request_for_existing_resource_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); // The client mostly acts as a factory for http requests. auto request = client->streaming_head(http::Request::Configuration::from_uri_as_string(url)); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); } TEST(StreamingHttpClient, get_request_for_existing_resource_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); // The client mostly acts as a factory for http requests. auto request = client->streaming_get(http::Request::Configuration::from_uri_as_string(url)); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(url, root["url"].asString()); } TEST(StreamingHttpClient, get_request_with_custom_headers_for_existing_resource_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::headers(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.header.set("Test1", "42"); configuration.header.set("Test2", "43"); auto request = client->streaming_get(configuration); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); auto headers = root["headers"]; EXPECT_EQ("42", headers["Test1"].asString()); EXPECT_EQ("43", headers["Test2"].asString()); } TEST(StreamingHttpClient, empty_header_values_are_handled_correctly) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::headers(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.header.set("Empty", std::string{}); auto request = client->streaming_get(configuration); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); auto headers = root["headers"]; EXPECT_EQ(std::string{}, headers["Empty"].asString()); } TEST(StreamingHttpClient, get_request_for_existing_resource_guarded_by_basic_auth_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::basic_auth(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.authentication_handler.for_http = [](const std::string&) { return http::Request::Credentials{"user", "passwd"}; }; auto request = client->streaming_get(configuration); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // We expect authentication to work. EXPECT_TRUE(root["authenticated"].asBool()); // With the correct user id EXPECT_EQ("user", root["user"].asString()); } // Digest auth is broken on httpbin.org. It even fails in the browser after the first successful access. TEST(StreamingHttpClient, DISABLED_get_request_for_existing_resource_guarded_by_digest_auth_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::digest_auth(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.authentication_handler.for_http = [](const std::string&) { return http::Request::Credentials{"user", "passwd"}; }; auto request = client->streaming_get(configuration); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // We expect authentication to work. EXPECT_TRUE(root["authenticated"].asBool()); // With the correct user id EXPECT_EQ("user", root["user"].asString()); } TEST(StreamingHttpClient, async_get_request_for_existing_resource_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Execute the client std::thread worker{[client]() { client->run(); }}; // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); // The client mostly acts as a factory for http requests. auto request = client->streaming_get(http::Request::Configuration::from_uri_as_string(url)); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); std::promise promise; auto future = promise.get_future(); // We finally execute the query asynchronously. request->async_execute( http::Request::Handler() .on_progress(default_progress_reporter) .on_response([&](const core::net::http::Response& response) { promise.set_value(response); }) .on_error([&](const core::net::Error& e) { promise.set_exception(std::make_exception_ptr(e)); }), dh->to_data_handler()); auto response = future.get(); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(url, root["url"].asString()); client->stop(); // We shut down our worker thread if (worker.joinable()) worker.join(); } TEST(StreamingHttpClient, async_get_request_for_existing_resource_guarded_by_basic_authentication_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Execute the client std::thread worker{[client]() { client->run(); }}; // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::basic_auth(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.authentication_handler.for_http = [](const std::string&) { return http::Request::Credentials{"user", "passwd"}; }; auto request = client->streaming_get(configuration); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; std::promise promise; auto future = promise.get_future(); // We finally execute the query asynchronously. request->async_execute( http::Request::Handler() .on_progress(default_progress_reporter) .on_response([&](const core::net::http::Response& response) { promise.set_value(response); client->stop(); }) .on_error([&](const core::net::Error& e) { promise.set_exception(std::make_exception_ptr(e)); client->stop(); }), dh->to_data_handler()); // And wait here for the response to arrive. auto response = future.get(); // We shut down our worker thread if (worker.joinable()) worker.join(); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // We expect authentication to work. EXPECT_TRUE(root["authenticated"].asBool()); // With the correct user id EXPECT_EQ("user", root["user"].asString()); } TEST(StreamingHttpClient, post_request_for_existing_resource_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::post(); std::string payload = "{ 'test': 'test' }"; // The client mostly acts as a factory for http requests. auto request = client->streaming_post(http::Request::Configuration::from_uri_as_string(url), payload, core::net::http::ContentType::json); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(payload, root["data"].asString()); } TEST(StreamingHttpClient, post_form_request_for_existing_resource_succeeds) { using namespace ::testing; // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_streaming_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::post(); std::map values { {"test", "test"} }; // The client mostly acts as a factory for http requests. auto request = client->streaming_post_form(http::Request::Configuration::from_uri_as_string(url), values); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); // We finally execute the query synchronously and store the response. auto response = request->execute(default_progress_reporter, dh->to_data_handler()); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; EXPECT_EQ(core::net::http::Status::ok, response.status); EXPECT_TRUE(reader.parse(response.body, root)); EXPECT_EQ("test", root["form"]["test"].asString()); } TEST(StreamingHttpClient, put_request_for_existing_resource_succeeds) { using namespace ::testing; auto client = http::make_streaming_client(); auto url = std::string(httpbin::host) + httpbin::resources::put(); const std::string value{"{ 'test': 'test' }"}; std::stringstream payload(value); auto request = client->streaming_put(http::Request::Configuration::from_uri_as_string(url), payload, value.size()); // Our mocked data handler. auto dh = MockDataHandler::create(); EXPECT_CALL(*dh, on_new_data(_)).Times(AtLeast(1)); json::Value root; json::Reader reader; auto response = request->execute(default_progress_reporter, dh->to_data_handler()); EXPECT_EQ(core::net::http::Status::ok, response.status); EXPECT_TRUE(reader.parse(response.body, root)); EXPECT_EQ(payload.str(), root["data"].asString()); } net-cpp-2.0.0/tests/httpbin.h.in0000664000175100017510000000514712553403510017036 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef HTTPBIN_H_ #define HTTPBIN_H_ #include #include /** * * Testing an HTTP Library can become difficult sometimes. Postbin is fantastic * for testing POST requests, but not much else. This exists to cover all kinds * of HTTP scenarios. Additional endpoints are being considered (e.g. * /deflate). * * All endpoint responses are JSON-encoded. * */ namespace httpbin { /** Fires up a local instance of httpbin. */ struct Instance { Instance() : server { core::posix::exec("/usr/bin/python", {"@CMAKE_CURRENT_BINARY_DIR@/httpbin/run.py"}, {}, core::posix::StandardStream::stdout | core::posix::StandardStream::stderr) } { std::this_thread::sleep_for(std::chrono::milliseconds{500}); } ~Instance() { try { server.send_signal_or_throw(core::posix::Signal::sig_kill); server.wait_for(core::posix::wait::Flags::untraced); } catch(...) { // Just ignoring errors here. } } core::posix::ChildProcess server; }; constexpr const char* host { "http://127.0.0.1:5000" }; namespace resources { /** A non-existing resource */ const char* does_not_exist() { return "/does_not_exist"; } /** Returns Origin IP. */ const char* ip() { return "/ip"; } /** Returns user-agent. */ const char* user_agent() { return "/user-agent"; } /** Returns header dict. */ const char* headers() { return "/headers"; } /** Returns GET data. */ const char* get() { return "/get"; } /** Returns POST data. */ const char* post() { return "/post"; } /** Returns PUT data. */ const char* put() { return "/put"; } /** Challenges basic authentication. */ const char* basic_auth() { return "/basic-auth/user/passwd"; } /** Challenges digest authentication. */ const char* digest_auth() { return "/digest-auth/auth/user/passwd"; } } } #endif // HTTPBIN_H_ net-cpp-2.0.0/tests/http_client_load_test.cpp0000664000175100017510000001724212553403510021666 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include #include #include "httpbin.h" #include "table.h" #include #include #include #include namespace http = core::net::http; namespace json = Json; namespace net = core::net; namespace { struct HttpClientLoadTest : public ::testing::Test { typedef std::function(const std::shared_ptr&)> RequestFactory; typedef std::function ResponseVerifier; void run(const RequestFactory& request_factory, const ResponseVerifier& response_verifier) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Execute the client std::thread worker{[client]() { client->run(); }}; // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); std::size_t completed{1}; std::size_t total{200}; auto on_completed = [&completed, total, client]() { if (++completed == total) { auto timings = client->timings(); testing::Table::Row<15, '|'> row; testing::Table::Row<15, '|'>::HorizontalSeparator<5> sep; std::cout << sep; std::cout << (row << "Indicator" << "Min [s]" << "Max [s]" << "Mean [s]" << "Std. Dev. [s]"); std::cout << sep; std::cout << (row << "NameLookup" << timings.name_look_up.min.count() << timings.name_look_up.max.count() << timings.name_look_up.mean.count() << std::sqrt(timings.name_look_up.variance.count())); std::cout << (row << "Connect" << timings.connect.min.count() << timings.connect.max.count() << timings.connect.mean.count() << std::sqrt(timings.connect.variance.count())); std::cout << (row << "AppConnect" << timings.app_connect.min.count() << timings.app_connect.max.count() << timings.app_connect.mean.count() << std::sqrt(timings.app_connect.variance.count())); std::cout << (row << "PreTransfer" << timings.pre_transfer.min.count() << timings.pre_transfer.max.count() << timings.pre_transfer.mean.count() << std::sqrt(timings.pre_transfer.variance.count())); std::cout << (row << "StartTransfer" << timings.start_transfer.min.count() << timings.start_transfer.max.count() << timings.start_transfer.mean.count() << std::sqrt(timings.start_transfer.variance.count())); std::cout << (row << "Total" << timings.total.min.count() << timings.total.max.count() << timings.total.mean.count() << std::sqrt(timings.total.variance.count())); std::cout << sep; client->stop(); } }; for (unsigned int i = 0; i < total; i++) { // The client mostly acts as a factory for http requests. auto request = request_factory(client); //auto once = client->request_store().add(request); // We finally execute the query asynchronously. request->async_execute( http::Request::Handler() .on_response([on_completed, response_verifier](const core::net::http::Response& response) mutable { EXPECT_TRUE(response_verifier(response)); on_completed(); //once(); }) .on_error([on_completed](const core::net::Error&) mutable { on_completed(); //once(); })); } // We shut down our worker threads if (worker.joinable()) worker.join(); } }; bool init() { static httpbin::Instance instance; return true; } static const bool is_initialized = init(); } TEST_F(HttpClientLoadTest, async_head_request_for_existing_resource_succeeds) { auto url = std::string(httpbin::host) + httpbin::resources::get(); auto request_factory = [url](const std::shared_ptr& client) { return client->head( http::Request::Configuration::from_uri_as_string(url)); }; auto response_verifier = [](const http::Response& response) -> bool { // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); return not ::testing::Test::HasFailure(); }; run(request_factory, response_verifier); } TEST_F(HttpClientLoadTest, async_get_request_for_existing_resource_succeeds) { auto url = std::string(httpbin::host) + httpbin::resources::get(); auto request_factory = [url](const std::shared_ptr& client) { return client->get( http::Request::Configuration::from_uri_as_string(url)); }; auto response_verifier = [url](const http::Response& response) -> bool { // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(url, root["url"].asString()); return not ::testing::Test::HasFailure(); }; run(request_factory, response_verifier); } TEST_F(HttpClientLoadTest, async_post_request_for_existing_resource_succeeds) { auto url = std::string(httpbin::host) + httpbin::resources::post(); auto payload = "{ 'test': 'test' }"; auto request_factory = [url, payload](const std::shared_ptr& client) { return client->post( http::Request::Configuration::from_uri_as_string(url), payload, core::net::http::ContentType::json); }; auto response_verifier = [payload](const http::Response& response) -> bool { // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(payload, root["data"].asString()); return not ::testing::Test::HasFailure(); }; run(request_factory, response_verifier); } net-cpp-2.0.0/tests/table.h0000664000175100017510000000570012553403510016043 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef TABLE_H #define TABLE_H #include #include namespace testing { struct Table { Table() = delete; template struct Row { template struct HorizontalSeparator { static constexpr int width = field_count*(2 + field_width + 1) + 1; }; template friend std::ostream& operator<<( std::ostream& out, const HorizontalSeparator&) { out << std::setw(HorizontalSeparator::width) << std::setfill('-') << '-' << std::setfill(' ') << std::endl; return out; } struct Field { static constexpr int width = field_width; static const std::string& prefix() { static const std::string s = std::string{separator} + " "; return s; } static const std::string& suffix() { static const std::string s{" "}; return s; } }; Row() { ss << std::setprecision(5) << std::fixed; } mutable std::stringstream ss; }; template friend Row& operator<<(Row& row, const T& value) { row.ss << Row::Field::prefix() << std::setw(Row::Field::width) << value << Row::Field::suffix(); return row; } template friend Row& operator<<(Row& row, T& value) { row.ss << Row::Field::prefix() << std::setw(Row::Field::width) << value << Row::Field::suffix(); return row; } template friend std::ostream& operator<<(std::ostream& out, const Row& row) { out << row.ss.str() << separator << std::endl; row.ss.str(std::string{}); return out; } }; } #endif // TABLE_H net-cpp-2.0.0/tests/http_client_test.cpp0000664000175100017510000005651612553403510020676 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include #include #include #include "httpbin.h" #include #include #include namespace http = core::net::http; namespace json = Json; namespace net = core::net; namespace { auto default_progress_reporter = [](const http::Request::Progress& progress) { if (progress.download.current > 0. && progress.download.total > 0.) std::cout << "Download progress: " << progress.download.current / progress.download.total << std::endl; if (progress.upload.current > 0. && progress.upload.total > 0.) std::cout << "Upload progress: " << progress.upload.current / progress.upload.total << std::endl; return http::Request::Progress::Next::continue_operation; }; bool init() { static httpbin::Instance instance; return true; } static const bool is_initialized = init(); } TEST(HttpClient, uri_to_string) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); EXPECT_EQ("http://baz.com", client->uri_to_string(net::make_uri("http://baz.com"))); EXPECT_EQ("http://foo.com/foo%20bar/baz%20boz", client->uri_to_string(net::make_uri("http://foo.com", { "foo bar", "baz boz" }))); EXPECT_EQ( "http://banana.fruit/my/endpoint?hello%20there=good%20bye&happy=sad", client->uri_to_string(net::make_uri("http://banana.fruit", { "my", "endpoint" }, { { "hello there", "good bye" }, { "happy", "sad" } }))); } TEST(HttpClient, head_request_for_existing_resource_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); // The client mostly acts as a factory for http requests. auto request = client->head(http::Request::Configuration::from_uri_as_string(url)); // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); } TEST(HttpClient, DISABLED_a_request_can_timeout) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); // The client mostly acts as a factory for http requests. auto request = client->head(http::Request::Configuration::from_uri_as_string(url)); request->set_timeout(std::chrono::milliseconds{1}); // We finally execute the query synchronously and story the response. EXPECT_THROW(auto response = request->execute(default_progress_reporter), core::net::Error); } TEST(HttpClient, DISABLED_get_request_against_app_store_succeeds) { auto client = http::make_client(); auto url = "https://search.apps.ubuntu.com/api/v1/search?q=%2Cframework%3Aubuntu-sdk-13.10%2Carchitecture%3Aamd64"; auto request = client->get(http::Request::Configuration::from_uri_as_string(url)); // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); response.header.enumerate([](const std::string& key, const std::set& values) { for (const auto& value : values) std::cout << key << " -> " << value << std::endl; }); } TEST(HttpClient, get_request_for_existing_resource_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); // The client mostly acts as a factory for http requests. auto request = client->get(http::Request::Configuration::from_uri_as_string(url)); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(url, root["url"].asString()); } TEST(HttpClient, get_request_with_custom_headers_for_existing_resource_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::headers(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.header.set("Test1", "42"); configuration.header.set("Test2", "43"); auto request = client->get(configuration); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); auto headers = root["headers"]; EXPECT_EQ("42", headers["Test1"].asString()); EXPECT_EQ("43", headers["Test2"].asString()); } TEST(HttpClient, empty_header_values_are_handled_correctly) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::headers(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.header.set("Empty", std::string{}); auto request = client->get(configuration); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); auto headers = root["headers"]; EXPECT_EQ(std::string{}, headers["Empty"].asString()); } TEST(HttpClient, get_request_for_existing_resource_guarded_by_basic_auth_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::basic_auth(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.authentication_handler.for_http = [](const std::string&) { return http::Request::Credentials{"user", "passwd"}; }; auto request = client->get(configuration); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // We expect authentication to work. EXPECT_TRUE(root["authenticated"].asBool()); // With the correct user id EXPECT_EQ("user", root["user"].asString()); } // Digest auth is broken on httpbin.org. It even fails in the browser after the first successful access. TEST(HttpClient, DISABLED_get_request_for_existing_resource_guarded_by_digest_auth_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::digest_auth(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.authentication_handler.for_http = [](const std::string&) { return http::Request::Credentials{"user", "passwd"}; }; auto request = client->get(configuration); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // We expect authentication to work. EXPECT_TRUE(root["authenticated"].asBool()); // With the correct user id EXPECT_EQ("user", root["user"].asString()); } TEST(HttpClient, async_get_request_for_existing_resource_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Execute the client std::thread worker{[client]() { client->run(); }}; // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::get(); // The client mostly acts as a factory for http requests. auto request = client->get(http::Request::Configuration::from_uri_as_string(url)); std::promise promise; auto future = promise.get_future(); // We finally execute the query asynchronously. request->async_execute( http::Request::Handler() .on_progress(default_progress_reporter) .on_response([&](const core::net::http::Response& response) { promise.set_value(response); }) .on_error([&](const core::net::Error& e) { promise.set_exception(std::make_exception_ptr(e)); })); auto response = future.get(); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(url, root["url"].asString()); client->stop(); // We shut down our worker thread if (worker.joinable()) worker.join(); } TEST(HttpClient, async_get_request_for_existing_resource_guarded_by_basic_authentication_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Execute the client std::thread worker{[client]() { client->run(); }}; // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::basic_auth(); // The client mostly acts as a factory for http requests. auto configuration = http::Request::Configuration::from_uri_as_string(url); configuration.authentication_handler.for_http = [](const std::string&) { return http::Request::Credentials{"user", "passwd"}; }; auto request = client->get(configuration); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; std::promise promise; auto future = promise.get_future(); // We finally execute the query asynchronously. request->async_execute( http::Request::Handler() .on_progress(default_progress_reporter) .on_response([&](const core::net::http::Response& response) { promise.set_value(response); client->stop(); }) .on_error([&](const core::net::Error& e) { promise.set_exception(std::make_exception_ptr(e)); client->stop(); })); // And wait here for the response to arrive. auto response = future.get(); // We shut down our worker thread if (worker.joinable()) worker.join(); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // We expect authentication to work. EXPECT_TRUE(root["authenticated"].asBool()); // With the correct user id EXPECT_EQ("user", root["user"].asString()); } TEST(HttpClient, post_request_for_existing_resource_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::post(); std::string payload = "{ 'test': 'test' }"; // The client mostly acts as a factory for http requests. auto request = client->post(http::Request::Configuration::from_uri_as_string(url), payload, core::net::http::ContentType::json); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; // We finally execute the query synchronously and story the response. auto response = request->execute(default_progress_reporter); // We expect the query to complete successfully EXPECT_EQ(core::net::http::Status::ok, response.status); // Parsing the body of the response as JSON should succeed. EXPECT_TRUE(reader.parse(response.body, root)); // The url field of the payload should equal the original url we requested. EXPECT_EQ(payload, root["data"].asString()); } TEST(HttpClient, post_form_request_for_existing_resource_succeeds) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Url pointing to the resource we would like to access via http. auto url = std::string(httpbin::host) + httpbin::resources::post(); std::map values { {"test", "test"} }; // The client mostly acts as a factory for http requests. auto request = client->post_form(http::Request::Configuration::from_uri_as_string(url), values); // We finally execute the query synchronously and store the response. auto response = request->execute(default_progress_reporter); // All endpoint data on httpbin.org is JSON encoded. json::Value root; json::Reader reader; EXPECT_EQ(core::net::http::Status::ok, response.status); EXPECT_TRUE(reader.parse(response.body, root)); EXPECT_EQ("test", root["form"]["test"].asString()); } TEST(HttpClient, put_request_for_existing_resource_succeeds) { auto client = http::make_client(); auto url = std::string(httpbin::host) + httpbin::resources::put(); const std::string value{"{ 'test': 'test' }"}; std::stringstream payload(value); auto request = client->put(http::Request::Configuration::from_uri_as_string(url), payload, value.size()); json::Value root; json::Reader reader; auto response = request->execute(default_progress_reporter); EXPECT_EQ(core::net::http::Status::ok, response.status); EXPECT_TRUE(reader.parse(response.body, root)); EXPECT_EQ(payload.str(), root["data"].asString()); } namespace com { namespace mozilla { namespace services { namespace location { constexpr const char* host { "https://location.services.mozilla.com" }; namespace resources { namespace v1 { const char* search() { return "/v1/search?key=net-cpp-testing"; } const char* submit() { return "/v1/submit?key=net-cpp-testing"; } } } } } } } // See https://mozilla-ichnaea.readthedocs.org/en/latest/api/search.html // for API and endpoint documentation. TEST(HttpClient, DISABLED_search_for_location_on_mozillas_location_service_succeeds) { json::FastWriter writer; json::Value search; json::Value cell; cell["radio"] = "umts"; cell["mcc"] = 123; cell["mnc"] = 123; cell["lac"] = 12345; cell["cid"] = 12345; cell["signal"] = -61; cell["asu"] = 26; json::Value wifi1, wifi2; wifi1["key"] = "01:23:45:67:89:ab"; wifi1["channel"] = 11; wifi1["frequency"] = 2412; wifi1["signal"] = -50; wifi2["key"] = "01:23:45:67:cd:ef"; search["radio"] = json::Value("gsm"); search["cell"].append(cell); search["wifi"].append(wifi1); search["wifi"].append(wifi2); auto client = http::make_client(); auto url = std::string(com::mozilla::services::location::host) + com::mozilla::services::location::resources::v1::search(); auto request = client->post(http::Request::Configuration::from_uri_as_string(url), writer.write(search), http::ContentType::json); auto response = request->execute(default_progress_reporter); json::Reader reader; json::Value result; EXPECT_EQ(core::net::http::Status::ok, response.status); EXPECT_TRUE(reader.parse(response.body, result)); // We cannot be sure that the server has got information for the given // cell and wifi ids. For that, we disable the test. EXPECT_EQ("ok", result["status"].asString()); //EXPECT_DOUBLE_EQ(-22.7539192, result["lat"].asDouble()); //EXPECT_DOUBLE_EQ(-43.4371081, result["lon"].asDouble()); } // See https://mozilla-ichnaea.readthedocs.org/en/latest/api/submit.html // for API and endpoint documentation. TEST(HttpClient, DISABLED_submit_of_location_on_mozillas_location_service_succeeds) { json::Value submit; json::Value cell; cell["radio"] = "umts"; cell["mcc"] = 123; cell["mnc"] = 123; cell["lac"] = 12345; cell["cid"] = 12345; cell["signal"] = -60; json::Value wifi1, wifi2; wifi1["key"] = "01:23:45:67:89:ab"; wifi1["channel"] = 11; wifi1["frequency"] = 2412; wifi1["signal"] = -50; wifi2["key"] = "01:23:45:67:cd:ef"; json::Value item; item["lat"] = -22.7539192; item["lon"] = -43.4371081; item["time"] = "2012-03-15T11:12:13.456Z"; item["accuracy"] = 10; item["altitude"] = 100; item["altitude_accuracy"] = 1; item["radio"] = "gsm"; item["cell"].append(cell); item["wifi"].append(wifi1); item["wifi"].append(wifi2); submit["items"].append(item); json::FastWriter writer; auto client = http::make_client(); auto url = std::string(com::mozilla::services::location::host) + com::mozilla::services::location::resources::v1::submit(); auto request = client->post(http::Request::Configuration::from_uri_as_string(url), writer.write(submit), http::ContentType::json); auto response = request->execute(default_progress_reporter); EXPECT_EQ(http::Status::no_content, response.status); } typedef std::pair StringPairTestParams; class HttpClientBase64Test : public ::testing::TestWithParam { }; TEST_P(HttpClientBase64Test, encoder) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Get our encoding parameters auto param = GetParam(); // Try the base64 encode out EXPECT_EQ(param.second, client->base64_encode(param.first)); } TEST_P(HttpClientBase64Test, decoder) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Get our encoding parameters auto param = GetParam(); // Try the base64 decode out EXPECT_EQ(param.first, client->base64_decode(param.second)); } INSTANTIATE_TEST_CASE_P(Base64Fixtures, HttpClientBase64Test, ::testing::Values( StringPairTestParams("", ""), StringPairTestParams("M", "TQ=="), StringPairTestParams("Ma", "TWE="), StringPairTestParams("Man", "TWFu"), StringPairTestParams("pleasure.", "cGxlYXN1cmUu"), StringPairTestParams("leasure.", "bGVhc3VyZS4="), StringPairTestParams("easure.", "ZWFzdXJlLg=="), StringPairTestParams("asure.", "YXN1cmUu"), StringPairTestParams("sure.", "c3VyZS4="), StringPairTestParams("bananas are tasty", "YmFuYW5hcyBhcmUgdGFzdHk=") )); class HttpClientUrlEscapeTest : public ::testing::TestWithParam { }; TEST_P(HttpClientUrlEscapeTest, url_escape) { // We obtain a default client instance, dispatching to the default implementation. auto client = http::make_client(); // Get our encoding parameters auto param = GetParam(); // Try the url_escape out EXPECT_EQ(param.second, client->url_escape(param.first)); } INSTANTIATE_TEST_CASE_P(UrlEscapeFixtures, HttpClientUrlEscapeTest, ::testing::Values( StringPairTestParams("", ""), StringPairTestParams("Hello Günter", "Hello%20G%C3%BCnter"), StringPairTestParams("That costs £20", "That%20costs%20%C2%A320"), StringPairTestParams("Microsoft®", "Microsoft%C2%AE") )); net-cpp-2.0.0/data/0000775000175100017510000000000012553403521014352 5ustar tvosstvoss00000000000000net-cpp-2.0.0/data/CMakeLists.txt0000664000175100017510000000146712553403510017120 0ustar tvosstvoss00000000000000# Copyright © 2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authored by: Thomas Voss configure_file( net-cpp.pc.in net-cpp.pc @ONLY ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/net-cpp.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) net-cpp-2.0.0/data/net-cpp.pc.in0000664000175100017510000000050512553403510016647 0ustar tvosstvoss00000000000000prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${exec_prefix}/include Name: @CMAKE_PROJECT_NAME@ Description: C++11 library for networking purposes. Version: @NET_CPP_VERSION_MAJOR@.@NET_CPP_VERSION_MINOR@.@NET_CPP_VERSION_PATCH@ Libs: -L${libdir} -lnet-cpp Cflags: -I${includedir}net-cpp-2.0.0/doc/0000775000175100017510000000000012553403521014206 5ustar tvosstvoss00000000000000net-cpp-2.0.0/doc/CMakeLists.txt0000664000175100017510000000121412553403510016742 0ustar tvosstvoss00000000000000option( NET_CPP_ENABLE_DOC_GENERATION "Generate package documentation with doxygen" ON ) if (NET_CPP_ENABLE_DOC_GENERATION) find_package(Doxygen) if (DOXYGEN_FOUND) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) add_custom_target(doc ALL ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Generating API documentation with Doxygen" VERBATIM) install( DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html DESTINATION ${CMAKE_INSTALL_DOCDIR}) endif (DOXYGEN_FOUND) endif (NET_CPP_ENABLE_DOC_GENERATION) net-cpp-2.0.0/doc/Doxyfile.in0000664000175100017510000023445112553403510016330 0ustar tvosstvoss00000000000000# Doxyfile 1.8.3.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or sequence of words) that should # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. PROJECT_NAME = @CMAKE_PROJECT_NAME@ # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = @NET_CPP_VERSION_MAJOR@.@NET_CPP_VERSION_MINOR@.@NET_CPP_VERSION_PATCH@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "C++11 library for networking purposes" # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = YES # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. Note that you specify absolute paths here, but also # relative paths, which will be relative from the directory where doxygen is # started. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, # and language is one of the parsers supported by doxygen: IDL, Java, # Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, # C++. For instance to make doxygen treat .inc files as Fortran files (default # is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note # that for custom extensions you also need to set FILE_PATTERNS otherwise the # files are not read by doxygen. EXTENSION_MAPPING = # If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all # comments according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you # can mix doxygen, HTML, and XML commands with Markdown formatting. # Disable only in case of backward compatibilities issues. MARKDOWN_SUPPORT = YES # When enabled doxygen tries to link words that correspond to documented classes, # or namespaces to their corresponding documentation. Such a link can be # prevented in individual cases by by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES (the # default) will make doxygen replace the get and set methods by a property in # the documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given # their name and scope. Since this can be an expensive process and often the # same symbol appear multiple times in the code, doxygen keeps a cache of # pre-resolved symbols. If the cache is too small doxygen will become slower. # If the cache is too large, memory is wasted. The cache size is given by this # formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_PACKAGE tag is set to YES all members with package or internal # scope will be included in the documentation. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if section-label ... \endif # and \cond section-label ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this # feature you need bibtex and perl available in the search path. Do not use # file names with spaces, bibtex cannot handle them. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @CMAKE_SOURCE_DIR@/include @CMAKE_CURRENT_SOURCE_DIR@ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @CMAKE_CURRENT_SOURCE_DIR@/../tests # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = YES # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = # If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page (index.html). # This can be useful if you have a project on for instance GitHub and want reuse # the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = @CMAKE_SOURCE_DIR@/README.md #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C, C++ and Fortran comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If left blank doxygen will # generate a default style sheet. Note that it is recommended to use # HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this # tag will in the future become obsolete. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify an additional # user-defined cascading style sheet that is included after the standard # style sheets created by doxygen. Using this option one can overrule # certain style aspects. This is preferred over using HTML_STYLESHEET # since it does not replace the standard style sheet and is therefor more # robust against future updates. Doxygen will copy the style sheet file to # the output directory. HTML_EXTRA_STYLESHEET = @CMAKE_CURRENT_SOURCE_DIR@/extra.css # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. HTML_DYNAMIC_SECTIONS = YES # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of # entries shown in the various tree structured indices initially; the user # can expand and collapse entries dynamically later on. Doxygen will expand # the tree to such a level that at most the specified number of entries are # visible (unless a fully collapsed tree already exceeds this amount). # So setting the number of entries 1 will produce a full collapsed tree by # default. 0 is a special value representing an infinite number of entries # and will result in a full expanded tree by default. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely # identify the documentation publisher. This should be a reverse domain-name # style string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = YES # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 1 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # thA MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and # SVG. The default value is HTML-CSS, which is slower, but has the best # compatibility. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to # the MathJax Content Delivery Network so you can quickly see the result without # installing MathJax. # However, it is strongly recommended to install a local # copy of MathJax from http://www.mathjax.org before deployment. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = NO # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a web server instead of a web client using Javascript. # There are two flavours of web server based search depending on the # EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for # searching and an index file used by the script. When EXTERNAL_SEARCH is # enabled the indexing and searching needs to be provided by external tools. # See the manual for details. SERVER_BASED_SEARCH = NO # When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP # script for searching. Instead the search results are written to an XML file # which needs to be processed by an external indexer. Doxygen will invoke an # external search engine pointed to by the SEARCHENGINE_URL option to obtain # the search results. Doxygen ships with an example indexer (doxyindexer) and # search engine (doxysearch.cgi) which are based on the open source search engine # library Xapian. See the manual for configuration details. EXTERNAL_SEARCH = NO # The SEARCHENGINE_URL should point to a search engine hosted by a web server # which will returned the search results when EXTERNAL_SEARCH is enabled. # Doxygen ships with an example search engine (doxysearch) which is based on # the open source search engine library Xapian. See the manual for configuration # details. SEARCHENGINE_URL = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed # search data is written to a file for indexing by an external tool. With the # SEARCHDATA_FILE tag the name of this file can be specified. SEARCHDATA_FILE = searchdata.xml # When SERVER_BASED_SEARCH AND EXTERNAL_SEARCH are both enabled the # EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is # useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple # projects and redirect the results back to the right project. EXTERNAL_SEARCH_ID = # The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen # projects other than the one defined by this configuration file, but that are # all added to the same external search index. Each project needs to have a # unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id # of to a relative location where the documentation can be found. # The format is: EXTRA_SEARCH_MAPPINGS = id1=loc1 id2=loc2 ... EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = YES # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = YES # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = YES # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. For each # tag file the location of the external documentation should be added. The # format of a tag file without this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths # or URLs. Note that each tag file must have a unique name (where the name does # NOT include the path). If a tag file is not located in the directory in which # doxygen is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = NO # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = YES # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = 1 # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = Helvetica # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = YES # If the UML_LOOK tag is enabled, the fields and methods are shown inside # the class node. If there are many fields or methods and many nodes the # graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS # threshold limits the number of items for each type to make the size more # managable. Set this to 0 for no limit. Note that the threshold may be # exceeded by 50% before the limit is enforced. UML_LIMIT_NUM_FIELDS = 10 # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = YES # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = YES # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = YES # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES net-cpp-2.0.0/include/0000775000175100017510000000000012553403521015064 5ustar tvosstvoss00000000000000net-cpp-2.0.0/include/CMakeLists.txt0000664000175100017510000000010612553403510017617 0ustar tvosstvoss00000000000000install( DIRECTORY core DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/) net-cpp-2.0.0/include/core/0000775000175100017510000000000012553403521016014 5ustar tvosstvoss00000000000000net-cpp-2.0.0/include/core/net/0000775000175100017510000000000012553403521016602 5ustar tvosstvoss00000000000000net-cpp-2.0.0/include/core/net/uri.h0000664000175100017510000000430212553403510017547 0ustar tvosstvoss00000000000000/* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Pete Woods */ #ifndef CORE_NET_URI_H_ #define CORE_NET_URI_H_ #include #include #include namespace core { namespace net { /** * @brief The Uri class encapsulates the components of a URI */ struct Uri { typedef std::string Host; typedef std::vector Path; typedef std::vector> QueryParameters; /** * @brief The host is the first part of the URI, including the protocol * * e.g. * \code{.cpp} * "http://www.ubuntu.com" * \endcode */ Host host; /** * @brief the path components * * e.g. * \code{.cpp} * {"api", "v3", "search"} * \endcode */ Path path; /** * @brief The CGI query parameters as ordered key-value pairs * * e.g. * \code{.cpp} * {{"key1", "value1"}, {"key2", "value2"}} * \endcode */ QueryParameters query_parameters; }; /** * @brief Build a URI from its components * * e.g. * \code{.cpp} * std::string query = "banana"; * auto uri = core::net::make_uri("https://api.mydomain.com", {"api", "v3", "search"}, {{"query", query}}); * \endcode * * When converted to a std::string with core::net::http::client::uri_to_string() * the endpoint and parameters will be URL-escaped. */ CORE_NET_DLL_PUBLIC Uri make_uri (const Uri::Host& host, const Uri::Path& path = Uri::Path(), const Uri::QueryParameters& query_parameters = Uri::QueryParameters()); } } #endif // CORE_NET_URI_H_ net-cpp-2.0.0/include/core/net/visibility.h0000664000175100017510000000200412553403510021134 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_VISIBILITY_H_ #define CORE_NET_VISIBILITY_H_ #if __GNUC__ >= 4 #define CORE_NET_DLL_PUBLIC __attribute__ ((visibility ("default"))) #define CORE_NET_DLL_LOCAL __attribute__ ((visibility ("hidden"))) #else #define CORE_NET_DLL_PUBLIC #define CORE_NET_DLL_LOCAL #endif #endif // CORE_NET_VISIBILITY_H_ net-cpp-2.0.0/include/core/net/http/0000775000175100017510000000000012553403521017561 5ustar tvosstvoss00000000000000net-cpp-2.0.0/include/core/net/http/streaming_request.h0000664000175100017510000000410512553403510023471 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_STREAMING_REQUEST_H_ #define CORE_NET_HTTP_STREAMING_REQUEST_H_ #include namespace core { namespace net { namespace http { /** * @brief The StreamingRequest class encapsulates a request for a web resource, * streaming data to the receiver as it receives in addition to accumulating all incoming data. */ class CORE_NET_DLL_PUBLIC StreamingRequest : public Request { public: /** DataHandler is invoked when a new chunk of data arrives from the server. */ typedef std::function DataHandler; /** * @brief Synchronously executes the request. * @throw core::net::http::Error in case of http-related errors. * @throw core::net::Error in case of network-related errors. * @return The response to the request. */ virtual Response execute(const ProgressHandler& ph, const DataHandler& dh) = 0; /** * @brief Asynchronously executes the request, reporting errors, progress and completion to the given handlers. * @param handler The handlers to called for events happening during execution of the request. * @param dh The data handler receiving chunks of data while executing the request. * @return The response to the request. */ virtual void async_execute(const Handler& handler, const DataHandler& dh) = 0; }; } } } #endif // CORE_NET_HTTP_STREAMING_REQUEST_H_ net-cpp-2.0.0/include/core/net/http/method.h0000664000175100017510000000171212553403510021211 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_METHOD_H_ #define CORE_NET_HTTP_METHOD_H_ #include #include namespace core { namespace net { namespace http { enum class Method { get, head, post, put }; } } } #endif // CORE_NET_HTTP_H_ net-cpp-2.0.0/include/core/net/http/content_type.h0000664000175100017510000000243612553403510022450 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_CONTENT_TYPE_H_ #define CORE_NET_HTTP_CONTENT_TYPE_H_ #include namespace core { namespace net { namespace http { /** * @brief Collection of known content types. */ struct CORE_NET_DLL_PUBLIC ContentType { ContentType() = delete; constexpr static const char* json { "application/json" }; constexpr static const char* xml { "application/xml" }; constexpr static const char* x_www_form_urlencoded { "application/x-www-form-urlencoded" }; }; } } } #endif // CORE_NET_HTTP_CONTENT_TYPE_H_ net-cpp-2.0.0/include/core/net/http/status.h0000664000175100017510000000406512553403510021260 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_STATUS_H_ #define CORE_NET_HTTP_STATUS_H_ #include #include namespace core { namespace net { namespace http { enum class Status { continue_ = 100, switching_protocols = 101, ok = 200, created = 201, accepted = 202, non_authorative_info = 203, no_content = 204, reset_content = 205, partial_content = 206, multiple_choices = 300, moved_permanently = 301, found = 302, see_other = 303, not_modified = 304, use_proxy = 305, temporary_redirect = 307, bad_request = 400, unauthorized = 401, payment_required = 402, forbidden = 403, not_found = 404, method_not_allowed = 405, not_acceptable = 406, proxy_auth_required = 407, request_timeout = 408, conflict = 409, gone = 410, length_required = 411, precondition_failed = 412, request_entity_too_large = 413, request_uri_too_long = 414, unsupported_media_type = 415, requested_range_not_satisfiable = 416, expectation_failed = 417, teapot = 418, internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503, gateway_timeout = 504, http_version_not_supported = 505 }; CORE_NET_DLL_PUBLIC std::ostream& operator<<(std::ostream& out, Status status); } } } #endif // CORE_NET_HTTP_STATUS_H_ net-cpp-2.0.0/include/core/net/http/header.h0000664000175100017510000000601012553403510021155 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_HEADER_H_ #define CORE_NET_HTTP_HEADER_H_ #include #include #include #include #include namespace core { namespace net { namespace http { /** * @brief The Header class encapsulates the headers of an HTTP request/response. */ class CORE_NET_DLL_PUBLIC Header { public: /** * @brief canonicalize_key returns the canonical form of the header key 'key'. * * The canonicalization converts the first * letter and any letter following a hyphen to upper case; * the rest are converted to lowercase. For example, the * canonical key for "accept-encoding" is "Accept-Encoding". * * @param key The key to be canonicalized. */ static std::string canonicalize_key(const std::string& key); virtual ~Header() = default; /** * @brief has checks if the header contains an entry for the given key with the given value. * @param key The key into the header map. * @param value The value to check for. */ virtual bool has(const std::string& key, const std::string& value) const; /** * @brief has checks if the header contains any entry for the given key. * @param key The key into the header map. */ virtual bool has(const std::string& key) const; /** * @brief add adds the given value for the given key to the header. */ virtual void add(const std::string& key, const std::string& value); /** * @brief remove erases all values for the given key from the header. */ virtual void remove(const std::string& key); /** * @brief remove erases the given value for the given key from the header. */ virtual void remove(const std::string& key, const std::string& value); /** * @brief set assigns the given value to the entry with key 'key' and replaces any previous value. */ virtual void set(const std::string& key, const std::string& value); /** * @brief enumerate iterates over the known fields and invokes the given enumerator for each of them. */ virtual void enumerate(const std::function&)>& enumerator) const; private: /// @cond std::map> fields; /// @endcond }; } } } #endif // CORE_NET_HTTP_HEADER_H_ net-cpp-2.0.0/include/core/net/http/request.h0000664000175100017510000002024112553403510021417 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_REQUEST_H_ #define CORE_NET_HTTP_REQUEST_H_ #include #include #include #include #include namespace core { namespace net { namespace http { class Response; /** * @brief The Request class encapsulates a request for a web resource. */ class CORE_NET_DLL_PUBLIC Request { public: /** * @brief The State enum describes the different states a request can be in. */ enum class State { ready, ///< The request is idle and needs execution. active, ///< The request is active and is actively being executed. done ///< Execution of the request has finished. }; /** * @brief The Errors struct collects the Request-specific exceptions and error modes. */ struct Errors { Errors() = delete; /** * @brief AlreadyActive is thrown when *execute is called on an active request. */ struct AlreadyActive : public core::net::http::Error { /** * @brief AlreadyActive creates a new instance with a location hint. * @param loc The location that the call originates from. */ AlreadyActive(const core::Location& loc); }; }; /** * @brief The Progress struct encapsulates progress information for web-resource requests. */ struct Progress { /** * @brief The Next enum summarizes the available return-types for the progress callback. */ enum class Next { continue_operation, ///< Continue the request. abort_operation ///< Abort the request. }; struct { double total{-1.}; ///< Total number of bytes to be downloaded. double current{-1.}; ///< Current number of bytes already downloaded. } download{}; struct { double total{-1.}; ///< Total number of bytes to be uploaded. double current{-1.}; ///< Current number of bytes already uploaded. } upload{}; }; /** * @brief ErrorHandler is invoked in case of errors arising while executing the request. */ typedef std::function ErrorHandler; /** * @brief ProgressHandler is invoked for progress updates while executing the request. */ typedef std::function ProgressHandler; /** * @brief ResponseHandler is invoked when a request completes. */ typedef std::function ResponseHandler; /** * @brief Encapsulates callbacks that can happen during request execution. */ class Handler { public: Handler() = default; /** @brief Returns the currently set progress handler. */ const ProgressHandler& on_progress() const; /** @brief Adjusts the currently set progress handler. */ Handler& on_progress(const ProgressHandler& handler); /** @brief Returns the currently set response handler. */ const ResponseHandler& on_response() const; /** @brief Adjusts the currently set response handler. */ Handler& on_response(const ResponseHandler& handler); /** @brief Returns the currently set error handler. */ const ErrorHandler& on_error() const; /** @brief Adjusts the currently set error handler. */ Handler& on_error(const ErrorHandler& handler); private: /** @cond */ ProgressHandler progress_handler{}; ResponseHandler response_handler{}; ErrorHandler error_handler{}; /** @endcond */ }; /** * @brief The Credentials struct encapsulates username and password for basic & digest authentication. */ struct Credentials { std::string username; std::string password; }; /** Function signature for querying credentials for a given URL. */ typedef std::function AuthenicationHandler; /** * @brief The Configuration struct encapsulates all options for creating requests. */ struct Configuration { /** * @brief from_uri_as_string creates a new instance of Configuration for a url. * @param uri The url of the web resource to issue a request for. * @return A new Configuration instance. */ inline static Configuration from_uri_as_string(const std::string& uri) { Configuration result; result.uri = uri; return result; } /** Uri of the web resource to issue a request for. */ std::string uri; /** Custom header fields that are added to the request. */ Header header; /** Invoked to report progress. */ ProgressHandler on_progress; /** Invoked to report a successfully finished request. */ ResponseHandler on_response; /** Invoked to report a request that finished with an error. */ ErrorHandler on_error; /** SSL-specific options. Please be very careful when adjusting these. */ struct { /** Yes, we want to verify our peer by default. */ bool verify_peer { true }; /** Yes, we want to be strict and verify the host by default, too. */ bool verify_host { true }; } ssl; /** Encapsulates proxy and http authentication handlers. */ struct { /** Invoked for querying user credentials to do basic/digest auth. */ AuthenicationHandler for_http; /** Invoked for querying user credentials to authenticate proxy accesses. */ AuthenicationHandler for_proxy; } authentication_handler; }; Request(const Request&) = delete; virtual ~Request() = default; Request& operator=(const Request&) = delete; bool operator==(const Request&) const = delete; /** * @brief state queries the current state of the operation. * @return A value from the State enumeration. */ virtual State state() = 0; /** * @brief Adjusts the timeout of a State::ready request. * @param timeout The timeout in milliseconds. */ virtual void set_timeout(const std::chrono::milliseconds& timeout) = 0; /** * @brief Synchronously executes the request. * @throw core::net::http::Error in case of http-related errors. * @throw core::net::Error in case of network-related errors. * @return The response to the request. */ virtual Response execute(const ProgressHandler& ph) = 0; /** * @brief Asynchronously executes the request, reporting errors, progress and completion to the given handlers. * @param handler The handlers to called for events happening during execution of the request. * @return The response to the request. */ virtual void async_execute(const Handler& handler) = 0; /** * @brief Returns the input string in URL-escaped format. * @param s The string to be URL escaped. */ virtual std::string url_escape(const std::string& s) = 0; /** * @brief Returns the input string in URL-unescaped format. * @param s The string to be URL unescaped. */ virtual std::string url_unescape(const std::string& s) = 0; protected: /** @cond */ Request() = default; /** @endcond */ }; } } } #endif // CORE_NET_HTTP_REQUEST_H_ net-cpp-2.0.0/include/core/net/http/streaming_client.h0000664000175100017510000001003412553403510023255 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_STREAMING_CLIENT_H_ #define CORE_NET_HTTP_STREAMING_CLIENT_H_ #include #include namespace core { namespace net { namespace http { class StreamingClient : public Client { public: virtual ~StreamingClient() = default; /** * @brief streaming_get is a convenience method for issueing a GET request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @return An executable instance of class Request. */ virtual std::shared_ptr streaming_get(const Request::Configuration& configuration) = 0; /** * @brief streaming_head is a convenience method for issueing a HEAD request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @return An executable instance of class Request. */ virtual std::shared_ptr streaming_head(const Request::Configuration& configuration) = 0; /** * @brief streaming_put is a convenience method for issuing a PUT request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @param payload The data to be transmitted as part of the PUT request. * @param size Size of the payload data in bytes. * @return An executable instance of class Request. */ virtual std::shared_ptr streaming_put(const Request::Configuration& configuration, std::istream& payload, std::size_t size) = 0; /** * @brief streaming_post is a convenience method for issuing a POST request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @param payload The data to be transmitted as part of the POST request. * @param type The content-type of the data. * @return An executable instance of class Request. */ virtual std::shared_ptr streaming_post(const Request::Configuration& configuration, const std::string& payload, const std::string& type) = 0; /** * @brief streaming_post_form is a convenience method for issuing a POST request for the given URI, with url-encoded payload. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @param values Key-value pairs to be added to the payload in url-encoded format. * @return An executable instance of class Request. */ virtual std::shared_ptr streaming_post_form(const Request::Configuration& configuration, const std::map& values) = 0; }; /** @brief Dispatches to the default implementation and returns a streaming client instance. */ CORE_NET_DLL_PUBLIC std::shared_ptr make_streaming_client(); } } } #endif // CORE_NET_HTTP_STREAMING_CLIENT_H_ net-cpp-2.0.0/include/core/net/http/client.h0000664000175100017510000001534012553403510021211 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_CLIENT_H_ #define CORE_NET_HTTP_CLIENT_H_ #include #include #include #include #include #include namespace core { namespace net { struct Uri; namespace http { class ContentType; class Request; class CORE_NET_DLL_PUBLIC Client { public: /** @brief Summarizes error conditions. */ struct Errors { Errors() = delete; /** @brief HttpMethodNotSupported is thrown if the underlying impl. * does not support the requested HTTP method. */ struct HttpMethodNotSupported : public http::Error { HttpMethodNotSupported(Method method, const core::Location&); Method method; }; }; /** @brief Summarizes timing information about completed requests. */ struct Timings { typedef std::chrono::duration Seconds; struct Statistics { /** Maximum duration that was encountered. */ Seconds max{Seconds::max()}; /** Minimum duration that was encountered. */ Seconds min{Seconds::max()}; /** Mean duration that was encountered. */ Seconds mean{Seconds::max()}; /** Variance in duration that was encountered. */ Seconds variance{Seconds::max()}; }; /** Time it took from the start until the name resolving was completed. */ Statistics name_look_up{}; /** Time it took from the finished name lookup until the connect to the * remote host (or proxy) was completed. */ Statistics connect{}; /** Time it took from the connect until the SSL/SSH connect/handshake to * the remote host was completed. */ Statistics app_connect{}; /** Time it took from app_connect until the file transfer is just about to begin. */ Statistics pre_transfer{}; /** Time it took from pre-transfer until the first byte is received by libcurl. */ Statistics start_transfer{}; /** Time in total that the previous transfer took. */ Statistics total{}; }; Client(const Client&) = delete; virtual ~Client() = default; Client& operator=(const Client&) = delete; bool operator==(const Client&) const = delete; virtual std::string uri_to_string (const core::net::Uri& uri) const; /** @brief Percent-encodes the given string. */ virtual std::string url_escape(const std::string& s) const = 0; /** @brief Base64-encodes the given string. */ virtual std::string base64_encode(const std::string& s) const = 0; /** @brief Base64-decodes the given string. */ virtual std::string base64_decode(const std::string& s) const = 0; /** @brief Queries timing statistics over all requests that have been executed by this client. */ virtual Timings timings() = 0; /** @brief Execute the client and any impl-specific thread-pool or runtime. */ virtual void run() = 0; /** @brief Stop the client and any impl-specific thread-pool or runtime. */ virtual void stop() = 0; /** * @brief get is a convenience method for issueing a GET request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @return An executable instance of class Request. */ virtual std::shared_ptr get(const Request::Configuration& configuration) = 0; /** * @brief head is a convenience method for issueing a HEAD request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @return An executable instance of class Request. */ virtual std::shared_ptr head(const Request::Configuration& configuration) = 0; /** * @brief put is a convenience method for issuing a PUT request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @param payload The data to be transmitted as part of the PUT request. * @param size Size of the payload data in bytes. * @return An executable instance of class Request. */ virtual std::shared_ptr put(const Request::Configuration& configuration, std::istream& payload, std::size_t size) = 0; /** * @brief post is a convenience method for issuing a POST request for the given URI. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @param payload The data to be transmitted as part of the POST request. * @param type The content-type of the data. * @return An executable instance of class Request. */ virtual std::shared_ptr post(const Request::Configuration& configuration, const std::string& payload, const std::string& type) = 0; /** * @brief post_form is a convenience method for issuing a POST request for the given URI, with url-encoded payload. * @throw Errors::HttpMethodNotSupported if the underlying implementation does not support the provided HTTP method. * @param configuration The configuration to issue a get request for. * @param values Key-value pairs to be added to the payload in url-encoded format. * @return An executable instance of class Request. */ virtual std::shared_ptr post_form(const Request::Configuration& configuration, const std::map& values); protected: Client() = default; }; /** @brief Dispatches to the default implementation and returns a client instance. */ CORE_NET_DLL_PUBLIC std::shared_ptr make_client(); } } } #endif // CORE_NET_HTTP_CLIENT_H_ net-cpp-2.0.0/include/core/net/http/response.h0000664000175100017510000000311012553403510021561 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_RESPONSE_H_ #define CORE_NET_HTTP_RESPONSE_H_ #include #include #include #include #include #include namespace core { namespace net { namespace http { /** * @brief The Response struct models a response to a core::net::http::Request. */ struct CORE_NET_DLL_PUBLIC Response { // TODO(tvoss): This really should be a stringstream, but libstdc++ is broken and // does not define move operators correctly. /** @brief The body of the response is a string. */ typedef std::string Body; /** @brief The HTTP status as sent by the server. */ Status status{Status::bad_request}; /** @brief The header fields of the response. */ Header header{}; /** @brief The body of the response. */ Body body{}; }; } } } #endif // CORE_NET_HTTP_RESPONSE_H_ net-cpp-2.0.0/include/core/net/http/error.h0000664000175100017510000000201612553403510021060 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_HTTP_ERROR_H_ #define CORE_NET_HTTP_ERROR_H_ #include namespace core { namespace net { namespace http { class Error : public core::net::Error { public: explicit Error(const std::string& what, const Location& loc); virtual ~Error() = default; }; } } } #endif // CORE_NET_HTTP_ERROR_H_ net-cpp-2.0.0/include/core/net/error.h0000664000175100017510000000200212553403510020074 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_NET_ERROR_H_ #define CORE_NET_ERROR_H_ #include #include namespace core { namespace net { class Error : public std::runtime_error { public: explicit Error(const std::string& what, const Location& el); virtual ~Error() = default; }; } } #endif // CORE_NET_ERROR_H_ net-cpp-2.0.0/include/core/location.h0000664000175100017510000000220412553403510017771 0ustar tvosstvoss00000000000000/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef CORE_LOCATION_H_ #define CORE_LOCATION_H_ #include namespace core { struct Location { std::string print_with_what(const std::string& what) const; std::string file{}; std::string function{}; std::size_t line{}; }; Location from_here(const std::string& file, const std::string& function, std::size_t line); } #define CORE_FROM_HERE() core::from_here(__FILE__, __FUNCTION__, __LINE__) #endif // CORE_LOCATION_H_ net-cpp-2.0.0/COPYING0000664000175100017510000001674312553403510014505 0ustar tvosstvoss00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.