diff --git a/.gitignore b/.gitignore index f2c52757cf..cc8f6cb399 100644 --- a/.gitignore +++ b/.gitignore @@ -23,8 +23,4 @@ contents.xcworkspacedata .DS_Store .svn profile -Builds/VisualStudio2012/Debug -Builds/VisualStudio2012/Release -project.xcworkspace -modules/beast_cryptopp bin/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index a322d54864..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: cpp - -compiler: - - gcc - - clang -before_install: - - sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test - - sudo add-apt-repository -y ppa:boost-latest/ppa - - sudo apt-get update -qq - - sudo apt-get install -qq python-software-properties - - sudo apt-get install -qq g++-4.8 - - sudo apt-get install -qq libboost1.55-all-dev - - sudo apt-get install -qq libssl-dev - - sudo apt-get install -qq gcc-4.8 - - sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8 - - sudo update-alternatives --set gcc /usr/bin/gcc-4.8 -# - sudo apt-get -y install binutils-gold - - g++ -v - - clang -v -script: - # Abort build on failure - - set -e - - scons -notifications: - email: - false diff --git a/BeastConfig.h b/BeastConfig.h deleted file mode 100644 index db9792f1c7..0000000000 --- a/BeastConfig.h +++ /dev/null @@ -1,139 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_BEASTCONFIG_H_INCLUDED -#define BEAST_BEASTCONFIG_H_INCLUDED - -/** Configuration file for Beast. - This sets various configurable options for Beast. In order to compile you - must place a copy of this file in a location where your build environment - can find it, and then customize its contents to suit your needs. - @file BeastConfig.h -*/ - -//------------------------------------------------------------------------------ -// -// Unit Tests -// -//------------------------------------------------------------------------------ - -/** Config: BEAST_NO_UNIT_TEST_INLINE - Prevents unit test definitions from being inserted into a global table. -*/ -#ifndef BEAST_NO_UNIT_TEST_INLINE -#define BEAST_NO_UNIT_TEST_INLINE 0 -#endif - -//------------------------------------------------------------------------------ -// -// Diagnostics -// -//------------------------------------------------------------------------------ - -/** Config: BEAST_FORCE_DEBUG - Normally, BEAST_DEBUG is set to 1 or 0 based on compiler and project - settings, but if you define this value, you can override this to force it - to be true or false. -*/ -#ifndef BEAST_FORCE_DEBUG -//#define BEAST_FORCE_DEBUG 1 -#endif - -/** Config: BEAST_CHECK_MEMORY_LEAKS - Enables a memory-leak check for certain objects when the app terminates. - See the LeakChecked class for more details about enabling leak checking for - specific classes. -*/ -#ifndef BEAST_CHECK_MEMORY_LEAKS -//#define BEAST_CHECK_MEMORY_LEAKS 0 -#endif - -//------------------------------------------------------------------------------ -// -// Libraries -// -//------------------------------------------------------------------------------ - -/** Config: BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES - In a Visual C++ build, this can be used to stop the required system libs - being automatically added to the link stage. -*/ -#ifndef BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES -//#define BEAST_DONT_AUTOLINK_TO_WIN32_LIBRARIES 1 -#endif - -/** Config: BEAST_INCLUDE_ZLIB_CODE - This can be used to disable Beast's embedded 3rd-party zlib code. - You might need to tweak this if you're linking to an external zlib library - in your app, but for normal apps, this option should be left alone. - - If you disable this, you might also want to set a value for - BEAST_ZLIB_INCLUDE_PATH, to specify the path where your zlib headers live. -*/ -#ifndef BEAST_INCLUDE_ZLIB_CODE -//#define BEAST_INCLUDE_ZLIB_CODE 1 -#endif - -/** Config: BEAST_ZLIB_INCLUDE_PATH - This is included when BEAST_INCLUDE_ZLIB_CODE is set to zero. -*/ -#ifndef BEAST_ZLIB_INCLUDE_PATH -#define BEAST_ZLIB_INCLUDE_PATH -#endif - -/** Config: BEAST_SQLITE_FORCE_NDEBUG - Setting this option forces sqlite into release mode even if NDEBUG is not set -*/ -#ifndef BEAST_SQLITE_FORCE_NDEBUG -//#define BEAST_SQLITE_FORCE_NDEBUG 1 -#endif - -/** Config: BEAST_FUNCTIONAL_USES_### - source configuration. - Set one of these to manually force a particular implementation of bind(). - If nothing is chosen then beast will use whatever is appropriate for your - environment based on what is available. - If you override these, set ONE to 1 and the rest to 0 -*/ -#ifndef BEAST_FUNCTIONAL_USES_STD -//#define BEAST_FUNCTIONAL_USES_STD 0 -#endif -#ifndef BEAST_FUNCTIONAL_USES_TR1 -//#define BEAST_FUNCTIONAL_USES_TR1 0 -#endif -#ifndef BEAST_FUNCTIONAL_USES_BOOST -//#define BEAST_FUNCTIONAL_USES_BOOST 0 -#endif - -//------------------------------------------------------------------------------ -// -// Boost -// -//------------------------------------------------------------------------------ - -/** Config: BEAST_USE_BOOST_FEATURES - This activates boost specific features and improvements. If this is - turned on, the include paths for your build environment must be set - correctly to find the boost headers. -*/ -#ifndef BEAST_USE_BOOST_FEATURES -//#define BEAST_USE_BOOST_FEATURES 1 -#endif - -#endif diff --git a/Jamroot b/Jamroot index aed04ce28e..5a032af582 100644 --- a/Jamroot +++ b/Jamroot @@ -48,6 +48,7 @@ else project beast : requirements . + ./include #/boost//headers /boost/system//boost_system /boost/filesystem//boost_filesystem diff --git a/README.md b/README.md index 32e2029926..f681da34d6 100644 --- a/README.md +++ b/README.md @@ -1 +1,12 @@ -# Beast: A C++ Library +# Beast + +Beast provides implementations of the HTTP and WebSocket protocols +built on top of Boost.Asio and other parts of boost. + +Requirements: + +* Boost +* C++11 or greater +* OpenSSL (optional) + +Documentation: http://vinniefalco.github.io/beast/ diff --git a/TODO.txt b/TODO.txt index d5767cb808..399a2baf5b 100644 --- a/TODO.txt +++ b/TODO.txt @@ -1,8 +1,22 @@ * kick out non-beast code - * redo directory structure - * Change build options to C++11 only - * Replace Jamroot with Jamfile +* Switch source material to Boost license +* Fix failing test/message.cpp +* Complete allocator testing in basic_streambuf, basic_headers +* Tidy up type_checks + - Derive from std::integral_constant +* Check DOXYGEN, GENERATIC_DOCS directives in source + - See if we can include them now that xsl is fixed +* Go over each header and split header material into detail and impl files +* Make buffers_debug a detail +* Ensure each public header has a unit test .cpp file +* Roll header-only http parser +* Define Parser concept in HTTP +* melpon sandbox? +* invokable unit test +* trim public interface of rfc2616.h to essentials only +* Use new http routines in JSONRPCClient +* Remove or change http::headers alias diff --git a/beast/asio.h b/beast/asio.h deleted file mode 100644 index 607b12a7c3..0000000000 --- a/beast/asio.h +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_H_INCLUDED -#define BEAST_ASIO_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/beast/asio/buffers_debug.h b/beast/asio/buffers_debug.h deleted file mode 100644 index e536179962..0000000000 --- a/beast/asio/buffers_debug.h +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_BUFFERS_DEBUG_H_INLUDED -#define BEAST_ASIO_BUFFERS_DEBUG_H_INLUDED - -#include -#include - -namespace beast { -namespace debug { - -template -std::string -buffers_to_string(Buffers const& bs) -{ - using boost::asio::buffer_cast; - using boost::asio::buffer_size; - std::string s; - s.reserve(buffer_size(bs)); - for(auto const& b : bs) - s.append(buffer_cast(b), - buffer_size(b)); - for(auto i = s.size(); i-- > 0;) - if(s[i] == '\r') - s.replace(i, 1, "\\r"); - else if(s[i] == '\n') - s.replace(i, 1, "\\n\n"); - return s; -} - -} // debug -} // beast - -#endif diff --git a/beast/asio/io_latency_probe.h b/beast/asio/io_latency_probe.h deleted file mode 100644 index 2ecd25248e..0000000000 --- a/beast/asio/io_latency_probe.h +++ /dev/null @@ -1,244 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED -#define BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace beast { - -/** Measures handler latency on an io_service queue. */ -template -class io_latency_probe -{ -private: - using duration = typename Clock::duration; - using time_point = typename Clock::time_point; - - std::recursive_mutex m_mutex; - std::condition_variable_any m_cond; - std::size_t m_count; - duration const m_period; - boost::asio::io_service& m_ios; - boost::asio::deadline_timer m_timer; - bool m_cancel; - -public: - io_latency_probe (duration const& period, - boost::asio::io_service& ios) - : m_count (1) - , m_period (period) - , m_ios (ios) - , m_timer (m_ios) - , m_cancel (false) - { - } - - ~io_latency_probe () - { - std::unique_lock lock (m_mutex); - cancel (lock, true); - } - - /** Return the io_service associated with the latency probe. */ - /** @{ */ - boost::asio::io_service& get_io_service () - { - return m_ios; - } - - boost::asio::io_service const& get_io_service () const - { - return m_ios; - } - /** @} */ - - /** Cancel all pending i/o. - Any handlers which have already been queued will still be called. - */ - /** @{ */ - void cancel () - { - std::unique_lock lock (m_mutex); - cancel (lock, true); - } - - void cancel_async () - { - std::unique_lock lock (m_mutex); - cancel (lock, false); - } - /** @} */ - - /** Measure one sample of i/o latency. - Handler will be called with this signature: - void Handler (Duration d); - */ - template - void sample_one (Handler&& handler) - { - std::lock_guard lock (m_mutex); - if (m_cancel) - throw std::logic_error ("io_latency_probe is canceled"); - m_ios.post (sample_op ( - std::forward (handler), - Clock::now(), false, this)); - } - - /** Initiate continuous i/o latency sampling. - Handler will be called with this signature: - void Handler (std::chrono::milliseconds); - */ - template - void sample (Handler&& handler) - { - std::lock_guard lock (m_mutex); - if (m_cancel) - throw std::logic_error ("io_latency_probe is canceled"); - m_ios.post (sample_op ( - std::forward (handler), - Clock::now(), true, this)); - } - -private: - void cancel (std::unique_lock & lock, - bool wait) - { - if (! m_cancel) - { - --m_count; - m_cancel = true; - } - - if (wait) -#ifdef BOOST_NO_CXX11_LAMBDAS - while (m_count != 0) - m_cond.wait (lock); -#else - m_cond.wait (lock, [this] { - return this->m_count == 0; }); -#endif - } - - void addref () - { - std::lock_guard lock (m_mutex); - ++m_count; - } - - void release () - { - std::lock_guard lock (m_mutex); - if (--m_count == 0) - m_cond.notify_all (); - } - - template - struct sample_op - { - Handler m_handler; - time_point m_start; - bool m_repeat; - io_latency_probe* m_probe; - - sample_op (Handler const& handler, time_point const& start, - bool repeat, io_latency_probe* probe) - : m_handler (handler) - , m_start (start) - , m_repeat (repeat) - , m_probe (probe) - { - m_probe->addref(); - } - - sample_op (sample_op const& other) - : m_handler (other.m_handler) - , m_start (other.m_start) - , m_probe (other.m_probe) - { - m_probe->addref(); - } - - ~sample_op () - { - m_probe->release(); - } - - void operator() () const - { - typename Clock::time_point const now (Clock::now()); - typename Clock::duration const elapsed (now - m_start); - - m_handler (elapsed); - - { - std::lock_guard m_mutex) - > lock (m_probe->m_mutex); - if (m_probe->m_cancel) - return; - } - - if (m_repeat) - { - // Calculate when we want to sample again, and - // adjust for the expected latency. - // - typename Clock::time_point const when ( - now + m_probe->m_period - 2 * elapsed); - - if (when <= now) - { - // The latency is too high to maintain the desired - // period so don't bother with a timer. - // - m_probe->m_ios.post (sample_op ( - m_handler, now, m_repeat, m_probe)); - } - else - { - boost::posix_time::microseconds mms ( - std::chrono::duration_cast < - std::chrono::microseconds> ( - when - now).count ()); - m_probe->m_timer.expires_from_now (mms); - m_probe->m_timer.async_wait (sample_op ( - m_handler, now, m_repeat, m_probe)); - } - } - } - - void operator () (boost::system::error_code const& ec) - { - typename Clock::time_point const now (Clock::now()); - m_probe->m_ios.post (sample_op ( - m_handler, now, m_repeat, m_probe)); - } - }; -}; - -} - -#endif diff --git a/beast/asio/placeholders.h b/beast/asio/placeholders.h deleted file mode 100644 index 03633b9f34..0000000000 --- a/beast/asio/placeholders.h +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_PLACEHOLDERS_H_INCLUDED -#define BEAST_ASIO_PLACEHOLDERS_H_INCLUDED - -#include - -namespace beast { -namespace asio { - -namespace placeholders { -// asio placeholders that work with std::bind -namespace { -static auto const error (std::placeholders::_1); -static auto const bytes_transferred (std::placeholders::_2); -static auto const iterator (std::placeholders::_2); -static auto const signal_number (std::placeholders::_2); -} -} - -} -} - -#endif diff --git a/beast/asio/src/test/beast_asio_bind_handler_test.cpp b/beast/asio/src/test/beast_asio_bind_handler_test.cpp deleted file mode 100644 index 826de07ac0..0000000000 --- a/beast/asio/src/test/beast_asio_bind_handler_test.cpp +++ /dev/null @@ -1,48 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include - -namespace beast { -namespace test { - -class bind_handler_test : public unit_test::suite -{ -public: - static void foo (int) - { - } - - void run() - { - auto f (bind_handler ( - std::bind (&foo, std::placeholders::_1), - 42)); - f(); - pass(); - } -}; - -BEAST_DEFINE_TESTSUITE(bind_handler,asio,beast); - -} // test -} // beast - diff --git a/beast/asio/src/test/beast_asio_buffers_test.cpp b/beast/asio/src/test/beast_asio_buffers_test.cpp deleted file mode 100644 index c0686cec49..0000000000 --- a/beast/asio/src/test/beast_asio_buffers_test.cpp +++ /dev/null @@ -1,362 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace test { - -class buffers_test : public unit_test::suite -{ -public: - template - static - std::string - to_string(ConstBufferSequence const& bs) - { - using boost::asio::buffer_cast; - using boost::asio::buffer_size; - std::string s; - s.reserve(buffer_size(bs)); - for(auto const& b : bs) - s.append(buffer_cast(b), - buffer_size(b)); - return s; - } - - void testStreambuf() - { - using boost::asio::buffer; - using boost::asio::buffer_cast; - using boost::asio::buffer_size; - std::string const s = "Hello, world"; - expect(s.size() == 12); - for(std::size_t i = 1; i < 12; ++i) { - for(std::size_t x = 1; x < 4; ++x) { - for(std::size_t y = 1; y < 4; ++y) { - for(std::size_t t = 1; t < 4; ++ t) { - for(std::size_t u = 1; u < 4; ++ u) { - std::size_t z = s.size() - (x + y); - std::size_t v = s.size() - (t + u); - { - streambuf sb(i); - decltype(sb)::mutable_buffers_type d; - d = sb.prepare(z); expect(buffer_size(d) == z); - d = sb.prepare(0); expect(buffer_size(d) == 0); - d = sb.prepare(y); expect(buffer_size(d) == y); - d = sb.prepare(x); expect(buffer_size(d) == x); - sb.commit(buffer_copy(d, buffer(s.data(), x))); - expect(sb.size() == x); - expect(buffer_size(sb.data()) == sb.size()); - d = sb.prepare(x); expect(buffer_size(d) == x); - d = sb.prepare(0); expect(buffer_size(d) == 0); - d = sb.prepare(z); expect(buffer_size(d) == z); - d = sb.prepare(y); expect(buffer_size(d) == y); - sb.commit(buffer_copy(d, buffer(s.data()+x, y))); - sb.commit(1); - expect(sb.size() == x + y); - expect(buffer_size(sb.data()) == sb.size()); - d = sb.prepare(x); expect(buffer_size(d) == x); - d = sb.prepare(y); expect(buffer_size(d) == y); - d = sb.prepare(0); expect(buffer_size(d) == 0); - d = sb.prepare(z); expect(buffer_size(d) == z); - sb.commit(buffer_copy(d, buffer(s.data()+x+y, z))); - sb.commit(2); - expect(sb.size() == x + y + z); - expect(buffer_size(sb.data()) == sb.size()); - expect(to_string(sb.data()) == s); - sb.consume(t); - d = sb.prepare(0); expect(buffer_size(d) == 0); - expect(to_string(sb.data()) == s.substr(t, std::string::npos)); - sb.consume(u); - expect(to_string(sb.data()) == s.substr(t + u, std::string::npos)); - sb.consume(v); - expect(to_string(sb.data()) == ""); - sb.consume(1); - d = sb.prepare(0); expect(buffer_size(d) == 0); - } - }}}}} - } - - void testBuffersAdapter() - { - using boost::asio::buffer; - using boost::asio::buffer_cast; - using boost::asio::buffer_size; - using boost::asio::const_buffer; - using boost::asio::mutable_buffer; - char buf[12]; - std::string const s = "Hello, world"; - expect(s.size() == sizeof(buf)); - for(std::size_t i = 1; i < 4; ++i) { - for(std::size_t j = 1; j < 4; ++j) { - for(std::size_t x = 1; x < 4; ++x) { - for(std::size_t y = 1; y < 4; ++y) { - for(std::size_t t = 1; t < 4; ++ t) { - for(std::size_t u = 1; u < 4; ++ u) { - std::size_t k = sizeof(buf) - (i + j); - std::size_t z = sizeof(buf) - (x + y); - std::size_t v = sizeof(buf) - (t + u); - { - std::memset(buf, 0, sizeof(buf)); - std::array bs{{ - mutable_buffer{&buf[0], i}, - mutable_buffer{&buf[i], j}, - mutable_buffer{&buf[i+j], k}}}; - buffers_adapter ba(std::move(bs)); - expect(ba.max_size() == sizeof(buf)); - decltype(ba)::mutable_buffers_type d; - d = ba.prepare(z); expect(buffer_size(d) == z); - d = ba.prepare(0); expect(buffer_size(d) == 0); - d = ba.prepare(y); expect(buffer_size(d) == y); - d = ba.prepare(x); expect(buffer_size(d) == x); - ba.commit(buffer_copy(d, buffer(s.data(), x))); - expect(ba.size() == x); - expect(ba.max_size() == sizeof(buf) - x); - expect(buffer_size(ba.data()) == ba.size()); - d = ba.prepare(x); expect(buffer_size(d) == x); - d = ba.prepare(0); expect(buffer_size(d) == 0); - d = ba.prepare(z); expect(buffer_size(d) == z); - d = ba.prepare(y); expect(buffer_size(d) == y); - ba.commit(buffer_copy(d, buffer(s.data()+x, y))); - ba.commit(1); - expect(ba.size() == x + y); - expect(ba.max_size() == sizeof(buf) - (x + y)); - expect(buffer_size(ba.data()) == ba.size()); - d = ba.prepare(x); expect(buffer_size(d) == x); - d = ba.prepare(y); expect(buffer_size(d) == y); - d = ba.prepare(0); expect(buffer_size(d) == 0); - d = ba.prepare(z); expect(buffer_size(d) == z); - ba.commit(buffer_copy(d, buffer(s.data()+x+y, z))); - ba.commit(2); - expect(ba.size() == x + y + z); - expect(ba.max_size() == 0); - expect(buffer_size(ba.data()) == ba.size()); - expect(to_string(ba.data()) == s); - ba.consume(t); - d = ba.prepare(0); expect(buffer_size(d) == 0); - expect(to_string(ba.data()) == s.substr(t, std::string::npos)); - ba.consume(u); - expect(to_string(ba.data()) == s.substr(t + u, std::string::npos)); - ba.consume(v); - expect(to_string(ba.data()) == ""); - ba.consume(1); - d = ba.prepare(0); expect(buffer_size(d) == 0); - try - { - ba.prepare(1); - fail(); - } - catch(...) - { - pass(); - } - } - }}}}}} - } - - void testConsuming() - { - using boost::asio::buffer; - using boost::asio::const_buffer; - char buf[12]; - std::string const s = "Hello, world"; - expect(s.size() == sizeof(buf)); - buffer_copy(buffer(buf), buffer(s)); - expect(to_string(buffer(buf)) == s); - for(std::size_t i = 1; i < 4; ++i) { - for(std::size_t j = 1; j < 4; ++j) { - for(std::size_t x = 1; x < 4; ++x) { - for(std::size_t y = 1; y < 4; ++y) { - std::size_t k = sizeof(buf) - (i + j); - std::size_t z = sizeof(buf) - (x + y); - { - std::array bs{{ - const_buffer{&buf[0], i}, - const_buffer{&buf[i], j}, - const_buffer{&buf[i+j], k}}}; - consuming_buffers cb(bs); - expect(to_string(cb) == s); - cb.consume(0); - expect(to_string(cb) == s); - cb.consume(x); - expect(to_string(cb) == s.substr(x)); - cb.consume(y); - expect(to_string(cb) == s.substr(x+y)); - cb.consume(z); - expect(to_string(cb) == ""); - cb.consume(1); - expect(to_string(cb) == ""); - } - }}}} - } - - void testStaticBuffers() - { - using boost::asio::buffer; - using boost::asio::buffer_cast; - using boost::asio::buffer_size; - char buf[12]; - std::string const s = "Hello, world"; - expect(s.size() == sizeof(buf)); - for(std::size_t i = 1; i < 4; ++i) { - for(std::size_t j = 1; j < 4; ++j) { - for(std::size_t x = 1; x < 4; ++x) { - for(std::size_t y = 1; y < 4; ++y) { - for(std::size_t t = 1; t < 4; ++ t) { - for(std::size_t u = 1; u < 4; ++ u) { - std::size_t z = sizeof(buf) - (x + y); - std::size_t v = sizeof(buf) - (t + u); - { - std::memset(buf, 0, sizeof(buf)); - static_streambuf_n ba; - decltype(ba)::mutable_buffers_type d; - d = ba.prepare(z); expect(buffer_size(d) == z); - d = ba.prepare(0); expect(buffer_size(d) == 0); - d = ba.prepare(y); expect(buffer_size(d) == y); - d = ba.prepare(x); expect(buffer_size(d) == x); - ba.commit(buffer_copy(d, buffer(s.data(), x))); - expect(ba.size() == x); - expect(buffer_size(ba.data()) == ba.size()); - d = ba.prepare(x); expect(buffer_size(d) == x); - d = ba.prepare(0); expect(buffer_size(d) == 0); - d = ba.prepare(z); expect(buffer_size(d) == z); - d = ba.prepare(y); expect(buffer_size(d) == y); - ba.commit(buffer_copy(d, buffer(s.data()+x, y))); - ba.commit(1); - expect(ba.size() == x + y); - expect(buffer_size(ba.data()) == ba.size()); - d = ba.prepare(x); expect(buffer_size(d) == x); - d = ba.prepare(y); expect(buffer_size(d) == y); - d = ba.prepare(0); expect(buffer_size(d) == 0); - d = ba.prepare(z); expect(buffer_size(d) == z); - ba.commit(buffer_copy(d, buffer(s.data()+x+y, z))); - ba.commit(2); - expect(ba.size() == x + y + z); - expect(buffer_size(ba.data()) == ba.size()); - expect(to_string(ba.data()) == s); - ba.consume(t); - d = ba.prepare(0); expect(buffer_size(d) == 0); - expect(to_string(ba.data()) == s.substr(t, std::string::npos)); - ba.consume(u); - expect(to_string(ba.data()) == s.substr(t + u, std::string::npos)); - ba.consume(v); - expect(to_string(ba.data()) == ""); - ba.consume(1); - d = ba.prepare(0); expect(buffer_size(d) == 0); - try - { - ba.prepare(1); - fail(); - } - catch(...) - { - pass(); - } - } - }}}}}} - } - - void testAppendBuffers() - { - using boost::asio::buffer_size; - using boost::asio::const_buffer; - char buf[10]; - std::list b1; - std::vector b2{ - const_buffer{buf+0, 1}, - const_buffer{buf+1, 2}}; - std::list b3; - std::array b4{{ - const_buffer{buf+3, 1}, - const_buffer{buf+4, 2}, - const_buffer{buf+6, 3}}}; - std::list b5{ - const_buffer{buf+9, 1}}; - std::list b6; - auto bs = append_buffers( - b1, b2, b3, b4, b5, b6); - expect(buffer_size(bs) == 10); - std::vector v; - for(auto iter = std::make_reverse_iterator(bs.end()); - iter != std::make_reverse_iterator(bs.begin()); ++iter) - v.emplace_back(*iter); - expect(buffer_size(bs) == 10); - decltype(bs) bs2(bs); - auto bs3(std::move(bs)); - bs = bs2; - bs3 = std::move(bs2); - { - streambuf sb1, sb2; - expect(buffer_size(append_buffers( - sb1.prepare(5), sb2.prepare(7))) == 12); - sb1.commit(5); - sb2.commit(7); - expect(buffer_size(append_buffers( - sb1.data(), sb2.data())) == 12); - } - } - - void testClipBuffers() - { - using boost::asio::const_buffer; - std::string const s = "Hello, world"; - expect(s.size() == 12); - for(std::size_t x = 1; x < 4; ++x) { - for(std::size_t y = 1; y < 4; ++y) { - std::size_t z = s.size() - (x + y); - { - std::array bs{{ - const_buffer{&s[0], x}, - const_buffer{&s[x], y}, - const_buffer{&s[x+y], z}}}; - for(std::size_t i = 0; i <= s.size() + 1; ++i) - expect(to_string(prepare_buffers(i, bs)) == - s.substr(0, i)); - } - }} - } - - void run() override - { - testStreambuf(); - testBuffersAdapter(); - testConsuming(); - testStaticBuffers(); - - testAppendBuffers(); - testClipBuffers(); - } -}; - -BEAST_DEFINE_TESTSUITE(buffers,asio,beast); - -} // test -} // beast diff --git a/beast/asio/src/test/beast_asio_error_test.cpp b/beast/asio/src/test/beast_asio_error_test.cpp deleted file mode 100644 index 9026ea2bbb..0000000000 --- a/beast/asio/src/test/beast_asio_error_test.cpp +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include - -namespace beast { - -class error_test : public unit_test::suite -{ -public: - void run() - { - { - boost::system::error_code ec = - boost::system::error_code (335544539, - boost::asio::error::get_ssl_category ()); - std::string const s = beast::error_message_with_ssl(ec); - expect(s == " (20,0,219) error:140000DB:SSL routines:SSL routines:short read"); - } - } -}; - -BEAST_DEFINE_TESTSUITE(error,asio,beast); - -} // beast diff --git a/beast/asio/ssl_bundle.h b/beast/asio/ssl_bundle.h deleted file mode 100644 index 41a4f1e0a4..0000000000 --- a/beast/asio/ssl_bundle.h +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_SSL_BUNDLE_H_INCLUDED -#define BEAST_ASIO_SSL_BUNDLE_H_INCLUDED - -#include -#include -#include -#include -#include - -namespace beast { -namespace asio { - -/** Work-around for non-movable boost::ssl::stream. - This allows ssl::stream to be movable and allows the stream to - construct from an already-existing socket. -*/ -struct ssl_bundle -{ - using socket_type = boost::asio::ip::tcp::socket; - using stream_type = boost::asio::ssl::stream ; - using shared_context = std::shared_ptr; - - template - ssl_bundle (shared_context const& context_, Args&&... args); - - // DEPRECATED - template - ssl_bundle (boost::asio::ssl::context& context_, Args&&... args); - - shared_context context; - socket_type socket; - stream_type stream; -}; - -template -ssl_bundle::ssl_bundle (shared_context const& context_, Args&&... args) - : socket(std::forward(args)...) - , stream (socket, *context_) -{ -} - -template -ssl_bundle::ssl_bundle (boost::asio::ssl::context& context_, Args&&... args) - : socket(std::forward(args)...) - , stream (socket, context_) -{ -} - -} // asio -} // beast - -#endif diff --git a/beast/asio/ssl_error.h b/beast/asio/ssl_error.h deleted file mode 100644 index 65afc8ffcf..0000000000 --- a/beast/asio/ssl_error.h +++ /dev/null @@ -1,72 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_SSL_ERROR_H_INCLUDED -#define BEAST_ASIO_SSL_ERROR_H_INCLUDED - -#include -//#include // Causes error with WinSock.h -#include -#include - -namespace beast { - -/** Returns a human readable message if the error code is SSL related. */ -template -std::string -error_message_with_ssl(boost::system::error_code const& ec) -{ - std::string error; - - if (ec.category() == boost::asio::error::get_ssl_category()) - { - error = " (" - + boost::lexical_cast(ERR_GET_LIB (ec.value ())) - + "," - + boost::lexical_cast(ERR_GET_FUNC (ec.value ())) - + "," - + boost::lexical_cast(ERR_GET_REASON (ec.value ())) - + ") "; - - // This buffer must be at least 120 bytes, most examples use 256. - // https://www.openssl.org/docs/crypto/ERR_error_string.html - char buf[256]; - ::ERR_error_string_n(ec.value (), buf, sizeof(buf)); - error += buf; - } - else - { - error = ec.message(); - } - - return error; -} - -/** Returns `true` if the error code is a SSL "short read." */ -inline -bool -is_short_read(boost::system::error_code const& ec) -{ - return (ec.category() == boost::asio::error::get_ssl_category()) - && (ERR_GET_REASON(ec.value()) == SSL_R_SHORT_READ); -} - -} // beast - -#endif diff --git a/beast/asio/streambuf.h b/beast/asio/streambuf.h deleted file mode 100644 index 22031930cc..0000000000 --- a/beast/asio/streambuf.h +++ /dev/null @@ -1,31 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_STREAMBUF_H_INCLUDED -#define BEAST_ASIO_STREAMBUF_H_INCLUDED - -#include - -namespace beast { - -using streambuf = basic_streambuf>; - -} // beast - -#endif diff --git a/beast/asio/temp_buffer.h b/beast/asio/temp_buffer.h deleted file mode 100644 index a36b9fb621..0000000000 --- a/beast/asio/temp_buffer.h +++ /dev/null @@ -1,109 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_TEMP_BUFFER_H_INCLUDED -#define BEAST_ASIO_TEMP_BUFFER_H_INCLUDED - -#include -#include -#include -#include -#include - -namespace beast { - -template -class temp_buffer -{ - Handler& h_; - std::size_t n_ = 0; - std::uint8_t* p_ = nullptr; - -public: - explicit - temp_buffer(Handler& h) - : h_(h) - { - } - - ~temp_buffer() - { - if(p_) - dealloc(); - } - - operator - boost::asio::const_buffer() const - { - return boost::asio::const_buffer{p_, n_}; - } - - operator - boost::asio::mutable_buffer() const - { - return boost::asio::mutable_buffer{p_, n_}; - } - - std::uint8_t* - data() const - { - return p_; - } - - std::size_t - size() - { - return n_; - } - - boost::asio::mutable_buffers_1 - buffers() const - { - return boost::asio::mutable_buffers_1{ - p_, n_}; - } - - void - alloc(std::size_t size) - { - if(n_ != size) - { - if(p_) - dealloc(); - n_ = size; - if(n_ > 0) - p_ = reinterpret_cast( - boost_asio_handler_alloc_helpers:: - allocate(n_, h_)); - } - } - - void - dealloc() - { - boost_asio_handler_alloc_helpers:: - deallocate(p_, n_, h_); - p_ = nullptr; - n_ = 0; - } -}; - -} // beast - -#endif diff --git a/beast/clock/abstract_clock.h b/beast/clock/abstract_clock.h deleted file mode 100644 index 352f389a18..0000000000 --- a/beast/clock/abstract_clock.h +++ /dev/null @@ -1,111 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CHRONO_ABSTRACT_CLOCK_H_INCLUDED -#define BEAST_CHRONO_ABSTRACT_CLOCK_H_INCLUDED - -#include -#include - -namespace beast { - -/** Abstract interface to a clock. - - This makes now() a member function instead of a static member, so - an instance of the class can be dependency injected, facilitating - unit tests where time may be controlled. - - An abstract_clock inherits all the nested types of the Clock - template parameter. - - Example: - - @code - - struct Implementation - { - using clock_type = abstract_clock ; - clock_type& clock_; - explicit Implementation (clock_type& clock) - : clock_(clock) - { - } - }; - - @endcode - - @tparam Clock A type meeting these requirements: - http://en.cppreference.com/w/cpp/concept/Clock -*/ -template -class abstract_clock -{ -public: - using rep = typename Clock::rep; - using period = typename Clock::period; - using duration = typename Clock::duration; - using time_point = typename Clock::time_point; - using clock_type = Clock; - - static bool const is_steady = Clock::is_steady; - - virtual ~abstract_clock() = default; - - /** Returns the current time. */ - virtual time_point now() const = 0; -}; - -//------------------------------------------------------------------------------ - -namespace detail { - -template -struct abstract_clock_wrapper - : public abstract_clock -{ - using typename abstract_clock::duration; - using typename abstract_clock::time_point; - - time_point - now() const override - { - return Clock::now(); - } -}; - -} - -//------------------------------------------------------------------------------ - -/** Returns a global instance of an abstract clock. - @tparam Facade A type meeting these requirements: - http://en.cppreference.com/w/cpp/concept/Clock - @tparam Clock The actual concrete clock to use. -*/ -template -abstract_clock& -get_abstract_clock() -{ - static detail::abstract_clock_wrapper clock; - return clock; -} - -} - -#endif diff --git a/beast/clock/basic_seconds_clock.h b/beast/clock/basic_seconds_clock.h deleted file mode 100644 index d2ce40db56..0000000000 --- a/beast/clock/basic_seconds_clock.h +++ /dev/null @@ -1,217 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED -#define BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED - -#include - -#include -#include -#include -#include -#include -#include - -namespace beast { - -namespace detail { - -class seconds_clock_worker -{ -public: - virtual void sample () = 0; -}; - -//------------------------------------------------------------------------------ - -// Updates the clocks -class seconds_clock_thread -{ -public: - using mutex = std::mutex; - using cond_var = std::condition_variable; - using lock_guard = std::lock_guard ; - using unique_lock = std::unique_lock ; - using clock_type = std::chrono::steady_clock; - using seconds = std::chrono::seconds; - using thread = std::thread; - using workers = std::vector ; - - bool stop_; - mutex mutex_; - cond_var cond_; - workers workers_; - thread thread_; - - seconds_clock_thread () - : stop_ (false) - { - thread_ = thread (std::bind( - &seconds_clock_thread::run, this)); - } - - ~seconds_clock_thread () - { - stop(); - } - - void add (seconds_clock_worker& w) - { - lock_guard lock (mutex_); - workers_.push_back (&w); - } - - void remove (seconds_clock_worker& w) - { - lock_guard lock (mutex_); - workers_.erase (std::find ( - workers_.begin (), workers_.end(), &w)); - } - - void stop() - { - if (thread_.joinable()) - { - { - lock_guard lock (mutex_); - stop_ = true; - } - cond_.notify_all(); - thread_.join(); - } - } - - void run() - { - unique_lock lock (mutex_);; - - for (;;) - { - for (auto iter : workers_) - iter->sample(); - - using namespace std::chrono; - clock_type::time_point const when ( - floor ( - clock_type::now().time_since_epoch()) + - seconds (1)); - - if (cond_.wait_until (lock, when, [this]{ return stop_; })) - return; - } - } - - static seconds_clock_thread& instance () - { - static seconds_clock_thread singleton; - return singleton; - } -}; - -} - -//------------------------------------------------------------------------------ - -/** Called before main exits to terminate the utility thread. - This is a workaround for Visual Studio 2013: - http://connect.microsoft.com/VisualStudio/feedback/details/786016/creating-a-global-c-object-that-used-thread-join-in-its-destructor-causes-a-lockup - http://stackoverflow.com/questions/10915233/stdthreadjoin-hangs-if-called-after-main-exits-when-using-vs2012-rc -*/ -inline -void -basic_seconds_clock_main_hook() -{ -#ifdef _MSC_VER - detail::seconds_clock_thread::instance().stop(); -#endif -} - -/** A clock whose minimum resolution is one second. - - The purpose of this class is to optimize the performance of the now() - member function call. It uses a dedicated thread that wakes up at least - once per second to sample the requested trivial clock. - - @tparam Clock A type meeting these requirements: - http://en.cppreference.com/w/cpp/concept/Clock -*/ -template -class basic_seconds_clock -{ -public: - using rep = typename Clock::rep; - using period = typename Clock::period; - using duration = typename Clock::duration; - using time_point = typename Clock::time_point; - - static bool const is_steady = Clock::is_steady; - - static time_point now() - { - // Make sure the thread is constructed before the - // worker otherwise we will crash during destruction - // of objects with static storage duration. - struct initializer - { - initializer () - { - detail::seconds_clock_thread::instance(); - } - }; - static initializer init; - - struct worker : detail::seconds_clock_worker - { - time_point m_now; - std::mutex mutex_; - - worker() - : m_now(Clock::now()) - { - detail::seconds_clock_thread::instance().add(*this); - } - - ~worker() - { - detail::seconds_clock_thread::instance().remove(*this); - } - - time_point now() - { - std::lock_guard lock (mutex_); - return m_now; - } - - void sample() - { - std::lock_guard lock (mutex_); - m_now = Clock::now(); - } - }; - - static worker w; - - return w.now(); - } -}; - -} - -#endif diff --git a/beast/clock/chrono_util.h b/beast/clock/chrono_util.h deleted file mode 100644 index 1adc676a4c..0000000000 --- a/beast/clock/chrono_util.h +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CHRONO_CHRONO_UTIL_H_INCLUDED -#define BEAST_CHRONO_CHRONO_UTIL_H_INCLUDED - -// From Howard Hinnant -// http://home.roadrunner.com/~hinnant/duration_io/chrono_util.html - -#if !defined(_MSC_FULL_VER) || (_MSC_FULL_VER <= 190023506) -// round down -template -To floor(std::chrono::duration const& d) -{ - To t = std::chrono::duration_cast(d); - if (t > d) - --t; - return t; -} - -// round to nearest, to even on tie -template -To round (std::chrono::duration const& d) -{ - To t0 = std::chrono::duration_cast(d); - To t1 = t0; - ++t1; - auto diff0 = d - t0; - auto diff1 = t1 - d; - if (diff0 == diff1) - { - if (t0.count() & 1) - return t1; - return t0; - } - else if (diff0 < diff1) - return t0; - return t1; -} - -// round up -template -To ceil (std::chrono::duration const& d) -{ - To t = std::chrono::duration_cast(d); - if (t < d) - ++t; - return t; -} -#endif - -#endif diff --git a/beast/clock/manual_clock.h b/beast/clock/manual_clock.h deleted file mode 100644 index 23b5165cd7..0000000000 --- a/beast/clock/manual_clock.h +++ /dev/null @@ -1,100 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CHRONO_MANUAL_CLOCK_H_INCLUDED -#define BEAST_CHRONO_MANUAL_CLOCK_H_INCLUDED - -#include -#include - -namespace beast { - -/** Manual clock implementation. - - This concrete class implements the @ref abstract_clock interface and - allows the time to be advanced manually, mainly for the purpose of - providing a clock in unit tests. - - @tparam Clock A type meeting these requirements: - http://en.cppreference.com/w/cpp/concept/Clock -*/ -template -class manual_clock - : public abstract_clock -{ -public: - using typename abstract_clock::rep; - using typename abstract_clock::duration; - using typename abstract_clock::time_point; - -private: - time_point now_; - -public: - explicit - manual_clock (time_point const& now = time_point(duration(0))) - : now_(now) - { - } - - time_point - now() const override - { - return now_; - } - - /** Set the current time of the manual clock. */ - void - set (time_point const& when) - { - assert(! Clock::is_steady || when >= now_); - now_ = when; - } - - /** Convenience for setting the time in seconds from epoch. */ - template - void - set(Integer seconds_from_epoch) - { - set(time_point(duration( - std::chrono::seconds(seconds_from_epoch)))); - } - - /** Advance the clock by a duration. */ - template - void - advance(std::chrono::duration const& elapsed) - { - assert(! Clock::is_steady || - (now_ + elapsed) >= now_); - now_ += elapsed; - } - - /** Convenience for advancing the clock by one second. */ - manual_clock& - operator++ () - { - advance(std::chrono::seconds(1)); - return *this; - } -}; - -} - -#endif diff --git a/beast/clock/tests/beast_abstract_clock_test.cpp b/beast/clock/tests/beast_abstract_clock_test.cpp deleted file mode 100644 index 1487f8aa11..0000000000 --- a/beast/clock/tests/beast_abstract_clock_test.cpp +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -// MODULES: ../impl/chrono_io.cpp - -#include -#include -#include -#include -#include -#include - -namespace beast { - -class abstract_clock_test : public unit_test::suite -{ -public: - template - void test (abstract_clock& c) - { - { - auto const t1 (c.now ()); - std::this_thread::sleep_for ( - std::chrono::milliseconds (1500)); - auto const t2 (c.now ()); - - std::stringstream ss; - ss << - "t1= " << t1.time_since_epoch().count() << - ", t2= " << t2.time_since_epoch().count() << - ", elapsed= " << (t2 - t1).count(); - log << ss.str(); - } - } - - void test_manual () - { - using clock_type = manual_clock; - clock_type c; - - std::stringstream ss; - - ss << "now() = " << c.now().time_since_epoch().count() << std::endl; - - c.set (clock_type::time_point (std::chrono::seconds(1))); - ss << "now() = " << c.now().time_since_epoch().count() << std::endl; - - c.set (clock_type::time_point (std::chrono::seconds(2))); - ss << "now() = " << c.now().time_since_epoch().count() << std::endl; - - log << ss.str(); - } - - void run () - { - log << "steady_clock"; - test (get_abstract_clock< - std::chrono::steady_clock>()); - - log << "system_clock"; - test (get_abstract_clock< - std::chrono::system_clock>()); - - log << "high_resolution_clock"; - test (get_abstract_clock< - std::chrono::high_resolution_clock>()); - - log << "manual_clock"; - test_manual (); - - pass (); - } -}; - -BEAST_DEFINE_TESTSUITE_MANUAL(abstract_clock,chrono,beast); - -} diff --git a/beast/clock/tests/beast_basic_seconds_clock_test.cpp b/beast/clock/tests/beast_basic_seconds_clock_test.cpp deleted file mode 100644 index 227aba5466..0000000000 --- a/beast/clock/tests/beast_basic_seconds_clock_test.cpp +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include - -#include - -namespace beast { - -class basic_seconds_clock_test : public unit_test::suite -{ -public: - void - run() - { - basic_seconds_clock < - std::chrono::steady_clock>::now (); - pass (); - } -}; - -BEAST_DEFINE_TESTSUITE(basic_seconds_clock,chrono,beast); - -} diff --git a/beast/crypto/detail/mac_facade.h b/beast/crypto/detail/mac_facade.h deleted file mode 100644 index 8fb80506ae..0000000000 --- a/beast/crypto/detail/mac_facade.h +++ /dev/null @@ -1,92 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_MAC_FACADE_H_INCLUDED -#define BEAST_CRYPTO_MAC_FACADE_H_INCLUDED - -#include -#include -#include -#include - -namespace beast { -namespace detail { - -// Message Authentication Code (MAC) facade -template -class mac_facade -{ -private: - Context ctx_; - -public: - static beast::endian const endian = - beast::endian::native; - - static std::size_t const digest_size = - Context::digest_size; - - using result_type = - std::array; - - mac_facade() noexcept - { - init(ctx_); - } - - ~mac_facade() - { - erase(std::integral_constant< - bool, Secure>{}); - } - - void - operator()(void const* data, - std::size_t size) noexcept - { - update(ctx_, data, size); - } - - explicit - operator result_type() noexcept - { - result_type digest; - finish(ctx_, &digest[0]); - return digest; - } - -private: - inline - void - erase (std::false_type) noexcept - { - } - - inline - void - erase (std::true_type) noexcept - { - secure_erase(&ctx_, sizeof(ctx_)); - } -}; - -} // detail -} // beast - -#endif diff --git a/beast/crypto/detail/ripemd_context.h b/beast/crypto/detail/ripemd_context.h deleted file mode 100644 index 0b89921bbd..0000000000 --- a/beast/crypto/detail/ripemd_context.h +++ /dev/null @@ -1,429 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_RIPEMD_CONTEXT_H_INCLUDED -#define BEAST_CRYPTO_RIPEMD_CONTEXT_H_INCLUDED - -#include -#include -#include - -namespace beast { -namespace detail { - -// Based on -// https://code.google.com/p/blockchain/source/browse/trunk/RIPEMD160.cpp -/* - Copyright (c) Katholieke Universiteit Leuven - 1996 All Rights Reserved - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ -// This implementation has been modified from the -// original. It has been updated for C++11. - -struct ripemd160_context -{ - static unsigned int const block_size = 64; - static unsigned int const digest_size = 20; - - unsigned int tot_len; - unsigned int len; - unsigned char block[256]; - std::uint32_t h[5]; -}; - -// ROL(x, n) cyclically rotates x over n bits to the left -// x must be of an unsigned 32 bits type and 0 <= n < 32. -#define BEAST_RIPEMD_ROL(x, n) (((x) << (n)) | ((x) >> (32-(n)))) - -// the five basic functions F(), G() and H() -#define BEAST_RIPEMD_F(x, y, z) ((x) ^ (y) ^ (z)) -#define BEAST_RIPEMD_G(x, y, z) (((x) & (y)) | (~(x) & (z))) -#define BEAST_RIPEMD_H(x, y, z) (((x) | ~(y)) ^ (z)) -#define BEAST_RIPEMD_I(x, y, z) (((x) & (z)) | ((y) & ~(z))) -#define BEAST_RIPEMD_J(x, y, z) ((x) ^ ((y) | ~(z))) - -// the ten basic operations FF() through III() -#define BEAST_RIPEMD_FF(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_F((b), (c), (d)) + (x); \ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_GG(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_G((b), (c), (d)) + (x) + 0x5a827999UL; \ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_HH(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_II(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_JJ(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_J((b), (c), (d)) + (x) + 0xa953fd4eUL;\ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_FFF(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_F((b), (c), (d)) + (x); \ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_GGG(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_HHH(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_H((b), (c), (d)) + (x) + 0x6d703ef3UL;\ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_III(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_I((b), (c), (d)) + (x) + 0x5c4dd124UL;\ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } -#define BEAST_RIPEMD_JJJ(a, b, c, d, e, x, s) { \ - (a) += BEAST_RIPEMD_J((b), (c), (d)) + (x) + 0x50a28be6UL;\ - (a) = BEAST_RIPEMD_ROL((a), (s)) + (e); \ - (c) = BEAST_RIPEMD_ROL((c), 10); } - -template -void ripemd_load (std::array& X, - unsigned char const* p) -{ - for(int i = 0; i < 16; ++i) - { - X[i] = - ((std::uint32_t) *((p)+3) << 24) | - ((std::uint32_t) *((p)+2) << 16) | - ((std::uint32_t) *((p)+1) << 8) | - ((std::uint32_t) * (p)); - p += 4; - } -} - -template -void ripemd_compress (ripemd160_context& ctx, - std::array& X) noexcept -{ - std::uint32_t aa = ctx.h[0]; - std::uint32_t bb = ctx.h[1]; - std::uint32_t cc = ctx.h[2]; - std::uint32_t dd = ctx.h[3]; - std::uint32_t ee = ctx.h[4]; - std::uint32_t aaa = ctx.h[0]; - std::uint32_t bbb = ctx.h[1]; - std::uint32_t ccc = ctx.h[2]; - std::uint32_t ddd = ctx.h[3]; - std::uint32_t eee = ctx.h[4]; - - // round 1 - BEAST_RIPEMD_FF(aa, bb, cc, dd, ee, X[ 0], 11); - BEAST_RIPEMD_FF(ee, aa, bb, cc, dd, X[ 1], 14); - BEAST_RIPEMD_FF(dd, ee, aa, bb, cc, X[ 2], 15); - BEAST_RIPEMD_FF(cc, dd, ee, aa, bb, X[ 3], 12); - BEAST_RIPEMD_FF(bb, cc, dd, ee, aa, X[ 4], 5); - BEAST_RIPEMD_FF(aa, bb, cc, dd, ee, X[ 5], 8); - BEAST_RIPEMD_FF(ee, aa, bb, cc, dd, X[ 6], 7); - BEAST_RIPEMD_FF(dd, ee, aa, bb, cc, X[ 7], 9); - BEAST_RIPEMD_FF(cc, dd, ee, aa, bb, X[ 8], 11); - BEAST_RIPEMD_FF(bb, cc, dd, ee, aa, X[ 9], 13); - BEAST_RIPEMD_FF(aa, bb, cc, dd, ee, X[10], 14); - BEAST_RIPEMD_FF(ee, aa, bb, cc, dd, X[11], 15); - BEAST_RIPEMD_FF(dd, ee, aa, bb, cc, X[12], 6); - BEAST_RIPEMD_FF(cc, dd, ee, aa, bb, X[13], 7); - BEAST_RIPEMD_FF(bb, cc, dd, ee, aa, X[14], 9); - BEAST_RIPEMD_FF(aa, bb, cc, dd, ee, X[15], 8); - - // round 2 - BEAST_RIPEMD_GG(ee, aa, bb, cc, dd, X[ 7], 7); - BEAST_RIPEMD_GG(dd, ee, aa, bb, cc, X[ 4], 6); - BEAST_RIPEMD_GG(cc, dd, ee, aa, bb, X[13], 8); - BEAST_RIPEMD_GG(bb, cc, dd, ee, aa, X[ 1], 13); - BEAST_RIPEMD_GG(aa, bb, cc, dd, ee, X[10], 11); - BEAST_RIPEMD_GG(ee, aa, bb, cc, dd, X[ 6], 9); - BEAST_RIPEMD_GG(dd, ee, aa, bb, cc, X[15], 7); - BEAST_RIPEMD_GG(cc, dd, ee, aa, bb, X[ 3], 15); - BEAST_RIPEMD_GG(bb, cc, dd, ee, aa, X[12], 7); - BEAST_RIPEMD_GG(aa, bb, cc, dd, ee, X[ 0], 12); - BEAST_RIPEMD_GG(ee, aa, bb, cc, dd, X[ 9], 15); - BEAST_RIPEMD_GG(dd, ee, aa, bb, cc, X[ 5], 9); - BEAST_RIPEMD_GG(cc, dd, ee, aa, bb, X[ 2], 11); - BEAST_RIPEMD_GG(bb, cc, dd, ee, aa, X[14], 7); - BEAST_RIPEMD_GG(aa, bb, cc, dd, ee, X[11], 13); - BEAST_RIPEMD_GG(ee, aa, bb, cc, dd, X[ 8], 12); - - // round 3 - BEAST_RIPEMD_HH(dd, ee, aa, bb, cc, X[ 3], 11); - BEAST_RIPEMD_HH(cc, dd, ee, aa, bb, X[10], 13); - BEAST_RIPEMD_HH(bb, cc, dd, ee, aa, X[14], 6); - BEAST_RIPEMD_HH(aa, bb, cc, dd, ee, X[ 4], 7); - BEAST_RIPEMD_HH(ee, aa, bb, cc, dd, X[ 9], 14); - BEAST_RIPEMD_HH(dd, ee, aa, bb, cc, X[15], 9); - BEAST_RIPEMD_HH(cc, dd, ee, aa, bb, X[ 8], 13); - BEAST_RIPEMD_HH(bb, cc, dd, ee, aa, X[ 1], 15); - BEAST_RIPEMD_HH(aa, bb, cc, dd, ee, X[ 2], 14); - BEAST_RIPEMD_HH(ee, aa, bb, cc, dd, X[ 7], 8); - BEAST_RIPEMD_HH(dd, ee, aa, bb, cc, X[ 0], 13); - BEAST_RIPEMD_HH(cc, dd, ee, aa, bb, X[ 6], 6); - BEAST_RIPEMD_HH(bb, cc, dd, ee, aa, X[13], 5); - BEAST_RIPEMD_HH(aa, bb, cc, dd, ee, X[11], 12); - BEAST_RIPEMD_HH(ee, aa, bb, cc, dd, X[ 5], 7); - BEAST_RIPEMD_HH(dd, ee, aa, bb, cc, X[12], 5); - - // round 4 - BEAST_RIPEMD_II(cc, dd, ee, aa, bb, X[ 1], 11); - BEAST_RIPEMD_II(bb, cc, dd, ee, aa, X[ 9], 12); - BEAST_RIPEMD_II(aa, bb, cc, dd, ee, X[11], 14); - BEAST_RIPEMD_II(ee, aa, bb, cc, dd, X[10], 15); - BEAST_RIPEMD_II(dd, ee, aa, bb, cc, X[ 0], 14); - BEAST_RIPEMD_II(cc, dd, ee, aa, bb, X[ 8], 15); - BEAST_RIPEMD_II(bb, cc, dd, ee, aa, X[12], 9); - BEAST_RIPEMD_II(aa, bb, cc, dd, ee, X[ 4], 8); - BEAST_RIPEMD_II(ee, aa, bb, cc, dd, X[13], 9); - BEAST_RIPEMD_II(dd, ee, aa, bb, cc, X[ 3], 14); - BEAST_RIPEMD_II(cc, dd, ee, aa, bb, X[ 7], 5); - BEAST_RIPEMD_II(bb, cc, dd, ee, aa, X[15], 6); - BEAST_RIPEMD_II(aa, bb, cc, dd, ee, X[14], 8); - BEAST_RIPEMD_II(ee, aa, bb, cc, dd, X[ 5], 6); - BEAST_RIPEMD_II(dd, ee, aa, bb, cc, X[ 6], 5); - BEAST_RIPEMD_II(cc, dd, ee, aa, bb, X[ 2], 12); - - // round 5 - BEAST_RIPEMD_JJ(bb, cc, dd, ee, aa, X[ 4], 9); - BEAST_RIPEMD_JJ(aa, bb, cc, dd, ee, X[ 0], 15); - BEAST_RIPEMD_JJ(ee, aa, bb, cc, dd, X[ 5], 5); - BEAST_RIPEMD_JJ(dd, ee, aa, bb, cc, X[ 9], 11); - BEAST_RIPEMD_JJ(cc, dd, ee, aa, bb, X[ 7], 6); - BEAST_RIPEMD_JJ(bb, cc, dd, ee, aa, X[12], 8); - BEAST_RIPEMD_JJ(aa, bb, cc, dd, ee, X[ 2], 13); - BEAST_RIPEMD_JJ(ee, aa, bb, cc, dd, X[10], 12); - BEAST_RIPEMD_JJ(dd, ee, aa, bb, cc, X[14], 5); - BEAST_RIPEMD_JJ(cc, dd, ee, aa, bb, X[ 1], 12); - BEAST_RIPEMD_JJ(bb, cc, dd, ee, aa, X[ 3], 13); - BEAST_RIPEMD_JJ(aa, bb, cc, dd, ee, X[ 8], 14); - BEAST_RIPEMD_JJ(ee, aa, bb, cc, dd, X[11], 11); - BEAST_RIPEMD_JJ(dd, ee, aa, bb, cc, X[ 6], 8); - BEAST_RIPEMD_JJ(cc, dd, ee, aa, bb, X[15], 5); - BEAST_RIPEMD_JJ(bb, cc, dd, ee, aa, X[13], 6); - - // parallel round 1 - BEAST_RIPEMD_JJJ(aaa, bbb, ccc, ddd, eee, X[ 5], 8); - BEAST_RIPEMD_JJJ(eee, aaa, bbb, ccc, ddd, X[14], 9); - BEAST_RIPEMD_JJJ(ddd, eee, aaa, bbb, ccc, X[ 7], 9); - BEAST_RIPEMD_JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11); - BEAST_RIPEMD_JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13); - BEAST_RIPEMD_JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15); - BEAST_RIPEMD_JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15); - BEAST_RIPEMD_JJJ(ddd, eee, aaa, bbb, ccc, X[ 4], 5); - BEAST_RIPEMD_JJJ(ccc, ddd, eee, aaa, bbb, X[13], 7); - BEAST_RIPEMD_JJJ(bbb, ccc, ddd, eee, aaa, X[ 6], 7); - BEAST_RIPEMD_JJJ(aaa, bbb, ccc, ddd, eee, X[15], 8); - BEAST_RIPEMD_JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11); - BEAST_RIPEMD_JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14); - BEAST_RIPEMD_JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14); - BEAST_RIPEMD_JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12); - BEAST_RIPEMD_JJJ(aaa, bbb, ccc, ddd, eee, X[12], 6); - - // parallel round 2 - BEAST_RIPEMD_III(eee, aaa, bbb, ccc, ddd, X[ 6], 9); - BEAST_RIPEMD_III(ddd, eee, aaa, bbb, ccc, X[11], 13); - BEAST_RIPEMD_III(ccc, ddd, eee, aaa, bbb, X[ 3], 15); - BEAST_RIPEMD_III(bbb, ccc, ddd, eee, aaa, X[ 7], 7); - BEAST_RIPEMD_III(aaa, bbb, ccc, ddd, eee, X[ 0], 12); - BEAST_RIPEMD_III(eee, aaa, bbb, ccc, ddd, X[13], 8); - BEAST_RIPEMD_III(ddd, eee, aaa, bbb, ccc, X[ 5], 9); - BEAST_RIPEMD_III(ccc, ddd, eee, aaa, bbb, X[10], 11); - BEAST_RIPEMD_III(bbb, ccc, ddd, eee, aaa, X[14], 7); - BEAST_RIPEMD_III(aaa, bbb, ccc, ddd, eee, X[15], 7); - BEAST_RIPEMD_III(eee, aaa, bbb, ccc, ddd, X[ 8], 12); - BEAST_RIPEMD_III(ddd, eee, aaa, bbb, ccc, X[12], 7); - BEAST_RIPEMD_III(ccc, ddd, eee, aaa, bbb, X[ 4], 6); - BEAST_RIPEMD_III(bbb, ccc, ddd, eee, aaa, X[ 9], 15); - BEAST_RIPEMD_III(aaa, bbb, ccc, ddd, eee, X[ 1], 13); - BEAST_RIPEMD_III(eee, aaa, bbb, ccc, ddd, X[ 2], 11); - - // parallel round 3 - BEAST_RIPEMD_HHH(ddd, eee, aaa, bbb, ccc, X[15], 9); - BEAST_RIPEMD_HHH(ccc, ddd, eee, aaa, bbb, X[ 5], 7); - BEAST_RIPEMD_HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15); - BEAST_RIPEMD_HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11); - BEAST_RIPEMD_HHH(eee, aaa, bbb, ccc, ddd, X[ 7], 8); - BEAST_RIPEMD_HHH(ddd, eee, aaa, bbb, ccc, X[14], 6); - BEAST_RIPEMD_HHH(ccc, ddd, eee, aaa, bbb, X[ 6], 6); - BEAST_RIPEMD_HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14); - BEAST_RIPEMD_HHH(aaa, bbb, ccc, ddd, eee, X[11], 12); - BEAST_RIPEMD_HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13); - BEAST_RIPEMD_HHH(ddd, eee, aaa, bbb, ccc, X[12], 5); - BEAST_RIPEMD_HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14); - BEAST_RIPEMD_HHH(bbb, ccc, ddd, eee, aaa, X[10], 13); - BEAST_RIPEMD_HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13); - BEAST_RIPEMD_HHH(eee, aaa, bbb, ccc, ddd, X[ 4], 7); - BEAST_RIPEMD_HHH(ddd, eee, aaa, bbb, ccc, X[13], 5); - - // parallel round 4 - BEAST_RIPEMD_GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15); - BEAST_RIPEMD_GGG(bbb, ccc, ddd, eee, aaa, X[ 6], 5); - BEAST_RIPEMD_GGG(aaa, bbb, ccc, ddd, eee, X[ 4], 8); - BEAST_RIPEMD_GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11); - BEAST_RIPEMD_GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14); - BEAST_RIPEMD_GGG(ccc, ddd, eee, aaa, bbb, X[11], 14); - BEAST_RIPEMD_GGG(bbb, ccc, ddd, eee, aaa, X[15], 6); - BEAST_RIPEMD_GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14); - BEAST_RIPEMD_GGG(eee, aaa, bbb, ccc, ddd, X[ 5], 6); - BEAST_RIPEMD_GGG(ddd, eee, aaa, bbb, ccc, X[12], 9); - BEAST_RIPEMD_GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12); - BEAST_RIPEMD_GGG(bbb, ccc, ddd, eee, aaa, X[13], 9); - BEAST_RIPEMD_GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12); - BEAST_RIPEMD_GGG(eee, aaa, bbb, ccc, ddd, X[ 7], 5); - BEAST_RIPEMD_GGG(ddd, eee, aaa, bbb, ccc, X[10], 15); - BEAST_RIPEMD_GGG(ccc, ddd, eee, aaa, bbb, X[14], 8); - - // parallel round 5 - BEAST_RIPEMD_FFF(bbb, ccc, ddd, eee, aaa, X[12] , 8); - BEAST_RIPEMD_FFF(aaa, bbb, ccc, ddd, eee, X[15] , 5); - BEAST_RIPEMD_FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12); - BEAST_RIPEMD_FFF(ddd, eee, aaa, bbb, ccc, X[ 4] , 9); - BEAST_RIPEMD_FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12); - BEAST_RIPEMD_FFF(bbb, ccc, ddd, eee, aaa, X[ 5] , 5); - BEAST_RIPEMD_FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14); - BEAST_RIPEMD_FFF(eee, aaa, bbb, ccc, ddd, X[ 7] , 6); - BEAST_RIPEMD_FFF(ddd, eee, aaa, bbb, ccc, X[ 6] , 8); - BEAST_RIPEMD_FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13); - BEAST_RIPEMD_FFF(bbb, ccc, ddd, eee, aaa, X[13] , 6); - BEAST_RIPEMD_FFF(aaa, bbb, ccc, ddd, eee, X[14] , 5); - BEAST_RIPEMD_FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15); - BEAST_RIPEMD_FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13); - BEAST_RIPEMD_FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11); - BEAST_RIPEMD_FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11); - - // combine results - ddd += cc + ctx.h[1]; // final result for h[0] - ctx.h[1] = ctx.h[2] + dd + eee; - ctx.h[2] = ctx.h[3] + ee + aaa; - ctx.h[3] = ctx.h[4] + aa + bbb; - ctx.h[4] = ctx.h[0] + bb + ccc; - ctx.h[0] = ddd; -} - -template -void init (ripemd160_context& ctx) noexcept -{ - ctx.len = 0; - ctx.tot_len = 0; - ctx.h[0] = 0x67452301UL; - ctx.h[1] = 0xefcdab89UL; - ctx.h[2] = 0x98badcfeUL; - ctx.h[3] = 0x10325476UL; - ctx.h[4] = 0xc3d2e1f0UL; -} - -template -void update (ripemd160_context& ctx, - void const* message, std::size_t size) noexcept -{ - auto const pm = reinterpret_cast< - unsigned char const*>(message); - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char *shifted_message; - tmp_len = ripemd160_context::block_size - ctx.len; - rem_len = size < tmp_len ? size : tmp_len; - std::memcpy(&ctx.block[ctx.len], pm, rem_len); - if (ctx.len + size < ripemd160_context::block_size) { - ctx.len += size; - return; - } - new_len = size - rem_len; - block_nb = new_len / ripemd160_context::block_size; - shifted_message = pm + rem_len; - std::array X; - ripemd_load(X, ctx.block); - ripemd_compress(ctx, X); - for (int i = 0; i < block_nb; ++i) - { - ripemd_load(X, shifted_message + - i * ripemd160_context::block_size); - ripemd_compress(ctx, X); - } - rem_len = new_len % ripemd160_context::block_size; - std::memcpy(ctx.block, &shifted_message[ - block_nb * ripemd160_context::block_size], - rem_len); - ctx.len = rem_len; - ctx.tot_len += (block_nb + 1) * - ripemd160_context::block_size; -} - -template -void finish (ripemd160_context& ctx, - void* digest) noexcept -{ - std::array X; - X.fill(0); - // put leftovers into X - auto p = &ctx.block[0]; - // uint8_t i goes into word X[i div 4] at pos. 8*(i mod 4) - for (int i = 0; i < ctx.len; ++i) - X[i >> 2] ^= (std::uint32_t) *p++ << (8 * (i & 3)); - ctx.tot_len += ctx.len; - // append the bit m_n == 1 - X[(ctx.tot_len>>2)&15] ^= - (uint32_t)1 << (8*(ctx.tot_len&3) + 7); - // length goes to next block? - if ((ctx.tot_len & 63) > 55) - { - ripemd_compress(ctx, X); - X.fill(0); - } - // append length in bits*/ - X[14] = ctx.tot_len << 3; - X[15] = (ctx.tot_len >> 29) | (0 << 3); - ripemd_compress(ctx, X); - - std::uint8_t* pd = reinterpret_cast< - std::uint8_t*>(digest); - for (std::uint32_t i = 0; i < 20; i += 4) - { - pd[i] = (std::uint8_t)(ctx.h[i>>2]); // implicit cast to uint8_t - pd[i+1] = (std::uint8_t)(ctx.h[i>>2] >> 8); // extracts the 8 least - pd[i+2] = (std::uint8_t)(ctx.h[i>>2] >> 16); // significant bits. - pd[i+3] = (std::uint8_t)(ctx.h[i>>2] >> 24); - } -} - -} // detail -} // beast - -#endif diff --git a/beast/crypto/detail/sha2_context.h b/beast/crypto/detail/sha2_context.h deleted file mode 100644 index 6786fca92a..0000000000 --- a/beast/crypto/detail/sha2_context.h +++ /dev/null @@ -1,428 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_SHA512_CONTEXT_H_INCLUDED -#define BEAST_CRYPTO_SHA512_CONTEXT_H_INCLUDED - -#include -#include - -namespace beast { -namespace detail { - -// Based on https://github.com/ogay/sha2 -// This implementation has been modified from the -// original. It has been updated for C++11. - -/* - * Updated to C++, zedwood.com 2012 - * Based on Olivier Gay's version - * See Modified BSD License below: - * - * FIPS 180-2 SHA-224/256/384/512 implementation - * Issue date: 04/30/2005 - * http://www.ouah.org/ogay/sha2/ - * - * Copyright (C) 2005, 2007 Olivier Gay - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -struct sha256_context -{ - static unsigned int const block_size = 64; - static unsigned int const digest_size = 32; - - unsigned int tot_len; - unsigned int len; - unsigned char block[2 * block_size]; - std::uint32_t h[8]; -}; - -struct sha512_context -{ - static unsigned int const block_size = 128; - static unsigned int const digest_size = 64; - - unsigned int tot_len; - unsigned int len; - unsigned char block[2 * block_size]; - std::uint64_t h[8]; -}; - -#define BEAST_SHA2_SHFR(x, n) (x >> n) -#define BEAST_SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define BEAST_SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define BEAST_SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) -#define BEAST_SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define BEAST_SHA256_F1(x) (BEAST_SHA2_ROTR(x, 2) ^ BEAST_SHA2_ROTR(x, 13) ^ BEAST_SHA2_ROTR(x, 22)) -#define BEAST_SHA256_F2(x) (BEAST_SHA2_ROTR(x, 6) ^ BEAST_SHA2_ROTR(x, 11) ^ BEAST_SHA2_ROTR(x, 25)) -#define BEAST_SHA256_F3(x) (BEAST_SHA2_ROTR(x, 7) ^ BEAST_SHA2_ROTR(x, 18) ^ BEAST_SHA2_SHFR(x, 3)) -#define BEAST_SHA256_F4(x) (BEAST_SHA2_ROTR(x, 17) ^ BEAST_SHA2_ROTR(x, 19) ^ BEAST_SHA2_SHFR(x, 10)) -#define BEAST_SHA512_F1(x) (BEAST_SHA2_ROTR(x, 28) ^ BEAST_SHA2_ROTR(x, 34) ^ BEAST_SHA2_ROTR(x, 39)) -#define BEAST_SHA512_F2(x) (BEAST_SHA2_ROTR(x, 14) ^ BEAST_SHA2_ROTR(x, 18) ^ BEAST_SHA2_ROTR(x, 41)) -#define BEAST_SHA512_F3(x) (BEAST_SHA2_ROTR(x, 1) ^ BEAST_SHA2_ROTR(x, 8) ^ BEAST_SHA2_SHFR(x, 7)) -#define BEAST_SHA512_F4(x) (BEAST_SHA2_ROTR(x, 19) ^ BEAST_SHA2_ROTR(x, 61) ^ BEAST_SHA2_SHFR(x, 6)) -#define BEAST_SHA2_PACK32(str, x) \ -{ \ - *(x) = \ - ((std::uint32_t) *((str) + 3) ) \ - | ((std::uint32_t) *((str) + 2) << 8) \ - | ((std::uint32_t) *((str) + 1) << 16) \ - | ((std::uint32_t) *((str) + 0) << 24); \ -} -#define BEAST_SHA2_UNPACK32(x, str) \ -{ \ - *((str) + 3) = (std::uint8_t) ((x) ); \ - *((str) + 2) = (std::uint8_t) ((x) >> 8); \ - *((str) + 1) = (std::uint8_t) ((x) >> 16); \ - *((str) + 0) = (std::uint8_t) ((x) >> 24); \ -} -#define BEAST_SHA2_PACK64(str, x) \ -{ \ - *(x) = \ - ((std::uint64_t) *((str) + 7) ) \ - | ((std::uint64_t) *((str) + 6) << 8) \ - | ((std::uint64_t) *((str) + 5) << 16) \ - | ((std::uint64_t) *((str) + 4) << 24) \ - | ((std::uint64_t) *((str) + 3) << 32) \ - | ((std::uint64_t) *((str) + 2) << 40) \ - | ((std::uint64_t) *((str) + 1) << 48) \ - | ((std::uint64_t) *((str) + 0) << 56); \ -} -#define BEAST_SHA2_UNPACK64(x, str) \ -{ \ - *((str) + 7) = (std::uint8_t) ((x) ); \ - *((str) + 6) = (std::uint8_t) ((x) >> 8); \ - *((str) + 5) = (std::uint8_t) ((x) >> 16); \ - *((str) + 4) = (std::uint8_t) ((x) >> 24); \ - *((str) + 3) = (std::uint8_t) ((x) >> 32); \ - *((str) + 2) = (std::uint8_t) ((x) >> 40); \ - *((str) + 1) = (std::uint8_t) ((x) >> 48); \ - *((str) + 0) = (std::uint8_t) ((x) >> 56); \ -} - -//------------------------------------------------------------------------------ - -// SHA256 - -template -void sha256_transform (sha256_context& ctx, - unsigned char const* message, - unsigned int block_nb) noexcept -{ - static unsigned long long const K[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 - }; - std::uint32_t w[64]; - std::uint32_t wv[8]; - std::uint32_t t1, t2; - unsigned char const* sub_block; - int i, j; - for (i = 0; i < (int) block_nb; i++) { - sub_block = message + (i << 6); - for (j = 0; j < 16; j++) - BEAST_SHA2_PACK32(&sub_block[j << 2], &w[j]); - for (j = 16; j < 64; j++) - w[j] = BEAST_SHA256_F4( - w[j - 2]) + w[j - 7] + - BEAST_SHA256_F3(w[j - 15]) + - w[j - 16]; - for (j = 0; j < 8; j++) - wv[j] = ctx.h[j]; - for (j = 0; j < 64; j++) { - t1 = wv[7] + BEAST_SHA256_F2(wv[4]) + - BEAST_SHA2_CH(wv[4], wv[5], wv[6]) + - K[j] + w[j]; - t2 = BEAST_SHA256_F1(wv[0]) + - BEAST_SHA2_MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } - for (j = 0; j < 8; j++) - ctx.h[j] += wv[j]; - } -} - -template -void init (sha256_context& ctx) noexcept -{ - ctx.len = 0; - ctx.tot_len = 0; - ctx.h[0] = 0x6a09e667; - ctx.h[1] = 0xbb67ae85; - ctx.h[2] = 0x3c6ef372; - ctx.h[3] = 0xa54ff53a; - ctx.h[4] = 0x510e527f; - ctx.h[5] = 0x9b05688c; - ctx.h[6] = 0x1f83d9ab; - ctx.h[7] = 0x5be0cd19; -} - -template -void update (sha256_context& ctx, - void const* message, std::size_t size) noexcept -{ - auto const pm = reinterpret_cast< - unsigned char const*>(message); - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char *shifted_message; - tmp_len = sha256_context::block_size - ctx.len; - rem_len = size < tmp_len ? size : tmp_len; - std::memcpy(&ctx.block[ctx.len], pm, rem_len); - if (ctx.len + size < sha256_context::block_size) { - ctx.len += size; - return; - } - new_len = size - rem_len; - block_nb = new_len / sha256_context::block_size; - shifted_message = pm + rem_len; - sha256_transform(ctx, ctx.block, 1); - sha256_transform(ctx, shifted_message, block_nb); - rem_len = new_len % sha256_context::block_size; - std::memcpy(ctx.block, &shifted_message[ - block_nb << 6], rem_len); - ctx.len = rem_len; - ctx.tot_len += (block_nb + 1) << 6; -} - -template -void finish (sha256_context& ctx, - void* digest) noexcept -{ - auto const pd = reinterpret_cast< - unsigned char*>(digest); - unsigned int block_nb; - unsigned int pm_len; - unsigned int len_b; - int i; - block_nb = (1 + ((sha256_context::block_size - 9) < - (ctx.len % sha256_context::block_size))); - len_b = (ctx.tot_len + ctx.len) << 3; - pm_len = block_nb << 6; - std::memset(ctx.block + ctx.len, 0, pm_len - ctx.len); - ctx.block[ctx.len] = 0x80; - BEAST_SHA2_UNPACK32(len_b, ctx.block + pm_len - 4); - sha256_transform(ctx, ctx.block, block_nb); - for (i = 0 ; i < 8; i++) - BEAST_SHA2_UNPACK32(ctx.h[i], &pd[i << 2]); -} - -//------------------------------------------------------------------------------ - -// SHA512 - -template -void sha512_transform (sha512_context& ctx, - unsigned char const* message, - unsigned int block_nb) noexcept -{ - static unsigned long long const K[80] = { - 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL}; - - std::uint64_t w[80]; - std::uint64_t wv[8]; - std::uint64_t t1, t2; - unsigned char const* sub_block; - int i, j; - for (i = 0; i < (int) block_nb; i++) - { - sub_block = message + (i << 7); - for (j = 0; j < 16; j++) - BEAST_SHA2_PACK64(&sub_block[j << 3], &w[j]); - for (j = 16; j < 80; j++) - w[j] = BEAST_SHA512_F4( - w[j - 2]) + w[j - 7] + - BEAST_SHA512_F3(w[j - 15]) + - w[j - 16]; - for (j = 0; j < 8; j++) - wv[j] = ctx.h[j]; - for (j = 0; j < 80; j++) { - t1 = wv[7] + BEAST_SHA512_F2(wv[4]) + - BEAST_SHA2_CH(wv[4], wv[5], wv[6]) + - K[j] + w[j]; - t2 = BEAST_SHA512_F1(wv[0]) + - BEAST_SHA2_MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } - for (j = 0; j < 8; j++) - ctx.h[j] += wv[j]; - } -} - -template -void init (sha512_context& ctx) noexcept -{ - ctx.len = 0; - ctx.tot_len = 0; - ctx.h[0] = 0x6a09e667f3bcc908ULL; - ctx.h[1] = 0xbb67ae8584caa73bULL; - ctx.h[2] = 0x3c6ef372fe94f82bULL; - ctx.h[3] = 0xa54ff53a5f1d36f1ULL; - ctx.h[4] = 0x510e527fade682d1ULL; - ctx.h[5] = 0x9b05688c2b3e6c1fULL; - ctx.h[6] = 0x1f83d9abfb41bd6bULL; - ctx.h[7] = 0x5be0cd19137e2179ULL; -} - -template -void update (sha512_context& ctx, - void const* message, std::size_t size) noexcept -{ - auto const pm = reinterpret_cast< - unsigned char const*>(message); - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char *shifted_message; - tmp_len = sha512_context::block_size - ctx.len; - rem_len = size < tmp_len ? size : tmp_len; - std::memcpy(&ctx.block[ctx.len], pm, rem_len); - if (ctx.len + size < sha512_context::block_size) { - ctx.len += size; - return; - } - new_len = size - rem_len; - block_nb = new_len / sha512_context::block_size; - shifted_message = pm + rem_len; - sha512_transform(ctx, ctx.block, 1); - sha512_transform(ctx, shifted_message, block_nb); - rem_len = new_len % sha512_context::block_size; - std::memcpy(ctx.block, &shifted_message[ - block_nb << 7], rem_len); - ctx.len = rem_len; - ctx.tot_len += (block_nb + 1) << 7; -} - -template -void finish (sha512_context& ctx, - void* digest) noexcept -{ - auto const pd = reinterpret_cast< - unsigned char*>(digest); - unsigned int block_nb; - unsigned int pm_len; - unsigned int len_b; - int i; - block_nb = 1 + ((sha512_context::block_size - 17) < - (ctx.len % sha512_context::block_size)); - len_b = (ctx.tot_len + ctx.len) << 3; - pm_len = block_nb << 7; - std::memset(ctx.block + ctx.len, 0, pm_len - ctx.len); - ctx.block[ctx.len] = 0x80; - BEAST_SHA2_UNPACK32(len_b, ctx.block + pm_len - 4); - sha512_transform(ctx, ctx.block, block_nb); - for (i = 0 ; i < 8; i++) - BEAST_SHA2_UNPACK64(ctx.h[i], &pd[i << 3]); -} - -} // detail -} // beast - -#endif diff --git a/beast/crypto/ripemd.h b/beast/crypto/ripemd.h deleted file mode 100644 index 968ffecced..0000000000 --- a/beast/crypto/ripemd.h +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_RIPEMD_H_INCLUDED -#define BEAST_CRYPTO_RIPEMD_H_INCLUDED - -#include -#include - -namespace beast { - -using ripemd160_hasher = detail::mac_facade< - detail::ripemd160_context, false>; - -// secure version -using ripemd160_hasher_s = detail::mac_facade< - detail::ripemd160_context, true>; - -} - -#endif diff --git a/beast/crypto/secure_erase.h b/beast/crypto/secure_erase.h deleted file mode 100644 index 48280108a7..0000000000 --- a/beast/crypto/secure_erase.h +++ /dev/null @@ -1,87 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_SECURE_ERASE_H_INCLUDED -#define BEAST_CRYPTO_SECURE_ERASE_H_INCLUDED - -#include -#include -#include - -namespace beast { - -namespace detail { - -class secure_erase_impl -{ -private: - struct base - { - virtual void operator()( - void* dest, std::size_t bytes) const = 0; - }; - - struct impl : base - { - void operator()( - void* dest, std::size_t bytes) const override - { - char volatile* volatile p = - const_cast( - reinterpret_cast(dest)); - if (bytes == 0) - return; - do - { - *p = 0; - } - while(*p++ == 0 && --bytes); - } - }; - - char buf_[sizeof(impl)]; - base& erase_; - -public: - secure_erase_impl() - : erase_(*new(buf_) impl) - { - } - - void operator()( - void* dest, std::size_t bytes) const - { - return erase_(dest, bytes); - } -}; - -} - -/** Guaranteed to fill memory with zeroes */ -template -void -secure_erase (void* dest, std::size_t bytes) -{ - static detail::secure_erase_impl const erase; - erase(dest, bytes); -} - -} - -#endif diff --git a/beast/crypto/sha.h b/beast/crypto/sha.h deleted file mode 100644 index 7d9b05a6c3..0000000000 --- a/beast/crypto/sha.h +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_SHA_H_INCLUDED -#define BEAST_CRYPTO_SHA_H_INCLUDED - -#include -#include - -namespace beast { - -// non-secure -using sha_hasher = detail::mac_facade< - detail::sha_context, false>; - -} - -#endif diff --git a/beast/crypto/sha2.h b/beast/crypto/sha2.h deleted file mode 100644 index 203b5c3cfe..0000000000 --- a/beast/crypto/sha2.h +++ /dev/null @@ -1,44 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_SHA2_H_INCLUDED -#define BEAST_CRYPTO_SHA2_H_INCLUDED - -#include -#include - -namespace beast { - -using sha256_hasher = detail::mac_facade< - detail::sha256_context, false>; - -// secure version -using sha256_hasher_s = detail::mac_facade< - detail::sha256_context, true>; - -using sha512_hasher = detail::mac_facade< - detail::sha512_context, false>; - -// secure version -using sha512_hasher_s = detail::mac_facade< - detail::sha512_context, true>; - -} - -#endif diff --git a/beast/cxx17/type_traits.h b/beast/cxx17/type_traits.h deleted file mode 100644 index 31bec59f6b..0000000000 --- a/beast/cxx17/type_traits.h +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CXX17_TYPE_TRAITS_H_INCLUDED -#define BEAST_CXX17_TYPE_TRAITS_H_INCLUDED - -#include -#include -#include - -namespace std { - -#ifndef _MSC_VER - -template -using void_t = void; - -template -using bool_constant = std::integral_constant; - -#endif - -// Ideas from Howard Hinnant -// -// Specializations of is_constructible for pair and tuple which -// work around an apparent defect in the standard that causes well -// formed expressions involving pairs or tuples of non default-constructible -// types to generate compile errors. -// -template -struct is_constructible > - : integral_constant ::value && - is_default_constructible ::value> -{ -}; - -} // std - -#endif diff --git a/beast/empty_base_optimization.h b/beast/empty_base_optimization.h deleted file mode 100644 index 199021bad4..0000000000 --- a/beast/empty_base_optimization.h +++ /dev/null @@ -1,111 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant , - Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_EMPTY_BASE_OPTIMIZATION_H_INCLUDED -#define BEAST_EMPTY_BASE_OPTIMIZATION_H_INCLUDED - -#include -#include - -namespace beast { - -namespace detail { - -template -struct empty_base_optimization_decide - : std::integral_constant ::value -#ifdef __clang__ - && !__is_final(T) -#endif - > -{ -}; - -} - -//------------------------------------------------------------------------------ - -template < - class T, - int UniqueID = 0, - bool ShouldDeriveFrom = - detail::empty_base_optimization_decide ::value -> -class empty_base_optimization : private T -{ -public: - empty_base_optimization() = default; - - empty_base_optimization(T const& t) - : T (t) - {} - - empty_base_optimization(T&& t) - : T (std::move (t)) - {} - - T& member() noexcept - { - return *this; - } - - T const& member() const noexcept - { - return *this; - } -}; - -//------------------------------------------------------------------------------ - -template < - class T, - int UniqueID -> -class empty_base_optimization -{ -public: - empty_base_optimization() = default; - - empty_base_optimization(T const& t) - : m_t (t) - {} - - empty_base_optimization(T&& t) - : m_t (std::move (t)) - {} - - T& member() noexcept - { - return m_t; - } - - T const& member() const noexcept - { - return m_t; - } - -private: - T m_t; -}; - -} - -#endif diff --git a/beast/hash/endian.h b/beast/hash/endian.h deleted file mode 100644 index fe15249e01..0000000000 --- a/beast/hash/endian.h +++ /dev/null @@ -1,52 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant , - Vinnie Falco , - Vinnie Falco -#include -#include - -namespace beast { - -// See http://www.isthe.com/chongo/tech/comp/fnv/ -// -class fnv1a -{ -private: - std::uint64_t state_ = 14695981039346656037ULL; - -public: - using result_type = std::size_t; - - fnv1a() = default; - - template ::value>* = nullptr> - explicit - fnv1a (Seed seed) - { - append (&seed, sizeof(seed)); - } - - void - operator() (void const* key, std::size_t len) noexcept - { - unsigned char const* p = - static_cast(key); - unsigned char const* const e = p + len; - for (; p < e; ++p) - state_ = (state_ ^ *p) * 1099511628211ULL; - } - - explicit - operator std::size_t() noexcept - { - return static_cast(state_); - } -}; - -} // beast - -#endif diff --git a/beast/hash/hash_append.h b/beast/hash/hash_append.h deleted file mode 100644 index 861c11ab12..0000000000 --- a/beast/hash/hash_append.h +++ /dev/null @@ -1,516 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant , - Vinnie Falco -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { - -namespace detail { - -template -/*constexpr*/ -inline -void -reverse_bytes(T& t) -{ - unsigned char* bytes = static_cast(std::memmove(std::addressof(t), - std::addressof(t), - sizeof(T))); - for (unsigned i = 0; i < sizeof(T)/2; ++i) - std::swap(bytes[i], bytes[sizeof(T)-1-i]); -} - -template -/*constexpr*/ -inline -void -maybe_reverse_bytes(T& t, std::false_type) -{ -} - -template -/*constexpr*/ -inline -void -maybe_reverse_bytes(T& t, std::true_type) -{ - reverse_bytes(t); -} - -template -/*constexpr*/ -inline -void -maybe_reverse_bytes(T& t, Hasher&) -{ - maybe_reverse_bytes(t, std::integral_constant{}); -} - -} // detail - -// is_uniquely_represented - -// A type T is contiguously hashable if for all combinations of two values of -// a type, say x and y, if x == y, then it must also be true that -// memcmp(addressof(x), addressof(y), sizeof(T)) == 0. I.e. if x == y, -// then x and y have the same bit pattern representation. - -template -struct is_uniquely_represented - : public std::integral_constant::value || - std::is_enum::value || - std::is_pointer::value> -{}; - -template -struct is_uniquely_represented - : public is_uniquely_represented -{}; - -template -struct is_uniquely_represented - : public is_uniquely_represented -{}; - -template -struct is_uniquely_represented - : public is_uniquely_represented -{}; - -// is_uniquely_represented> - -template -struct is_uniquely_represented> - : public std::integral_constant::value && - is_uniquely_represented::value && - sizeof(T) + sizeof(U) == sizeof(std::pair)> -{ -}; - -// is_uniquely_represented> - -template -struct is_uniquely_represented> - : public std::integral_constant::value...>::value && - static_sum::value == sizeof(std::tuple)> -{ -}; - -// is_uniquely_represented - -template -struct is_uniquely_represented - : public is_uniquely_represented -{ -}; - -// is_uniquely_represented> - -template -struct is_uniquely_represented> - : public std::integral_constant::value && - sizeof(T)*N == sizeof(std::array)> -{ -}; - -/** Metafunction returning `true` if the type can be hashed in one call. - - For `is_contiguously_hashable::value` to be true, then for every - combination of possible values of `T` held in `x` and `y`, - if `x == y`, then it must be true that `memcmp(&x, &y, sizeof(T))` - return 0; i.e. that `x` and `y` are represented by the same bit pattern. - - For example: A two's complement `int` should be contiguously hashable. - Every bit pattern produces a unique value that does not compare equal to - any other bit pattern's value. A IEEE floating point should not be - contiguously hashable because -0. and 0. have different bit patterns, - though they compare equal. -*/ -/** @{ */ -template -struct is_contiguously_hashable - : public std::integral_constant::value && - (sizeof(T) == 1 || - HashAlgorithm::endian == endian::native)> -{}; - -template -struct is_contiguously_hashable - : public std::integral_constant::value && - (sizeof(T) == 1 || - HashAlgorithm::endian == endian::native)> -{}; -/** @} */ - -//------------------------------------------------------------------------------ - -/** Logically concatenate input data to a `Hasher`. - - Hasher requirements: - - `X` is the type `Hasher` - `h` is a value of type `x` - `p` is a value convertible to `void const*` - `n` is a value of type `std::size_t`, greater than zero - - Expression: - `h.append (p, n);` - Throws: - Never - Effect: - Adds the input data to the hasher state. - - Expression: - `static_cast(j)` - Throws: - Never - Effect: - Returns the reslting hash of all the input data. -*/ -/** @{ */ - -// scalars - -template -inline -std::enable_if_t -< - is_contiguously_hashable::value -> -hash_append(Hasher& h, T const& t) noexcept -{ - h(std::addressof(t), sizeof(t)); -} - -template -inline -std::enable_if_t -< - !is_contiguously_hashable::value && - (std::is_integral::value || std::is_pointer::value || std::is_enum::value) -> -hash_append(Hasher& h, T t) noexcept -{ - detail::reverse_bytes(t); - h(std::addressof(t), sizeof(t)); -} - -template -inline -std::enable_if_t -< - std::is_floating_point::value -> -hash_append(Hasher& h, T t) noexcept -{ - if (t == 0) - t = 0; - detail::maybe_reverse_bytes(t, h); - h(&t, sizeof(t)); -} - -template -inline -void -hash_append(Hasher& h, std::nullptr_t) noexcept -{ - void const* p = nullptr; - detail::maybe_reverse_bytes(p, h); - h(&p, sizeof(p)); -} - -// Forward declarations for ADL purposes - -template -std::enable_if_t -< - !is_contiguously_hashable::value -> -hash_append(Hasher& h, T (&a)[N]) noexcept; - -template -std::enable_if_t -< - !is_contiguously_hashable::value -> -hash_append(Hasher& h, std::basic_string const& s) noexcept; - -template -std::enable_if_t -< - is_contiguously_hashable::value -> -hash_append(Hasher& h, std::basic_string const& s) noexcept; - -template -std::enable_if_t -< - !is_contiguously_hashable, Hasher>::value -> -hash_append (Hasher& h, std::pair const& p) noexcept; - -template -std::enable_if_t -< - !is_contiguously_hashable::value -> -hash_append(Hasher& h, std::vector const& v) noexcept; - -template -std::enable_if_t -< - is_contiguously_hashable::value -> -hash_append(Hasher& h, std::vector const& v) noexcept; - -template -std::enable_if_t -< - !is_contiguously_hashable, Hasher>::value -> -hash_append(Hasher& h, std::array const& a) noexcept; - -template -std::enable_if_t -< - !is_contiguously_hashable, Hasher>::value -> -hash_append(Hasher& h, std::tuple const& t) noexcept; - -template -void -hash_append(Hasher& h, std::unordered_map const& m); - -template -void -hash_append(Hasher& h, std::unordered_set const& s); - -template -void -hash_append (Hasher& h, T0 const& t0, T1 const& t1, T const& ...t) noexcept; - -// c-array - -template -std::enable_if_t -< - !is_contiguously_hashable::value -> -hash_append(Hasher& h, T (&a)[N]) noexcept -{ - for (auto const& t : a) - hash_append(h, t); -} - -// basic_string - -template -inline -std::enable_if_t -< - !is_contiguously_hashable::value -> -hash_append(Hasher& h, std::basic_string const& s) noexcept -{ - for (auto c : s) - hash_append(h, c); - hash_append(h, s.size()); -} - -template -inline -std::enable_if_t -< - is_contiguously_hashable::value -> -hash_append(Hasher& h, std::basic_string const& s) noexcept -{ - h(s.data(), s.size()*sizeof(CharT)); - hash_append(h, s.size()); -} - -// pair - -template -inline -std::enable_if_t -< - !is_contiguously_hashable, Hasher>::value -> -hash_append (Hasher& h, std::pair const& p) noexcept -{ - hash_append (h, p.first, p.second); -} - -// vector - -template -inline -std::enable_if_t -< - !is_contiguously_hashable::value -> -hash_append(Hasher& h, std::vector const& v) noexcept -{ - for (auto const& t : v) - hash_append(h, t); - hash_append(h, v.size()); -} - -template -inline -std::enable_if_t -< - is_contiguously_hashable::value -> -hash_append(Hasher& h, std::vector const& v) noexcept -{ - h(v.data(), v.size()*sizeof(T)); - hash_append(h, v.size()); -} - -// array - -template -std::enable_if_t -< - !is_contiguously_hashable, Hasher>::value -> -hash_append(Hasher& h, std::array const& a) noexcept -{ - for (auto const& t : a) - hash_append(h, t); -} - -// tuple - -namespace detail -{ - -inline -void -for_each_item(...) noexcept -{ -} - -template -inline -int -hash_one(Hasher& h, T const& t) noexcept -{ - hash_append(h, t); - return 0; -} - -template -inline -void -tuple_hash(Hasher& h, std::tuple const& t, std::index_sequence) noexcept -{ - for_each_item(hash_one(h, std::get(t))...); -} - -} // detail - -template -inline -std::enable_if_t -< - !is_contiguously_hashable, Hasher>::value -> -hash_append(Hasher& h, std::tuple const& t) noexcept -{ - detail::tuple_hash(h, t, std::index_sequence_for{}); -} - -// shared_ptr - -template -inline -void -hash_append (Hasher& h, std::shared_ptr const& p) noexcept -{ - hash_append(h, p.get()); -} - -// chrono - -template -inline -void -hash_append (Hasher& h, std::chrono::duration const& d) noexcept -{ - hash_append(h, d.count()); -} - -template -inline -void -hash_append (Hasher& h, std::chrono::time_point const& tp) noexcept -{ - hash_append(h, tp.time_since_epoch()); -} - -// variadic - -template -inline -void -hash_append (Hasher& h, T0 const& t0, T1 const& t1, T const& ...t) noexcept -{ - hash_append(h, t0); - hash_append(h, t1, t...); -} - -// error_code - -template -inline -void -hash_append(HashAlgorithm& h, std::error_code const& ec) -{ - hash_append(h, ec.value(), &ec.category()); -} - -} // beast - -#endif diff --git a/beast/hash/impl/hash_speed_test.cpp b/beast/hash/impl/hash_speed_test.cpp deleted file mode 100644 index 7ad3e52580..0000000000 --- a/beast/hash/impl/hash_speed_test.cpp +++ /dev/null @@ -1,85 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { - -class hash_speed_test : public beast::unit_test::suite -{ -public: - using clock_type = - std::chrono::high_resolution_clock; - template - void - test (std::string const& what, std::size_t n) - { - using namespace std; - using namespace std::chrono; - xor_shift_engine g(1); - array key; - auto const start = clock_type::now(); - while(n--) - { - rngfill (key, g); - Hasher h; - h.append(key.data(), KeySize); - volatile size_t temp = - static_cast(h); - (void)temp; - } - auto const elapsed = clock_type::now() - start; - log << setw(12) << what << " " << - duration(elapsed) << "s"; - } - - void - run() - { - enum - { - N = 100000000 - }; - - #if ! BEAST_NO_XXHASH - test ("xxhash", N); - #endif - test ("fnv1a", N); - test ("siphash", N); - pass(); - } -}; - -BEAST_DEFINE_TESTSUITE_MANUAL(hash_speed,container,beast); - -} // beast diff --git a/beast/hash/impl/siphash.cpp b/beast/hash/impl/siphash.cpp deleted file mode 100644 index 22125f53e0..0000000000 --- a/beast/hash/impl/siphash.cpp +++ /dev/null @@ -1,165 +0,0 @@ -//------------------------------- siphash.h ------------------------------------ -// -// This software is in the public domain. The only restriction on its use is -// that no one can remove it from the public domain by claiming ownership of it, -// including the original authors. -// -// There is no warranty of correctness on the software contained herein. Use -// at your own risk. -// -// Derived from: -// -// SipHash reference C implementation -// -// Written in 2012 by Jean-Philippe Aumasson -// Daniel J. Bernstein -// -// To the extent possible under law, the author(s) have dedicated all copyright -// and related and neighboring rights to this software to the public domain -// worldwide. This software is distributed without any warranty. -// -// You should have received a copy of the CC0 Public Domain Dedication along -// with this software. If not, see -// . -// -//------------------------------------------------------------------------------ - -#include -#include -#include -#include - -// namespace acme is used to demonstrate example code. It is not proposed. - -namespace beast { -namespace detail { - -using u64 = std::uint64_t; -using u32 = std::uint32_t; -using u8 = std::uint8_t; - -inline -u64 -rotl(u64 x, u64 b) -{ - return (x << b) | (x >> (64 - b)); -} - -inline -u64 -u8to64_le(const u8* p) -{ -#if BEAST_LITTLE_ENDIAN - return *static_cast(static_cast(p)); -#else - return static_cast(p[7]) << 56 | static_cast(p[6]) << 48 | - static_cast(p[5]) << 40 | static_cast(p[4]) << 32 | - static_cast(p[3]) << 24 | static_cast(p[2]) << 16 | - static_cast(p[1]) << 8 | static_cast(p[0]); -#endif -} - -inline -void -sipround(u64& v0, u64& v1, u64& v2, u64& v3) -{ - v0 += v1; - v1 = rotl(v1, 13); - v1 ^= v0; - v0 = rotl(v0, 32); - v2 += v3; - v3 = rotl(v3, 16); - v3 ^= v2; - v0 += v3; - v3 = rotl(v3, 21); - v3 ^= v0; - v2 += v1; - v1 = rotl(v1, 17); - v1 ^= v2; - v2 = rotl(v2, 32); -} - -} // detail - -siphash::siphash(std::uint64_t k0, std::uint64_t k1) noexcept -{ - v3_ ^= k1; - v2_ ^= k0; - v1_ ^= k1; - v0_ ^= k0; -} - -void -siphash::operator() (void const* key, std::size_t inlen) noexcept -{ - using namespace detail; - u8 const* in = static_cast(key); - total_length_ += inlen; - if (bufsize_ + inlen < 8) - { - std::copy(in, in+inlen, buf_ + bufsize_); - bufsize_ += inlen; - return; - } - if (bufsize_ > 0) - { - auto t = 8 - bufsize_; - std::copy(in, in+t, buf_ + bufsize_); - u64 m = u8to64_le( buf_ ); - v3_ ^= m; - sipround(v0_, v1_, v2_, v3_); - sipround(v0_, v1_, v2_, v3_); - v0_ ^= m; - in += t; - inlen -= t; - } - bufsize_ = inlen & 7; - u8 const* const end = in + (inlen - bufsize_); - for ( ; in != end; in += 8 ) - { - u64 m = u8to64_le( in ); - v3_ ^= m; - sipround(v0_, v1_, v2_, v3_); - sipround(v0_, v1_, v2_, v3_); - v0_ ^= m; - } - std::copy(end, end + bufsize_, buf_); -} - -siphash::operator std::size_t() noexcept -{ - using namespace detail; - std::size_t b = static_cast(total_length_) << 56; - switch(bufsize_) - { - case 7: - b |= static_cast(buf_[6]) << 48; - case 6: - b |= static_cast(buf_[5]) << 40; - case 5: - b |= static_cast(buf_[4]) << 32; - case 4: - b |= static_cast(buf_[3]) << 24; - case 3: - b |= static_cast(buf_[2]) << 16; - case 2: - b |= static_cast(buf_[1]) << 8; - case 1: - b |= static_cast(buf_[0]); - case 0: - break; - } - v3_ ^= b; - sipround(v0_, v1_, v2_, v3_); - sipround(v0_, v1_, v2_, v3_); - v0_ ^= b; - v2_ ^= 0xff; - sipround(v0_, v1_, v2_, v3_); - sipround(v0_, v1_, v2_, v3_); - sipround(v0_, v1_, v2_, v3_); - sipround(v0_, v1_, v2_, v3_); - b = v0_ ^ v1_ ^ v2_ ^ v3_; - return b; -} - -} // beast diff --git a/beast/hash/impl/spookyv2.cpp b/beast/hash/impl/spookyv2.cpp deleted file mode 100644 index 85f65d3eec..0000000000 --- a/beast/hash/impl/spookyv2.cpp +++ /dev/null @@ -1,361 +0,0 @@ -// Spooky Hash -// A 128-bit noncryptographic hash, for checksums and table lookup -// By Bob Jenkins. Public domain. -// Oct 31 2010: published framework, disclaimer ShortHash isn't right -// Nov 7 2010: disabled ShortHash -// Oct 31 2011: replace End, ShortMix, ShortEnd, enable ShortHash again -// April 10 2012: buffer overflow on platforms without unaligned reads -// July 12 2012: was passing out variables in final to in/out in short -// July 30 2012: I reintroduced the buffer overflow -// August 5 2012: SpookyV2: d = should be d += in short hash, and remove extra mix from long hash - -#include -#include - -#ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable: 4127) // conditional expression is constant -#pragma warning (disable: 4244) // conversion from 'size_t' to 'uint8', possible loss of data -#endif - -#define ALLOW_UNALIGNED_READS 1 - -// -// short hash ... it could be used on any message, -// but it's used by Spooky just for short messages. -// -void SpookyHash::Short( - const void *message, - size_t length, - uint64 *hash1, - uint64 *hash2) -{ - uint64 buf[2*sc_numVars]; - union - { - const uint8 *p8; - uint32 *p32; - uint64 *p64; - size_t i; - } u; - - u.p8 = (const uint8 *)message; - - if (!ALLOW_UNALIGNED_READS && (u.i & 0x7)) - { - memcpy(buf, message, length); - u.p64 = buf; - } - - size_t remainder = length%32; - uint64 a=*hash1; - uint64 b=*hash2; - uint64 c=sc_const; - uint64 d=sc_const; - - if (length > 15) - { - const uint64 *end = u.p64 + (length/32)*4; - - // handle all complete sets of 32 bytes - for (; u.p64 < end; u.p64 += 4) - { - c += u.p64[0]; - d += u.p64[1]; - ShortMix(a,b,c,d); - a += u.p64[2]; - b += u.p64[3]; - } - - //Handle the case of 16+ remaining bytes. - if (remainder >= 16) - { - c += u.p64[0]; - d += u.p64[1]; - ShortMix(a,b,c,d); - u.p64 += 2; - remainder -= 16; - } - } - - // Handle the last 0..15 bytes, and its length - d += ((uint64)length) << 56; - switch (remainder) - { - case 15: - d += ((uint64)u.p8[14]) << 48; - case 14: - d += ((uint64)u.p8[13]) << 40; - case 13: - d += ((uint64)u.p8[12]) << 32; - case 12: - d += u.p32[2]; - c += u.p64[0]; - break; - case 11: - d += ((uint64)u.p8[10]) << 16; - case 10: - d += ((uint64)u.p8[9]) << 8; - case 9: - d += (uint64)u.p8[8]; - case 8: - c += u.p64[0]; - break; - case 7: - c += ((uint64)u.p8[6]) << 48; - case 6: - c += ((uint64)u.p8[5]) << 40; - case 5: - c += ((uint64)u.p8[4]) << 32; - case 4: - c += u.p32[0]; - break; - case 3: - c += ((uint64)u.p8[2]) << 16; - case 2: - c += ((uint64)u.p8[1]) << 8; - case 1: - c += (uint64)u.p8[0]; - break; - case 0: - c += sc_const; - d += sc_const; - } - ShortEnd(a,b,c,d); - *hash1 = a; - *hash2 = b; -} - - - - -// do the whole hash in one call -void SpookyHash::Hash128( - const void *message, - size_t length, - uint64 *hash1, - uint64 *hash2) -{ - if (length < sc_bufSize) - { - Short(message, length, hash1, hash2); - return; - } - - uint64 h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11; - uint64 buf[sc_numVars]; - uint64 *end; - union - { - const uint8 *p8; - uint64 *p64; - size_t i; - } u; - size_t remainder; - - h0=h3=h6=h9 = *hash1; - h1=h4=h7=h10 = *hash2; - h2=h5=h8=h11 = sc_const; - - u.p8 = (const uint8 *)message; - end = u.p64 + (length/sc_blockSize)*sc_numVars; - - // handle all whole sc_blockSize blocks of bytes - if (ALLOW_UNALIGNED_READS || ((u.i & 0x7) == 0)) - { - while (u.p64 < end) - { - Mix(u.p64, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - u.p64 += sc_numVars; - } - } - else - { - while (u.p64 < end) - { - memcpy(buf, u.p64, sc_blockSize); - Mix(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - u.p64 += sc_numVars; - } - } - - // handle the last partial block of sc_blockSize bytes - remainder = (length - ((const uint8 *)end-(const uint8 *)message)); - memcpy(buf, end, remainder); - memset(((uint8 *)buf)+remainder, 0, sc_blockSize-remainder); - ((uint8 *)buf)[sc_blockSize-1] = - static_cast(remainder); - - // do some final mixing - End(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - *hash1 = h0; - *hash2 = h1; -} - - - -// init spooky state -void SpookyHash::Init(uint64 seed1, uint64 seed2) -{ - m_length = 0; - m_remainder = 0; - m_state[0] = seed1; - m_state[1] = seed2; -} - - -// add a message fragment to the state -void SpookyHash::Update(const void *message, size_t length) -{ - uint64 h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11; - size_t newLength = length + m_remainder; - uint8 remainder; - union - { - const uint8 *p8; - uint64 *p64; - size_t i; - } u; - const uint64 *end; - - // Is this message fragment too short? If it is, stuff it away. - if (newLength < sc_bufSize) - { - memcpy(&((uint8 *)m_data)[m_remainder], message, length); - m_length = length + m_length; - m_remainder = (uint8)newLength; - return; - } - - // init the variables - if (m_length < sc_bufSize) - { - h0=h3=h6=h9 = m_state[0]; - h1=h4=h7=h10 = m_state[1]; - h2=h5=h8=h11 = sc_const; - } - else - { - h0 = m_state[0]; - h1 = m_state[1]; - h2 = m_state[2]; - h3 = m_state[3]; - h4 = m_state[4]; - h5 = m_state[5]; - h6 = m_state[6]; - h7 = m_state[7]; - h8 = m_state[8]; - h9 = m_state[9]; - h10 = m_state[10]; - h11 = m_state[11]; - } - m_length = length + m_length; - - // if we've got anything stuffed away, use it now - if (m_remainder) - { - uint8 prefix = sc_bufSize-m_remainder; - memcpy(&(((uint8 *)m_data)[m_remainder]), message, prefix); - u.p64 = m_data; - Mix(u.p64, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - Mix(&u.p64[sc_numVars], h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - u.p8 = ((const uint8 *)message) + prefix; - length -= prefix; - } - else - { - u.p8 = (const uint8 *)message; - } - - // handle all whole blocks of sc_blockSize bytes - end = u.p64 + (length/sc_blockSize)*sc_numVars; - remainder = (uint8)(length-((const uint8 *)end-u.p8)); - if (ALLOW_UNALIGNED_READS || (u.i & 0x7) == 0) - { - while (u.p64 < end) - { - Mix(u.p64, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - u.p64 += sc_numVars; - } - } - else - { - while (u.p64 < end) - { - memcpy(m_data, u.p8, sc_blockSize); - Mix(m_data, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - u.p64 += sc_numVars; - } - } - - // stuff away the last few bytes - m_remainder = remainder; - memcpy(m_data, end, remainder); - - // stuff away the variables - m_state[0] = h0; - m_state[1] = h1; - m_state[2] = h2; - m_state[3] = h3; - m_state[4] = h4; - m_state[5] = h5; - m_state[6] = h6; - m_state[7] = h7; - m_state[8] = h8; - m_state[9] = h9; - m_state[10] = h10; - m_state[11] = h11; -} - - -// report the hash for the concatenation of all message fragments so far -void SpookyHash::Final(uint64 *hash1, uint64 *hash2) -{ - // init the variables - if (m_length < sc_bufSize) - { - *hash1 = m_state[0]; - *hash2 = m_state[1]; - Short( m_data, m_length, hash1, hash2); - return; - } - - const uint64 *data = (const uint64 *)m_data; - uint8 remainder = m_remainder; - - uint64 h0 = m_state[0]; - uint64 h1 = m_state[1]; - uint64 h2 = m_state[2]; - uint64 h3 = m_state[3]; - uint64 h4 = m_state[4]; - uint64 h5 = m_state[5]; - uint64 h6 = m_state[6]; - uint64 h7 = m_state[7]; - uint64 h8 = m_state[8]; - uint64 h9 = m_state[9]; - uint64 h10 = m_state[10]; - uint64 h11 = m_state[11]; - - if (remainder >= sc_blockSize) - { - // m_data can contain two blocks; handle any whole first block - Mix(data, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - data += sc_numVars; - remainder -= sc_blockSize; - } - - // mix in the last partial block, and the length mod sc_blockSize - memset(&((uint8 *)data)[remainder], 0, (sc_blockSize-remainder)); - - ((uint8 *)data)[sc_blockSize-1] = remainder; - - // do some final mixing - End(data, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - - *hash1 = h0; - *hash2 = h1; -} - -#ifdef _MSC_VER -#pragma warning (pop) -#endif diff --git a/beast/hash/impl/spookyv2.h b/beast/hash/impl/spookyv2.h deleted file mode 100644 index de198b43df..0000000000 --- a/beast/hash/impl/spookyv2.h +++ /dev/null @@ -1,301 +0,0 @@ -// -// SpookyHash: a 128-bit noncryptographic hash function -// By Bob Jenkins, public domain -// Oct 31 2010: alpha, framework + SpookyHash::Mix appears right -// Oct 31 2011: alpha again, Mix only good to 2^^69 but rest appears right -// Dec 31 2011: beta, improved Mix, tested it for 2-bit deltas -// Feb 2 2012: production, same bits as beta -// Feb 5 2012: adjusted definitions of uint* to be more portable -// Mar 30 2012: 3 bytes/cycle, not 4. Alpha was 4 but wasn't thorough enough. -// August 5 2012: SpookyV2 (different results) -// -// Up to 3 bytes/cycle for long messages. Reasonably fast for short messages. -// All 1 or 2 bit deltas achieve avalanche within 1% bias per output bit. -// -// This was developed for and tested on 64-bit x86-compatible processors. -// It assumes the processor is little-endian. There is a macro -// controlling whether unaligned reads are allowed (by default they are). -// This should be an equally good hash on big-endian machines, but it will -// compute different results on them than on little-endian machines. -// -// Google's CityHash has similar specs to SpookyHash, and CityHash is faster -// on new Intel boxes. MD4 and MD5 also have similar specs, but they are orders -// of magnitude slower. CRCs are two or more times slower, but unlike -// SpookyHash, they have nice math for combining the CRCs of pieces to form -// the CRCs of wholes. There are also cryptographic hashes, but those are even -// slower than MD5. -// - -#ifndef BEAST_HASH_SPOOKYV2_H_INCLUDED -#define BEAST_HASH_SPOOKYV2_H_INCLUDED - -#include - -#ifdef _MSC_VER -# define INLINE __forceinline - typedef unsigned __int64 uint64; - typedef unsigned __int32 uint32; - typedef unsigned __int16 uint16; - typedef unsigned __int8 uint8; -#else -#include -# define INLINE inline - typedef uint64_t uint64; - typedef uint32_t uint32; - typedef uint16_t uint16; - typedef uint8_t uint8; -#endif - - -class SpookyHash -{ -public: - // - // SpookyHash: hash a single message in one call, produce 128-bit output - // - static void Hash128( - const void *message, // message to hash - size_t length, // length of message in bytes - uint64 *hash1, // in/out: in seed 1, out hash value 1 - uint64 *hash2); // in/out: in seed 2, out hash value 2 - - // - // Hash64: hash a single message in one call, return 64-bit output - // - static uint64 Hash64( - const void *message, // message to hash - size_t length, // length of message in bytes - uint64 seed) // seed - { - uint64 hash1 = seed; - Hash128(message, length, &hash1, &seed); - return hash1; - } - - // - // Hash32: hash a single message in one call, produce 32-bit output - // - static uint32 Hash32( - const void *message, // message to hash - size_t length, // length of message in bytes - uint32 seed) // seed - { - uint64 hash1 = seed, hash2 = seed; - Hash128(message, length, &hash1, &hash2); - return (uint32)hash1; - } - - // - // Init: initialize the context of a SpookyHash - // - void Init( - uint64 seed1, // any 64-bit value will do, including 0 - uint64 seed2); // different seeds produce independent hashes - - // - // Update: add a piece of a message to a SpookyHash state - // - void Update( - const void *message, // message fragment - size_t length); // length of message fragment in bytes - - - // - // Final: compute the hash for the current SpookyHash state - // - // This does not modify the state; you can keep updating it afterward - // - // The result is the same as if SpookyHash() had been called with - // all the pieces concatenated into one message. - // - void Final( - uint64 *hash1, // out only: first 64 bits of hash value. - uint64 *hash2); // out only: second 64 bits of hash value. - - // - // left rotate a 64-bit value by k bytes - // - static INLINE uint64 Rot64(uint64 x, int k) - { - return (x << k) | (x >> (64 - k)); - } - - // - // This is used if the input is 96 bytes long or longer. - // - // The internal state is fully overwritten every 96 bytes. - // Every input bit appears to cause at least 128 bits of entropy - // before 96 other bytes are combined, when run forward or backward - // For every input bit, - // Two inputs differing in just that input bit - // Where "differ" means xor or subtraction - // And the base value is random - // When run forward or backwards one Mix - // I tried 3 pairs of each; they all differed by at least 212 bits. - // - static INLINE void Mix( - const uint64 *data, - uint64 &s0, uint64 &s1, uint64 &s2, uint64 &s3, - uint64 &s4, uint64 &s5, uint64 &s6, uint64 &s7, - uint64 &s8, uint64 &s9, uint64 &s10,uint64 &s11) - { - s0 += data[0]; s2 ^= s10; s11 ^= s0; s0 = Rot64(s0,11); s11 += s1; - s1 += data[1]; s3 ^= s11; s0 ^= s1; s1 = Rot64(s1,32); s0 += s2; - s2 += data[2]; s4 ^= s0; s1 ^= s2; s2 = Rot64(s2,43); s1 += s3; - s3 += data[3]; s5 ^= s1; s2 ^= s3; s3 = Rot64(s3,31); s2 += s4; - s4 += data[4]; s6 ^= s2; s3 ^= s4; s4 = Rot64(s4,17); s3 += s5; - s5 += data[5]; s7 ^= s3; s4 ^= s5; s5 = Rot64(s5,28); s4 += s6; - s6 += data[6]; s8 ^= s4; s5 ^= s6; s6 = Rot64(s6,39); s5 += s7; - s7 += data[7]; s9 ^= s5; s6 ^= s7; s7 = Rot64(s7,57); s6 += s8; - s8 += data[8]; s10 ^= s6; s7 ^= s8; s8 = Rot64(s8,55); s7 += s9; - s9 += data[9]; s11 ^= s7; s8 ^= s9; s9 = Rot64(s9,54); s8 += s10; - s10 += data[10]; s0 ^= s8; s9 ^= s10; s10 = Rot64(s10,22); s9 += s11; - s11 += data[11]; s1 ^= s9; s10 ^= s11; s11 = Rot64(s11,46); s10 += s0; - } - - // - // Mix all 12 inputs together so that h0, h1 are a hash of them all. - // - // For two inputs differing in just the input bits - // Where "differ" means xor or subtraction - // And the base value is random, or a counting value starting at that bit - // The final result will have each bit of h0, h1 flip - // For every input bit, - // with probability 50 +- .3% - // For every pair of input bits, - // with probability 50 +- 3% - // - // This does not rely on the last Mix() call having already mixed some. - // Two iterations was almost good enough for a 64-bit result, but a - // 128-bit result is reported, so End() does three iterations. - // - static INLINE void EndPartial( - uint64 &h0, uint64 &h1, uint64 &h2, uint64 &h3, - uint64 &h4, uint64 &h5, uint64 &h6, uint64 &h7, - uint64 &h8, uint64 &h9, uint64 &h10,uint64 &h11) - { - h11+= h1; h2 ^= h11; h1 = Rot64(h1,44); - h0 += h2; h3 ^= h0; h2 = Rot64(h2,15); - h1 += h3; h4 ^= h1; h3 = Rot64(h3,34); - h2 += h4; h5 ^= h2; h4 = Rot64(h4,21); - h3 += h5; h6 ^= h3; h5 = Rot64(h5,38); - h4 += h6; h7 ^= h4; h6 = Rot64(h6,33); - h5 += h7; h8 ^= h5; h7 = Rot64(h7,10); - h6 += h8; h9 ^= h6; h8 = Rot64(h8,13); - h7 += h9; h10^= h7; h9 = Rot64(h9,38); - h8 += h10; h11^= h8; h10= Rot64(h10,53); - h9 += h11; h0 ^= h9; h11= Rot64(h11,42); - h10+= h0; h1 ^= h10; h0 = Rot64(h0,54); - } - - static INLINE void End( - const uint64 *data, - uint64 &h0, uint64 &h1, uint64 &h2, uint64 &h3, - uint64 &h4, uint64 &h5, uint64 &h6, uint64 &h7, - uint64 &h8, uint64 &h9, uint64 &h10,uint64 &h11) - { - h0 += data[0]; h1 += data[1]; h2 += data[2]; h3 += data[3]; - h4 += data[4]; h5 += data[5]; h6 += data[6]; h7 += data[7]; - h8 += data[8]; h9 += data[9]; h10 += data[10]; h11 += data[11]; - EndPartial(h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - EndPartial(h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - EndPartial(h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); - } - - // - // The goal is for each bit of the input to expand into 128 bits of - // apparent entropy before it is fully overwritten. - // n trials both set and cleared at least m bits of h0 h1 h2 h3 - // n: 2 m: 29 - // n: 3 m: 46 - // n: 4 m: 57 - // n: 5 m: 107 - // n: 6 m: 146 - // n: 7 m: 152 - // when run forwards or backwards - // for all 1-bit and 2-bit diffs - // with diffs defined by either xor or subtraction - // with a base of all zeros plus a counter, or plus another bit, or random - // - static INLINE void ShortMix(uint64 &h0, uint64 &h1, uint64 &h2, uint64 &h3) - { - h2 = Rot64(h2,50); h2 += h3; h0 ^= h2; - h3 = Rot64(h3,52); h3 += h0; h1 ^= h3; - h0 = Rot64(h0,30); h0 += h1; h2 ^= h0; - h1 = Rot64(h1,41); h1 += h2; h3 ^= h1; - h2 = Rot64(h2,54); h2 += h3; h0 ^= h2; - h3 = Rot64(h3,48); h3 += h0; h1 ^= h3; - h0 = Rot64(h0,38); h0 += h1; h2 ^= h0; - h1 = Rot64(h1,37); h1 += h2; h3 ^= h1; - h2 = Rot64(h2,62); h2 += h3; h0 ^= h2; - h3 = Rot64(h3,34); h3 += h0; h1 ^= h3; - h0 = Rot64(h0,5); h0 += h1; h2 ^= h0; - h1 = Rot64(h1,36); h1 += h2; h3 ^= h1; - } - - // - // Mix all 4 inputs together so that h0, h1 are a hash of them all. - // - // For two inputs differing in just the input bits - // Where "differ" means xor or subtraction - // And the base value is random, or a counting value starting at that bit - // The final result will have each bit of h0, h1 flip - // For every input bit, - // with probability 50 +- .3% (it is probably better than that) - // For every pair of input bits, - // with probability 50 +- .75% (the worst case is approximately that) - // - static INLINE void ShortEnd(uint64 &h0, uint64 &h1, uint64 &h2, uint64 &h3) - { - h3 ^= h2; h2 = Rot64(h2,15); h3 += h2; - h0 ^= h3; h3 = Rot64(h3,52); h0 += h3; - h1 ^= h0; h0 = Rot64(h0,26); h1 += h0; - h2 ^= h1; h1 = Rot64(h1,51); h2 += h1; - h3 ^= h2; h2 = Rot64(h2,28); h3 += h2; - h0 ^= h3; h3 = Rot64(h3,9); h0 += h3; - h1 ^= h0; h0 = Rot64(h0,47); h1 += h0; - h2 ^= h1; h1 = Rot64(h1,54); h2 += h1; - h3 ^= h2; h2 = Rot64(h2,32); h3 += h2; - h0 ^= h3; h3 = Rot64(h3,25); h0 += h3; - h1 ^= h0; h0 = Rot64(h0,63); h1 += h0; - } - -private: - - // - // Short is used for messages under 192 bytes in length - // Short has a low startup cost, the normal mode is good for long - // keys, the cost crossover is at about 192 bytes. The two modes were - // held to the same quality bar. - // - static void Short( - const void *message, // message (array of bytes, not necessarily aligned) - size_t length, // length of message (in bytes) - uint64 *hash1, // in/out: in the seed, out the hash value - uint64 *hash2); // in/out: in the seed, out the hash value - - // number of uint64's in internal state - static const size_t sc_numVars = 12; - - // size of the internal state - static const size_t sc_blockSize = sc_numVars*8; - - // size of buffer of unhashed data, in bytes - static const size_t sc_bufSize = 2*sc_blockSize; - - // - // sc_const: a constant which: - // * is not zero - // * is odd - // * is a not-very-regular mix of 1's and 0's - // * does not need any other special mathematical properties - // - static const uint64 sc_const = 0xdeadbeefdeadbeefUL; - - uint64 m_data[2*sc_numVars]; // unhashed data, for partial messages - uint64 m_state[sc_numVars]; // internal state of the hash - size_t m_length; // total length of the input so far - uint8 m_remainder; // length of unhashed data stashed in m_data -}; - -#endif // BEAST_SPOOKYV2_H_INCLUDED diff --git a/beast/hash/impl/xxhash.c b/beast/hash/impl/xxhash.c deleted file mode 100644 index 7d5f6f2244..0000000000 --- a/beast/hash/impl/xxhash.c +++ /dev/null @@ -1,934 +0,0 @@ -/* -xxHash - Fast Hash algorithm -Copyright (C) 2012-2014, Yann Collet. -BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -* Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -You can contact the author at : -- xxHash source repository : http://code.google.com/p/xxhash/ -- public discussion board : https://groups.google.com/forum/#!forum/lz4c -*/ - -#include - -//************************************** -// Tuning parameters -//************************************** -// Unaligned memory access is automatically enabled for "common" CPU, such as x86. -// For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected. -// If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance. -// You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32). -#if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) -# define XXH_USE_UNALIGNED_ACCESS 1 -#endif - -// XXH_ACCEPT_NULL_INPUT_POINTER : -// If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer. -// When this option is enabled, xxHash output for null input pointers will be the same as a null-length input. -// This option has a very small performance cost (only measurable on small inputs). -// By default, this option is disabled. To enable it, uncomment below define : -// #define XXH_ACCEPT_NULL_INPUT_POINTER 1 - -// XXH_FORCE_NATIVE_FORMAT : -// By default, xxHash library provides endian-independant Hash values, based on little-endian convention. -// Results are therefore identical for little-endian and big-endian CPU. -// This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. -// Should endian-independance be of no importance for your application, you may set the #define below to 1. -// It will improve speed for Big-endian CPU. -// This option has no impact on Little_Endian CPU. -#define XXH_FORCE_NATIVE_FORMAT 0 - -//************************************** -// Compiler Specific Options -//************************************** -// Disable some Visual warning messages -#ifdef _MSC_VER // Visual Studio -# pragma warning(disable : 4127) // disable: C4127: conditional expression is constant -#endif - -#ifdef _MSC_VER // Visual Studio -# define FORCE_INLINE static __forceinline -#else -# ifdef __GNUC__ -# define FORCE_INLINE static inline __attribute__((always_inline)) -# else -# define FORCE_INLINE static inline -# endif -#endif - -//************************************** -// Includes & Memory related functions -//************************************** -//#include "xxhash.h" -// Modify the local functions below should you wish to use some other memory routines -// for malloc(), free() -#include -static void* XXH_malloc(size_t s) { return malloc(s); } -static void XXH_free (void* p) { free(p); } -// for memcpy() -#include -static void* XXH_memcpy(void* dest, const void* src, size_t size) -{ - return memcpy(dest,src,size); -} - - -//************************************** -// Basic Types -//************************************** -#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L // C99 -# include -typedef uint8_t BYTE; -typedef uint16_t U16; -typedef uint32_t U32; -typedef int32_t S32; -typedef uint64_t U64; -#else -typedef unsigned char BYTE; -typedef unsigned short U16; -typedef unsigned int U32; -typedef signed int S32; -typedef unsigned long long U64; -#endif - -#if defined(__GNUC__) && !defined(XXH_USE_UNALIGNED_ACCESS) -# define _PACKED __attribute__ ((packed)) -#else -# define _PACKED -#endif - -#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) -# ifdef __IBMC__ -# pragma pack(1) -# else -# pragma pack(push, 1) -# endif -#endif - -namespace beast { -namespace detail { - -typedef struct _U32_S -{ - U32 v; -} _PACKED U32_S; -typedef struct _U64_S -{ - U64 v; -} _PACKED U64_S; - -#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) -# pragma pack(pop) -#endif - -#define A32(x) (((U32_S *)(x))->v) -#define A64(x) (((U64_S *)(x))->v) - - -//*************************************** -// Compiler-specific Functions and Macros -//*************************************** -#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) - -// Note : although _rotl exists for minGW (GCC under windows), performance seems poor -#if defined(_MSC_VER) -# define XXH_rotl32(x,r) _rotl(x,r) -# define XXH_rotl64(x,r) _rotl64(x,r) -#else -# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) -# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) -#endif - -#if defined(_MSC_VER) // Visual Studio -# define XXH_swap32 _byteswap_ulong -# define XXH_swap64 _byteswap_uint64 -#elif GCC_VERSION >= 403 -# define XXH_swap32 __builtin_bswap32 -# define XXH_swap64 __builtin_bswap64 -#else -static inline U32 XXH_swap32 (U32 x) -{ - return ((x << 24) & 0xff000000 ) | - ((x << 8) & 0x00ff0000 ) | - ((x >> 8) & 0x0000ff00 ) | - ((x >> 24) & 0x000000ff ); -} -static inline U64 XXH_swap64 (U64 x) -{ - return ((x << 56) & 0xff00000000000000ULL) | - ((x << 40) & 0x00ff000000000000ULL) | - ((x << 24) & 0x0000ff0000000000ULL) | - ((x << 8) & 0x000000ff00000000ULL) | - ((x >> 8) & 0x00000000ff000000ULL) | - ((x >> 24) & 0x0000000000ff0000ULL) | - ((x >> 40) & 0x000000000000ff00ULL) | - ((x >> 56) & 0x00000000000000ffULL); -} -#endif - - -//************************************** -// Constants -//************************************** -#define PRIME32_1 2654435761U -#define PRIME32_2 2246822519U -#define PRIME32_3 3266489917U -#define PRIME32_4 668265263U -#define PRIME32_5 374761393U - -#define PRIME64_1 11400714785074694791ULL -#define PRIME64_2 14029467366897019727ULL -#define PRIME64_3 1609587929392839161ULL -#define PRIME64_4 9650029242287828579ULL -#define PRIME64_5 2870177450012600261ULL - -//************************************** -// Architecture Macros -//************************************** -typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; -#ifndef XXH_CPU_LITTLE_ENDIAN // It is possible to define XXH_CPU_LITTLE_ENDIAN externally, for example using a compiler switch -static const int one = 1; -# define XXH_CPU_LITTLE_ENDIAN (*(char*)(&one)) -#endif - - -//************************************** -// Macros -//************************************** -#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(!!(c)) }; } // use only *after* variable declarations - - -//**************************** -// Memory reads -//**************************** -typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; - -FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align) -{ - if (align==XXH_unaligned) - return endian==XXH_littleEndian ? A32(ptr) : XXH_swap32(A32(ptr)); - else - return endian==XXH_littleEndian ? *(U32*)ptr : XXH_swap32(*(U32*)ptr); -} - -FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian) -{ - return XXH_readLE32_align(ptr, endian, XXH_unaligned); -} - -FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align) -{ - if (align==XXH_unaligned) - return endian==XXH_littleEndian ? A64(ptr) : XXH_swap64(A64(ptr)); - else - return endian==XXH_littleEndian ? *(U64*)ptr : XXH_swap64(*(U64*)ptr); -} - -FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian) -{ - return XXH_readLE64_align(ptr, endian, XXH_unaligned); -} - - -//**************************** -// Simple Hash Functions -//**************************** -FORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* bEnd = p + len; - U32 h32; -#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align) - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (p==NULL) - { - len=0; - bEnd=p=(const BYTE*)(size_t)16; - } -#endif - - if (len>=16) - { - const BYTE* const limit = bEnd - 16; - U32 v1 = seed + PRIME32_1 + PRIME32_2; - U32 v2 = seed + PRIME32_2; - U32 v3 = seed + 0; - U32 v4 = seed - PRIME32_1; - - do - { - v1 += XXH_get32bits(p) * PRIME32_2; - v1 = XXH_rotl32(v1, 13); - v1 *= PRIME32_1; - p+=4; - v2 += XXH_get32bits(p) * PRIME32_2; - v2 = XXH_rotl32(v2, 13); - v2 *= PRIME32_1; - p+=4; - v3 += XXH_get32bits(p) * PRIME32_2; - v3 = XXH_rotl32(v3, 13); - v3 *= PRIME32_1; - p+=4; - v4 += XXH_get32bits(p) * PRIME32_2; - v4 = XXH_rotl32(v4, 13); - v4 *= PRIME32_1; - p+=4; - } - while (p<=limit); - - h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); - } - else - { - h32 = seed + PRIME32_5; - } - - h32 += (U32) len; - - while (p+4<=bEnd) - { - h32 += XXH_get32bits(p) * PRIME32_3; - h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; - p+=4; - } - - while (p> 15; - h32 *= PRIME32_2; - h32 ^= h32 >> 13; - h32 *= PRIME32_3; - h32 ^= h32 >> 16; - - return h32; -} - - -unsigned int XXH32 (const void* input, size_t len, unsigned seed) -{ -#if 0 - // Simple version, good for code maintenance, but unfortunately slow for small inputs - XXH32_state_t state; - XXH32_reset(&state, seed); - XXH32_update(&state, input, len); - return XXH32_digest(&state); -#else - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - -# if !defined(XXH_USE_UNALIGNED_ACCESS) - if ((((size_t)input) & 3) == 0) // Input is aligned, let's leverage the speed advantage - { - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); - else - return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); - } -# endif - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); - else - return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); -#endif -} - -FORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* bEnd = p + len; - U64 h64; -#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align) - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (p==NULL) - { - len=0; - bEnd=p=(const BYTE*)(size_t)32; - } -#endif - - if (len>=32) - { - const BYTE* const limit = bEnd - 32; - U64 v1 = seed + PRIME64_1 + PRIME64_2; - U64 v2 = seed + PRIME64_2; - U64 v3 = seed + 0; - U64 v4 = seed - PRIME64_1; - - do - { - v1 += XXH_get64bits(p) * PRIME64_2; - p+=8; - v1 = XXH_rotl64(v1, 31); - v1 *= PRIME64_1; - v2 += XXH_get64bits(p) * PRIME64_2; - p+=8; - v2 = XXH_rotl64(v2, 31); - v2 *= PRIME64_1; - v3 += XXH_get64bits(p) * PRIME64_2; - p+=8; - v3 = XXH_rotl64(v3, 31); - v3 *= PRIME64_1; - v4 += XXH_get64bits(p) * PRIME64_2; - p+=8; - v4 = XXH_rotl64(v4, 31); - v4 *= PRIME64_1; - } - while (p<=limit); - - h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); - - v1 *= PRIME64_2; - v1 = XXH_rotl64(v1, 31); - v1 *= PRIME64_1; - h64 ^= v1; - h64 = h64 * PRIME64_1 + PRIME64_4; - - v2 *= PRIME64_2; - v2 = XXH_rotl64(v2, 31); - v2 *= PRIME64_1; - h64 ^= v2; - h64 = h64 * PRIME64_1 + PRIME64_4; - - v3 *= PRIME64_2; - v3 = XXH_rotl64(v3, 31); - v3 *= PRIME64_1; - h64 ^= v3; - h64 = h64 * PRIME64_1 + PRIME64_4; - - v4 *= PRIME64_2; - v4 = XXH_rotl64(v4, 31); - v4 *= PRIME64_1; - h64 ^= v4; - h64 = h64 * PRIME64_1 + PRIME64_4; - } - else - { - h64 = seed + PRIME64_5; - } - - h64 += (U64) len; - - while (p+8<=bEnd) - { - U64 k1 = XXH_get64bits(p); - k1 *= PRIME64_2; - k1 = XXH_rotl64(k1,31); - k1 *= PRIME64_1; - h64 ^= k1; - h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; - p+=8; - } - - if (p+4<=bEnd) - { - h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; - h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; - p+=4; - } - - while (p> 33; - h64 *= PRIME64_2; - h64 ^= h64 >> 29; - h64 *= PRIME64_3; - h64 ^= h64 >> 32; - - return h64; -} - - -unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed) -{ -#if 0 - // Simple version, good for code maintenance, but unfortunately slow for small inputs - XXH64_state_t state; - XXH64_reset(&state, seed); - XXH64_update(&state, input, len); - return XXH64_digest(&state); -#else - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - -# if !defined(XXH_USE_UNALIGNED_ACCESS) - if ((((size_t)input) & 7)==0) // Input is aligned, let's leverage the speed advantage - { - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); - else - return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); - } -# endif - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); - else - return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); -#endif -} - -/**************************************************** - * Advanced Hash Functions -****************************************************/ - -/*** Allocation ***/ -typedef struct -{ - U64 total_len; - U32 seed; - U32 v1; - U32 v2; - U32 v3; - U32 v4; - U32 mem32[4]; /* defined as U32 for alignment */ - U32 memsize; -} XXH_istate32_t; - -typedef struct -{ - U64 total_len; - U64 seed; - U64 v1; - U64 v2; - U64 v3; - U64 v4; - U64 mem64[4]; /* defined as U64 for alignment */ - U32 memsize; -} XXH_istate64_t; - - -XXH32_state_t* XXH32_createState(void) -{ - static_assert(sizeof(XXH32_state_t) >= sizeof(XXH_istate32_t), ""); // A compilation error here means XXH32_state_t is not large enough - return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); -} -XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) -{ - XXH_free(statePtr); - return XXH_OK; -}; - -XXH64_state_t* XXH64_createState(void) -{ - static_assert(sizeof(XXH64_state_t) >= sizeof(XXH_istate64_t), ""); // A compilation error here means XXH64_state_t is not large enough - return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); -} -XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) -{ - XXH_free(statePtr); - return XXH_OK; -}; - - -/*** Hash feed ***/ - -XXH_errorcode XXH32_reset(XXH32_state_t* state_in, U32 seed) -{ - XXH_istate32_t* state = (XXH_istate32_t*) state_in; - state->seed = seed; - state->v1 = seed + PRIME32_1 + PRIME32_2; - state->v2 = seed + PRIME32_2; - state->v3 = seed + 0; - state->v4 = seed - PRIME32_1; - state->total_len = 0; - state->memsize = 0; - return XXH_OK; -} - -XXH_errorcode XXH64_reset(XXH64_state_t* state_in, unsigned long long seed) -{ - XXH_istate64_t* state = (XXH_istate64_t*) state_in; - state->seed = seed; - state->v1 = seed + PRIME64_1 + PRIME64_2; - state->v2 = seed + PRIME64_2; - state->v3 = seed + 0; - state->v4 = seed - PRIME64_1; - state->total_len = 0; - state->memsize = 0; - return XXH_OK; -} - - -FORCE_INLINE XXH_errorcode XXH32_update_endian (XXH32_state_t* state_in, const void* input, size_t len, XXH_endianess endian) -{ - XXH_istate32_t* state = (XXH_istate32_t *) state_in; - const BYTE* p = (const BYTE*)input; - const BYTE* const bEnd = p + len; - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (input==NULL) return XXH_ERROR; -#endif - - state->total_len += len; - - if (state->memsize + len < 16) // fill in tmp buffer - { - XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len); - state->memsize += (U32)len; - return XXH_OK; - } - - if (state->memsize) // some data left from previous update - { - XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize); - { - const U32* p32 = state->mem32; - state->v1 += XXH_readLE32(p32, endian) * PRIME32_2; - state->v1 = XXH_rotl32(state->v1, 13); - state->v1 *= PRIME32_1; - p32++; - state->v2 += XXH_readLE32(p32, endian) * PRIME32_2; - state->v2 = XXH_rotl32(state->v2, 13); - state->v2 *= PRIME32_1; - p32++; - state->v3 += XXH_readLE32(p32, endian) * PRIME32_2; - state->v3 = XXH_rotl32(state->v3, 13); - state->v3 *= PRIME32_1; - p32++; - state->v4 += XXH_readLE32(p32, endian) * PRIME32_2; - state->v4 = XXH_rotl32(state->v4, 13); - state->v4 *= PRIME32_1; - p32++; - } - p += 16-state->memsize; - state->memsize = 0; - } - - if (p <= bEnd-16) - { - const BYTE* const limit = bEnd - 16; - U32 v1 = state->v1; - U32 v2 = state->v2; - U32 v3 = state->v3; - U32 v4 = state->v4; - - do - { - v1 += XXH_readLE32(p, endian) * PRIME32_2; - v1 = XXH_rotl32(v1, 13); - v1 *= PRIME32_1; - p+=4; - v2 += XXH_readLE32(p, endian) * PRIME32_2; - v2 = XXH_rotl32(v2, 13); - v2 *= PRIME32_1; - p+=4; - v3 += XXH_readLE32(p, endian) * PRIME32_2; - v3 = XXH_rotl32(v3, 13); - v3 *= PRIME32_1; - p+=4; - v4 += XXH_readLE32(p, endian) * PRIME32_2; - v4 = XXH_rotl32(v4, 13); - v4 *= PRIME32_1; - p+=4; - } - while (p<=limit); - - state->v1 = v1; - state->v2 = v2; - state->v3 = v3; - state->v4 = v4; - } - - if (p < bEnd) - { - XXH_memcpy(state->mem32, p, bEnd-p); - state->memsize = (int)(bEnd-p); - } - - return XXH_OK; -} - -XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_update_endian(state_in, input, len, XXH_littleEndian); - else - return XXH32_update_endian(state_in, input, len, XXH_bigEndian); -} - - - -FORCE_INLINE U32 XXH32_digest_endian (const XXH32_state_t* state_in, XXH_endianess endian) -{ - XXH_istate32_t* state = (XXH_istate32_t*) state_in; - const BYTE * p = (const BYTE*)state->mem32; - BYTE* bEnd = (BYTE*)(state->mem32) + state->memsize; - U32 h32; - - if (state->total_len >= 16) - { - h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); - } - else - { - h32 = state->seed + PRIME32_5; - } - - h32 += (U32) state->total_len; - - while (p+4<=bEnd) - { - h32 += XXH_readLE32(p, endian) * PRIME32_3; - h32 = XXH_rotl32(h32, 17) * PRIME32_4; - p+=4; - } - - while (p> 15; - h32 *= PRIME32_2; - h32 ^= h32 >> 13; - h32 *= PRIME32_3; - h32 ^= h32 >> 16; - - return h32; -} - - -U32 XXH32_digest (const XXH32_state_t* state_in) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_digest_endian(state_in, XXH_littleEndian); - else - return XXH32_digest_endian(state_in, XXH_bigEndian); -} - - -FORCE_INLINE XXH_errorcode XXH64_update_endian (XXH64_state_t* state_in, const void* input, size_t len, XXH_endianess endian) -{ - XXH_istate64_t * state = (XXH_istate64_t *) state_in; - const BYTE* p = (const BYTE*)input; - const BYTE* const bEnd = p + len; - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (input==NULL) return XXH_ERROR; -#endif - - state->total_len += len; - - if (state->memsize + len < 32) // fill in tmp buffer - { - XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len); - state->memsize += (U32)len; - return XXH_OK; - } - - if (state->memsize) // some data left from previous update - { - XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize); - { - const U64* p64 = state->mem64; - state->v1 += XXH_readLE64(p64, endian) * PRIME64_2; - state->v1 = XXH_rotl64(state->v1, 31); - state->v1 *= PRIME64_1; - p64++; - state->v2 += XXH_readLE64(p64, endian) * PRIME64_2; - state->v2 = XXH_rotl64(state->v2, 31); - state->v2 *= PRIME64_1; - p64++; - state->v3 += XXH_readLE64(p64, endian) * PRIME64_2; - state->v3 = XXH_rotl64(state->v3, 31); - state->v3 *= PRIME64_1; - p64++; - state->v4 += XXH_readLE64(p64, endian) * PRIME64_2; - state->v4 = XXH_rotl64(state->v4, 31); - state->v4 *= PRIME64_1; - p64++; - } - p += 32-state->memsize; - state->memsize = 0; - } - - if (p+32 <= bEnd) - { - const BYTE* const limit = bEnd - 32; - U64 v1 = state->v1; - U64 v2 = state->v2; - U64 v3 = state->v3; - U64 v4 = state->v4; - - do - { - v1 += XXH_readLE64(p, endian) * PRIME64_2; - v1 = XXH_rotl64(v1, 31); - v1 *= PRIME64_1; - p+=8; - v2 += XXH_readLE64(p, endian) * PRIME64_2; - v2 = XXH_rotl64(v2, 31); - v2 *= PRIME64_1; - p+=8; - v3 += XXH_readLE64(p, endian) * PRIME64_2; - v3 = XXH_rotl64(v3, 31); - v3 *= PRIME64_1; - p+=8; - v4 += XXH_readLE64(p, endian) * PRIME64_2; - v4 = XXH_rotl64(v4, 31); - v4 *= PRIME64_1; - p+=8; - } - while (p<=limit); - - state->v1 = v1; - state->v2 = v2; - state->v3 = v3; - state->v4 = v4; - } - - if (p < bEnd) - { - XXH_memcpy(state->mem64, p, bEnd-p); - state->memsize = (int)(bEnd-p); - } - - return XXH_OK; -} - -XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_update_endian(state_in, input, len, XXH_littleEndian); - else - return XXH64_update_endian(state_in, input, len, XXH_bigEndian); -} - - - -FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state_in, XXH_endianess endian) -{ - XXH_istate64_t * state = (XXH_istate64_t *) state_in; - const BYTE * p = (const BYTE*)state->mem64; - BYTE* bEnd = (BYTE*)state->mem64 + state->memsize; - U64 h64; - - if (state->total_len >= 32) - { - U64 v1 = state->v1; - U64 v2 = state->v2; - U64 v3 = state->v3; - U64 v4 = state->v4; - - h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); - - v1 *= PRIME64_2; - v1 = XXH_rotl64(v1, 31); - v1 *= PRIME64_1; - h64 ^= v1; - h64 = h64*PRIME64_1 + PRIME64_4; - - v2 *= PRIME64_2; - v2 = XXH_rotl64(v2, 31); - v2 *= PRIME64_1; - h64 ^= v2; - h64 = h64*PRIME64_1 + PRIME64_4; - - v3 *= PRIME64_2; - v3 = XXH_rotl64(v3, 31); - v3 *= PRIME64_1; - h64 ^= v3; - h64 = h64*PRIME64_1 + PRIME64_4; - - v4 *= PRIME64_2; - v4 = XXH_rotl64(v4, 31); - v4 *= PRIME64_1; - h64 ^= v4; - h64 = h64*PRIME64_1 + PRIME64_4; - } - else - { - h64 = state->seed + PRIME64_5; - } - - h64 += (U64) state->total_len; - - while (p+8<=bEnd) - { - U64 k1 = XXH_readLE64(p, endian); - k1 *= PRIME64_2; - k1 = XXH_rotl64(k1,31); - k1 *= PRIME64_1; - h64 ^= k1; - h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; - p+=8; - } - - if (p+4<=bEnd) - { - h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1; - h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; - p+=4; - } - - while (p> 33; - h64 *= PRIME64_2; - h64 ^= h64 >> 29; - h64 *= PRIME64_3; - h64 ^= h64 >> 32; - - return h64; -} - - -unsigned long long XXH64_digest (const XXH64_state_t* state_in) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_digest_endian(state_in, XXH_littleEndian); - else - return XXH64_digest_endian(state_in, XXH_bigEndian); -} - - -} // detail -} // beast diff --git a/beast/hash/impl/xxhash.h b/beast/hash/impl/xxhash.h deleted file mode 100644 index 4281f746a9..0000000000 --- a/beast/hash/impl/xxhash.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - xxHash - Extremely Fast Hash algorithm - Header File - Copyright (C) 2012-2014, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - xxHash source repository : http://code.google.com/p/xxhash/ -*/ - -/* Notice extracted from xxHash homepage : - -xxHash is an extremely fast Hash algorithm, running at RAM speed limits. -It also successfully passes all tests from the SMHasher suite. - -Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) - -Name Speed Q.Score Author -xxHash 5.4 GB/s 10 -CrapWow 3.2 GB/s 2 Andrew -MumurHash 3a 2.7 GB/s 10 Austin Appleby -SpookyHash 2.0 GB/s 10 Bob Jenkins -SBox 1.4 GB/s 9 Bret Mulvey -Lookup3 1.2 GB/s 9 Bob Jenkins -SuperFastHash 1.2 GB/s 1 Paul Hsieh -CityHash64 1.05 GB/s 10 Pike & Alakuijala -FNV 0.55 GB/s 5 Fowler, Noll, Vo -CRC32 0.43 GB/s 9 -MD5-32 0.33 GB/s 10 Ronald L. Rivest -SHA1-32 0.28 GB/s 10 - -Q.Score is a measure of quality of the hash function. -It depends on successfully passing SMHasher test set. -10 is a perfect score. -*/ - -#ifndef BEAST_HASH_XXHASH_H_INCLUDED -#define BEAST_HASH_XXHASH_H_INCLUDED - -/***************************** - Includes -*****************************/ -#include /* size_t */ - -namespace beast { -namespace detail { - -/***************************** - Type -*****************************/ -typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; - - - -/***************************** - Simple Hash Functions -*****************************/ - -unsigned int XXH32 (const void* input, size_t length, unsigned seed); -unsigned long long XXH64 (const void* input, size_t length, unsigned long long seed); - -/* -XXH32() : - Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input". - The memory between input & input+length must be valid (allocated and read-accessible). - "seed" can be used to alter the result predictably. - This function successfully passes all SMHasher tests. - Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s -XXH64() : - Calculate the 64-bits hash of sequence of length "len" stored at memory address "input". -*/ - - - -/***************************** - Advanced Hash Functions -*****************************/ -typedef struct { long long ll[ 6]; } XXH32_state_t; -typedef struct { long long ll[11]; } XXH64_state_t; - -/* -These structures allow static allocation of XXH states. -States must then be initialized using XXHnn_reset() before first use. - -If you prefer dynamic allocation, please refer to functions below. -*/ - -XXH32_state_t* XXH32_createState(void); -XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); - -XXH64_state_t* XXH64_createState(void); -XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); - -/* -These functions create and release memory for XXH state. -States must then be initialized using XXHnn_reset() before first use. -*/ - - -XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned seed); -XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); -unsigned int XXH32_digest (const XXH32_state_t* statePtr); - -XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed); -XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length); -unsigned long long XXH64_digest (const XXH64_state_t* statePtr); - -/* -These functions calculate the xxHash of an input provided in multiple smaller packets, -as opposed to an input provided as a single block. - -XXH state space must first be allocated, using either static or dynamic method provided above. - -Start a new hash by initializing state with a seed, using XXHnn_reset(). - -Then, feed the hash state by calling XXHnn_update() as many times as necessary. -Obviously, input must be valid, meaning allocated and read accessible. -The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. - -Finally, you can produce a hash anytime, by using XXHnn_digest(). -This function returns the final nn-bits hash. -You can nonetheless continue feeding the hash state with more input, -and therefore get some new hashes, by calling again XXHnn_digest(). - -When you are done, don't forget to free XXH state space, using typically XXHnn_freeState(). -*/ - -} // detail -} // beast - -#endif diff --git a/beast/hash/meta.h b/beast/hash/meta.h deleted file mode 100644 index 2aaa65b41a..0000000000 --- a/beast/hash/meta.h +++ /dev/null @@ -1,140 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HASH_META_H_INCLUDED -#define BEAST_HASH_META_H_INCLUDED - -#include - -namespace beast { - -template struct static_and; - -template -struct static_and - : public std::integral_constant < - bool, b0 && static_and::value> -{ -}; - -template <> -struct static_and<> - : public std::true_type -{ -}; - -static_assert( static_and::value, ""); -static_assert(!static_and::value, ""); - -template -struct static_sum; - -template -struct static_sum - : public std::integral_constant < - std::size_t, s0 + static_sum::value> -{ -}; - -template <> -struct static_sum<> - : public std::integral_constant -{ -}; - -static_assert(static_sum<5, 2, 17, 0>::value == 24, ""); - -template -struct enable_if_lvalue - : public std::enable_if - < - std::is_same, U>::value && - std::is_lvalue_reference::value - > -{ -}; - -/** Ensure const reference function parameters are valid lvalues. - - Some functions, especially class constructors, accept const references and - store them for later use. If any of those parameters are rvalue objects, - the object will be freed as soon as the function returns. This could - potentially lead to a variety of "use after free" errors. - - If the function is rewritten as a template using this type and the - parameters references as rvalue references (eg. TX&&), a compiler - error will be generated if an rvalue is provided in the caller. - - @code - // Example: - struct X - { - }; - struct Y - { - }; - - struct Unsafe - { - Unsafe (X const& x, Y const& y) - : x_ (x) - , y_ (y) - { - } - - X const& x_; - Y const& y_; - }; - - struct Safe - { - template , - class = beast::enable_if_lvalue_t < TY, Y >> - Safe (TX&& x, TY&& y) - : x_ (x) - , y_ (y) - { - } - - X const& x_; - Y const& y_; - }; - - struct demo - { - void - createObjects () - { - X x {}; - Y const y {}; - Unsafe u1 (x, y); // ok - Unsafe u2 (X (), y); // compiles, but u2.x_ becomes invalid at the end of the line. - Safe s1 (x, y); // ok - // Safe s2 (X (), y); // compile-time error - } - }; - @endcode -*/ -template -using enable_if_lvalue_t = typename enable_if_lvalue::type; - -} // beast - -#endif // BEAST_UTILITY_META_H_INCLUDED diff --git a/beast/hash/siphash.h b/beast/hash/siphash.h deleted file mode 100644 index e4a4b363fb..0000000000 --- a/beast/hash/siphash.h +++ /dev/null @@ -1,60 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant , - Vinnie Falco -#include - -namespace beast { - -// See https://131002.net/siphash/ -class siphash -{ -private: - std::uint64_t v0_ = 0x736f6d6570736575ULL; - std::uint64_t v1_ = 0x646f72616e646f6dULL; - std::uint64_t v2_ = 0x6c7967656e657261ULL; - std::uint64_t v3_ = 0x7465646279746573ULL; - unsigned char buf_[8]; - unsigned bufsize_ = 0; - unsigned total_length_ = 0; - -public: - using result_type = std::size_t; - - static beast::endian const endian = beast::endian::native; - - siphash() = default; - - explicit - siphash (std::uint64_t k0, std::uint64_t k1 = 0) noexcept; - - void - operator() (void const* key, std::size_t len) noexcept; - - explicit - operator std::size_t() noexcept; -}; - -} // beast - -#endif diff --git a/beast/hash/spooky.h b/beast/hash/spooky.h deleted file mode 100644 index 228517ddab..0000000000 --- a/beast/hash/spooky.h +++ /dev/null @@ -1,61 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant , - Vinnie Falco -#include - -namespace beast { - -// See http://burtleburtle.net/bob/hash/spooky.html -class spooky -{ -private: - SpookyHash state_; - -public: - using result_type = std::size_t; - static beast::endian const endian = beast::endian::native; - - spooky (std::size_t seed1 = 1, std::size_t seed2 = 2) noexcept - { - state_.Init (seed1, seed2); - } - - void - operator() (void const* key, std::size_t len) noexcept - { - state_.Update (key, len); - } - - explicit - operator std::size_t() noexcept - { - std::uint64_t h1, h2; - state_.Final (&h1, &h2); - return static_cast (h1); - } -}; - -} // beast - -#endif diff --git a/beast/hash/tests/hash_append_test.cpp b/beast/hash/tests/hash_append_test.cpp deleted file mode 100644 index 672082c7f2..0000000000 --- a/beast/hash/tests/hash_append_test.cpp +++ /dev/null @@ -1,490 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { - -template -class block_stream -{ -private: - Block m_block; - std::size_t m_size; - - std::size_t - needed() const noexcept - { - return sizeof(Block) - m_size; - } - - void* - tail() noexcept - { - return ((char *)&m_block) + m_size; - } - -protected: - void - finish() - { - if (m_size > 0) - { - // zero-pad - memset (tail(), 0, needed()); - static_cast (this)->process_block (m_block); - } - } - -public: - block_stream () - : m_size(0) - { - } - - void - operator() (void const* data, std::size_t bytes) noexcept - { - // handle leftovers - if (m_size > 0) - { - std::size_t const n (std::min (needed(), bytes)); - std::memcpy (tail(), data, n); - data = ((char const*)data) + n; - bytes -= n; - m_size += n; - - if (m_size < sizeof(Block)) - return; - - static_cast (this)->process_block (m_block); - } - - // loop over complete blocks - while (bytes >= sizeof(Block)) - { - m_block = *((Block const*)data); - static_cast (this)->process_block (m_block); - data = ((char const*)data) + sizeof(m_block); - bytes -= sizeof(m_block); - } - - // save leftovers - if (bytes > 0) - { - memcpy (tail(), data, bytes); - m_size += bytes; - } - } -}; - -//------------------------------------------------------------------------------ - -namespace hash_append_tests { - -template class fnv1a_imp; - -template <> -class fnv1a_imp<64> -{ -private: - std::uint64_t state_ = 14695981039346656037u; - -public: - static beast::endian const endian = beast::endian::native; - - void - operator() (void const* key, std::size_t len) noexcept - { - unsigned char const* p = static_cast(key); - unsigned char const* const e = p + len; - for (; p < e; ++p) - state_ = (state_ ^ *p) * 1099511628211u; - } - - explicit - operator std::size_t() noexcept - { - return state_; - } -}; - -template <> -class fnv1a_imp<32> -{ -private: - std::uint32_t state_ = 2166136261; - -public: - static beast::endian const endian = beast::endian::native; - - void - operator() (void const* key, std::size_t len) noexcept - { - unsigned char const* p = static_cast(key); - unsigned char const* const e = p + len; - for (; p < e; ++p) - state_ = (state_ ^ *p) * 16777619; - } - - explicit - operator std::size_t() noexcept - { - return state_; - } -}; - -class fnv1a - : public fnv1a_imp -{ -public: -}; - -class jenkins1 -{ -private: - std::size_t state_ = 0; - -public: - static beast::endian const endian = beast::endian::native; - - void - operator() (void const* key, std::size_t len) noexcept - { - unsigned char const* p = static_cast (key); - unsigned char const* const e = p + len; - for (; p < e; ++p) - { - state_ += *p; - state_ += state_ << 10; - state_ ^= state_ >> 6; - } - } - - explicit - operator std::size_t() noexcept - { - state_ += state_ << 3; - state_ ^= state_ >> 11; - state_ += state_ << 15; - return state_; - } -}; - -class spooky -{ -private: - SpookyHash state_; - -public: - static beast::endian const endian = beast::endian::native; - - spooky(std::size_t seed1 = 1, std::size_t seed2 = 2) noexcept - { - state_.Init(seed1, seed2); - } - - void - operator()(void const* key, std::size_t len) noexcept - { - state_.Update(key, len); - } - - explicit - operator std::size_t() noexcept - { - std::uint64_t h1, h2; - state_.Final(&h1, &h2); - return h1; - } - -}; - -template < - class PRNG = std::conditional_t < - sizeof(std::size_t)==sizeof(std::uint64_t), - std::mt19937_64, - std::mt19937 - > -> -class prng_hasher - : public block_stream > -{ -private: - std::size_t m_seed; - PRNG m_prng; - - using base = block_stream >; - friend base; - - // compress - void - process_block (std::size_t block) - { - m_prng.seed (m_seed + block); - m_seed = m_prng(); - } - -public: - prng_hasher (std::size_t seed = 0) - : m_seed (seed) - { - } - - void - operator() (void const* data, std::size_t bytes) noexcept - { - base::operator() (data, bytes); - } - - explicit - operator std::size_t() noexcept - { - base::finish(); - return m_seed; - } -}; - -class SlowKey -{ -private: - std::tuple date_; - std::vector > data_; - -public: - SlowKey() - { - static beast::xor_shift_engine eng; - std::uniform_int_distribution yeardata(1900, 2014); - std::uniform_int_distribution monthdata(1, 12); - std::uniform_int_distribution daydata(1, 28); - std::uniform_int_distribution veclen(0, 100); - std::uniform_int_distribution int1data(1, 10); - std::uniform_int_distribution int2data(-3, 5000); - std::get<0>(date_) = yeardata(eng); - std::get<1>(date_) = (unsigned char)monthdata(eng); - std::get<2>(date_) = (unsigned char)daydata(eng); - data_.resize(veclen(eng)); - for (auto& p : data_) - { - p.first = int1data(eng); - p.second = int2data(eng); - } - } - - // Hook into the system like this - template - friend - void - hash_append (Hasher& h, SlowKey const& x) noexcept - { - using beast::hash_append; - hash_append (h, x.date_, x.data_); - } - - friend - bool operator< (SlowKey const& x, SlowKey const& y) noexcept - { - return std::tie(x.date_, x.data_) < std::tie(y.date_, y.data_); - } - - // Hook into the std::system like this - friend struct std::hash; - friend struct X_fnv1a; -}; - -struct FastKey -{ -private: - std::array m_values; - -public: - FastKey() - { - static beast::xor_shift_engine eng; - for (auto& v : m_values) - v = eng(); - } - - friend - bool - operator< (FastKey const& x, FastKey const& y) noexcept - { - return x.m_values < y.m_values; - } -}; - -} // hash_append_tests - -//------------------------------------------------------------------------------ - -template -struct is_contiguously_hashable - : std::integral_constant, - HashAlgorithm>::value> -{ -}; - -//------------------------------------------------------------------------------ - -class hash_append_test : public unit_test::suite -{ -public: - using SlowKey = hash_append_tests::SlowKey; - using FastKey = hash_append_tests::FastKey; - - struct results_t - { - results_t() - : collision_factor (0) - , distribution_factor (0) - , elapsed (0) - { - } - - float collision_factor; - float distribution_factor; - float windowed_score; - std::chrono::milliseconds elapsed; - }; - - // Generate a set of keys - template - std::set - make_keys (std::size_t count) - { - std::set keys; - while (count--) - keys.emplace(); - return keys; - } - - // Generate a set of hashes from a container - template - std::vector - make_hashes (Keys const& keys) - { - std::vector hashes; - hashes.reserve (keys.size()); - for (auto const& key : keys) - { - Hasher h; - hash_append (h, key); - hashes.push_back (static_cast (h)); - } - return hashes; - } - - template - void - measure_hashes (results_t& results, Hashes const& hashes) - { - results.collision_factor = - hash_metrics::collision_factor ( - hashes.begin(), hashes.end()); - - results.distribution_factor = - hash_metrics::distribution_factor ( - hashes.begin(), hashes.end()); - - results.windowed_score = - hash_metrics::windowed_score ( - hashes.begin(), hashes.end()); - } - - template - void - measure_keys (results_t& results, Keys const& keys) - { - auto const start ( - std::chrono::high_resolution_clock::now()); - - auto const hashes (make_hashes (keys)); - - results.elapsed = std::chrono::duration_cast ( - std::chrono::high_resolution_clock::now() - start); - - measure_hashes (results, hashes); - } - - template - void - test_hasher (std::string const& name, std::size_t n) - { - results_t results; - auto const keys (make_keys (n)); - measure_keys (results, keys); - report (name, results); - } - - void - report (std::string const& name, results_t const& results) - { - log << - std::left << - std::setw (39) << name << " | " << - std::right << - std::setw (13) << std::setprecision (5) << - results.collision_factor << " | " << - std::setw (13) << std::setprecision (5) << - results.distribution_factor << " | " << - std::setw (13) << std::setprecision (5) << - results.windowed_score << " | " << - std::left << - results.elapsed.count(); - pass (); - } - - void - run() - { - log << - "name | collision | distribution | windowed | time (milliseconds)" << std::endl << - "----------------------------------------+---------------+---------------+---------------+--------------------"; - - //test_hasher , SlowKey> ("prng_hasher ", 10000); - //test_hasher , FastKey> ("prng_hasher ", 100000); - - test_hasher ("jenkins1 ", 1000000); - test_hasher ("spooky ", 1000000); - test_hasher ("fnv1a ", 1000000); - - test_hasher ("jenkins1 ", 1000000); - test_hasher ("spooky ", 1000000); - test_hasher ("fnv1a ", 1000000); - } -}; - -BEAST_DEFINE_TESTSUITE_MANUAL(hash_append,container,beast); - -} diff --git a/beast/hash/tests/hash_metrics.h b/beast/hash/tests/hash_metrics.h deleted file mode 100644 index 088cef3d63..0000000000 --- a/beast/hash/tests/hash_metrics.h +++ /dev/null @@ -1,200 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant , - Vinnie Falco -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace hash_metrics { - -// Metrics for measuring the quality of container hash functions - -/** Returns the fraction of duplicate items in the sequence. */ -template -float -collision_factor (FwdIter first, FwdIter last) -{ - std::set s (first, last); - return 1 - static_cast (s.size()) / std::distance (first, last); -} - -//------------------------------------------------------------------------------ - -/** Returns the deviation of the sequence from the ideal distribution. */ -template -float -distribution_factor (FwdIter first, FwdIter last) -{ - using value_type = typename FwdIter::value_type; - static_assert (std::is_unsigned ::value, ""); - - const unsigned nbits = CHAR_BIT * sizeof(std::size_t); - const unsigned rows = nbits / 4; - unsigned counts[rows][16] = {}; - std::for_each (first, last, [&](typename FwdIter::value_type h) - { - std::size_t mask = 0xF; - for (unsigned i = 0; i < rows; ++i, mask <<= 4) - counts[i][(h & mask) >> 4*i] += 1; - }); - float mean_rows[rows] = {0}; - float mean_cols[16] = {0}; - for (unsigned i = 0; i < rows; ++i) - { - for (unsigned j = 0; j < 16; ++j) - { - mean_rows[i] += counts[i][j]; - mean_cols[j] += counts[i][j]; - } - } - for (unsigned i = 0; i < rows; ++i) - mean_rows[i] /= 16; - for (unsigned j = 0; j < 16; ++j) - mean_cols[j] /= rows; - std::pair dev[rows][16]; - for (unsigned i = 0; i < rows; ++i) - { - for (unsigned j = 0; j < 16; ++j) - { - dev[i][j].first = std::abs(counts[i][j] - mean_rows[i]) / mean_rows[i]; - dev[i][j].second = std::abs(counts[i][j] - mean_cols[j]) / mean_cols[j]; - } - } - float max_err = 0; - for (unsigned i = 0; i < rows; ++i) - { - for (unsigned j = 0; j < 16; ++j) - { - if (max_err < dev[i][j].first) - max_err = dev[i][j].first; - if (max_err < dev[i][j].second) - max_err = dev[i][j].second; - } - } - return max_err; -} - -//------------------------------------------------------------------------------ - -namespace detail { - -template -inline -T -sqr(T t) -{ - return t*t; -} - -double -score (int const* bins, std::size_t const bincount, double const k) -{ - double const n = bincount; - // compute rms^2 value - double rms_sq = 0; - for(std::size_t i = 0; i < bincount; ++i) - rms_sq += sqr(bins[i]);; - rms_sq /= n; - // compute fill factor - double const f = (sqr(k) - 1) / (n*rms_sq - k); - // rescale to (0,1) with 0 = good, 1 = bad - return 1 - (f / n); -} - -template -std::uint32_t -window (T* blob, int start, int count ) -{ - std::size_t const len = sizeof(T); - static_assert((len & 3) == 0, ""); - if(count == 0) - return 0; - int const nbits = len * CHAR_BIT; - start %= nbits; - int ndwords = len / 4; - std::uint32_t const* k = static_cast < - std::uint32_t const*>(static_cast(blob)); - int c = start & (32-1); - int d = start / 32; - if(c == 0) - return (k[d] & ((1 << count) - 1)); - int ia = (d + 1) % ndwords; - int ib = (d + 0) % ndwords; - std::uint32_t a = k[ia]; - std::uint32_t b = k[ib]; - std::uint32_t t = (a << (32-c)) | (b >> c); - t &= ((1 << count)-1); - return t; -} - -} // detail - -/** Calculated a windowed metric using bins. - TODO Need reference (SMHasher?) -*/ -template -double -windowed_score (FwdIter first, FwdIter last) -{ - auto const size (std::distance (first, last)); - int maxwidth = 20; - // We need at least 5 keys per bin to reliably test distribution biases - // down to 1%, so don't bother to test sparser distributions than that - while (static_cast(size) / (1ull << maxwidth) < 5.0) - maxwidth--; - double worst = 0; - std::vector bins (1ull << maxwidth); - int const hashbits = sizeof(std::size_t) * CHAR_BIT; - for (int start = 0; start < hashbits; ++start) - { - int width = maxwidth; - bins.assign (1ull << width, 0); - for (auto iter (first); iter != last; ++iter) - ++bins[detail::window(&*iter, start, width)]; - // Test the distribution, then fold the bins in half, - // repeat until we're down to 256 bins - while (bins.size() >= 256) - { - double score (detail::score ( - bins.data(), bins.size(), size)); - worst = std::max(score, worst); - if (--width < 8) - break; - for (std::size_t i = 0, j = bins.size() / 2; j < bins.size(); ++i, ++j) - bins[i] += bins[j]; - bins.resize(bins.size() / 2); - } - } - return worst; -} - -} // hash_metrics -} // beast - -#endif diff --git a/beast/hash/tests/hash_speed_test.cpp b/beast/hash/tests/hash_speed_test.cpp deleted file mode 100644 index 3518e4a8f3..0000000000 --- a/beast/hash/tests/hash_speed_test.cpp +++ /dev/null @@ -1,119 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { - -class hash_speed_test : public beast::unit_test::suite -{ -public: - template - static - void - rngfill (void* buffer, std::size_t bytes, - Generator& g) - { - using result_type = - typename Generator::result_type; - while (bytes >= sizeof(result_type)) - { - auto const v = g(); - std::memcpy(buffer, &v, sizeof(v)); - buffer = reinterpret_cast< - std::uint8_t*>(buffer) + sizeof(v); - bytes -= sizeof(v); - } - if (bytes > 0) - { - auto const v = g(); - std::memcpy(buffer, &v, bytes); - } - } - - template > - static - void - rngfill (std::array& a, Generator& g) - { - using result_type = - typename Generator::result_type; - auto i = N / sizeof(result_type); - result_type* p = - reinterpret_cast(a.data()); - while (i--) - *p++ = g(); - } - using clock_type = - std::chrono::high_resolution_clock; - template - void - test (std::string const& what, std::size_t n) - { - using namespace std; - using namespace std::chrono; - xor_shift_engine g(1); - array key; - auto const start = clock_type::now(); - while(n--) - { - rngfill (key, g); - Hasher h; - h(key.data(), KeySize); - volatile size_t temp = - static_cast(h); - (void)temp; - } - auto const elapsed = clock_type::now() - start; - log << setw(12) << what << " " << - duration(elapsed).count() << "s"; - } - - void - run() - { - enum - { - N = 100000000 - }; - - #if ! BEAST_NO_XXHASH - test ("xxhash", N); - #endif - test ("fnv1a", N); - test ("siphash", N); - pass(); - } -}; - -BEAST_DEFINE_TESTSUITE_MANUAL(hash_speed,container,beast); - -} // beast diff --git a/beast/hash/uhash.h b/beast/hash/uhash.h deleted file mode 100644 index 456c8b2b26..0000000000 --- a/beast/hash/uhash.h +++ /dev/null @@ -1,47 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant , - Vinnie Falco -#include - -namespace beast { - -// Universal hash function -template -struct uhash -{ - using result_type = typename Hasher::result_type; - - template - result_type - operator()(T const& t) const noexcept - { - Hasher h; - hash_append (h, t); - return static_cast(h); - } -}; - -} // beast - -#endif diff --git a/beast/hash/xxhasher.h b/beast/hash/xxhasher.h deleted file mode 100644 index 057255f497..0000000000 --- a/beast/hash/xxhasher.h +++ /dev/null @@ -1,88 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HASH_XXHASHER_H_INCLUDED -#define BEAST_HASH_XXHASHER_H_INCLUDED - -#ifndef BEAST_NO_XXHASH -#define BEAST_NO_XXHASH 0 -#endif - -#if ! BEAST_NO_XXHASH - -#include -#include -#include -#include - -namespace beast { - -class xxhasher -{ -private: - // requires 64-bit std::size_t - static_assert(sizeof(std::size_t)==8, ""); - - detail::XXH64_state_t state_; - -public: - using result_type = std::size_t; - - static beast::endian const endian = beast::endian::native; - - xxhasher() noexcept - { - detail::XXH64_reset (&state_, 1); - } - - template ::value>* = nullptr> - explicit - xxhasher (Seed seed) - { - detail::XXH64_reset (&state_, seed); - } - - template ::value>* = nullptr> - xxhasher (Seed seed, Seed) - { - detail::XXH64_reset (&state_, seed); - } - - void - operator()(void const* key, std::size_t len) noexcept - { - detail::XXH64_update (&state_, key, len); - } - - explicit - operator std::size_t() noexcept - { - return detail::XXH64_digest(&state_); - } -}; - -} // beast - -#endif - -#endif diff --git a/beast/http.h b/beast/http.h deleted file mode 100644 index f9ead2b69e..0000000000 --- a/beast/http.h +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_H_INCLUDED -#define BEAST_HTTP_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/beast/http/body.h b/beast/http/body.h deleted file mode 100644 index 90511d2d06..0000000000 --- a/beast/http/body.h +++ /dev/null @@ -1,150 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_BODY_H_INCLUDED -#define BEAST_HTTP_BODY_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace deprecated_http { - -/** Container for the HTTP content-body. */ -class body -{ -private: - using buffer_type = boost::asio::streambuf; - - // Hack: use unique_ptr because streambuf cant be moved - std::unique_ptr buf_; - -public: - using const_buffers_type = buffer_type::const_buffers_type; - - body(); - body (body&& other); - body& operator= (body&& other); - - body (body const&) = delete; - body& operator= (body const&) = delete; - - template - void - clear(); - - void - write (void const* data, std::size_t bytes); - - template - void - write (ConstBufferSequence const& buffers); - - std::size_t - size() const; - - const_buffers_type - data() const; -}; - -template -std::string -to_string (body const& b) -{ - std::string s; - auto const& data (b.data()); - auto const n (boost::asio::buffer_size (data)); - s.resize (n); - boost::asio::buffer_copy ( - boost::asio::buffer (&s[0], n), data); - return s; -} - -//------------------------------------------------------------------------------ - -inline -body::body() - : buf_ (std::make_unique ()) -{ -} - -inline -body::body (body&& other) - : buf_ (std::move(other.buf_)) -{ - other.clear(); -} - -inline -body& -body::operator= (body&& other) -{ - buf_ = std::move(other.buf_); - other.clear(); - return *this; -} - -template -void -body::clear() -{ - buf_ = std::make_unique (); -} - -inline -void -body::write (void const* data, std::size_t bytes) -{ - buf_->commit (boost::asio::buffer_copy (buf_->prepare (bytes), - boost::asio::const_buffers_1 (data, bytes))); -} - -template -void -body::write (ConstBufferSequence const& buffers) -{ - for (auto const& buffer : buffers) - write (boost::asio::buffer_cast (buffer), - boost::asio::buffer_size (buffer)); -} - -inline -std::size_t -body::size() const -{ - return buf_->size(); -} - -inline -auto -body::data() const - -> const_buffers_type -{ - return buf_->data(); -} - -} // deprecated_http -} // beast - -#endif diff --git a/beast/http/empty_body.h b/beast/http/empty_body.h deleted file mode 100644 index ffe74fd458..0000000000 --- a/beast/http/empty_body.h +++ /dev/null @@ -1,87 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_EMPTY_BODY_H_INCLUDED -#define BEAST_HTTP_EMPTY_BODY_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace http { - -/** An empty content-body. -*/ -struct empty_body -{ - struct value_type - { - }; - - struct reader - { - template - explicit - reader(message&) - { - } - - void - write(void const*, std::size_t, error_code&) - { - } - }; - - struct writer - { - template - explicit - writer(message const& m) - { - } - - void - init(error_code& ec) - { - } - - std::size_t - content_length() const - { - return 0; - } - - template - boost::tribool - operator()(resume_context&&, error_code&, Write&& write) - { - write(boost::asio::null_buffers{}); - return true; - } - }; -}; - -} // http -} // beast - -#endif diff --git a/beast/http/headers.h b/beast/http/headers.h deleted file mode 100644 index 7457b8111f..0000000000 --- a/beast/http/headers.h +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_HEADERS_H_INCLUDED -#define BEAST_HTTP_HEADERS_H_INCLUDED - -#include -#include - -namespace beast { -namespace http { - -template -using headers = basic_headers; - -using http_headers = - basic_headers>; - -} // http -} // beast - -#endif diff --git a/beast/http/impl/README.md b/beast/http/impl/README.md deleted file mode 100644 index ab82bbba99..0000000000 --- a/beast/http/impl/README.md +++ /dev/null @@ -1,3 +0,0 @@ -git-subtree: "http-parser" -remote: https://github.com/joyent/http-parser.git -branch: master diff --git a/beast/http/impl/http-parser/.gitignore b/beast/http/impl/http-parser/.gitignore deleted file mode 100644 index c122e76fb9..0000000000 --- a/beast/http/impl/http-parser/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -/out/ -core -tags -*.o -test -test_g -test_fast -bench -url_parser -parsertrace -parsertrace_g -*.mk -*.Makefile -*.so.* -*.exe.* -*.exe -*.a - - -# Visual Studio uglies -*.suo -*.sln -*.vcxproj -*.vcxproj.filters -*.vcxproj.user -*.opensdf -*.ncrunchsolution* -*.sdf -*.vsp -*.psess diff --git a/beast/http/impl/http-parser/.mailmap b/beast/http/impl/http-parser/.mailmap deleted file mode 100644 index 278d141263..0000000000 --- a/beast/http/impl/http-parser/.mailmap +++ /dev/null @@ -1,8 +0,0 @@ -# update AUTHORS with: -# git log --all --reverse --format='%aN <%aE>' | perl -ne 'BEGIN{print "# Authors ordered by first contribution.\n"} print unless $h{$_}; $h{$_} = 1' > AUTHORS -Ryan Dahl -Salman Haq -Simon Zimmermann -Thomas LE ROUX LE ROUX Thomas -Thomas LE ROUX Thomas LE ROUX -Fedor Indutny diff --git a/beast/http/impl/http-parser/.travis.yml b/beast/http/impl/http-parser/.travis.yml deleted file mode 100644 index 4b038e6e62..0000000000 --- a/beast/http/impl/http-parser/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: c - -compiler: - - clang - - gcc - -script: - - "make" - -notifications: - email: false - irc: - - "irc.freenode.net#node-ci" diff --git a/beast/http/impl/http-parser/Makefile b/beast/http/impl/http-parser/Makefile deleted file mode 100644 index b3e0ff4ae0..0000000000 --- a/beast/http/impl/http-parser/Makefile +++ /dev/null @@ -1,149 +0,0 @@ -# Copyright Joyent, Inc. and other Node contributors. All rights reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. - -PLATFORM ?= $(shell sh -c 'uname -s | tr "[A-Z]" "[a-z]"') -HELPER ?= -BINEXT ?= -ifeq (darwin,$(PLATFORM)) -SONAME ?= libhttp_parser.2.6.1.dylib -SOEXT ?= dylib -else ifeq (wine,$(PLATFORM)) -CC = winegcc -BINEXT = .exe.so -HELPER = wine -else -SONAME ?= libhttp_parser.so.2.6.1 -SOEXT ?= so -endif - -CC?=gcc -AR?=ar - -CPPFLAGS ?= -LDFLAGS ?= - -CPPFLAGS += -I. -CPPFLAGS_DEBUG = $(CPPFLAGS) -DHTTP_PARSER_STRICT=1 -CPPFLAGS_DEBUG += $(CPPFLAGS_DEBUG_EXTRA) -CPPFLAGS_FAST = $(CPPFLAGS) -DHTTP_PARSER_STRICT=0 -CPPFLAGS_FAST += $(CPPFLAGS_FAST_EXTRA) -CPPFLAGS_BENCH = $(CPPFLAGS_FAST) - -CFLAGS += -Wall -Wextra -Werror -CFLAGS_DEBUG = $(CFLAGS) -O0 -g $(CFLAGS_DEBUG_EXTRA) -CFLAGS_FAST = $(CFLAGS) -O3 $(CFLAGS_FAST_EXTRA) -CFLAGS_BENCH = $(CFLAGS_FAST) -Wno-unused-parameter -CFLAGS_LIB = $(CFLAGS_FAST) -fPIC - -LDFLAGS_LIB = $(LDFLAGS) -shared - -INSTALL ?= install -PREFIX ?= $(DESTDIR)/usr/local -LIBDIR = $(PREFIX)/lib -INCLUDEDIR = $(PREFIX)/include - -ifneq (darwin,$(PLATFORM)) -# TODO(bnoordhuis) The native SunOS linker expects -h rather than -soname... -LDFLAGS_LIB += -Wl,-soname=$(SONAME) -endif - -test: test_g test_fast - $(HELPER) ./test_g$(BINEXT) - $(HELPER) ./test_fast$(BINEXT) - -test_g: http_parser_g.o test_g.o - $(CC) $(CFLAGS_DEBUG) $(LDFLAGS) http_parser_g.o test_g.o -o $@ - -test_g.o: test.c http_parser.h Makefile - $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c test.c -o $@ - -http_parser_g.o: http_parser.c http_parser.h Makefile - $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c http_parser.c -o $@ - -test_fast: http_parser.o test.o http_parser.h - $(CC) $(CFLAGS_FAST) $(LDFLAGS) http_parser.o test.o -o $@ - -test.o: test.c http_parser.h Makefile - $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c test.c -o $@ - -bench: http_parser.o bench.o - $(CC) $(CFLAGS_BENCH) $(LDFLAGS) http_parser.o bench.o -o $@ - -bench.o: bench.c http_parser.h Makefile - $(CC) $(CPPFLAGS_BENCH) $(CFLAGS_BENCH) -c bench.c -o $@ - -http_parser.o: http_parser.c http_parser.h Makefile - $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c http_parser.c - -test-run-timed: test_fast - while(true) do time $(HELPER) ./test_fast$(BINEXT) > /dev/null; done - -test-valgrind: test_g - valgrind ./test_g - -libhttp_parser.o: http_parser.c http_parser.h Makefile - $(CC) $(CPPFLAGS_FAST) $(CFLAGS_LIB) -c http_parser.c -o libhttp_parser.o - -library: libhttp_parser.o - $(CC) $(LDFLAGS_LIB) -o $(SONAME) $< - -package: http_parser.o - $(AR) rcs libhttp_parser.a http_parser.o - -url_parser: http_parser.o contrib/url_parser.c - $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) $^ -o $@ - -url_parser_g: http_parser_g.o contrib/url_parser.c - $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) $^ -o $@ - -parsertrace: http_parser.o contrib/parsertrace.c - $(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) $^ -o parsertrace$(BINEXT) - -parsertrace_g: http_parser_g.o contrib/parsertrace.c - $(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) $^ -o parsertrace_g$(BINEXT) - -tags: http_parser.c http_parser.h test.c - ctags $^ - -install: library - $(INSTALL) -D http_parser.h $(INCLUDEDIR)/http_parser.h - $(INSTALL) -D $(SONAME) $(LIBDIR)/$(SONAME) - ln -s $(LIBDIR)/$(SONAME) $(LIBDIR)/libhttp_parser.$(SOEXT) - -install-strip: library - $(INSTALL) -D http_parser.h $(INCLUDEDIR)/http_parser.h - $(INSTALL) -D -s $(SONAME) $(LIBDIR)/$(SONAME) - ln -s $(LIBDIR)/$(SONAME) $(LIBDIR)/libhttp_parser.$(SOEXT) - -uninstall: - rm $(INCLUDEDIR)/http_parser.h - rm $(LIBDIR)/$(SONAME) - rm $(LIBDIR)/libhttp_parser.so - -clean: - rm -f *.o *.a tags test test_fast test_g \ - http_parser.tar libhttp_parser.so.* \ - url_parser url_parser_g parsertrace parsertrace_g \ - *.exe *.exe.so - -contrib/url_parser.c: http_parser.h -contrib/parsertrace.c: http_parser.h - -.PHONY: clean package test-run test-run-timed test-valgrind install install-strip uninstall diff --git a/beast/http/impl/http-parser/bench.c b/beast/http/impl/http-parser/bench.c deleted file mode 100644 index 5b452fa1cd..0000000000 --- a/beast/http/impl/http-parser/bench.c +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright Fedor Indutny. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - */ -#include "http_parser.h" -#include -#include -#include -#include - -static const char data[] = - "POST /joyent/http-parser HTTP/1.1\r\n" - "Host: github.com\r\n" - "DNT: 1\r\n" - "Accept-Encoding: gzip, deflate, sdch\r\n" - "Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4\r\n" - "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) " - "AppleWebKit/537.36 (KHTML, like Gecko) " - "Chrome/39.0.2171.65 Safari/537.36\r\n" - "Accept: text/html,application/xhtml+xml,application/xml;q=0.9," - "image/webp,*/*;q=0.8\r\n" - "Referer: https://github.com/joyent/http-parser\r\n" - "Connection: keep-alive\r\n" - "Transfer-Encoding: chunked\r\n" - "Cache-Control: max-age=0\r\n\r\nb\r\nhello world\r\n0\r\n\r\n"; -static const size_t data_len = sizeof(data) - 1; - -static int on_info(http_parser* p) { - return 0; -} - - -static int on_data(http_parser* p, const char *at, size_t length) { - return 0; -} - -static http_parser_settings settings = { - .on_message_begin = on_info, - .on_headers_complete = on_info, - .on_message_complete = on_info, - .on_header_field = on_data, - .on_header_value = on_data, - .on_url = on_data, - .on_status = on_data, - .on_body = on_data -}; - -int bench(int iter_count, int silent) { - struct http_parser parser; - int i; - int err; - struct timeval start; - struct timeval end; - float rps; - - if (!silent) { - err = gettimeofday(&start, NULL); - assert(err == 0); - } - - for (i = 0; i < iter_count; i++) { - size_t parsed; - http_parser_init(&parser, HTTP_REQUEST); - - parsed = http_parser_execute(&parser, &settings, data, data_len); - assert(parsed == data_len); - } - - if (!silent) { - err = gettimeofday(&end, NULL); - assert(err == 0); - - fprintf(stdout, "Benchmark result:\n"); - - rps = (float) (end.tv_sec - start.tv_sec) + - (end.tv_usec - start.tv_usec) * 1e-6f; - fprintf(stdout, "Took %f seconds to run\n", rps); - - rps = (float) iter_count / rps; - fprintf(stdout, "%f req/sec\n", rps); - fflush(stdout); - } - - return 0; -} - -int main(int argc, char** argv) { - if (argc == 2 && strcmp(argv[1], "infinite") == 0) { - for (;;) - bench(5000000, 1); - return 0; - } else { - return bench(5000000, 0); - } -} diff --git a/beast/http/impl/http-parser/contrib/parsertrace.c b/beast/http/impl/http-parser/contrib/parsertrace.c deleted file mode 100644 index e7153680f4..0000000000 --- a/beast/http/impl/http-parser/contrib/parsertrace.c +++ /dev/null @@ -1,160 +0,0 @@ -/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev - * - * Additional changes are licensed under the same terms as NGINX and - * copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - */ - -/* Dump what the parser finds to stdout as it happen */ - -#include "http_parser.h" -#include -#include -#include - -int on_message_begin(http_parser* _) { - (void)_; - printf("\n***MESSAGE BEGIN***\n\n"); - return 0; -} - -int on_headers_complete(http_parser* _) { - (void)_; - printf("\n***HEADERS COMPLETE***\n\n"); - return 0; -} - -int on_message_complete(http_parser* _) { - (void)_; - printf("\n***MESSAGE COMPLETE***\n\n"); - return 0; -} - -int on_url(http_parser* _, const char* at, size_t length) { - (void)_; - printf("Url: %.*s\n", (int)length, at); - return 0; -} - -int on_header_field(http_parser* _, const char* at, size_t length) { - (void)_; - printf("Header field: %.*s\n", (int)length, at); - return 0; -} - -int on_header_value(http_parser* _, const char* at, size_t length) { - (void)_; - printf("Header value: %.*s\n", (int)length, at); - return 0; -} - -int on_body(http_parser* _, const char* at, size_t length) { - (void)_; - printf("Body: %.*s\n", (int)length, at); - return 0; -} - -void usage(const char* name) { - fprintf(stderr, - "Usage: %s $type $filename\n" - " type: -x, where x is one of {r,b,q}\n" - " parses file as a Response, reQuest, or Both\n", - name); - exit(EXIT_FAILURE); -} - -int main(int argc, char* argv[]) { - enum http_parser_type file_type; - - if (argc != 3) { - usage(argv[0]); - } - - char* type = argv[1]; - if (type[0] != '-') { - usage(argv[0]); - } - - switch (type[1]) { - /* in the case of "-", type[1] will be NUL */ - case 'r': - file_type = HTTP_RESPONSE; - break; - case 'q': - file_type = HTTP_REQUEST; - break; - case 'b': - file_type = HTTP_BOTH; - break; - default: - usage(argv[0]); - } - - char* filename = argv[2]; - FILE* file = fopen(filename, "r"); - if (file == NULL) { - perror("fopen"); - goto fail; - } - - fseek(file, 0, SEEK_END); - long file_length = ftell(file); - if (file_length == -1) { - perror("ftell"); - goto fail; - } - fseek(file, 0, SEEK_SET); - - char* data = malloc(file_length); - if (fread(data, 1, file_length, file) != (size_t)file_length) { - fprintf(stderr, "couldn't read entire file\n"); - free(data); - goto fail; - } - - http_parser_settings settings; - memset(&settings, 0, sizeof(settings)); - settings.on_message_begin = on_message_begin; - settings.on_url = on_url; - settings.on_header_field = on_header_field; - settings.on_header_value = on_header_value; - settings.on_headers_complete = on_headers_complete; - settings.on_body = on_body; - settings.on_message_complete = on_message_complete; - - http_parser parser; - http_parser_init(&parser, file_type); - size_t nparsed = http_parser_execute(&parser, &settings, data, file_length); - free(data); - - if (nparsed != (size_t)file_length) { - fprintf(stderr, - "Error: %s (%s)\n", - http_errno_description(HTTP_PARSER_ERRNO(&parser)), - http_errno_name(HTTP_PARSER_ERRNO(&parser))); - goto fail; - } - - return EXIT_SUCCESS; - -fail: - fclose(file); - return EXIT_FAILURE; -} diff --git a/beast/http/impl/http-parser/contrib/url_parser.c b/beast/http/impl/http-parser/contrib/url_parser.c deleted file mode 100644 index f235bed9e4..0000000000 --- a/beast/http/impl/http-parser/contrib/url_parser.c +++ /dev/null @@ -1,47 +0,0 @@ -#include "http_parser.h" -#include -#include - -void -dump_url (const char *url, const struct http_parser_url *u) -{ - unsigned int i; - - printf("\tfield_set: 0x%x, port: %u\n", u->field_set, u->port); - for (i = 0; i < UF_MAX; i++) { - if ((u->field_set & (1 << i)) == 0) { - printf("\tfield_data[%u]: unset\n", i); - continue; - } - - printf("\tfield_data[%u]: off: %u, len: %u, part: %.*s\n", - i, - u->field_data[i].off, - u->field_data[i].len, - u->field_data[i].len, - url + u->field_data[i].off); - } -} - -int main(int argc, char ** argv) { - struct http_parser_url u; - int len, connect, result; - - if (argc != 3) { - printf("Syntax : %s connect|get url\n", argv[0]); - return 1; - } - len = strlen(argv[2]); - connect = strcmp("connect", argv[1]) == 0 ? 1 : 0; - printf("Parsing %s, connect %d\n", argv[2], connect); - - http_parser_url_init(&u); - result = http_parser_parse_url(argv[2], len, connect, &u); - if (result != 0) { - printf("Parse error : %d\n", result); - return result; - } - printf("Parse ok, result : \n"); - dump_url(argv[2], &u); - return 0; -} diff --git a/beast/http/impl/http-parser/http_parser.gyp b/beast/http/impl/http-parser/http_parser.gyp deleted file mode 100644 index ef34ecaeae..0000000000 --- a/beast/http/impl/http-parser/http_parser.gyp +++ /dev/null @@ -1,111 +0,0 @@ -# This file is used with the GYP meta build system. -# http://code.google.com/p/gyp/ -# To build try this: -# svn co http://gyp.googlecode.com/svn/trunk gyp -# ./gyp/gyp -f make --depth=`pwd` http_parser.gyp -# ./out/Debug/test -{ - 'target_defaults': { - 'default_configuration': 'Debug', - 'configurations': { - # TODO: hoist these out and put them somewhere common, because - # RuntimeLibrary MUST MATCH across the entire project - 'Debug': { - 'defines': [ 'DEBUG', '_DEBUG' ], - 'cflags': [ '-Wall', '-Wextra', '-O0', '-g', '-ftrapv' ], - 'msvs_settings': { - 'VCCLCompilerTool': { - 'RuntimeLibrary': 1, # static debug - }, - }, - }, - 'Release': { - 'defines': [ 'NDEBUG' ], - 'cflags': [ '-Wall', '-Wextra', '-O3' ], - 'msvs_settings': { - 'VCCLCompilerTool': { - 'RuntimeLibrary': 0, # static release - }, - }, - } - }, - 'msvs_settings': { - 'VCCLCompilerTool': { - }, - 'VCLibrarianTool': { - }, - 'VCLinkerTool': { - 'GenerateDebugInformation': 'true', - }, - }, - 'conditions': [ - ['OS == "win"', { - 'defines': [ - 'WIN32' - ], - }] - ], - }, - - 'targets': [ - { - 'target_name': 'http_parser', - 'type': 'static_library', - 'include_dirs': [ '.' ], - 'direct_dependent_settings': { - 'defines': [ 'HTTP_PARSER_STRICT=0' ], - 'include_dirs': [ '.' ], - }, - 'defines': [ 'HTTP_PARSER_STRICT=0' ], - 'sources': [ './http_parser.c', ], - 'conditions': [ - ['OS=="win"', { - 'msvs_settings': { - 'VCCLCompilerTool': { - # Compile as C++. http_parser.c is actually C99, but C++ is - # close enough in this case. - 'CompileAs': 2, - }, - }, - }] - ], - }, - - { - 'target_name': 'http_parser_strict', - 'type': 'static_library', - 'include_dirs': [ '.' ], - 'direct_dependent_settings': { - 'defines': [ 'HTTP_PARSER_STRICT=1' ], - 'include_dirs': [ '.' ], - }, - 'defines': [ 'HTTP_PARSER_STRICT=1' ], - 'sources': [ './http_parser.c', ], - 'conditions': [ - ['OS=="win"', { - 'msvs_settings': { - 'VCCLCompilerTool': { - # Compile as C++. http_parser.c is actually C99, but C++ is - # close enough in this case. - 'CompileAs': 2, - }, - }, - }] - ], - }, - - { - 'target_name': 'test-nonstrict', - 'type': 'executable', - 'dependencies': [ 'http_parser' ], - 'sources': [ 'test.c' ] - }, - - { - 'target_name': 'test-strict', - 'type': 'executable', - 'dependencies': [ 'http_parser_strict' ], - 'sources': [ 'test.c' ] - } - ] -} diff --git a/beast/http/impl/http-parser/test.c b/beast/http/impl/http-parser/test.c deleted file mode 100644 index 4fcebaf79e..0000000000 --- a/beast/http/impl/http-parser/test.c +++ /dev/null @@ -1,4127 +0,0 @@ -/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - */ -#include "http_parser.h" -#include -#include -#include -#include /* rand */ -#include -#include - -#if defined(__APPLE__) -# undef strlcat -# undef strlncpy -# undef strlcpy -#endif /* defined(__APPLE__) */ - -#undef TRUE -#define TRUE 1 -#undef FALSE -#define FALSE 0 - -#define MAX_HEADERS 13 -#define MAX_ELEMENT_SIZE 2048 -#define MAX_CHUNKS 16 - -#define MIN(a,b) ((a) < (b) ? (a) : (b)) - -static http_parser *parser; - -struct message { - const char *name; // for debugging purposes - const char *raw; - enum http_parser_type type; - enum http_method method; - int status_code; - char response_status[MAX_ELEMENT_SIZE]; - char request_path[MAX_ELEMENT_SIZE]; - char request_url[MAX_ELEMENT_SIZE]; - char fragment[MAX_ELEMENT_SIZE]; - char query_string[MAX_ELEMENT_SIZE]; - char body[MAX_ELEMENT_SIZE]; - size_t body_size; - const char *host; - const char *userinfo; - uint16_t port; - int num_headers; - enum { NONE=0, FIELD, VALUE } last_header_element; - char headers [MAX_HEADERS][2][MAX_ELEMENT_SIZE]; - int should_keep_alive; - - int num_chunks; - int num_chunks_complete; - int chunk_lengths[MAX_CHUNKS]; - - const char *upgrade; // upgraded body - - unsigned short http_major; - unsigned short http_minor; - - int message_begin_cb_called; - int headers_complete_cb_called; - int message_complete_cb_called; - int message_complete_on_eof; - int body_is_final; -}; - -static int currently_parsing_eof; - -static struct message messages[5]; -static int num_messages; -static http_parser_settings *current_pause_parser; - -/* * R E Q U E S T S * */ -const struct message requests[] = -#define CURL_GET 0 -{ {.name= "curl get" - ,.type= HTTP_REQUEST - ,.raw= "GET /test HTTP/1.1\r\n" - "User-Agent: curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n" - "Host: 0.0.0.0=5000\r\n" - "Accept: */*\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/test" - ,.request_url= "/test" - ,.num_headers= 3 - ,.headers= - { { "User-Agent", "curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1" } - , { "Host", "0.0.0.0=5000" } - , { "Accept", "*/*" } - } - ,.body= "" - } - -#define FIREFOX_GET 1 -, {.name= "firefox get" - ,.type= HTTP_REQUEST - ,.raw= "GET /favicon.ico HTTP/1.1\r\n" - "Host: 0.0.0.0=5000\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0\r\n" - "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" - "Accept-Language: en-us,en;q=0.5\r\n" - "Accept-Encoding: gzip,deflate\r\n" - "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" - "Keep-Alive: 300\r\n" - "Connection: keep-alive\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/favicon.ico" - ,.request_url= "/favicon.ico" - ,.num_headers= 8 - ,.headers= - { { "Host", "0.0.0.0=5000" } - , { "User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0" } - , { "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } - , { "Accept-Language", "en-us,en;q=0.5" } - , { "Accept-Encoding", "gzip,deflate" } - , { "Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7" } - , { "Keep-Alive", "300" } - , { "Connection", "keep-alive" } - } - ,.body= "" - } - -#define DUMBFUCK 2 -, {.name= "dumbfuck" - ,.type= HTTP_REQUEST - ,.raw= "GET /dumbfuck HTTP/1.1\r\n" - "aaaaaaaaaaaaa:++++++++++\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/dumbfuck" - ,.request_url= "/dumbfuck" - ,.num_headers= 1 - ,.headers= - { { "aaaaaaaaaaaaa", "++++++++++" } - } - ,.body= "" - } - -#define FRAGMENT_IN_URI 3 -, {.name= "fragment in url" - ,.type= HTTP_REQUEST - ,.raw= "GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "page=1" - ,.fragment= "posts-17408" - ,.request_path= "/forums/1/topics/2375" - /* XXX request url does include fragment? */ - ,.request_url= "/forums/1/topics/2375?page=1#posts-17408" - ,.num_headers= 0 - ,.body= "" - } - -#define GET_NO_HEADERS_NO_BODY 4 -, {.name= "get no headers no body" - ,.type= HTTP_REQUEST - ,.raw= "GET /get_no_headers_no_body/world HTTP/1.1\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE /* would need Connection: close */ - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/get_no_headers_no_body/world" - ,.request_url= "/get_no_headers_no_body/world" - ,.num_headers= 0 - ,.body= "" - } - -#define GET_ONE_HEADER_NO_BODY 5 -, {.name= "get one header no body" - ,.type= HTTP_REQUEST - ,.raw= "GET /get_one_header_no_body HTTP/1.1\r\n" - "Accept: */*\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE /* would need Connection: close */ - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/get_one_header_no_body" - ,.request_url= "/get_one_header_no_body" - ,.num_headers= 1 - ,.headers= - { { "Accept" , "*/*" } - } - ,.body= "" - } - -#define GET_FUNKY_CONTENT_LENGTH 6 -, {.name= "get funky content length body hello" - ,.type= HTTP_REQUEST - ,.raw= "GET /get_funky_content_length_body_hello HTTP/1.0\r\n" - "conTENT-Length: 5\r\n" - "\r\n" - "HELLO" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/get_funky_content_length_body_hello" - ,.request_url= "/get_funky_content_length_body_hello" - ,.num_headers= 1 - ,.headers= - { { "conTENT-Length" , "5" } - } - ,.body= "HELLO" - } - -#define POST_IDENTITY_BODY_WORLD 7 -, {.name= "post identity body world" - ,.type= HTTP_REQUEST - ,.raw= "POST /post_identity_body_world?q=search#hey HTTP/1.1\r\n" - "Accept: */*\r\n" - "Transfer-Encoding: identity\r\n" - "Content-Length: 5\r\n" - "\r\n" - "World" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.query_string= "q=search" - ,.fragment= "hey" - ,.request_path= "/post_identity_body_world" - ,.request_url= "/post_identity_body_world?q=search#hey" - ,.num_headers= 3 - ,.headers= - { { "Accept", "*/*" } - , { "Transfer-Encoding", "identity" } - , { "Content-Length", "5" } - } - ,.body= "World" - } - -#define POST_CHUNKED_ALL_YOUR_BASE 8 -, {.name= "post - chunked body: all your base are belong to us" - ,.type= HTTP_REQUEST - ,.raw= "POST /post_chunked_all_your_base HTTP/1.1\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "1e\r\nall your base are belong to us\r\n" - "0\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/post_chunked_all_your_base" - ,.request_url= "/post_chunked_all_your_base" - ,.num_headers= 1 - ,.headers= - { { "Transfer-Encoding" , "chunked" } - } - ,.body= "all your base are belong to us" - ,.num_chunks_complete= 2 - ,.chunk_lengths= { 0x1e } - } - -#define TWO_CHUNKS_MULT_ZERO_END 9 -, {.name= "two chunks ; triple zero ending" - ,.type= HTTP_REQUEST - ,.raw= "POST /two_chunks_mult_zero_end HTTP/1.1\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "5\r\nhello\r\n" - "6\r\n world\r\n" - "000\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/two_chunks_mult_zero_end" - ,.request_url= "/two_chunks_mult_zero_end" - ,.num_headers= 1 - ,.headers= - { { "Transfer-Encoding", "chunked" } - } - ,.body= "hello world" - ,.num_chunks_complete= 3 - ,.chunk_lengths= { 5, 6 } - } - -#define CHUNKED_W_TRAILING_HEADERS 10 -, {.name= "chunked with trailing headers. blech." - ,.type= HTTP_REQUEST - ,.raw= "POST /chunked_w_trailing_headers HTTP/1.1\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "5\r\nhello\r\n" - "6\r\n world\r\n" - "0\r\n" - "Vary: *\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/chunked_w_trailing_headers" - ,.request_url= "/chunked_w_trailing_headers" - ,.num_headers= 3 - ,.headers= - { { "Transfer-Encoding", "chunked" } - , { "Vary", "*" } - , { "Content-Type", "text/plain" } - } - ,.body= "hello world" - ,.num_chunks_complete= 3 - ,.chunk_lengths= { 5, 6 } - } - -#define CHUNKED_W_BULLSHIT_AFTER_LENGTH 11 -, {.name= "with bullshit after the length" - ,.type= HTTP_REQUEST - ,.raw= "POST /chunked_w_bullshit_after_length HTTP/1.1\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "5; ihatew3;whatthefuck=aretheseparametersfor\r\nhello\r\n" - "6; blahblah; blah\r\n world\r\n" - "0\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/chunked_w_bullshit_after_length" - ,.request_url= "/chunked_w_bullshit_after_length" - ,.num_headers= 1 - ,.headers= - { { "Transfer-Encoding", "chunked" } - } - ,.body= "hello world" - ,.num_chunks_complete= 3 - ,.chunk_lengths= { 5, 6 } - } - -#define WITH_QUOTES 12 -, {.name= "with quotes" - ,.type= HTTP_REQUEST - ,.raw= "GET /with_\"stupid\"_quotes?foo=\"bar\" HTTP/1.1\r\n\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "foo=\"bar\"" - ,.fragment= "" - ,.request_path= "/with_\"stupid\"_quotes" - ,.request_url= "/with_\"stupid\"_quotes?foo=\"bar\"" - ,.num_headers= 0 - ,.headers= { } - ,.body= "" - } - -#define APACHEBENCH_GET 13 -/* The server receiving this request SHOULD NOT wait for EOF - * to know that content-length == 0. - * How to represent this in a unit test? message_complete_on_eof - * Compare with NO_CONTENT_LENGTH_RESPONSE. - */ -, {.name = "apachebench get" - ,.type= HTTP_REQUEST - ,.raw= "GET /test HTTP/1.0\r\n" - "Host: 0.0.0.0:5000\r\n" - "User-Agent: ApacheBench/2.3\r\n" - "Accept: */*\r\n\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/test" - ,.request_url= "/test" - ,.num_headers= 3 - ,.headers= { { "Host", "0.0.0.0:5000" } - , { "User-Agent", "ApacheBench/2.3" } - , { "Accept", "*/*" } - } - ,.body= "" - } - -#define QUERY_URL_WITH_QUESTION_MARK_GET 14 -/* Some clients include '?' characters in query strings. - */ -, {.name = "query url with question mark" - ,.type= HTTP_REQUEST - ,.raw= "GET /test.cgi?foo=bar?baz HTTP/1.1\r\n\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "foo=bar?baz" - ,.fragment= "" - ,.request_path= "/test.cgi" - ,.request_url= "/test.cgi?foo=bar?baz" - ,.num_headers= 0 - ,.headers= {} - ,.body= "" - } - -#define PREFIX_NEWLINE_GET 15 -/* Some clients, especially after a POST in a keep-alive connection, - * will send an extra CRLF before the next request - */ -, {.name = "newline prefix get" - ,.type= HTTP_REQUEST - ,.raw= "\r\nGET /test HTTP/1.1\r\n\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/test" - ,.request_url= "/test" - ,.num_headers= 0 - ,.headers= { } - ,.body= "" - } - -#define UPGRADE_REQUEST 16 -, {.name = "upgrade request" - ,.type= HTTP_REQUEST - ,.raw= "GET /demo HTTP/1.1\r\n" - "Host: example.com\r\n" - "Connection: Upgrade\r\n" - "Sec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\n" - "Sec-WebSocket-Protocol: sample\r\n" - "Upgrade: WebSocket\r\n" - "Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5\r\n" - "Origin: http://example.com\r\n" - "\r\n" - "Hot diggity dogg" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/demo" - ,.request_url= "/demo" - ,.num_headers= 7 - ,.upgrade="Hot diggity dogg" - ,.headers= { { "Host", "example.com" } - , { "Connection", "Upgrade" } - , { "Sec-WebSocket-Key2", "12998 5 Y3 1 .P00" } - , { "Sec-WebSocket-Protocol", "sample" } - , { "Upgrade", "WebSocket" } - , { "Sec-WebSocket-Key1", "4 @1 46546xW%0l 1 5" } - , { "Origin", "http://example.com" } - } - ,.body= "" - } - -#define CONNECT_REQUEST 17 -, {.name = "connect request" - ,.type= HTTP_REQUEST - ,.raw= "CONNECT 0-home0.netscape.com:443 HTTP/1.0\r\n" - "User-agent: Mozilla/1.1N\r\n" - "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" - "\r\n" - "some data\r\n" - "and yet even more data" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.method= HTTP_CONNECT - ,.query_string= "" - ,.fragment= "" - ,.request_path= "" - ,.request_url= "0-home0.netscape.com:443" - ,.num_headers= 2 - ,.upgrade="some data\r\nand yet even more data" - ,.headers= { { "User-agent", "Mozilla/1.1N" } - , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } - } - ,.body= "" - } - -#define REPORT_REQ 18 -, {.name= "report request" - ,.type= HTTP_REQUEST - ,.raw= "REPORT /test HTTP/1.1\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_REPORT - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/test" - ,.request_url= "/test" - ,.num_headers= 0 - ,.headers= {} - ,.body= "" - } - -#define NO_HTTP_VERSION 19 -, {.name= "request with no http version" - ,.type= HTTP_REQUEST - ,.raw= "GET /\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 0 - ,.http_minor= 9 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/" - ,.request_url= "/" - ,.num_headers= 0 - ,.headers= {} - ,.body= "" - } - -#define MSEARCH_REQ 20 -, {.name= "m-search request" - ,.type= HTTP_REQUEST - ,.raw= "M-SEARCH * HTTP/1.1\r\n" - "HOST: 239.255.255.250:1900\r\n" - "MAN: \"ssdp:discover\"\r\n" - "ST: \"ssdp:all\"\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_MSEARCH - ,.query_string= "" - ,.fragment= "" - ,.request_path= "*" - ,.request_url= "*" - ,.num_headers= 3 - ,.headers= { { "HOST", "239.255.255.250:1900" } - , { "MAN", "\"ssdp:discover\"" } - , { "ST", "\"ssdp:all\"" } - } - ,.body= "" - } - -#define LINE_FOLDING_IN_HEADER 21 -, {.name= "line folding in header value" - ,.type= HTTP_REQUEST - ,.raw= "GET / HTTP/1.1\r\n" - "Line1: abc\r\n" - "\tdef\r\n" - " ghi\r\n" - "\t\tjkl\r\n" - " mno \r\n" - "\t \tqrs\r\n" - "Line2: \t line2\t\r\n" - "Line3:\r\n" - " line3\r\n" - "Line4: \r\n" - " \r\n" - "Connection:\r\n" - " close\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/" - ,.request_url= "/" - ,.num_headers= 5 - ,.headers= { { "Line1", "abc\tdef ghi\t\tjkl mno \t \tqrs" } - , { "Line2", "line2\t" } - , { "Line3", "line3" } - , { "Line4", "" } - , { "Connection", "close" }, - } - ,.body= "" - } - - -#define QUERY_TERMINATED_HOST 22 -, {.name= "host terminated by a query string" - ,.type= HTTP_REQUEST - ,.raw= "GET http://hypnotoad.org?hail=all HTTP/1.1\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "hail=all" - ,.fragment= "" - ,.request_path= "" - ,.request_url= "http://hypnotoad.org?hail=all" - ,.host= "hypnotoad.org" - ,.num_headers= 0 - ,.headers= { } - ,.body= "" - } - -#define QUERY_TERMINATED_HOSTPORT 23 -, {.name= "host:port terminated by a query string" - ,.type= HTTP_REQUEST - ,.raw= "GET http://hypnotoad.org:1234?hail=all HTTP/1.1\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "hail=all" - ,.fragment= "" - ,.request_path= "" - ,.request_url= "http://hypnotoad.org:1234?hail=all" - ,.host= "hypnotoad.org" - ,.port= 1234 - ,.num_headers= 0 - ,.headers= { } - ,.body= "" - } - -#define SPACE_TERMINATED_HOSTPORT 24 -, {.name= "host:port terminated by a space" - ,.type= HTTP_REQUEST - ,.raw= "GET http://hypnotoad.org:1234 HTTP/1.1\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "" - ,.request_url= "http://hypnotoad.org:1234" - ,.host= "hypnotoad.org" - ,.port= 1234 - ,.num_headers= 0 - ,.headers= { } - ,.body= "" - } - -#define PATCH_REQ 25 -, {.name = "PATCH request" - ,.type= HTTP_REQUEST - ,.raw= "PATCH /file.txt HTTP/1.1\r\n" - "Host: www.example.com\r\n" - "Content-Type: application/example\r\n" - "If-Match: \"e0023aa4e\"\r\n" - "Content-Length: 10\r\n" - "\r\n" - "cccccccccc" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_PATCH - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/file.txt" - ,.request_url= "/file.txt" - ,.num_headers= 4 - ,.headers= { { "Host", "www.example.com" } - , { "Content-Type", "application/example" } - , { "If-Match", "\"e0023aa4e\"" } - , { "Content-Length", "10" } - } - ,.body= "cccccccccc" - } - -#define CONNECT_CAPS_REQUEST 26 -, {.name = "connect caps request" - ,.type= HTTP_REQUEST - ,.raw= "CONNECT HOME0.NETSCAPE.COM:443 HTTP/1.0\r\n" - "User-agent: Mozilla/1.1N\r\n" - "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.method= HTTP_CONNECT - ,.query_string= "" - ,.fragment= "" - ,.request_path= "" - ,.request_url= "HOME0.NETSCAPE.COM:443" - ,.num_headers= 2 - ,.upgrade="" - ,.headers= { { "User-agent", "Mozilla/1.1N" } - , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } - } - ,.body= "" - } - -#if !HTTP_PARSER_STRICT -#define UTF8_PATH_REQ 27 -, {.name= "utf-8 path request" - ,.type= HTTP_REQUEST - ,.raw= "GET /δ¶/δt/pope?q=1#narf HTTP/1.1\r\n" - "Host: github.com\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "q=1" - ,.fragment= "narf" - ,.request_path= "/δ¶/δt/pope" - ,.request_url= "/δ¶/δt/pope?q=1#narf" - ,.num_headers= 1 - ,.headers= { {"Host", "github.com" } - } - ,.body= "" - } - -#define HOSTNAME_UNDERSCORE 28 -, {.name = "hostname underscore" - ,.type= HTTP_REQUEST - ,.raw= "CONNECT home_0.netscape.com:443 HTTP/1.0\r\n" - "User-agent: Mozilla/1.1N\r\n" - "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.method= HTTP_CONNECT - ,.query_string= "" - ,.fragment= "" - ,.request_path= "" - ,.request_url= "home_0.netscape.com:443" - ,.num_headers= 2 - ,.upgrade="" - ,.headers= { { "User-agent", "Mozilla/1.1N" } - , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } - } - ,.body= "" - } -#endif /* !HTTP_PARSER_STRICT */ - -/* see https://github.com/ry/http-parser/issues/47 */ -#define EAT_TRAILING_CRLF_NO_CONNECTION_CLOSE 29 -, {.name = "eat CRLF between requests, no \"Connection: close\" header" - ,.raw= "POST / HTTP/1.1\r\n" - "Host: www.example.com\r\n" - "Content-Type: application/x-www-form-urlencoded\r\n" - "Content-Length: 4\r\n" - "\r\n" - "q=42\r\n" /* note the trailing CRLF */ - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/" - ,.request_url= "/" - ,.num_headers= 3 - ,.upgrade= 0 - ,.headers= { { "Host", "www.example.com" } - , { "Content-Type", "application/x-www-form-urlencoded" } - , { "Content-Length", "4" } - } - ,.body= "q=42" - } - -/* see https://github.com/ry/http-parser/issues/47 */ -#define EAT_TRAILING_CRLF_WITH_CONNECTION_CLOSE 30 -, {.name = "eat CRLF between requests even if \"Connection: close\" is set" - ,.raw= "POST / HTTP/1.1\r\n" - "Host: www.example.com\r\n" - "Content-Type: application/x-www-form-urlencoded\r\n" - "Content-Length: 4\r\n" - "Connection: close\r\n" - "\r\n" - "q=42\r\n" /* note the trailing CRLF */ - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE /* input buffer isn't empty when on_message_complete is called */ - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/" - ,.request_url= "/" - ,.num_headers= 4 - ,.upgrade= 0 - ,.headers= { { "Host", "www.example.com" } - , { "Content-Type", "application/x-www-form-urlencoded" } - , { "Content-Length", "4" } - , { "Connection", "close" } - } - ,.body= "q=42" - } - -#define PURGE_REQ 31 -, {.name = "PURGE request" - ,.type= HTTP_REQUEST - ,.raw= "PURGE /file.txt HTTP/1.1\r\n" - "Host: www.example.com\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_PURGE - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/file.txt" - ,.request_url= "/file.txt" - ,.num_headers= 1 - ,.headers= { { "Host", "www.example.com" } } - ,.body= "" - } - -#define SEARCH_REQ 32 -, {.name = "SEARCH request" - ,.type= HTTP_REQUEST - ,.raw= "SEARCH / HTTP/1.1\r\n" - "Host: www.example.com\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_SEARCH - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/" - ,.request_url= "/" - ,.num_headers= 1 - ,.headers= { { "Host", "www.example.com" } } - ,.body= "" - } - -#define PROXY_WITH_BASIC_AUTH 33 -, {.name= "host:port and basic_auth" - ,.type= HTTP_REQUEST - ,.raw= "GET http://a%12:b!&*$@hypnotoad.org:1234/toto HTTP/1.1\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.fragment= "" - ,.request_path= "/toto" - ,.request_url= "http://a%12:b!&*$@hypnotoad.org:1234/toto" - ,.host= "hypnotoad.org" - ,.userinfo= "a%12:b!&*$" - ,.port= 1234 - ,.num_headers= 0 - ,.headers= { } - ,.body= "" - } - -#define LINE_FOLDING_IN_HEADER_WITH_LF 34 -, {.name= "line folding in header value" - ,.type= HTTP_REQUEST - ,.raw= "GET / HTTP/1.1\n" - "Line1: abc\n" - "\tdef\n" - " ghi\n" - "\t\tjkl\n" - " mno \n" - "\t \tqrs\n" - "Line2: \t line2\t\n" - "Line3:\n" - " line3\n" - "Line4: \n" - " \n" - "Connection:\n" - " close\n" - "\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/" - ,.request_url= "/" - ,.num_headers= 5 - ,.headers= { { "Line1", "abc\tdef ghi\t\tjkl mno \t \tqrs" } - , { "Line2", "line2\t" } - , { "Line3", "line3" } - , { "Line4", "" } - , { "Connection", "close" }, - } - ,.body= "" - } - -#define CONNECTION_MULTI 35 -, {.name = "multiple connection header values with folding" - ,.type= HTTP_REQUEST - ,.raw= "GET /demo HTTP/1.1\r\n" - "Host: example.com\r\n" - "Connection: Something,\r\n" - " Upgrade, ,Keep-Alive\r\n" - "Sec-WebSocket-Key2: 12998 5 Y3 1 .P00\r\n" - "Sec-WebSocket-Protocol: sample\r\n" - "Upgrade: WebSocket\r\n" - "Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5\r\n" - "Origin: http://example.com\r\n" - "\r\n" - "Hot diggity dogg" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/demo" - ,.request_url= "/demo" - ,.num_headers= 7 - ,.upgrade="Hot diggity dogg" - ,.headers= { { "Host", "example.com" } - , { "Connection", "Something, Upgrade, ,Keep-Alive" } - , { "Sec-WebSocket-Key2", "12998 5 Y3 1 .P00" } - , { "Sec-WebSocket-Protocol", "sample" } - , { "Upgrade", "WebSocket" } - , { "Sec-WebSocket-Key1", "4 @1 46546xW%0l 1 5" } - , { "Origin", "http://example.com" } - } - ,.body= "" - } - -#define CONNECTION_MULTI_LWS 36 -, {.name = "multiple connection header values with folding and lws" - ,.type= HTTP_REQUEST - ,.raw= "GET /demo HTTP/1.1\r\n" - "Connection: keep-alive, upgrade\r\n" - "Upgrade: WebSocket\r\n" - "\r\n" - "Hot diggity dogg" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/demo" - ,.request_url= "/demo" - ,.num_headers= 2 - ,.upgrade="Hot diggity dogg" - ,.headers= { { "Connection", "keep-alive, upgrade" } - , { "Upgrade", "WebSocket" } - } - ,.body= "" - } - -#define CONNECTION_MULTI_LWS_CRLF 37 -, {.name = "multiple connection header values with folding and lws" - ,.type= HTTP_REQUEST - ,.raw= "GET /demo HTTP/1.1\r\n" - "Connection: keep-alive, \r\n upgrade\r\n" - "Upgrade: WebSocket\r\n" - "\r\n" - "Hot diggity dogg" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_GET - ,.query_string= "" - ,.fragment= "" - ,.request_path= "/demo" - ,.request_url= "/demo" - ,.num_headers= 2 - ,.upgrade="Hot diggity dogg" - ,.headers= { { "Connection", "keep-alive, upgrade" } - , { "Upgrade", "WebSocket" } - } - ,.body= "" - } - -#define UPGRADE_POST_REQUEST 38 -, {.name = "upgrade post request" - ,.type= HTTP_REQUEST - ,.raw= "POST /demo HTTP/1.1\r\n" - "Host: example.com\r\n" - "Connection: Upgrade\r\n" - "Upgrade: HTTP/2.0\r\n" - "Content-Length: 15\r\n" - "\r\n" - "sweet post body" - "Hot diggity dogg" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_POST - ,.request_path= "/demo" - ,.request_url= "/demo" - ,.num_headers= 4 - ,.upgrade="Hot diggity dogg" - ,.headers= { { "Host", "example.com" } - , { "Connection", "Upgrade" } - , { "Upgrade", "HTTP/2.0" } - , { "Content-Length", "15" } - } - ,.body= "sweet post body" - } - -#define CONNECT_WITH_BODY_REQUEST 39 -, {.name = "connect with body request" - ,.type= HTTP_REQUEST - ,.raw= "CONNECT foo.bar.com:443 HTTP/1.0\r\n" - "User-agent: Mozilla/1.1N\r\n" - "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n" - "Content-Length: 10\r\n" - "\r\n" - "blarfcicle" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.method= HTTP_CONNECT - ,.request_url= "foo.bar.com:443" - ,.num_headers= 3 - ,.upgrade="blarfcicle" - ,.headers= { { "User-agent", "Mozilla/1.1N" } - , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" } - , { "Content-Length", "10" } - } - ,.body= "" - } - -/* Examples from the Internet draft for LINK/UNLINK methods: - * https://tools.ietf.org/id/draft-snell-link-method-01.html#rfc.section.5 - */ - -#define LINK_REQUEST 40 -, {.name = "link request" - ,.type= HTTP_REQUEST - ,.raw= "LINK /images/my_dog.jpg HTTP/1.1\r\n" - "Host: example.com\r\n" - "Link: ; rel=\"tag\"\r\n" - "Link: ; rel=\"tag\"\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_LINK - ,.request_path= "/images/my_dog.jpg" - ,.request_url= "/images/my_dog.jpg" - ,.query_string= "" - ,.fragment= "" - ,.num_headers= 3 - ,.headers= { { "Host", "example.com" } - , { "Link", "; rel=\"tag\"" } - , { "Link", "; rel=\"tag\"" } - } - ,.body= "" - } - -#define UNLINK_REQUEST 41 -, {.name = "link request" - ,.type= HTTP_REQUEST - ,.raw= "UNLINK /images/my_dog.jpg HTTP/1.1\r\n" - "Host: example.com\r\n" - "Link: ; rel=\"tag\"\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.method= HTTP_UNLINK - ,.request_path= "/images/my_dog.jpg" - ,.request_url= "/images/my_dog.jpg" - ,.query_string= "" - ,.fragment= "" - ,.num_headers= 2 - ,.headers= { { "Host", "example.com" } - , { "Link", "; rel=\"tag\"" } - } - ,.body= "" - } - -, {.name= NULL } /* sentinel */ -}; - -/* * R E S P O N S E S * */ -const struct message responses[] = -#define GOOGLE_301 0 -{ {.name= "google 301" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 301 Moved Permanently\r\n" - "Location: http://www.google.com/\r\n" - "Content-Type: text/html; charset=UTF-8\r\n" - "Date: Sun, 26 Apr 2009 11:11:49 GMT\r\n" - "Expires: Tue, 26 May 2009 11:11:49 GMT\r\n" - "X-$PrototypeBI-Version: 1.6.0.3\r\n" /* $ char in header field */ - "Cache-Control: public, max-age=2592000\r\n" - "Server: gws\r\n" - "Content-Length: 219 \r\n" - "\r\n" - "\n" - "301 Moved\n" - "

301 Moved

\n" - "The document has moved\n" - "here.\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 301 - ,.response_status= "Moved Permanently" - ,.num_headers= 8 - ,.headers= - { { "Location", "http://www.google.com/" } - , { "Content-Type", "text/html; charset=UTF-8" } - , { "Date", "Sun, 26 Apr 2009 11:11:49 GMT" } - , { "Expires", "Tue, 26 May 2009 11:11:49 GMT" } - , { "X-$PrototypeBI-Version", "1.6.0.3" } - , { "Cache-Control", "public, max-age=2592000" } - , { "Server", "gws" } - , { "Content-Length", "219 " } - } - ,.body= "\n" - "301 Moved\n" - "

301 Moved

\n" - "The document has moved\n" - "here.\r\n" - "\r\n" - } - -#define NO_CONTENT_LENGTH_RESPONSE 1 -/* The client should wait for the server's EOF. That is, when content-length - * is not specified, and "Connection: close", the end of body is specified - * by the EOF. - * Compare with APACHEBENCH_GET - */ -, {.name= "no content-length response" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Date: Tue, 04 Aug 2009 07:59:32 GMT\r\n" - "Server: Apache\r\n" - "X-Powered-By: Servlet/2.5 JSP/2.1\r\n" - "Content-Type: text/xml; charset=utf-8\r\n" - "Connection: close\r\n" - "\r\n" - "\n" - "\n" - " \n" - " \n" - " SOAP-ENV:Client\n" - " Client Error\n" - " \n" - " \n" - "" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 5 - ,.headers= - { { "Date", "Tue, 04 Aug 2009 07:59:32 GMT" } - , { "Server", "Apache" } - , { "X-Powered-By", "Servlet/2.5 JSP/2.1" } - , { "Content-Type", "text/xml; charset=utf-8" } - , { "Connection", "close" } - } - ,.body= "\n" - "\n" - " \n" - " \n" - " SOAP-ENV:Client\n" - " Client Error\n" - " \n" - " \n" - "" - } - -#define NO_HEADERS_NO_BODY_404 2 -, {.name= "404 no headers no body" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 404 Not Found\r\n\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 404 - ,.response_status= "Not Found" - ,.num_headers= 0 - ,.headers= {} - ,.body_size= 0 - ,.body= "" - } - -#define NO_REASON_PHRASE 3 -, {.name= "301 no response phrase" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 301\r\n\r\n" - ,.should_keep_alive = FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 301 - ,.response_status= "" - ,.num_headers= 0 - ,.headers= {} - ,.body= "" - } - -#define TRAILING_SPACE_ON_CHUNKED_BODY 4 -, {.name="200 trailing space on chunked body" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "25 \r\n" - "This is the data in the first chunk\r\n" - "\r\n" - "1C\r\n" - "and this is the second one\r\n" - "\r\n" - "0 \r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 2 - ,.headers= - { {"Content-Type", "text/plain" } - , {"Transfer-Encoding", "chunked" } - } - ,.body_size = 37+28 - ,.body = - "This is the data in the first chunk\r\n" - "and this is the second one\r\n" - ,.num_chunks_complete= 3 - ,.chunk_lengths= { 0x25, 0x1c } - } - -#define NO_CARRIAGE_RET 5 -, {.name="no carriage ret" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\n" - "Content-Type: text/html; charset=utf-8\n" - "Connection: close\n" - "\n" - "these headers are from http://news.ycombinator.com/" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 2 - ,.headers= - { {"Content-Type", "text/html; charset=utf-8" } - , {"Connection", "close" } - } - ,.body= "these headers are from http://news.ycombinator.com/" - } - -#define PROXY_CONNECTION 6 -, {.name="proxy connection" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Content-Type: text/html; charset=UTF-8\r\n" - "Content-Length: 11\r\n" - "Proxy-Connection: close\r\n" - "Date: Thu, 31 Dec 2009 20:55:48 +0000\r\n" - "\r\n" - "hello world" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 4 - ,.headers= - { {"Content-Type", "text/html; charset=UTF-8" } - , {"Content-Length", "11" } - , {"Proxy-Connection", "close" } - , {"Date", "Thu, 31 Dec 2009 20:55:48 +0000"} - } - ,.body= "hello world" - } - -#define UNDERSTORE_HEADER_KEY 7 - // shown by - // curl -o /dev/null -v "http://ad.doubleclick.net/pfadx/DARTSHELLCONFIGXML;dcmt=text/xml;" -, {.name="underscore header key" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Server: DCLK-AdSvr\r\n" - "Content-Type: text/xml\r\n" - "Content-Length: 0\r\n" - "DCLK_imp: v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o\r\n\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 4 - ,.headers= - { {"Server", "DCLK-AdSvr" } - , {"Content-Type", "text/xml" } - , {"Content-Length", "0" } - , {"DCLK_imp", "v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o" } - } - ,.body= "" - } - -#define BONJOUR_MADAME_FR 8 -/* The client should not merge two headers fields when the first one doesn't - * have a value. - */ -, {.name= "bonjourmadame.fr" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.0 301 Moved Permanently\r\n" - "Date: Thu, 03 Jun 2010 09:56:32 GMT\r\n" - "Server: Apache/2.2.3 (Red Hat)\r\n" - "Cache-Control: public\r\n" - "Pragma: \r\n" - "Location: http://www.bonjourmadame.fr/\r\n" - "Vary: Accept-Encoding\r\n" - "Content-Length: 0\r\n" - "Content-Type: text/html; charset=UTF-8\r\n" - "Connection: keep-alive\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.status_code= 301 - ,.response_status= "Moved Permanently" - ,.num_headers= 9 - ,.headers= - { { "Date", "Thu, 03 Jun 2010 09:56:32 GMT" } - , { "Server", "Apache/2.2.3 (Red Hat)" } - , { "Cache-Control", "public" } - , { "Pragma", "" } - , { "Location", "http://www.bonjourmadame.fr/" } - , { "Vary", "Accept-Encoding" } - , { "Content-Length", "0" } - , { "Content-Type", "text/html; charset=UTF-8" } - , { "Connection", "keep-alive" } - } - ,.body= "" - } - -#define RES_FIELD_UNDERSCORE 9 -/* Should handle spaces in header fields */ -, {.name= "field underscore" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Date: Tue, 28 Sep 2010 01:14:13 GMT\r\n" - "Server: Apache\r\n" - "Cache-Control: no-cache, must-revalidate\r\n" - "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n" - ".et-Cookie: PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com\r\n" - "Vary: Accept-Encoding\r\n" - "_eep-Alive: timeout=45\r\n" /* semantic value ignored */ - "_onnection: Keep-Alive\r\n" /* semantic value ignored */ - "Transfer-Encoding: chunked\r\n" - "Content-Type: text/html\r\n" - "Connection: close\r\n" - "\r\n" - "0\r\n\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 11 - ,.headers= - { { "Date", "Tue, 28 Sep 2010 01:14:13 GMT" } - , { "Server", "Apache" } - , { "Cache-Control", "no-cache, must-revalidate" } - , { "Expires", "Mon, 26 Jul 1997 05:00:00 GMT" } - , { ".et-Cookie", "PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com" } - , { "Vary", "Accept-Encoding" } - , { "_eep-Alive", "timeout=45" } - , { "_onnection", "Keep-Alive" } - , { "Transfer-Encoding", "chunked" } - , { "Content-Type", "text/html" } - , { "Connection", "close" } - } - ,.body= "" - ,.num_chunks_complete= 1 - ,.chunk_lengths= {} - } - -#define NON_ASCII_IN_STATUS_LINE 10 -/* Should handle non-ASCII in status line */ -, {.name= "non-ASCII in status line" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 500 Oriëntatieprobleem\r\n" - "Date: Fri, 5 Nov 2010 23:07:12 GMT+2\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 500 - ,.response_status= "Oriëntatieprobleem" - ,.num_headers= 3 - ,.headers= - { { "Date", "Fri, 5 Nov 2010 23:07:12 GMT+2" } - , { "Content-Length", "0" } - , { "Connection", "close" } - } - ,.body= "" - } - -#define HTTP_VERSION_0_9 11 -/* Should handle HTTP/0.9 */ -, {.name= "http version 0.9" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/0.9 200 OK\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 0 - ,.http_minor= 9 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 0 - ,.headers= - {} - ,.body= "" - } - -#define NO_CONTENT_LENGTH_NO_TRANSFER_ENCODING_RESPONSE 12 -/* The client should wait for the server's EOF. That is, when neither - * content-length nor transfer-encoding is specified, the end of body - * is specified by the EOF. - */ -, {.name= "neither content-length nor transfer-encoding response" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "hello world" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 1 - ,.headers= - { { "Content-Type", "text/plain" } - } - ,.body= "hello world" - } - -#define NO_BODY_HTTP10_KA_200 13 -, {.name= "HTTP/1.0 with keep-alive and EOF-terminated 200 status" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.0 200 OK\r\n" - "Connection: keep-alive\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 0 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 1 - ,.headers= - { { "Connection", "keep-alive" } - } - ,.body_size= 0 - ,.body= "" - } - -#define NO_BODY_HTTP10_KA_204 14 -, {.name= "HTTP/1.0 with keep-alive and a 204 status" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.0 204 No content\r\n" - "Connection: keep-alive\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.status_code= 204 - ,.response_status= "No content" - ,.num_headers= 1 - ,.headers= - { { "Connection", "keep-alive" } - } - ,.body_size= 0 - ,.body= "" - } - -#define NO_BODY_HTTP11_KA_200 15 -, {.name= "HTTP/1.1 with an EOF-terminated 200 status" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 0 - ,.headers={} - ,.body_size= 0 - ,.body= "" - } - -#define NO_BODY_HTTP11_KA_204 16 -, {.name= "HTTP/1.1 with a 204 status" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 204 No content\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 204 - ,.response_status= "No content" - ,.num_headers= 0 - ,.headers={} - ,.body_size= 0 - ,.body= "" - } - -#define NO_BODY_HTTP11_NOKA_204 17 -, {.name= "HTTP/1.1 with a 204 status and keep-alive disabled" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 204 No content\r\n" - "Connection: close\r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 204 - ,.response_status= "No content" - ,.num_headers= 1 - ,.headers= - { { "Connection", "close" } - } - ,.body_size= 0 - ,.body= "" - } - -#define NO_BODY_HTTP11_KA_CHUNKED_200 18 -, {.name= "HTTP/1.1 with chunked endocing and a 200 response" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "0\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 1 - ,.headers= - { { "Transfer-Encoding", "chunked" } - } - ,.body_size= 0 - ,.body= "" - ,.num_chunks_complete= 1 - } - -#if !HTTP_PARSER_STRICT -#define SPACE_IN_FIELD_RES 19 -/* Should handle spaces in header fields */ -, {.name= "field space" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 OK\r\n" - "Server: Microsoft-IIS/6.0\r\n" - "X-Powered-By: ASP.NET\r\n" - "en-US Content-Type: text/xml\r\n" /* this is the problem */ - "Content-Type: text/xml\r\n" - "Content-Length: 16\r\n" - "Date: Fri, 23 Jul 2010 18:45:38 GMT\r\n" - "Connection: keep-alive\r\n" - "\r\n" - "hello" /* fake body */ - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 7 - ,.headers= - { { "Server", "Microsoft-IIS/6.0" } - , { "X-Powered-By", "ASP.NET" } - , { "en-US Content-Type", "text/xml" } - , { "Content-Type", "text/xml" } - , { "Content-Length", "16" } - , { "Date", "Fri, 23 Jul 2010 18:45:38 GMT" } - , { "Connection", "keep-alive" } - } - ,.body= "hello" - } -#endif /* !HTTP_PARSER_STRICT */ - -#define AMAZON_COM 20 -, {.name= "amazon.com" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 301 MovedPermanently\r\n" - "Date: Wed, 15 May 2013 17:06:33 GMT\r\n" - "Server: Server\r\n" - "x-amz-id-1: 0GPHKXSJQ826RK7GZEB2\r\n" - "p3p: policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \"\r\n" - "x-amz-id-2: STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD\r\n" - "Location: http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846\r\n" - "Vary: Accept-Encoding,User-Agent\r\n" - "Content-Type: text/html; charset=ISO-8859-1\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "1\r\n" - "\n\r\n" - "0\r\n" - "\r\n" - ,.should_keep_alive= TRUE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 301 - ,.response_status= "MovedPermanently" - ,.num_headers= 9 - ,.headers= { { "Date", "Wed, 15 May 2013 17:06:33 GMT" } - , { "Server", "Server" } - , { "x-amz-id-1", "0GPHKXSJQ826RK7GZEB2" } - , { "p3p", "policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \"" } - , { "x-amz-id-2", "STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD" } - , { "Location", "http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846" } - , { "Vary", "Accept-Encoding,User-Agent" } - , { "Content-Type", "text/html; charset=ISO-8859-1" } - , { "Transfer-Encoding", "chunked" } - } - ,.body= "\n" - ,.num_chunks_complete= 2 - ,.chunk_lengths= { 1 } - } - -#define EMPTY_REASON_PHRASE_AFTER_SPACE 20 -, {.name= "empty reason phrase after space" - ,.type= HTTP_RESPONSE - ,.raw= "HTTP/1.1 200 \r\n" - "\r\n" - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= TRUE - ,.http_major= 1 - ,.http_minor= 1 - ,.status_code= 200 - ,.response_status= "" - ,.num_headers= 0 - ,.headers= {} - ,.body= "" - } - -, {.name= NULL } /* sentinel */ -}; - -/* strnlen() is a POSIX.2008 addition. Can't rely on it being available so - * define it ourselves. - */ -size_t -strnlen(const char *s, size_t maxlen) -{ - const char *p; - - p = memchr(s, '\0', maxlen); - if (p == NULL) - return maxlen; - - return p - s; -} - -size_t -strlncat(char *dst, size_t len, const char *src, size_t n) -{ - size_t slen; - size_t dlen; - size_t rlen; - size_t ncpy; - - slen = strnlen(src, n); - dlen = strnlen(dst, len); - - if (dlen < len) { - rlen = len - dlen; - ncpy = slen < rlen ? slen : (rlen - 1); - memcpy(dst + dlen, src, ncpy); - dst[dlen + ncpy] = '\0'; - } - - assert(len > slen + dlen); - return slen + dlen; -} - -size_t -strlcat(char *dst, const char *src, size_t len) -{ - return strlncat(dst, len, src, (size_t) -1); -} - -size_t -strlncpy(char *dst, size_t len, const char *src, size_t n) -{ - size_t slen; - size_t ncpy; - - slen = strnlen(src, n); - - if (len > 0) { - ncpy = slen < len ? slen : (len - 1); - memcpy(dst, src, ncpy); - dst[ncpy] = '\0'; - } - - assert(len > slen); - return slen; -} - -size_t -strlcpy(char *dst, const char *src, size_t len) -{ - return strlncpy(dst, len, src, (size_t) -1); -} - -int -request_url_cb (http_parser *p, const char *buf, size_t len) -{ - assert(p == parser); - strlncat(messages[num_messages].request_url, - sizeof(messages[num_messages].request_url), - buf, - len); - return 0; -} - -int -header_field_cb (http_parser *p, const char *buf, size_t len) -{ - assert(p == parser); - struct message *m = &messages[num_messages]; - - if (m->last_header_element != FIELD) - m->num_headers++; - - strlncat(m->headers[m->num_headers-1][0], - sizeof(m->headers[m->num_headers-1][0]), - buf, - len); - - m->last_header_element = FIELD; - - return 0; -} - -int -header_value_cb (http_parser *p, const char *buf, size_t len) -{ - assert(p == parser); - struct message *m = &messages[num_messages]; - - strlncat(m->headers[m->num_headers-1][1], - sizeof(m->headers[m->num_headers-1][1]), - buf, - len); - - m->last_header_element = VALUE; - - return 0; -} - -void -check_body_is_final (const http_parser *p) -{ - if (messages[num_messages].body_is_final) { - fprintf(stderr, "\n\n *** Error http_body_is_final() should return 1 " - "on last on_body callback call " - "but it doesn't! ***\n\n"); - assert(0); - abort(); - } - messages[num_messages].body_is_final = http_body_is_final(p); -} - -int -body_cb (http_parser *p, const char *buf, size_t len) -{ - assert(p == parser); - strlncat(messages[num_messages].body, - sizeof(messages[num_messages].body), - buf, - len); - messages[num_messages].body_size += len; - check_body_is_final(p); - // printf("body_cb: '%s'\n", requests[num_messages].body); - return 0; -} - -int -count_body_cb (http_parser *p, const char *buf, size_t len) -{ - assert(p == parser); - assert(buf); - messages[num_messages].body_size += len; - check_body_is_final(p); - return 0; -} - -int -message_begin_cb (http_parser *p) -{ - assert(p == parser); - messages[num_messages].message_begin_cb_called = TRUE; - return 0; -} - -int -headers_complete_cb (http_parser *p) -{ - assert(p == parser); - messages[num_messages].method = parser->method; - messages[num_messages].status_code = parser->status_code; - messages[num_messages].http_major = parser->http_major; - messages[num_messages].http_minor = parser->http_minor; - messages[num_messages].headers_complete_cb_called = TRUE; - messages[num_messages].should_keep_alive = http_should_keep_alive(parser); - return 0; -} - -int -message_complete_cb (http_parser *p) -{ - assert(p == parser); - if (messages[num_messages].should_keep_alive != http_should_keep_alive(parser)) - { - fprintf(stderr, "\n\n *** Error http_should_keep_alive() should have same " - "value in both on_message_complete and on_headers_complete " - "but it doesn't! ***\n\n"); - assert(0); - abort(); - } - - if (messages[num_messages].body_size && - http_body_is_final(p) && - !messages[num_messages].body_is_final) - { - fprintf(stderr, "\n\n *** Error http_body_is_final() should return 1 " - "on last on_body callback call " - "but it doesn't! ***\n\n"); - assert(0); - abort(); - } - - messages[num_messages].message_complete_cb_called = TRUE; - - messages[num_messages].message_complete_on_eof = currently_parsing_eof; - - num_messages++; - return 0; -} - -int -response_status_cb (http_parser *p, const char *buf, size_t len) -{ - assert(p == parser); - strlncat(messages[num_messages].response_status, - sizeof(messages[num_messages].response_status), - buf, - len); - return 0; -} - -int -chunk_header_cb (http_parser *p) -{ - assert(p == parser); - int chunk_idx = messages[num_messages].num_chunks; - messages[num_messages].num_chunks++; - if (chunk_idx < MAX_CHUNKS) { - messages[num_messages].chunk_lengths[chunk_idx] = p->content_length; - } - - return 0; -} - -int -chunk_complete_cb (http_parser *p) -{ - assert(p == parser); - - /* Here we want to verify that each chunk_header_cb is matched by a - * chunk_complete_cb, so not only should the total number of calls to - * both callbacks be the same, but they also should be interleaved - * properly */ - assert(messages[num_messages].num_chunks == - messages[num_messages].num_chunks_complete + 1); - - messages[num_messages].num_chunks_complete++; - return 0; -} - -/* These dontcall_* callbacks exist so that we can verify that when we're - * paused, no additional callbacks are invoked */ -int -dontcall_message_begin_cb (http_parser *p) -{ - if (p) { } // gcc - fprintf(stderr, "\n\n*** on_message_begin() called on paused parser ***\n\n"); - abort(); -} - -int -dontcall_header_field_cb (http_parser *p, const char *buf, size_t len) -{ - if (p || buf || len) { } // gcc - fprintf(stderr, "\n\n*** on_header_field() called on paused parser ***\n\n"); - abort(); -} - -int -dontcall_header_value_cb (http_parser *p, const char *buf, size_t len) -{ - if (p || buf || len) { } // gcc - fprintf(stderr, "\n\n*** on_header_value() called on paused parser ***\n\n"); - abort(); -} - -int -dontcall_request_url_cb (http_parser *p, const char *buf, size_t len) -{ - if (p || buf || len) { } // gcc - fprintf(stderr, "\n\n*** on_request_url() called on paused parser ***\n\n"); - abort(); -} - -int -dontcall_body_cb (http_parser *p, const char *buf, size_t len) -{ - if (p || buf || len) { } // gcc - fprintf(stderr, "\n\n*** on_body_cb() called on paused parser ***\n\n"); - abort(); -} - -int -dontcall_headers_complete_cb (http_parser *p) -{ - if (p) { } // gcc - fprintf(stderr, "\n\n*** on_headers_complete() called on paused " - "parser ***\n\n"); - abort(); -} - -int -dontcall_message_complete_cb (http_parser *p) -{ - if (p) { } // gcc - fprintf(stderr, "\n\n*** on_message_complete() called on paused " - "parser ***\n\n"); - abort(); -} - -int -dontcall_response_status_cb (http_parser *p, const char *buf, size_t len) -{ - if (p || buf || len) { } // gcc - fprintf(stderr, "\n\n*** on_status() called on paused parser ***\n\n"); - abort(); -} - -int -dontcall_chunk_header_cb (http_parser *p) -{ - if (p) { } // gcc - fprintf(stderr, "\n\n*** on_chunk_header() called on paused parser ***\n\n"); - exit(1); -} - -int -dontcall_chunk_complete_cb (http_parser *p) -{ - if (p) { } // gcc - fprintf(stderr, "\n\n*** on_chunk_complete() " - "called on paused parser ***\n\n"); - exit(1); -} - -static http_parser_settings settings_dontcall = - {.on_message_begin = dontcall_message_begin_cb - ,.on_header_field = dontcall_header_field_cb - ,.on_header_value = dontcall_header_value_cb - ,.on_url = dontcall_request_url_cb - ,.on_status = dontcall_response_status_cb - ,.on_body = dontcall_body_cb - ,.on_headers_complete = dontcall_headers_complete_cb - ,.on_message_complete = dontcall_message_complete_cb - ,.on_chunk_header = dontcall_chunk_header_cb - ,.on_chunk_complete = dontcall_chunk_complete_cb - }; - -/* These pause_* callbacks always pause the parser and just invoke the regular - * callback that tracks content. Before returning, we overwrite the parser - * settings to point to the _dontcall variety so that we can verify that - * the pause actually did, you know, pause. */ -int -pause_message_begin_cb (http_parser *p) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return message_begin_cb(p); -} - -int -pause_header_field_cb (http_parser *p, const char *buf, size_t len) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return header_field_cb(p, buf, len); -} - -int -pause_header_value_cb (http_parser *p, const char *buf, size_t len) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return header_value_cb(p, buf, len); -} - -int -pause_request_url_cb (http_parser *p, const char *buf, size_t len) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return request_url_cb(p, buf, len); -} - -int -pause_body_cb (http_parser *p, const char *buf, size_t len) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return body_cb(p, buf, len); -} - -int -pause_headers_complete_cb (http_parser *p) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return headers_complete_cb(p); -} - -int -pause_message_complete_cb (http_parser *p) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return message_complete_cb(p); -} - -int -pause_response_status_cb (http_parser *p, const char *buf, size_t len) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return response_status_cb(p, buf, len); -} - -int -pause_chunk_header_cb (http_parser *p) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return chunk_header_cb(p); -} - -int -pause_chunk_complete_cb (http_parser *p) -{ - http_parser_pause(p, 1); - *current_pause_parser = settings_dontcall; - return chunk_complete_cb(p); -} - -static http_parser_settings settings_pause = - {.on_message_begin = pause_message_begin_cb - ,.on_header_field = pause_header_field_cb - ,.on_header_value = pause_header_value_cb - ,.on_url = pause_request_url_cb - ,.on_status = pause_response_status_cb - ,.on_body = pause_body_cb - ,.on_headers_complete = pause_headers_complete_cb - ,.on_message_complete = pause_message_complete_cb - ,.on_chunk_header = pause_chunk_header_cb - ,.on_chunk_complete = pause_chunk_complete_cb - }; - -static http_parser_settings settings = - {.on_message_begin = message_begin_cb - ,.on_header_field = header_field_cb - ,.on_header_value = header_value_cb - ,.on_url = request_url_cb - ,.on_status = response_status_cb - ,.on_body = body_cb - ,.on_headers_complete = headers_complete_cb - ,.on_message_complete = message_complete_cb - ,.on_chunk_header = chunk_header_cb - ,.on_chunk_complete = chunk_complete_cb - }; - -static http_parser_settings settings_count_body = - {.on_message_begin = message_begin_cb - ,.on_header_field = header_field_cb - ,.on_header_value = header_value_cb - ,.on_url = request_url_cb - ,.on_status = response_status_cb - ,.on_body = count_body_cb - ,.on_headers_complete = headers_complete_cb - ,.on_message_complete = message_complete_cb - ,.on_chunk_header = chunk_header_cb - ,.on_chunk_complete = chunk_complete_cb - }; - -static http_parser_settings settings_null = - {.on_message_begin = 0 - ,.on_header_field = 0 - ,.on_header_value = 0 - ,.on_url = 0 - ,.on_status = 0 - ,.on_body = 0 - ,.on_headers_complete = 0 - ,.on_message_complete = 0 - ,.on_chunk_header = 0 - ,.on_chunk_complete = 0 - }; - -void -parser_init (enum http_parser_type type) -{ - num_messages = 0; - - assert(parser == NULL); - - parser = malloc(sizeof(http_parser)); - - http_parser_init(parser, type); - - memset(&messages, 0, sizeof messages); - -} - -void -parser_free () -{ - assert(parser); - free(parser); - parser = NULL; -} - -size_t parse (const char *buf, size_t len) -{ - size_t nparsed; - currently_parsing_eof = (len == 0); - nparsed = http_parser_execute(parser, &settings, buf, len); - return nparsed; -} - -size_t parse_count_body (const char *buf, size_t len) -{ - size_t nparsed; - currently_parsing_eof = (len == 0); - nparsed = http_parser_execute(parser, &settings_count_body, buf, len); - return nparsed; -} - -size_t parse_pause (const char *buf, size_t len) -{ - size_t nparsed; - http_parser_settings s = settings_pause; - - currently_parsing_eof = (len == 0); - current_pause_parser = &s; - nparsed = http_parser_execute(parser, current_pause_parser, buf, len); - return nparsed; -} - -static inline int -check_str_eq (const struct message *m, - const char *prop, - const char *expected, - const char *found) { - if ((expected == NULL) != (found == NULL)) { - printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); - printf("expected %s\n", (expected == NULL) ? "NULL" : expected); - printf(" found %s\n", (found == NULL) ? "NULL" : found); - return 0; - } - if (expected != NULL && 0 != strcmp(expected, found)) { - printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); - printf("expected '%s'\n", expected); - printf(" found '%s'\n", found); - return 0; - } - return 1; -} - -static inline int -check_num_eq (const struct message *m, - const char *prop, - int expected, - int found) { - if (expected != found) { - printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name); - printf("expected %d\n", expected); - printf(" found %d\n", found); - return 0; - } - return 1; -} - -#define MESSAGE_CHECK_STR_EQ(expected, found, prop) \ - if (!check_str_eq(expected, #prop, expected->prop, found->prop)) return 0 - -#define MESSAGE_CHECK_NUM_EQ(expected, found, prop) \ - if (!check_num_eq(expected, #prop, expected->prop, found->prop)) return 0 - -#define MESSAGE_CHECK_URL_EQ(u, expected, found, prop, fn) \ -do { \ - char ubuf[256]; \ - \ - if ((u)->field_set & (1 << (fn))) { \ - memcpy(ubuf, (found)->request_url + (u)->field_data[(fn)].off, \ - (u)->field_data[(fn)].len); \ - ubuf[(u)->field_data[(fn)].len] = '\0'; \ - } else { \ - ubuf[0] = '\0'; \ - } \ - \ - check_str_eq(expected, #prop, expected->prop, ubuf); \ -} while(0) - -int -message_eq (int index, const struct message *expected) -{ - int i; - struct message *m = &messages[index]; - - MESSAGE_CHECK_NUM_EQ(expected, m, http_major); - MESSAGE_CHECK_NUM_EQ(expected, m, http_minor); - - if (expected->type == HTTP_REQUEST) { - MESSAGE_CHECK_NUM_EQ(expected, m, method); - } else { - MESSAGE_CHECK_NUM_EQ(expected, m, status_code); - MESSAGE_CHECK_STR_EQ(expected, m, response_status); - } - - MESSAGE_CHECK_NUM_EQ(expected, m, should_keep_alive); - MESSAGE_CHECK_NUM_EQ(expected, m, message_complete_on_eof); - - assert(m->message_begin_cb_called); - assert(m->headers_complete_cb_called); - assert(m->message_complete_cb_called); - - - MESSAGE_CHECK_STR_EQ(expected, m, request_url); - - /* Check URL components; we can't do this w/ CONNECT since it doesn't - * send us a well-formed URL. - */ - if (*m->request_url && m->method != HTTP_CONNECT) { - struct http_parser_url u; - - if (http_parser_parse_url(m->request_url, strlen(m->request_url), 0, &u)) { - fprintf(stderr, "\n\n*** failed to parse URL %s ***\n\n", - m->request_url); - abort(); - } - - if (expected->host) { - MESSAGE_CHECK_URL_EQ(&u, expected, m, host, UF_HOST); - } - - if (expected->userinfo) { - MESSAGE_CHECK_URL_EQ(&u, expected, m, userinfo, UF_USERINFO); - } - - m->port = (u.field_set & (1 << UF_PORT)) ? - u.port : 0; - - MESSAGE_CHECK_URL_EQ(&u, expected, m, query_string, UF_QUERY); - MESSAGE_CHECK_URL_EQ(&u, expected, m, fragment, UF_FRAGMENT); - MESSAGE_CHECK_URL_EQ(&u, expected, m, request_path, UF_PATH); - MESSAGE_CHECK_NUM_EQ(expected, m, port); - } - - if (expected->body_size) { - MESSAGE_CHECK_NUM_EQ(expected, m, body_size); - } else { - MESSAGE_CHECK_STR_EQ(expected, m, body); - } - - assert(m->num_chunks == m->num_chunks_complete); - MESSAGE_CHECK_NUM_EQ(expected, m, num_chunks_complete); - for (i = 0; i < m->num_chunks && i < MAX_CHUNKS; i++) { - MESSAGE_CHECK_NUM_EQ(expected, m, chunk_lengths[i]); - } - - MESSAGE_CHECK_NUM_EQ(expected, m, num_headers); - - int r; - for (i = 0; i < m->num_headers; i++) { - r = check_str_eq(expected, "header field", expected->headers[i][0], m->headers[i][0]); - if (!r) return 0; - r = check_str_eq(expected, "header value", expected->headers[i][1], m->headers[i][1]); - if (!r) return 0; - } - - MESSAGE_CHECK_STR_EQ(expected, m, upgrade); - - return 1; -} - -/* Given a sequence of varargs messages, return the number of them that the - * parser should successfully parse, taking into account that upgraded - * messages prevent all subsequent messages from being parsed. - */ -size_t -count_parsed_messages(const size_t nmsgs, ...) { - size_t i; - va_list ap; - - va_start(ap, nmsgs); - - for (i = 0; i < nmsgs; i++) { - struct message *m = va_arg(ap, struct message *); - - if (m->upgrade) { - va_end(ap); - return i + 1; - } - } - - va_end(ap); - return nmsgs; -} - -/* Given a sequence of bytes and the number of these that we were able to - * parse, verify that upgrade bodies are correct. - */ -void -upgrade_message_fix(char *body, const size_t nread, const size_t nmsgs, ...) { - va_list ap; - size_t i; - size_t off = 0; - - va_start(ap, nmsgs); - - for (i = 0; i < nmsgs; i++) { - struct message *m = va_arg(ap, struct message *); - - off += strlen(m->raw); - - if (m->upgrade) { - off -= strlen(m->upgrade); - - /* Check the portion of the response after its specified upgrade */ - if (!check_str_eq(m, "upgrade", body + off, body + nread)) { - abort(); - } - - /* Fix up the response so that message_eq() will verify the beginning - * of the upgrade */ - *(body + nread + strlen(m->upgrade)) = '\0'; - messages[num_messages -1 ].upgrade = body + nread; - - va_end(ap); - return; - } - } - - va_end(ap); - printf("\n\n*** Error: expected a message with upgrade ***\n"); - - abort(); -} - -static void -print_error (const char *raw, size_t error_location) -{ - fprintf(stderr, "\n*** %s ***\n\n", - http_errno_description(HTTP_PARSER_ERRNO(parser))); - - int this_line = 0, char_len = 0; - size_t i, j, len = strlen(raw), error_location_line = 0; - for (i = 0; i < len; i++) { - if (i == error_location) this_line = 1; - switch (raw[i]) { - case '\r': - char_len = 2; - fprintf(stderr, "\\r"); - break; - - case '\n': - fprintf(stderr, "\\n\n"); - - if (this_line) goto print; - - error_location_line = 0; - continue; - - default: - char_len = 1; - fputc(raw[i], stderr); - break; - } - if (!this_line) error_location_line += char_len; - } - - fprintf(stderr, "[eof]\n"); - - print: - for (j = 0; j < error_location_line; j++) { - fputc(' ', stderr); - } - fprintf(stderr, "^\n\nerror location: %u\n", (unsigned int)error_location); -} - -void -test_preserve_data (void) -{ - char my_data[] = "application-specific data"; - http_parser parser; - parser.data = my_data; - http_parser_init(&parser, HTTP_REQUEST); - if (parser.data != my_data) { - printf("\n*** parser.data not preserved accross http_parser_init ***\n\n"); - abort(); - } -} - -struct url_test { - const char *name; - const char *url; - int is_connect; - struct http_parser_url u; - int rv; -}; - -const struct url_test url_tests[] = -{ {.name="proxy request" - ,.url="http://hostname/" - ,.is_connect=0 - ,.u= - {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH) - ,.port=0 - ,.field_data= - {{ 0, 4 } /* UF_SCHEMA */ - ,{ 7, 8 } /* UF_HOST */ - ,{ 0, 0 } /* UF_PORT */ - ,{ 15, 1 } /* UF_PATH */ - ,{ 0, 0 } /* UF_QUERY */ - ,{ 0, 0 } /* UF_FRAGMENT */ - ,{ 0, 0 } /* UF_USERINFO */ - } - } - ,.rv=0 - } - -, {.name="proxy request with port" - ,.url="http://hostname:444/" - ,.is_connect=0 - ,.u= - {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PORT) | (1 << UF_PATH) - ,.port=444 - ,.field_data= - {{ 0, 4 } /* UF_SCHEMA */ - ,{ 7, 8 } /* UF_HOST */ - ,{ 16, 3 } /* UF_PORT */ - ,{ 19, 1 } /* UF_PATH */ - ,{ 0, 0 } /* UF_QUERY */ - ,{ 0, 0 } /* UF_FRAGMENT */ - ,{ 0, 0 } /* UF_USERINFO */ - } - } - ,.rv=0 - } - -, {.name="CONNECT request" - ,.url="hostname:443" - ,.is_connect=1 - ,.u= - {.field_set=(1 << UF_HOST) | (1 << UF_PORT) - ,.port=443 - ,.field_data= - {{ 0, 0 } /* UF_SCHEMA */ - ,{ 0, 8 } /* UF_HOST */ - ,{ 9, 3 } /* UF_PORT */ - ,{ 0, 0 } /* UF_PATH */ - ,{ 0, 0 } /* UF_QUERY */ - ,{ 0, 0 } /* UF_FRAGMENT */ - ,{ 0, 0 } /* UF_USERINFO */ - } - } - ,.rv=0 - } - -, {.name="CONNECT request but not connect" - ,.url="hostname:443" - ,.is_connect=0 - ,.rv=1 - } - -, {.name="proxy ipv6 request" - ,.url="http://[1:2::3:4]/" - ,.is_connect=0 - ,.u= - {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH) - ,.port=0 - ,.field_data= - {{ 0, 4 } /* UF_SCHEMA */ - ,{ 8, 8 } /* UF_HOST */ - ,{ 0, 0 } /* UF_PORT */ - ,{ 17, 1 } /* UF_PATH */ - ,{ 0, 0 } /* UF_QUERY */ - ,{ 0, 0 } /* UF_FRAGMENT */ - ,{ 0, 0 } /* UF_USERINFO */ - } - } - ,.rv=0 - } - -, {.name="proxy ipv6 request with port" - ,.url="http://[1:2::3:4]:67/" - ,.is_connect=0 - ,.u= - {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PORT) | (1 << UF_PATH) - ,.port=67 - ,.field_data= - {{ 0, 4 } /* UF_SCHEMA */ - ,{ 8, 8 } /* UF_HOST */ - ,{ 18, 2 } /* UF_PORT */ - ,{ 20, 1 } /* UF_PATH */ - ,{ 0, 0 } /* UF_QUERY */ - ,{ 0, 0 } /* UF_FRAGMENT */ - ,{ 0, 0 } /* UF_USERINFO */ - } - } - ,.rv=0 - } - -, {.name="CONNECT ipv6 address" - ,.url="[1:2::3:4]:443" - ,.is_connect=1 - ,.u= - {.field_set=(1 << UF_HOST) | (1 << UF_PORT) - ,.port=443 - ,.field_data= - {{ 0, 0 } /* UF_SCHEMA */ - ,{ 1, 8 } /* UF_HOST */ - ,{ 11, 3 } /* UF_PORT */ - ,{ 0, 0 } /* UF_PATH */ - ,{ 0, 0 } /* UF_QUERY */ - ,{ 0, 0 } /* UF_FRAGMENT */ - ,{ 0, 0 } /* UF_USERINFO */ - } - } - ,.rv=0 - } - -, {.name="ipv4 in ipv6 address" - ,.url="http://[2001:0000:0000:0000:0000:0000:1.9.1.1]/" - ,.is_connect=0 - ,.u= - {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH) - ,.port=0 - ,.field_data= - {{ 0, 4 } /* UF_SCHEMA */ - ,{ 8, 37 } /* UF_HOST */ - ,{ 0, 0 } /* UF_PORT */ - ,{ 46, 1 } /* UF_PATH */ - ,{ 0, 0 } /* UF_QUERY */ - ,{ 0, 0 } /* UF_FRAGMENT */ - ,{ 0, 0 } /* UF_USERINFO */ - } - } - ,.rv=0 - } - -, {.name="extra ? in query string" - ,.url="http://a.tbcdn.cn/p/fp/2010c/??fp-header-min.css,fp-base-min.css," - "fp-channel-min.css,fp-product-min.css,fp-mall-min.css,fp-category-min.css," - "fp-sub-min.css,fp-gdp4p-min.css,fp-css3-min.css,fp-misc-min.css?t=20101022.css" - ,.is_connect=0 - ,.u= - {.field_set=(1<field_set, u->port); - for (i = 0; i < UF_MAX; i++) { - if ((u->field_set & (1 << i)) == 0) { - printf("\tfield_data[%u]: unset\n", i); - continue; - } - - printf("\tfield_data[%u]: off: %u len: %u part: \"%.*s\n\"", - i, - u->field_data[i].off, - u->field_data[i].len, - u->field_data[i].len, - url + u->field_data[i].off); - } -} - -void -test_parse_url (void) -{ - struct http_parser_url u; - const struct url_test *test; - unsigned int i; - int rv; - - for (i = 0; i < (sizeof(url_tests) / sizeof(url_tests[0])); i++) { - test = &url_tests[i]; - memset(&u, 0, sizeof(u)); - - rv = http_parser_parse_url(test->url, - strlen(test->url), - test->is_connect, - &u); - - if (test->rv == 0) { - if (rv != 0) { - printf("\n*** http_parser_parse_url(\"%s\") \"%s\" test failed, " - "unexpected rv %d ***\n\n", test->url, test->name, rv); - abort(); - } - - if (memcmp(&u, &test->u, sizeof(u)) != 0) { - printf("\n*** http_parser_parse_url(\"%s\") \"%s\" failed ***\n", - test->url, test->name); - - printf("target http_parser_url:\n"); - dump_url(test->url, &test->u); - printf("result http_parser_url:\n"); - dump_url(test->url, &u); - - abort(); - } - } else { - /* test->rv != 0 */ - if (rv == 0) { - printf("\n*** http_parser_parse_url(\"%s\") \"%s\" test failed, " - "unexpected rv %d ***\n\n", test->url, test->name, rv); - abort(); - } - } - } -} - -void -test_method_str (void) -{ - assert(0 == strcmp("GET", http_method_str(HTTP_GET))); - assert(0 == strcmp("", http_method_str(1337))); -} - -void -test_message (const struct message *message) -{ - size_t raw_len = strlen(message->raw); - size_t msg1len; - for (msg1len = 0; msg1len < raw_len; msg1len++) { - parser_init(message->type); - - size_t read; - const char *msg1 = message->raw; - const char *msg2 = msg1 + msg1len; - size_t msg2len = raw_len - msg1len; - - if (msg1len) { - read = parse(msg1, msg1len); - - if (message->upgrade && parser->upgrade && num_messages > 0) { - messages[num_messages - 1].upgrade = msg1 + read; - goto test; - } - - if (read != msg1len) { - print_error(msg1, read); - abort(); - } - } - - - read = parse(msg2, msg2len); - - if (message->upgrade && parser->upgrade) { - messages[num_messages - 1].upgrade = msg2 + read; - goto test; - } - - if (read != msg2len) { - print_error(msg2, read); - abort(); - } - - read = parse(NULL, 0); - - if (read != 0) { - print_error(message->raw, read); - abort(); - } - - test: - - if (num_messages != 1) { - printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name); - abort(); - } - - if(!message_eq(0, message)) abort(); - - parser_free(); - } -} - -void -test_message_count_body (const struct message *message) -{ - parser_init(message->type); - - size_t read; - size_t l = strlen(message->raw); - size_t i, toread; - size_t chunk = 4024; - - for (i = 0; i < l; i+= chunk) { - toread = MIN(l-i, chunk); - read = parse_count_body(message->raw + i, toread); - if (read != toread) { - print_error(message->raw, read); - abort(); - } - } - - - read = parse_count_body(NULL, 0); - if (read != 0) { - print_error(message->raw, read); - abort(); - } - - if (num_messages != 1) { - printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name); - abort(); - } - - if(!message_eq(0, message)) abort(); - - parser_free(); -} - -void -test_simple (const char *buf, enum http_errno err_expected) -{ - parser_init(HTTP_REQUEST); - - enum http_errno err; - - parse(buf, strlen(buf)); - err = HTTP_PARSER_ERRNO(parser); - parse(NULL, 0); - - parser_free(); - - /* In strict mode, allow us to pass with an unexpected HPE_STRICT as - * long as the caller isn't expecting success. - */ -#if HTTP_PARSER_STRICT - if (err_expected != err && err_expected != HPE_OK && err != HPE_STRICT) { -#else - if (err_expected != err) { -#endif - fprintf(stderr, "\n*** test_simple expected %s, but saw %s ***\n\n%s\n", - http_errno_name(err_expected), http_errno_name(err), buf); - abort(); - } -} - -void -test_invalid_header_content (int req, const char* str) -{ - http_parser parser; - http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); - size_t parsed; - const char *buf; - buf = req ? - "GET / HTTP/1.1\r\n" : - "HTTP/1.1 200 OK\r\n"; - parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); - assert(parsed == strlen(buf)); - - buf = str; - size_t buflen = strlen(buf); - - parsed = http_parser_execute(&parser, &settings_null, buf, buflen); - if (parsed != buflen) { - assert(HTTP_PARSER_ERRNO(&parser) == HPE_INVALID_HEADER_TOKEN); - return; - } - - fprintf(stderr, - "\n*** Error expected but none in invalid header content test ***\n"); - abort(); -} - -void -test_invalid_header_field_content_error (int req) -{ - test_invalid_header_content(req, "Foo: F\01ailure"); - test_invalid_header_content(req, "Foo: B\02ar"); -} - -void -test_invalid_header_field (int req, const char* str) -{ - http_parser parser; - http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); - size_t parsed; - const char *buf; - buf = req ? - "GET / HTTP/1.1\r\n" : - "HTTP/1.1 200 OK\r\n"; - parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); - assert(parsed == strlen(buf)); - - buf = str; - size_t buflen = strlen(buf); - - parsed = http_parser_execute(&parser, &settings_null, buf, buflen); - if (parsed != buflen) { - assert(HTTP_PARSER_ERRNO(&parser) == HPE_INVALID_HEADER_TOKEN); - return; - } - - fprintf(stderr, - "\n*** Error expected but none in invalid header token test ***\n"); - abort(); -} - -void -test_invalid_header_field_token_error (int req) -{ - test_invalid_header_field(req, "Fo@: Failure"); - test_invalid_header_field(req, "Foo\01\test: Bar"); -} - -void -test_double_content_length_error (int req) -{ - http_parser parser; - http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); - size_t parsed; - const char *buf; - buf = req ? - "GET / HTTP/1.1\r\n" : - "HTTP/1.1 200 OK\r\n"; - parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); - assert(parsed == strlen(buf)); - - buf = "Content-Length: 0\r\nContent-Length: 1\r\n\r\n"; - size_t buflen = strlen(buf); - - parsed = http_parser_execute(&parser, &settings_null, buf, buflen); - if (parsed != buflen) { - assert(HTTP_PARSER_ERRNO(&parser) == HPE_UNEXPECTED_CONTENT_LENGTH); - return; - } - - fprintf(stderr, - "\n*** Error expected but none in double content-length test ***\n"); - abort(); -} - -void -test_chunked_content_length_error (int req) -{ - http_parser parser; - http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); - size_t parsed; - const char *buf; - buf = req ? - "GET / HTTP/1.1\r\n" : - "HTTP/1.1 200 OK\r\n"; - parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); - assert(parsed == strlen(buf)); - - buf = "Transfer-Encoding: chunked\r\nContent-Length: 1\r\n\r\n"; - size_t buflen = strlen(buf); - - parsed = http_parser_execute(&parser, &settings_null, buf, buflen); - if (parsed != buflen) { - assert(HTTP_PARSER_ERRNO(&parser) == HPE_UNEXPECTED_CONTENT_LENGTH); - return; - } - - fprintf(stderr, - "\n*** Error expected but none in chunked content-length test ***\n"); - abort(); -} - -void -test_header_cr_no_lf_error (int req) -{ - http_parser parser; - http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); - size_t parsed; - const char *buf; - buf = req ? - "GET / HTTP/1.1\r\n" : - "HTTP/1.1 200 OK\r\n"; - parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); - assert(parsed == strlen(buf)); - - buf = "Foo: 1\rBar: 1\r\n\r\n"; - size_t buflen = strlen(buf); - - parsed = http_parser_execute(&parser, &settings_null, buf, buflen); - if (parsed != buflen) { - assert(HTTP_PARSER_ERRNO(&parser) == HPE_LF_EXPECTED); - return; - } - - fprintf(stderr, - "\n*** Error expected but none in header whitespace test ***\n"); - abort(); -} - -void -test_header_overflow_error (int req) -{ - http_parser parser; - http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); - size_t parsed; - const char *buf; - buf = req ? "GET / HTTP/1.1\r\n" : "HTTP/1.0 200 OK\r\n"; - parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); - assert(parsed == strlen(buf)); - - buf = "header-key: header-value\r\n"; - size_t buflen = strlen(buf); - - int i; - for (i = 0; i < 10000; i++) { - parsed = http_parser_execute(&parser, &settings_null, buf, buflen); - if (parsed != buflen) { - //fprintf(stderr, "error found on iter %d\n", i); - assert(HTTP_PARSER_ERRNO(&parser) == HPE_HEADER_OVERFLOW); - return; - } - } - - fprintf(stderr, "\n*** Error expected but none in header overflow test ***\n"); - abort(); -} - - -void -test_header_nread_value () -{ - http_parser parser; - http_parser_init(&parser, HTTP_REQUEST); - size_t parsed; - const char *buf; - buf = "GET / HTTP/1.1\r\nheader: value\nhdr: value\r\n"; - parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf)); - assert(parsed == strlen(buf)); - - assert(parser.nread == strlen(buf)); -} - - -static void -test_content_length_overflow (const char *buf, size_t buflen, int expect_ok) -{ - http_parser parser; - http_parser_init(&parser, HTTP_RESPONSE); - http_parser_execute(&parser, &settings_null, buf, buflen); - - if (expect_ok) - assert(HTTP_PARSER_ERRNO(&parser) == HPE_OK); - else - assert(HTTP_PARSER_ERRNO(&parser) == HPE_INVALID_CONTENT_LENGTH); -} - -void -test_header_content_length_overflow_error (void) -{ -#define X(size) \ - "HTTP/1.1 200 OK\r\n" \ - "Content-Length: " #size "\r\n" \ - "\r\n" - const char a[] = X(1844674407370955160); /* 2^64 / 10 - 1 */ - const char b[] = X(18446744073709551615); /* 2^64-1 */ - const char c[] = X(18446744073709551616); /* 2^64 */ -#undef X - test_content_length_overflow(a, sizeof(a) - 1, 1); /* expect ok */ - test_content_length_overflow(b, sizeof(b) - 1, 0); /* expect failure */ - test_content_length_overflow(c, sizeof(c) - 1, 0); /* expect failure */ -} - -void -test_chunk_content_length_overflow_error (void) -{ -#define X(size) \ - "HTTP/1.1 200 OK\r\n" \ - "Transfer-Encoding: chunked\r\n" \ - "\r\n" \ - #size "\r\n" \ - "..." - const char a[] = X(FFFFFFFFFFFFFFE); /* 2^64 / 16 - 1 */ - const char b[] = X(FFFFFFFFFFFFFFFF); /* 2^64-1 */ - const char c[] = X(10000000000000000); /* 2^64 */ -#undef X - test_content_length_overflow(a, sizeof(a) - 1, 1); /* expect ok */ - test_content_length_overflow(b, sizeof(b) - 1, 0); /* expect failure */ - test_content_length_overflow(c, sizeof(c) - 1, 0); /* expect failure */ -} - -void -test_no_overflow_long_body (int req, size_t length) -{ - http_parser parser; - http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE); - size_t parsed; - size_t i; - char buf1[3000]; - size_t buf1len = sprintf(buf1, "%s\r\nConnection: Keep-Alive\r\nContent-Length: %lu\r\n\r\n", - req ? "POST / HTTP/1.0" : "HTTP/1.0 200 OK", (unsigned long)length); - parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len); - if (parsed != buf1len) - goto err; - - for (i = 0; i < length; i++) { - char foo = 'a'; - parsed = http_parser_execute(&parser, &settings_null, &foo, 1); - if (parsed != 1) - goto err; - } - - parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len); - if (parsed != buf1len) goto err; - return; - - err: - fprintf(stderr, - "\n*** error in test_no_overflow_long_body %s of length %lu ***\n", - req ? "REQUEST" : "RESPONSE", - (unsigned long)length); - abort(); -} - -void -test_multiple3 (const struct message *r1, const struct message *r2, const struct message *r3) -{ - int message_count = count_parsed_messages(3, r1, r2, r3); - - char total[ strlen(r1->raw) - + strlen(r2->raw) - + strlen(r3->raw) - + 1 - ]; - total[0] = '\0'; - - strcat(total, r1->raw); - strcat(total, r2->raw); - strcat(total, r3->raw); - - parser_init(r1->type); - - size_t read; - - read = parse(total, strlen(total)); - - if (parser->upgrade) { - upgrade_message_fix(total, read, 3, r1, r2, r3); - goto test; - } - - if (read != strlen(total)) { - print_error(total, read); - abort(); - } - - read = parse(NULL, 0); - - if (read != 0) { - print_error(total, read); - abort(); - } - -test: - - if (message_count != num_messages) { - fprintf(stderr, "\n\n*** Parser didn't see 3 messages only %d *** \n", num_messages); - abort(); - } - - if (!message_eq(0, r1)) abort(); - if (message_count > 1 && !message_eq(1, r2)) abort(); - if (message_count > 2 && !message_eq(2, r3)) abort(); - - parser_free(); -} - -/* SCAN through every possible breaking to make sure the - * parser can handle getting the content in any chunks that - * might come from the socket - */ -void -test_scan (const struct message *r1, const struct message *r2, const struct message *r3) -{ - char total[80*1024] = "\0"; - char buf1[80*1024] = "\0"; - char buf2[80*1024] = "\0"; - char buf3[80*1024] = "\0"; - - strcat(total, r1->raw); - strcat(total, r2->raw); - strcat(total, r3->raw); - - size_t read; - - int total_len = strlen(total); - - int total_ops = 2 * (total_len - 1) * (total_len - 2) / 2; - int ops = 0 ; - - size_t buf1_len, buf2_len, buf3_len; - int message_count = count_parsed_messages(3, r1, r2, r3); - - int i,j,type_both; - for (type_both = 0; type_both < 2; type_both ++ ) { - for (j = 2; j < total_len; j ++ ) { - for (i = 1; i < j; i ++ ) { - - if (ops % 1000 == 0) { - printf("\b\b\b\b%3.0f%%", 100 * (float)ops /(float)total_ops); - fflush(stdout); - } - ops += 1; - - parser_init(type_both ? HTTP_BOTH : r1->type); - - buf1_len = i; - strlncpy(buf1, sizeof(buf1), total, buf1_len); - buf1[buf1_len] = 0; - - buf2_len = j - i; - strlncpy(buf2, sizeof(buf1), total+i, buf2_len); - buf2[buf2_len] = 0; - - buf3_len = total_len - j; - strlncpy(buf3, sizeof(buf1), total+j, buf3_len); - buf3[buf3_len] = 0; - - read = parse(buf1, buf1_len); - - if (parser->upgrade) goto test; - - if (read != buf1_len) { - print_error(buf1, read); - goto error; - } - - read += parse(buf2, buf2_len); - - if (parser->upgrade) goto test; - - if (read != buf1_len + buf2_len) { - print_error(buf2, read); - goto error; - } - - read += parse(buf3, buf3_len); - - if (parser->upgrade) goto test; - - if (read != buf1_len + buf2_len + buf3_len) { - print_error(buf3, read); - goto error; - } - - parse(NULL, 0); - -test: - if (parser->upgrade) { - upgrade_message_fix(total, read, 3, r1, r2, r3); - } - - if (message_count != num_messages) { - fprintf(stderr, "\n\nParser didn't see %d messages only %d\n", - message_count, num_messages); - goto error; - } - - if (!message_eq(0, r1)) { - fprintf(stderr, "\n\nError matching messages[0] in test_scan.\n"); - goto error; - } - - if (message_count > 1 && !message_eq(1, r2)) { - fprintf(stderr, "\n\nError matching messages[1] in test_scan.\n"); - goto error; - } - - if (message_count > 2 && !message_eq(2, r3)) { - fprintf(stderr, "\n\nError matching messages[2] in test_scan.\n"); - goto error; - } - - parser_free(); - } - } - } - puts("\b\b\b\b100%"); - return; - - error: - fprintf(stderr, "i=%d j=%d\n", i, j); - fprintf(stderr, "buf1 (%u) %s\n\n", (unsigned int)buf1_len, buf1); - fprintf(stderr, "buf2 (%u) %s\n\n", (unsigned int)buf2_len , buf2); - fprintf(stderr, "buf3 (%u) %s\n", (unsigned int)buf3_len, buf3); - abort(); -} - -// user required to free the result -// string terminated by \0 -char * -create_large_chunked_message (int body_size_in_kb, const char* headers) -{ - int i; - size_t wrote = 0; - size_t headers_len = strlen(headers); - size_t bufsize = headers_len + (5+1024+2)*body_size_in_kb + 6; - char * buf = malloc(bufsize); - - memcpy(buf, headers, headers_len); - wrote += headers_len; - - for (i = 0; i < body_size_in_kb; i++) { - // write 1kb chunk into the body. - memcpy(buf + wrote, "400\r\n", 5); - wrote += 5; - memset(buf + wrote, 'C', 1024); - wrote += 1024; - strcpy(buf + wrote, "\r\n"); - wrote += 2; - } - - memcpy(buf + wrote, "0\r\n\r\n", 6); - wrote += 6; - assert(wrote == bufsize); - - return buf; -} - -/* Verify that we can pause parsing at any of the bytes in the - * message and still get the result that we're expecting. */ -void -test_message_pause (const struct message *msg) -{ - char *buf = (char*) msg->raw; - size_t buflen = strlen(msg->raw); - size_t nread; - - parser_init(msg->type); - - do { - nread = parse_pause(buf, buflen); - - // We can only set the upgrade buffer once we've gotten our message - // completion callback. - if (messages[0].message_complete_cb_called && - msg->upgrade && - parser->upgrade) { - messages[0].upgrade = buf + nread; - goto test; - } - - if (nread < buflen) { - - // Not much do to if we failed a strict-mode check - if (HTTP_PARSER_ERRNO(parser) == HPE_STRICT) { - parser_free(); - return; - } - - assert (HTTP_PARSER_ERRNO(parser) == HPE_PAUSED); - } - - buf += nread; - buflen -= nread; - http_parser_pause(parser, 0); - } while (buflen > 0); - - nread = parse_pause(NULL, 0); - assert (nread == 0); - -test: - if (num_messages != 1) { - printf("\n*** num_messages != 1 after testing '%s' ***\n\n", msg->name); - abort(); - } - - if(!message_eq(0, msg)) abort(); - - parser_free(); -} - -int -main (void) -{ - parser = NULL; - int i, j, k; - int request_count; - int response_count; - unsigned long version; - unsigned major; - unsigned minor; - unsigned patch; - - version = http_parser_version(); - major = (version >> 16) & 255; - minor = (version >> 8) & 255; - patch = version & 255; - printf("http_parser v%u.%u.%u (0x%06lx)\n", major, minor, patch, version); - - printf("sizeof(http_parser) = %u\n", (unsigned int)sizeof(http_parser)); - - for (request_count = 0; requests[request_count].name; request_count++); - for (response_count = 0; responses[response_count].name; response_count++); - - //// API - test_preserve_data(); - test_parse_url(); - test_method_str(); - - //// NREAD - test_header_nread_value(); - - //// OVERFLOW CONDITIONS - - test_header_overflow_error(HTTP_REQUEST); - test_no_overflow_long_body(HTTP_REQUEST, 1000); - test_no_overflow_long_body(HTTP_REQUEST, 100000); - - test_header_overflow_error(HTTP_RESPONSE); - test_no_overflow_long_body(HTTP_RESPONSE, 1000); - test_no_overflow_long_body(HTTP_RESPONSE, 100000); - - test_header_content_length_overflow_error(); - test_chunk_content_length_overflow_error(); - - //// HEADER FIELD CONDITIONS - test_double_content_length_error(HTTP_REQUEST); - test_chunked_content_length_error(HTTP_REQUEST); - test_header_cr_no_lf_error(HTTP_REQUEST); - test_invalid_header_field_token_error(HTTP_REQUEST); - test_invalid_header_field_content_error(HTTP_REQUEST); - test_double_content_length_error(HTTP_RESPONSE); - test_chunked_content_length_error(HTTP_RESPONSE); - test_header_cr_no_lf_error(HTTP_RESPONSE); - test_invalid_header_field_token_error(HTTP_RESPONSE); - test_invalid_header_field_content_error(HTTP_RESPONSE); - - //// RESPONSES - - for (i = 0; i < response_count; i++) { - test_message(&responses[i]); - } - - for (i = 0; i < response_count; i++) { - test_message_pause(&responses[i]); - } - - for (i = 0; i < response_count; i++) { - if (!responses[i].should_keep_alive) continue; - for (j = 0; j < response_count; j++) { - if (!responses[j].should_keep_alive) continue; - for (k = 0; k < response_count; k++) { - test_multiple3(&responses[i], &responses[j], &responses[k]); - } - } - } - - test_message_count_body(&responses[NO_HEADERS_NO_BODY_404]); - test_message_count_body(&responses[TRAILING_SPACE_ON_CHUNKED_BODY]); - - // test very large chunked response - { - char * msg = create_large_chunked_message(31337, - "HTTP/1.0 200 OK\r\n" - "Transfer-Encoding: chunked\r\n" - "Content-Type: text/plain\r\n" - "\r\n"); - struct message large_chunked = - {.name= "large chunked" - ,.type= HTTP_RESPONSE - ,.raw= msg - ,.should_keep_alive= FALSE - ,.message_complete_on_eof= FALSE - ,.http_major= 1 - ,.http_minor= 0 - ,.status_code= 200 - ,.response_status= "OK" - ,.num_headers= 2 - ,.headers= - { { "Transfer-Encoding", "chunked" } - , { "Content-Type", "text/plain" } - } - ,.body_size= 31337*1024 - ,.num_chunks_complete= 31338 - }; - for (i = 0; i < MAX_CHUNKS; i++) { - large_chunked.chunk_lengths[i] = 1024; - } - test_message_count_body(&large_chunked); - free(msg); - } - - - - printf("response scan 1/2 "); - test_scan( &responses[TRAILING_SPACE_ON_CHUNKED_BODY] - , &responses[NO_BODY_HTTP10_KA_204] - , &responses[NO_REASON_PHRASE] - ); - - printf("response scan 2/2 "); - test_scan( &responses[BONJOUR_MADAME_FR] - , &responses[UNDERSTORE_HEADER_KEY] - , &responses[NO_CARRIAGE_RET] - ); - - puts("responses okay"); - - - /// REQUESTS - - test_simple("GET / HTP/1.1\r\n\r\n", HPE_INVALID_VERSION); - - // Well-formed but incomplete - test_simple("GET / HTTP/1.1\r\n" - "Content-Type: text/plain\r\n" - "Content-Length: 6\r\n" - "\r\n" - "fooba", - HPE_OK); - - static const char *all_methods[] = { - "DELETE", - "GET", - "HEAD", - "POST", - "PUT", - //"CONNECT", //CONNECT can't be tested like other methods, it's a tunnel - "OPTIONS", - "TRACE", - "COPY", - "LOCK", - "MKCOL", - "MOVE", - "PROPFIND", - "PROPPATCH", - "SEARCH", - "UNLOCK", - "BIND", - "REBIND", - "UNBIND", - "ACL", - "REPORT", - "MKACTIVITY", - "CHECKOUT", - "MERGE", - "M-SEARCH", - "NOTIFY", - "SUBSCRIBE", - "UNSUBSCRIBE", - "PATCH", - "PURGE", - "MKCALENDAR", - "LINK", - "UNLINK", - 0 }; - const char **this_method; - for (this_method = all_methods; *this_method; this_method++) { - char buf[200]; - sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method); - test_simple(buf, HPE_OK); - } - - static const char *bad_methods[] = { - "ASDF", - "C******", - "COLA", - "GEM", - "GETA", - "M****", - "MKCOLA", - "PROPPATCHA", - "PUN", - "PX", - "SA", - "hello world", - 0 }; - for (this_method = bad_methods; *this_method; this_method++) { - char buf[200]; - sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method); - test_simple(buf, HPE_INVALID_METHOD); - } - - // illegal header field name line folding - test_simple("GET / HTTP/1.1\r\n" - "name\r\n" - " : value\r\n" - "\r\n", - HPE_INVALID_HEADER_TOKEN); - - const char *dumbfuck2 = - "GET / HTTP/1.1\r\n" - "X-SSL-Bullshit: -----BEGIN CERTIFICATE-----\r\n" - "\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\r\n" - "\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\r\n" - "\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\r\n" - "\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\r\n" - "\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\r\n" - "\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\r\n" - "\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC/1R64fAcEF\r\n" - "\tW51rEyFYiIeZGx/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\r\n" - "\tgW7cMA/s/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi/F1SiFlPDxuDfmdiNzL31+sL\r\n" - "\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW/iaLB0/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\r\n" - "\tu2MSpFyf+9BbC/aXgaZuiCvSR+8Snv3xApQY+fULK/xY8h8Ua51iXoQ5jrgu2SqR\r\n" - "\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\r\n" - "\tA1UdEwEB/wQCMAAwEQYJYIZIAYb4QgHTTPAQDAgWgMA4GA1UdDwEB/wQEAwID6DAs\r\n" - "\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\r\n" - "\tVR0OBBYEFDTt/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\r\n" - "\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\r\n" - "\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\r\n" - "\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\r\n" - "\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\r\n" - "\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\r\n" - "\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\r\n" - "\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\r\n" - "\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\r\n" - "\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS/U4iiooBENGW/Hwmmd3\r\n" - "\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv/hmi0qlnlHs+k/3Iobc3LjS5AMYr5L8\r\n" - "\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\r\n" - "\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\r\n" - "\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7/ZhW6DqT8UFvsAdjvQbXyhV8Eu\r\n" - "\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0/ES5gDGsABo4fqovUKlgop3\r\n" - "\tRA==\r\n" - "\t-----END CERTIFICATE-----\r\n" - "\r\n"; - test_simple(dumbfuck2, HPE_OK); - - const char *corrupted_connection = - "GET / HTTP/1.1\r\n" - "Host: www.example.com\r\n" - "Connection\r\033\065\325eep-Alive\r\n" - "Accept-Encoding: gzip\r\n" - "\r\n"; - test_simple(corrupted_connection, HPE_INVALID_HEADER_TOKEN); - - const char *corrupted_header_name = - "GET / HTTP/1.1\r\n" - "Host: www.example.com\r\n" - "X-Some-Header\r\033\065\325eep-Alive\r\n" - "Accept-Encoding: gzip\r\n" - "\r\n"; - test_simple(corrupted_header_name, HPE_INVALID_HEADER_TOKEN); - -#if 0 - // NOTE(Wed Nov 18 11:57:27 CET 2009) this seems okay. we just read body - // until EOF. - // - // no content-length - // error if there is a body without content length - const char *bad_get_no_headers_no_body = "GET /bad_get_no_headers_no_body/world HTTP/1.1\r\n" - "Accept: */*\r\n" - "\r\n" - "HELLO"; - test_simple(bad_get_no_headers_no_body, 0); -#endif - /* TODO sending junk and large headers gets rejected */ - - - /* check to make sure our predefined requests are okay */ - for (i = 0; requests[i].name; i++) { - test_message(&requests[i]); - } - - for (i = 0; i < request_count; i++) { - test_message_pause(&requests[i]); - } - - for (i = 0; i < request_count; i++) { - if (!requests[i].should_keep_alive) continue; - for (j = 0; j < request_count; j++) { - if (!requests[j].should_keep_alive) continue; - for (k = 0; k < request_count; k++) { - test_multiple3(&requests[i], &requests[j], &requests[k]); - } - } - } - - printf("request scan 1/4 "); - test_scan( &requests[GET_NO_HEADERS_NO_BODY] - , &requests[GET_ONE_HEADER_NO_BODY] - , &requests[GET_NO_HEADERS_NO_BODY] - ); - - printf("request scan 2/4 "); - test_scan( &requests[POST_CHUNKED_ALL_YOUR_BASE] - , &requests[POST_IDENTITY_BODY_WORLD] - , &requests[GET_FUNKY_CONTENT_LENGTH] - ); - - printf("request scan 3/4 "); - test_scan( &requests[TWO_CHUNKS_MULT_ZERO_END] - , &requests[CHUNKED_W_TRAILING_HEADERS] - , &requests[CHUNKED_W_BULLSHIT_AFTER_LENGTH] - ); - - printf("request scan 4/4 "); - test_scan( &requests[QUERY_URL_WITH_QUESTION_MARK_GET] - , &requests[PREFIX_NEWLINE_GET ] - , &requests[CONNECT_REQUEST] - ); - - puts("requests okay"); - - return 0; -} diff --git a/beast/http/message.h b/beast/http/message.h deleted file mode 100644 index 6dc09a3b7f..0000000000 --- a/beast/http/message.h +++ /dev/null @@ -1,409 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_MESSAGE_H_INCLUDED -#define BEAST_HTTP_MESSAGE_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace http { - -namespace detail { - -struct request_fields -{ - http::method_t method; - std::string url; -}; - -struct response_fields -{ - int status; - std::string reason; -}; - -} // detail - -struct request_params -{ - http::method_t method; - std::string url; - int version; -}; - -struct response_params -{ - int status; - std::string reason; - int version; -}; - -/** A HTTP message. - - A message can be a request or response, depending on the `isRequest` - template argument value. Requests and responses have different types, - so functions may be overloaded on them if desired. - - The `Body` template argument type determines the model used - to read or write the content body of the message. - - @tparam isRequest `true` if this is a request. - - @tparam Body A type meeting the requirements of Body. - - @tparam Headers A type meeting the requirements of Headers. -*/ -template -struct message - : std::conditional_t -{ - /** The trait type characterizing the body. - - The body member will be of type body_type::value_type. - */ - using body_type = Body; - using headers_type = Headers; - - using is_request = - std::integral_constant; - - int version; // 10 or 11 - headers_type headers; - typename Body::value_type body; - - message(); - message(message&&) = default; - message(message const&) = default; - message& operator=(message&&) = default; - message& operator=(message const&) = default; - - /** Construct a HTTP request. - */ - explicit - message(request_params params); - - /** Construct a HTTP response. - */ - explicit - message(response_params params); - - /// Serialize the request or response line to a Streambuf. - template - void - write_firstline(Streambuf& streambuf) const - { - write_firstline(streambuf, - std::integral_constant{}); - } - - /// Diagnostics only - template - friend - std::ostream& - operator<<(std::ostream& os, - message const& m); - -private: - template - void - write_firstline(Streambuf& streambuf, - std::true_type) const; - - template - void - write_firstline(Streambuf& streambuf, - std::false_type) const; -}; - -#if ! GENERATING_DOCS - -/// A typical HTTP request -template>> -using request = message; - -/// A typical HTTP response -template>> -using response = message; - -#endif - -// For diagnostic output only -template -std::ostream& -operator<<(std::ostream& os, - message const& m); - -/// Write a FieldSequence to a Streambuf. -template -void -write_fields(Streambuf& streambuf, FieldSequence const& fields); - -/// Returns `true` if a message indicates a keep alive -template -bool -is_keep_alive(message const& msg); - -/// Returns `true` if a message indicates a HTTP Upgrade request or response -template -bool -is_upgrade(message const& msg); - -} // http -} // beast - -#include - -//------------------------------------------------------------------------------ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace deprecated_http { - -inline -std::pair -http_1_0() -{ - return std::pair(1, 0); -} - -inline -std::pair -http_1_1() -{ - return std::pair(1, 1); -} - -class message -{ -private: - bool request_; - - // request - beast::http::method_t method_; - std::string url_; - - // response - int status_; - std::string reason_; - - // message - std::pair version_; - bool keep_alive_; - bool upgrade_; - -public: - ~message() = default; - message (message const&) = default; - message (message&& other) = default; - message& operator= (message const&) = default; - message& operator= (message&& other) = default; - - template - message(); - - // Memberspace - beast::http::headers> headers; - - bool - request() const - { - return request_; - } - - void - request (bool value) - { - request_ = value; - } - - // Request - - void - method (beast::http::method_t http_method) - { - method_ = http_method; - } - - beast::http::method_t - method() const - { - return method_; - } - - void - url (std::string const& s) - { - url_ = s; - } - - std::string const& - url() const - { - return url_; - } - - /** Returns `false` if this is not the last message. - When keep_alive returns `false`: - * Server roles respond with a "Connection: close" header. - * Client roles close the connection. - */ - bool - keep_alive() const - { - return keep_alive_; - } - - /** Set the keep_alive setting. */ - void - keep_alive (bool value) - { - keep_alive_ = value; - } - - /** Returns `true` if this is an HTTP Upgrade message. - @note Upgrade messages have no content body. - */ - bool - upgrade() const - { - return upgrade_; - } - - /** Set the upgrade setting. */ - void - upgrade (bool value) - { - upgrade_ = value; - } - - int - status() const - { - return status_; - } - - void - status (int code) - { - status_ = code; - } - - std::string const& - reason() const - { - return reason_; - } - - void - reason (std::string const& text) - { - reason_ = text; - } - - // Message - - void - version (int major, int minor) - { - version_ = std::make_pair (major, minor); - } - - void - version (std::pair p) - { - version_ = p; - } - - std::pair - version() const - { - return version_; - } -}; - -//------------------------------------------------------------------------------ - -template -message::message() - : request_ (true) - , method_ (beast::http::method_t::http_get) - , url_ ("/") - , status_ (200) - , version_ (1, 1) - , keep_alive_ (false) - , upgrade_ (false) -{ -} - -//------------------------------------------------------------------------------ - -template -void -write (Streambuf& stream, message const& m) -{ - if (m.request()) - { - http::detail::write (stream, to_string(m.method())); - http::detail::write (stream, " "); - http::detail::write (stream, m.url()); - http::detail::write (stream, " HTTP/"); - http::detail::write (stream, std::to_string(m.version().first)); - http::detail::write (stream, "."); - http::detail::write (stream, std::to_string(m.version().second)); - } - else - { - http::detail::write (stream, "HTTP/"); - http::detail::write (stream, std::to_string(m.version().first)); - http::detail::write (stream, "."); - http::detail::write (stream, std::to_string(m.version().second)); - http::detail::write (stream, " "); - http::detail::write (stream, std::to_string(m.status())); - http::detail::write (stream, " "); - http::detail::write (stream, m.reason()); - } - http::detail::write (stream, "\r\n"); - write_fields(stream, m.headers); - http::detail::write (stream, "\r\n"); -} - -} // deprecated_http -} // beast - -#endif diff --git a/beast/http/parser.h b/beast/http/parser.h deleted file mode 100644 index 826803e397..0000000000 --- a/beast/http/parser.h +++ /dev/null @@ -1,282 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_PARSER_H_INCLUDED -#define BEAST_HTTP_PARSER_H_INCLUDED - -#include -#include -#include -#include -#include -#include // -#include - -namespace beast { -namespace http { - -/** A HTTP parser. - - The parser may only be used once. -*/ -template -class parser - : public basic_parser> -{ - using message_type = - message; - - message_type m_; - typename message_type::body_type::reader r_; - bool started_ = false; - -public: - parser(parser&&) = default; - - parser() - : http::basic_parser(isRequest) - , r_(m_) - { - } - - /// Returns `true` if at least one byte has been processed - bool - started() - { - return started_; - } - - message_type - release() - { - return std::move(m_); - } - -private: - friend class http::basic_parser; - - void - on_start() - { - started_ = true; - } - - void - on_field(std::string const& field, std::string const& value) - { - m_.headers.insert(field, value); - } - - void - on_headers_complete(error_code&) - { - // vFALCO TODO Decode the Content-Length and - // Transfer-Encoding, see if we can reserve the buffer. - // - // r_.reserve(content_length) - } - - bool - on_request(http::method_t method, std::string const& url, - int major, int minor, bool keep_alive, bool upgrade, - std::true_type) - { - m_.method = method; - m_.url = url; - m_.version = major * 10 + minor; - return true; - } - - bool - on_request(http::method_t, std::string const&, - int, int, bool, bool, - std::false_type) - { - return true; - } - - bool - on_request(http::method_t method, std::string const& url, - int major, int minor, bool keep_alive, bool upgrade) - { - return on_request(method, url, - major, minor, keep_alive, upgrade, - typename message_type::is_request{}); - } - - bool - on_response(int status, std::string const& reason, - int major, int minor, bool keep_alive, bool upgrade, - std::true_type) - { - m_.status = status; - m_.reason = reason; - m_.version = major * 10 + minor; - // VFALCO TODO return expect_body_ - return true; - } - - bool - on_response(int, std::string const&, int, int, bool, bool, - std::false_type) - { - return true; - } - - bool - on_response(int status, std::string const& reason, - int major, int minor, bool keep_alive, bool upgrade) - { - return on_response( - status, reason, major, minor, keep_alive, upgrade, - std::integral_constant{}); - } - - void - on_body(void const* data, - std::size_t size, error_code& ec) - { - r_.write(data, size, ec); - } - - void - on_complete() - { - } -}; - -} // http -} // beast - -//------------------------------------------------------------------------------ - -// -// LEGACY -// - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace deprecated_http { - -/** Parser for HTTP messages. - The result is stored in a message object. -*/ -class parser - : public beast::http::basic_parser -{ -// friend class basic_parser; - - message& m_; - std::function write_body_; - -public: - parser(parser&&) = default; - parser(parser const&) = delete; - parser& operator=(parser&&) = delete; - parser& operator=(parser const&) = delete; - - /** Construct a parser for HTTP request or response. - The headers plus request or status line are stored in message. - The content-body, if any, is passed as a series of calls to - the write_body function. Transfer encodings are applied before - any data is passed to the write_body function. - */ - parser(std::function write_body, - message& m, bool request) - : basic_parser(request) - , m_(m) - , write_body_(std::move(write_body)) - { - m_.request(request); - } - - parser(message& m, body& b, bool request) - : basic_parser(request) - , m_(m) - { - write_body_ = [&b](void const* data, std::size_t size) - { - b.write(data, size); - }; - m_.request(request); - } - -//private: - void - on_start() - { - } - - void - on_headers_complete(error_code&) - { - } - - bool - on_request(http::method_t method, std::string const& url, - int major, int minor, bool keep_alive, bool upgrade) - { - m_.method(method); - m_.url(url); - m_.version(major, minor); - m_.keep_alive(keep_alive); - m_.upgrade(upgrade); - return true; - } - - bool - on_response(int status, std::string const& text, - int major, int minor, bool keep_alive, bool upgrade) - { - m_.status(status); - m_.reason(text); - m_.version(major, minor); - m_.keep_alive(keep_alive); - m_.upgrade(upgrade); - return true; - } - - void - on_field(std::string const& field, std::string const& value) - { - m_.headers.insert(field, value); - } - - void - on_body(void const* data, std::size_t bytes, error_code&) - { - write_body_(data, bytes); - } - - void - on_complete() - { - } -}; - -} // deprecated_http -} // beast - -#endif diff --git a/beast/http/resume_context.h b/beast/http/resume_context.h deleted file mode 100644 index 944c712b2f..0000000000 --- a/beast/http/resume_context.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_RESUME_CONTEXT_H_INCLUDED -#define BEAST_HTTP_RESUME_CONTEXT_H_INCLUDED - -#include - -namespace beast { -namespace http { - -/** A functor that resumes a write operation. - - An rvalue reference to an object of this type is provided by the - write implementation to the `writer` associated with the body of - a message being sent. - - If it is desired that the `writer` suspend the write operation (for - example, to wait until data is ready), it can take ownership of - the resume context using a move. Then, it returns `boost::indeterminate` - to indicate that the write operation should suspend. Later, the calling - code invokes the resume function and the write operation continues - from where it left off. -*/ -using resume_context = std::function; - -} // http -} // beast - -#endif diff --git a/beast/http/src/beast_http_nodejs_parser.cpp b/beast/http/src/beast_http_nodejs_parser.cpp deleted file mode 100644 index cd0620f971..0000000000 --- a/beast/http/src/beast_http_nodejs_parser.cpp +++ /dev/null @@ -1,90 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include - -#ifdef _MSC_VER -# pragma warning (push) -# pragma warning (disable: 4127) // conditional expression is constant -# pragma warning (disable: 4244) // integer conversion, possible loss of data -#endif -#include -#ifdef _MSC_VER -# pragma warning (pop) -#endif - -beast::http::method_t -convert_http_method(http_method m) -{ - using namespace beast; - switch (m) - { - case HTTP_DELETE: return http::method_t::http_delete; - case HTTP_GET: return http::method_t::http_get; - case HTTP_HEAD: return http::method_t::http_head; - case HTTP_POST: return http::method_t::http_post; - case HTTP_PUT: return http::method_t::http_put; - - // pathological - case HTTP_CONNECT: return http::method_t::http_connect; - case HTTP_OPTIONS: return http::method_t::http_options; - case HTTP_TRACE: return http::method_t::http_trace; - - // webdav - case HTTP_COPY: return http::method_t::http_copy; - case HTTP_LOCK: return http::method_t::http_lock; - case HTTP_MKCOL: return http::method_t::http_mkcol; - case HTTP_MOVE: return http::method_t::http_move; - case HTTP_PROPFIND: return http::method_t::http_propfind; - case HTTP_PROPPATCH: return http::method_t::http_proppatch; - case HTTP_SEARCH: return http::method_t::http_search; - case HTTP_UNLOCK: return http::method_t::http_unlock; - case HTTP_BIND: return http::method_t::http_bind; - case HTTP_REBIND: return http::method_t::http_rebind; - case HTTP_UNBIND: return http::method_t::http_unbind; - case HTTP_ACL: return http::method_t::http_acl; - - // subversion - case HTTP_REPORT: return http::method_t::http_report; - case HTTP_MKACTIVITY: return http::method_t::http_mkactivity; - case HTTP_CHECKOUT: return http::method_t::http_checkout; - case HTTP_MERGE: return http::method_t::http_merge; - - // upnp - case HTTP_MSEARCH: return http::method_t::http_msearch; - case HTTP_NOTIFY: return http::method_t::http_notify; - case HTTP_SUBSCRIBE: return http::method_t::http_subscribe; - case HTTP_UNSUBSCRIBE: return http::method_t::http_unsubscribe; - - // RFC-5789 - case HTTP_PATCH: return http::method_t::http_patch; - case HTTP_PURGE: return http::method_t::http_purge; - - // CalDav - case HTTP_MKCALENDAR: return http::method_t::http_mkcalendar; - - // RFC-2068, section 19.6.1.2 - case HTTP_LINK: return http::method_t::http_link; - case HTTP_UNLINK: return http::method_t::http_unlink; - }; - - return http::method_t::http_get; -} diff --git a/beast/http/src/nodejs_parser.h b/beast/http/src/nodejs_parser.h deleted file mode 100644 index ae5ab9ad69..0000000000 --- a/beast/http/src/nodejs_parser.h +++ /dev/null @@ -1,45 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_NODEJS_PARSER_H_INCLUDED -#define BEAST_HTTP_NODEJS_PARSER_H_INCLUDED - -#include -#include -#include - -beast::http::method_t -convert_http_method(http_method m); - -namespace boost { -namespace system { -template<> -struct is_error_code_enum - : std::true_type -{ -}; -template<> -struct is_error_condition_enum - : std::true_type -{ -}; -} // system -} // boost - -#endif diff --git a/beast/http/src/test/beast_http_parser_test.cpp b/beast/http/src/test/beast_http_parser_test.cpp deleted file mode 100644 index a54e50dc11..0000000000 --- a/beast/http/src/test/beast_http_parser_test.cpp +++ /dev/null @@ -1,94 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include -#include - -namespace beast { -namespace deprecated_http { -namespace test { - -class parser_test : public beast::unit_test::suite -{ -public: - message - request(std::string const& text) - { - body b; - message m; - parser p(m, b, true); - auto const used = - p.write(boost::asio::buffer(text)); - expect(used == text.size()); - p.write_eof(); - return m; - } - - void - test_headers() - { - beast::http::headers> h; - h.insert("Field", "Value"); - expect (h.erase("Field") == 1); - } - - void - run() - { - test_headers(); - - { - std::string const text = - "GET / HTTP/1.1\r\n" - "\r\n" - ; - body b; - message m; - parser p (m, b, true); - auto const used = p.write( - boost::asio::buffer(text)); - expect(used == text.size()); - p.write_eof(); - expect(p.complete()); - } - - { - // malformed - std::string const text = - "GET\r\n" - "\r\n" - ; - body b; - message m; - parser p(m, b, true); - boost::system::error_code ec; - p.write(boost::asio::buffer(text), ec); - if(expect(ec)) - expect(ec.message() == "invalid HTTP method"); - } - } -}; - -BEAST_DEFINE_TESTSUITE(parser,http,beast); - -} // test -} // deprecated_http -} // beast diff --git a/beast/http/type_check.h b/beast/http/type_check.h deleted file mode 100644 index 8bde8001b0..0000000000 --- a/beast/http/type_check.h +++ /dev/null @@ -1,84 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_TYPE_CHECK_H_INCLUDED -#define BEAST_HTTP_TYPE_CHECK_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include // - -namespace beast { -namespace http { - -#if GENERATING_DOCS -namespace detail { -#else -namespace concept { -#endif - -struct Reader -{ - template - Reader(message&) noexcept; - void write(void const*, std::size_t, error_code&) noexcept; -}; - -} // concept - -/// Evaluates to std::true_type if `T` models Body -template -struct is_Body : std::true_type -{ -}; - -/// Evalulates to std::true_type if Body has a reader -template -struct is_ReadableBody : std::true_type -{ -}; - -/// Evalulates to std::true_type if Body has a writer -template -struct is_WritableBody : std::true_type -{ -}; - -/// Evaluates to std::true_type if `T` models HTTPMessage -template -struct is_HTTPMessage : std::false_type -{ -}; - -/// Evaluates to std::true_type if `HTTPMessage` is a request -template -struct is_HTTPRequest : std::true_type -{ -}; - -} // http -} // beast - -#endif diff --git a/beast/streams/abstract_ostream.h b/beast/streams/abstract_ostream.h deleted file mode 100644 index b4275feff9..0000000000 --- a/beast/streams/abstract_ostream.h +++ /dev/null @@ -1,32 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STREAMS_ABSTRACT_OSTREAM_H_INCLUDED -#define BEAST_STREAMS_ABSTRACT_OSTREAM_H_INCLUDED - -#include - -namespace beast { - -/** An abstract ostream for `char`. */ -using abstract_ostream = basic_abstract_ostream ; - -} - -#endif diff --git a/beast/streams/basic_std_ostream.h b/beast/streams/basic_std_ostream.h deleted file mode 100644 index 316d53a4d4..0000000000 --- a/beast/streams/basic_std_ostream.h +++ /dev/null @@ -1,73 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STREAMS_BASIC_STD_OSTREAM_H_INCLUDED -#define BEAST_STREAMS_BASIC_STD_OSTREAM_H_INCLUDED - -#include - -#include - -namespace beast { - -/** Wraps an existing std::basic_ostream as an abstract_ostream. */ -template < - class CharT, - class Traits = std::char_traits -> -class basic_std_ostream - : public basic_abstract_ostream -{ -private: - using typename basic_abstract_ostream ::string_type; - - std::reference_wrapper m_stream; - -public: - explicit basic_std_ostream ( - std::basic_ostream & stream) - : m_stream (stream) - { - } - - void - write (string_type const& s) override - { - m_stream.get() << s << std::endl; - } -}; - -using std_ostream = basic_std_ostream ; - -//------------------------------------------------------------------------------ - -/** Returns a basic_std_ostream using template argument deduction. */ -template < - class CharT, - class Traits = std::char_traits -> -basic_std_ostream -make_std_ostream (std::basic_ostream & stream) -{ - return basic_std_ostream (stream); -} - -} - -#endif diff --git a/beast/streams/debug_ostream.h b/beast/streams/debug_ostream.h deleted file mode 100644 index fc6322f41e..0000000000 --- a/beast/streams/debug_ostream.h +++ /dev/null @@ -1,91 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STREAMS_DEBUG_OSTREAM_H_INCLUDED -#define BEAST_STREAMS_DEBUG_OSTREAM_H_INCLUDED - -#include - -#include - -#ifdef _MSC_VER -# ifndef WIN32_LEAN_AND_MEAN // VC_EXTRALEAN -# define WIN32_LEAN_AND_MEAN -#include -# undef WIN32_LEAN_AND_MEAN -# else -#include -# endif -# ifdef min -# undef min -# endif -# ifdef max -# undef max -# endif -#endif - -namespace beast { - -#ifdef _MSC_VER -/** A basic_abstract_ostream that redirects output to an attached debugger. */ -class debug_ostream - : public abstract_ostream -{ -private: - bool m_debugger; - -public: - debug_ostream() - : m_debugger (IsDebuggerPresent() != FALSE) - { - // Note that the check for an attached debugger is made only - // during construction time, for efficiency. A stream created before - // the debugger is attached will not have output redirected. - } - - void - write (string_type const& s) override - { - if (m_debugger) - { - OutputDebugStringA ((s + "\n").c_str()); - return; - } - - std::cout << s << std::endl; - } -}; - -#else -class debug_ostream - : public abstract_ostream -{ -public: - void - write (string_type const& s) override - { - std::cout << s << std::endl; - } -}; - -#endif - -} - -#endif diff --git a/beast/streams/tests/beast_basic_abstract_ostream_test.cpp b/beast/streams/tests/beast_basic_abstract_ostream_test.cpp deleted file mode 100644 index df2ea3c021..0000000000 --- a/beast/streams/tests/beast_basic_abstract_ostream_test.cpp +++ /dev/null @@ -1,66 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#if BEAST_INCLUDE_BEASTCONFIG -#include "../../BeastConfig.h" -#endif - -#include - -#include - -namespace beast { - -class basic_abstract_ostream_test : public unit_test::suite -{ -public: - class test_stream : public basic_abstract_ostream - { - public: - test_stream& - operator= (test_stream const&) = delete; - - explicit - test_stream (unit_test::suite& suite_) - : m_suite (suite_) - { - } - - void write (string_type const& s) override - { - m_suite.log << s; - } - - private: - unit_test::suite& m_suite; - }; - - void run() - { - test_stream ts (*this); - - ts << "Hello"; - - pass(); - } -}; - -BEAST_DEFINE_TESTSUITE(basic_abstract_ostream,streams,beast); - -} diff --git a/beast/type_name.h b/beast/type_name.h deleted file mode 100644 index 59222ee4fc..0000000000 --- a/beast/type_name.h +++ /dev/null @@ -1,73 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Howard Hinnant - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_TYPE_NAME_H_INCLUDED -#define BEAST_TYPE_NAME_H_INCLUDED - -#include -#include -#include -#ifndef _MSC_VER -#include -#endif -#include -#include -#include -#include - -namespace beast { - -#ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable: 4127) // conditional expression is constant -#endif - -template -std::string -type_name() -{ - using TR = typename std::remove_reference::type; - std::unique_ptr own ( - #ifndef _MSC_VER - abi::__cxa_demangle (typeid(TR).name(), nullptr, - nullptr, nullptr), - #else - nullptr, - #endif - std::free - ); - std::string r = own != nullptr ? own.get() : typeid(TR).name(); - if (std::is_const::value) - r += " const"; - if (std::is_volatile::value) - r += " volatile"; - if (std::is_lvalue_reference::value) - r += "&"; - else if (std::is_rvalue_reference::value) - r += "&&"; - return r; -} - -#ifdef _MSC_VER -#pragma warning (pop) -#endif - -} // beast - -#endif diff --git a/beast/unit_test.h b/beast/unit_test.h deleted file mode 100644 index 2c99801d02..0000000000 --- a/beast/unit_test.h +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_H_INCLUDED -#define BEAST_UNIT_TEST_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/beast/unit_test/README.md b/beast/unit_test/README.md deleted file mode 100644 index 0382e28270..0000000000 --- a/beast/unit_test/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# beast.unit_test - -This provides a framework for defining and running unit tests. diff --git a/beast/unit_test/amount.h b/beast/unit_test/amount.h deleted file mode 100644 index 317f5be810..0000000000 --- a/beast/unit_test/amount.h +++ /dev/null @@ -1,67 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_AMOUNT_H_INCLUDED -#define BEAST_UNIT_TEST_AMOUNT_H_INCLUDED - -#include -#include -#include - -namespace beast { -namespace unit_test { - -/** Utility for producing nicely composed output of amounts with units. */ -class amount -{ -private: - std::size_t n_; - std::string const& what_; - -public: - amount (amount const&) = default; - amount& operator= (amount const&) = delete; - - template - amount (std::size_t n, std::string const& what); - - friend - std::ostream& - operator<< (std::ostream& s, amount const& t); -}; - -template -amount::amount (std::size_t n, std::string const& what) - : n_ (n) - , what_ (what) -{ -} - -inline -std::ostream& -operator<< (std::ostream& s, amount const& t) -{ - s << t.n_ << " " << t.what_ << ((t.n_ != 1) ? "s" : ""); - return s; -} - -} // unit_test -} // beast - -#endif diff --git a/beast/unit_test/global_suites.h b/beast/unit_test/global_suites.h deleted file mode 100644 index 8a446c91ed..0000000000 --- a/beast/unit_test/global_suites.h +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_GLOBAL_SUITES_H_INCLUDED -#define BEAST_UNIT_TEST_GLOBAL_SUITES_H_INCLUDED - -#include - -namespace beast { -namespace unit_test { - -namespace detail { - -template -suite_list& -global_suites() -{ - static suite_list s; - return s; -} - -template -struct insert_suite -{ - template - insert_suite (char const* name, char const* module, - char const* library, bool manual); -}; - -template -template -insert_suite::insert_suite (char const* name, - char const* module, char const* library, bool manual) -{ - global_suites().insert ( - name, module, library, manual); -} - -} // detail - -/** Holds suites registered during static initialization. */ -inline -suite_list const& -global_suites() -{ - return detail::global_suites(); -} - -} -} - -#endif diff --git a/beast/unit_test/print.h b/beast/unit_test/print.h deleted file mode 100644 index 376cc8686e..0000000000 --- a/beast/unit_test/print.h +++ /dev/null @@ -1,80 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_PRINT_H_INCLUDED -#define BEAST_UNIT_TEST_PRINT_H_INCLUDED - -#include -#include - -#include -#include - -#include -#include - -namespace beast { -namespace unit_test { - -/** Write test results to the specified output stream. */ -/** @{ */ -template -void -print (results const& r, abstract_ostream& stream) -{ - for (auto const& s : r) - { - for (auto const& c : s) - { - stream << - s.name() << - (c.name().empty() ? "" : ("." + c.name())); - - std::size_t i (1); - for (auto const& t : c.tests) - { - if (! t.pass) - stream << - "#" << i << - " failed: " << t.reason; - ++i; - } - } - } - - stream << - amount (r.size(), "suite") << ", " << - amount (r.cases(), "case") << ", " << - amount (r.total(), "test") << " total, " << - amount (r.failed(), "failure") - ; -} - -template -void -print (results const& r, std::ostream& stream = std::cout) -{ - auto s (make_std_ostream (stream)); - print (r, s); -} - -} // unit_test -} // beast - -#endif diff --git a/beast/unity/beast_asio_unity.cpp b/beast/unity/beast_asio_unity.cpp deleted file mode 100644 index 74208df9d0..0000000000 --- a/beast/unity/beast_asio_unity.cpp +++ /dev/null @@ -1,22 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include diff --git a/beast/unity/beast_clock_unity.cpp b/beast/unity/beast_clock_unity.cpp deleted file mode 100644 index cb54279ce3..0000000000 --- a/beast/unity/beast_clock_unity.cpp +++ /dev/null @@ -1,21 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include diff --git a/beast/unity/beast_crypto_unity.cpp b/beast/unity/beast_crypto_unity.cpp deleted file mode 100644 index fdb2e106dd..0000000000 --- a/beast/unity/beast_crypto_unity.cpp +++ /dev/null @@ -1,21 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include - diff --git a/beast/unity/beast_hash_unity.cpp b/beast/unity/beast_hash_unity.cpp deleted file mode 100644 index f1b89f4f7c..0000000000 --- a/beast/unity/beast_hash_unity.cpp +++ /dev/null @@ -1,29 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include - -#if ! BEAST_NO_XXHASH -#include -#endif -#include - -#include -#include diff --git a/beast/unity/beast_http_unity.cpp b/beast/unity/beast_http_unity.cpp deleted file mode 100644 index 8e8684a258..0000000000 --- a/beast/unity/beast_http_unity.cpp +++ /dev/null @@ -1,27 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include -#include - -// VFALCO Must come last otherwise Windows 10 SDK -// gets a compile error in winnt.h -#include diff --git a/beast/unity/beast_streams_unity.cpp b/beast/unity/beast_streams_unity.cpp deleted file mode 100644 index 7de0dea249..0000000000 --- a/beast/unity/beast_streams_unity.cpp +++ /dev/null @@ -1,20 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include diff --git a/beast/unity/beast_test_unity.cpp b/beast/unity/beast_test_unity.cpp deleted file mode 100644 index 654d00821f..0000000000 --- a/beast/unity/beast_test_unity.cpp +++ /dev/null @@ -1,20 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include diff --git a/beast/unity/beast_wsproto_unity.cpp b/beast/unity/beast_wsproto_unity.cpp deleted file mode 100644 index c41bd2ac69..0000000000 --- a/beast/unity/beast_wsproto_unity.cpp +++ /dev/null @@ -1,21 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include diff --git a/beast/wsproto.h b/beast/wsproto.h deleted file mode 100644 index 542b308a3f..0000000000 --- a/beast/wsproto.h +++ /dev/null @@ -1,30 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_H_INCLUDED -#define BEAST_WSPROTO_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -#endif diff --git a/beast/wsproto/README.md b/beast/wsproto/README.md deleted file mode 100644 index 22fc6a518c..0000000000 --- a/beast/wsproto/README.md +++ /dev/null @@ -1,232 +0,0 @@ -# Beast.WSProto - --------------------------------------------------------------------------------- - -Beast.WSProto provides developers with a robust WebSocket implementation -built on Boost.Asio with a consistent asynchronous model using a modern -C++ approach. - -## Introduction - -Today's web applications increasingly rely on alternatives to standard HTTP -to achieve performance and/or responsiveness. While WebSocket implementations -are widely available in common web development languages such as Javascript, -good implementations in C++ are scarce. A survey of existing C++ WebSocket -solutions reveals interfaces which have performance limitations, place -unecessary restrictions on callers, exhibit excess complexity, and fail to -take advantage of C++ features or the underlying network transport. - -Beast.WSProto is built on Boost.Asio, a robust cross platform networking -framework that is part of Boost and also offered as a standalone library. -A proposal to add networking functionality to the C++ standard library, -based on Boost.Asio, is under consideration by the standards committee. -Since the final approved networking interface for the C++ standard library -will likely closely resemble the current interface of Boost.Asio, it is -logical for Beast.WSProto to use Boost.Asio as its network transport. - -Beast.WSProto addresses the following goals: - -* **Ease of Use.** WSProto offers only one socket object, whose interface -resembles that of Boost.Asio socket as closely as possible. Users familiar -with Boost.Asio will be immediately comfortable using a `wsproto::socket`. - -* **Flexibility.** Library interfaces should provide callers with maximum -flexibility in implementation; Important decisions such as how to manage -buffers or be notified of completed asynchronous operations should be made -by callers not the library. - -* **Performance.** The implementation should achieve the highest level -of performance possible, with no penalty for using abstractions. - -* **Scalability.** The library should facilitate the development of -network applications that scale to thousands of concurrent connections. - -* **Efficiency.** The library should support techniques such as -scatter-gather I/O, and allow programs to minimise data copying. - -* **Basis for further abstraction.** The library should permit the -development of other libraries that provide higher levels of abstraction. - -Beast.WSProto takes advantage of Boost.Asio's universal Asynchronous -model, handler allocation, and handler invocation hooks. Calls to wsproto -asynchronous initiation functions allow callers the choice of using a -completion handler, stackful or stackless coroutines, futures, or user -defined customizations (for example, Boost.Fiber). The implementation -uses handler invocation hooks (`asio_handler_invoke`), providing -execution guarantees on composed operations in a manner identical to -Boost.Asio. The implementation also uses handler allocation hooks -(`asio_handler_allocate`) when allocating memory internally for composed -operations. - -There is no need for inheritance or virtual members in `wsproto::socket`. -All operations are templated and transparent to the compiler, allowing for -maximum inlining and optimization. - -## Usage - -All examples and identifiers mentioned in this document are written as -if the following declarations are in effect: -```C++ -#include -using namespace beast; -using namespace boost::asio; -``` - -### Creating a Socket - -To participate in a WebSocket connection, callers create an instance -of `wsproto::socket` templated on the `Stream` argument, which must meet -the requirements of `AsyncReadStream`, `AsyncWriteStream`, `SyncReadStream`, -and `SyncWriteStream`. Examples of types that meet these requirements are -`ip::tcp::socket` and `ssl::stream<...>`: -```c++ -io_service ios; -wsproto::socket ws1(ios); // owns the socket - -ssl::context ctx(ssl::context::sslv23); -wsproto::socket> wss(ios, ctx); // owns the socket - -ip::tcp::socket sock(ios); -wsproto::socket ws2(sock); // does not own the socket -``` - -### Connection Establishment - -Callers are responsible for performing tasks such as connection establishment -before attempting websocket activities. -```c++ -io_service ios; -wsproto::socket ws(ios); -ws.next_layer().connect(ip::tcp::endpoint( - ip::tcp::address::from_string("127.0.0.1"), 80)); -``` - -### WebSocket Handshake - -After the connection is established, the socket may be used to initiate -or accept a WebSocket Update request. - -```c++ -// send a WebSocket Upgrade request. -ws.handshake(); -``` - -### Sending and Receiving Messages - -After the WebSocket handshake is accomplished, callers may send and receive -messages using the message oriented interface: -```c++ -void echo(wsproto::socket& ws) -{ - streambuf sb; - wsproto::opcode op; - wsproto::read(ws, op, sb); - wsproto::write(ws, op, sb.data()); - sb.consume(sb.size()); -} -``` - -Alternatively, callers may process incoming message data -incrementally: -```c++ -void echo(wsproto::socket& ws) -{ - streambuf sb; - wsproto::msg_info mi{}; - for(;;) - { - ws.read_some(mi, sb); - if(mi.fin) - break; - } - wsproto::write(ws, op, sb.data()); -} -``` - -### Asynchronous Completions, Coroutines, and Futures - -Asynchronous versions are available for all functions: -```c++ -wsproto::async_read(ws, sb, std::bind( - &on_read, beast::asio::placeholders::error)); -``` - -Calls to WSProto asynchronous initiation functions support -asio-style completion handlers, and other completion tokens -such as support for coroutines or futures: -```c++ -void echo(wsproto::socket& ws, - boost::asio::yield_context yield) -{ - wsproto::async_read(ws, sb, yield); - std::future fut = - wsproto::async_write(ws, sb.data(), boost::use_future); - ... -} -``` - -## Implementation - -### Buffers - -Because calls to read WebSocket data may return a variable amount of bytes, -the interface to calls that read data require an object that meets the -requirements of `Streambuf`. This concept is modeled on -`boost::asio::basic_streambuf`, which meets the requirements of `Streambuf` -defined below. - -The `Streambuf` concept is intended to permit the following implementation -strategies: - -* A single contiguous character array, which is reallocated as necessary to - accommodate changes in the size of the byte sequence. This is the - implementation approach currently used in `boost::asio::basic_streambuf`. -* A sequence of one or more byte arrays, where each array is of the same - size. Additional byte array objects are appended to the sequence to - accommodate changes in the size of the byte sequence. -* A sequence of one or more byte arrays of varying sizes. Additional byte - array objects are appended to the sequence to accommodate changes in the - size of the byte sequence. This is the implementation approach currently - used in `beast::basic_streambuf`. - -#### `Streambuf` requirements: - -In the table below, `X` denotes a class, `a` denotes a value -of type `X`, `n` denotes a value convertible to `std::size_t`, -and `U` and `T` denote unspecified types. - -expression | return | type assertion/note/pre/post-condition -------------------------- | ------------- | -------------------------------------- -`X::const_buffers_type` | `T` | `T` meets the requirements for `ConstBufferSequence`. -`X::mutable_buffers_type` | `U` | `U` meets the requirements for `MutableBufferSequence`. -`a.commit(n)` | | Moves bytes from the output sequence to the input sequence. -`a.consume(n)` | | Removes bytes from the input sequence. -`a.data()` | `T` | Returns a list of buffers that represents the input sequence. -`a.prepare(n)` | `U` | Returns a list of buffers that represents the output sequence, with the given size. -`a.size()` | `std::size_t` | Returns the size of the input sequence. -`a.max_size()` | `std::size_t` | Returns the maximum size of the `Streambuf`. - -### Thread Safety - -Like a regular asio socket, a `wsproto::socket` is not thread safe. Callers are -responsible for synchronizing operations on the socket using an implicit or -explicit strand, as per the Asio documentation. A `wsproto::socket` supports -one active read and one active write at the same time (caller initiated close, -ping, and pong operations count as a write). - -### Buffering - -The implementation does not perform queueing or buffering of messages. If desired, -these features should be implemented by callers. The impact of this design is -that the caller is in full control of the allocation strategy used to store -data and the back-pressure applied on the read and write side of the underlying -TCP/IP connection. - -### The `io_service` - -The creation and operation of the `boost::asio::io_service` associated with the -Stream object underlying the `wsproto::socket` is completely left up to the -user of the library, permitting any implementation strategy including one that -does not require threads for environments where threads are unavailable. -Beast.WSProto itself does not use or require threads. diff --git a/beast/wsproto/detail/hybi13.h b/beast/wsproto/detail/hybi13.h deleted file mode 100644 index ec7d56559e..0000000000 --- a/beast/wsproto/detail/hybi13.h +++ /dev/null @@ -1,66 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_HYBI13_H_INCLUDED -#define BEAST_WSPROTO_HYBI13_H_INCLUDED - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace wsproto { -namespace detail { - -template -std::string -make_sec_ws_key(Gen& g) -{ - union U - { - std::array a4; - std::array a16; - }; - U u; - for(int i = 0; i < 4; ++i) - u.a4[i] = g(); - return base64_encode(u.a16.data(), u.a16.size()); -} - -template -std::string -make_sec_ws_accept(boost::string_ref const& key) -{ - std::string s(key.data(), key.size()); - s += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - beast::sha_hasher h; - h(s.data(), s.size()); - auto const digest = static_cast< - beast::sha_hasher::result_type>(h); - return base64_encode(digest.data(), digest.size()); -} - -} // detail -} // wsproto -} // beast - -#endif diff --git a/beast/wsproto/error.h b/beast/wsproto/error.h deleted file mode 100644 index 1ccb658ab7..0000000000 --- a/beast/wsproto/error.h +++ /dev/null @@ -1,72 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_ERROR_H_INCLUDED -#define BEAST_WSPROTO_ERROR_H_INCLUDED - -#include - -namespace beast { -namespace wsproto { - -using error_code = boost::system::error_code; - -/// Error values -enum class error -{ - /// Both sides performed a WebSocket close - closed = 1, - - /// WebSocket connection failed, protocol violation - failed, - - /// Upgrade request failed, connection is closed - handshake_failed, - - /// Upgrade request failed, but connection is still open - keep_alive, - - /// HTTP response is malformed - response_malformed, - - /// HTTP response failed the upgrade - response_failed, - - /// Upgrade request denied for invalid fields. - response_denied, - - /// Upgrade request is malformed - request_malformed, - - /// Upgrade request fields incorrect - request_invalid, - - /// Upgrade request denied - request_denied -}; - -error_code -make_error_code(error e); - -} // wsproto -} // beast - -#include - -#endif diff --git a/beast/wsproto/impl/error.ipp b/beast/wsproto/impl/error.ipp deleted file mode 100644 index 85a7fe9540..0000000000 --- a/beast/wsproto/impl/error.ipp +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_ERROR_IPP_H_INCLUDED -#define BEAST_WSPROTO_ERROR_IPP_H_INCLUDED - -#include - -namespace beast { -namespace wsproto { - -inline -error_code -make_error_code(error e) -{ - return error_code( - static_cast(e), detail::get_error_category()); -} - -} // wsproto -} // beast - -#endif diff --git a/beast/wsproto/src/test/async_echo_peer.h b/beast/wsproto/src/test/async_echo_peer.h deleted file mode 100644 index b81fc8234c..0000000000 --- a/beast/wsproto/src/test/async_echo_peer.h +++ /dev/null @@ -1,285 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_ASYNC_ECHO_PEER_H_INCLUDED -#define BEAST_WSPROTO_ASYNC_ECHO_PEER_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace wsproto { -namespace test { - -// Asynchronous WebSocket echo client/server -// -class async_echo_peer -{ -public: - static std::size_t constexpr autobahnCycles = 520; - - using error_code = boost::system::error_code; - using endpoint_type = boost::asio::ip::tcp::endpoint; - using address_type = boost::asio::ip::address; - using socket_type = boost::asio::ip::tcp::socket; - -private: - unit_test::suite& suite_; - boost::asio::io_service ios_; - socket_type sock_; - boost::asio::ip::tcp::acceptor acceptor_; - std::vector thread_; - std::size_t n_ = 0; - -public: - async_echo_peer(bool server, - endpoint_type const& ep, unit_test::suite& suite) - : suite_(suite) - , sock_(ios_) - , acceptor_(ios_) - { - if(server) - { - error_code ec; - acceptor_.open(ep.protocol(), ec); - maybe_throw(ec, "open"); - acceptor_.bind(ep, ec); - maybe_throw(ec, "bind"); - acceptor_.listen( - boost::asio::socket_base::max_connections, ec); - maybe_throw(ec, "listen"); - acceptor_.async_accept(sock_, - std::bind(&async_echo_peer::on_accept, this, - beast::asio::placeholders::error)); - } - else - { - Peer{std::move(sock_), ep, suite_}; - } - auto const n = 1; - thread_.reserve(n); - for(int i = 0; i < n; ++i) - thread_.emplace_back(suite_, - [&] { ios_.run(); }); - } - - ~async_echo_peer() - { - error_code ec; - ios_.dispatch( - [&]{ acceptor_.close(ec); }); - for(auto& t : thread_) - t.join(); - } - -private: - class Peer - { - struct data - { - int state = 0; - unit_test::suite& suite; - boost::optional ep; - wsproto::socket ws; - wsproto::opcode op; - beast::streambuf sb; - int id; - - data(socket_type&& sock_, - unit_test::suite& suite_) - : suite(suite_) - , ws(std::move(sock_)) - , id([] - { - static int n = 0; - return ++n; - }()) - { - } - - data(socket_type&& sock_, endpoint_type const& ep_, - unit_test::suite& suite_) - : suite(suite_) - , ep(ep_) - , ws(std::move(sock_)) - , id([] - { - static int n = 0; - return ++n; - }()) - { - } - }; - - std::shared_ptr d_; - - public: - Peer(Peer&&) = default; - Peer(Peer const&) = default; - Peer& operator=(Peer&&) = delete; - Peer& operator=(Peer const&) = delete; - - struct identity - { - template - void - operator()(http::message& req) - { - req.headers.replace("User-Agent", "async_echo_client"); - } - - template - void - operator()(http::message& resp) - { - resp.headers.replace("Server", "async_echo_server"); - } - }; - - template - explicit - Peer(socket_type&& sock, Args&&... args) - : d_(std::make_shared( - std::forward(sock), - std::forward(args)...)) - { - auto& d = *d_; - d.ws.set_option(decorate(identity{})); - //d.ws.set_option(auto_fragment_size(0)); - d.ws.set_option(read_message_max(64 * 1024 * 1024)); - run(); - } - - void run() - { - auto& d = *d_; - if(! d.ep) - { - d.ws.async_accept(std::move(*this)); - } - else - { - d.state = 4; - d.ws.next_layer().async_connect( - *d.ep, std::move(*this)); - } - } - - void operator()(error_code ec) - { - auto& d = *d_; - switch(d_->state) - { - // did accept - case 0: - if(ec) - return fail(ec, "async_accept"); - - // start - case 1: - if(ec) - return fail(ec, "async_handshake"); - d.sb.consume(d.sb.size()); - // read message - d.state = 2; - d.ws.async_read(d.op, d.sb, std::move(*this)); - return; - - // got message - case 2: - if(ec == wsproto::error::closed) - return; - if(ec) - return fail(ec, "async_read"); - // write message - d.state = 1; - d.ws.set_option(wsproto::message_type(d.op)); - d.ws.async_write(d.sb.data(), std::move(*this)); - return; - - // connected - case 4: - if(ec) - return fail(ec, "async_connect"); - d.state = 1; - d.ws.async_handshake( - d.ep->address().to_string() + ":" + - std::to_string(d.ep->port()), - "/", std::move(*this)); - return; - } - } - - private: - void - fail(error_code ec, std::string what) - { - if(ec != wsproto::error::closed) - { - d_->suite.log << - "#" << std::to_string(d_->id) << " " << - what << ": " << ec.message(); - } - } - }; - - void - fail(error_code ec, std::string what) - { - suite_.log << - what << ": " << ec.message(); - } - - void - maybe_throw(error_code ec, std::string what) - { - if(ec) - { - fail(ec, what); - throw ec; - } - } - - void - on_accept(error_code ec) - { - if(! acceptor_.is_open()) - return; - maybe_throw(ec, "accept"); - socket_type sock(std::move(sock_)); - if(n_ < autobahnCycles) - acceptor_.async_accept(sock_, - std::bind(&async_echo_peer::on_accept, this, - beast::asio::placeholders::error)); - Peer{std::move(sock), suite_}; - } -}; - -} // test -} // wsproto -} // beast - -#endif diff --git a/beast/wsproto/src/test/beast_wsproto_ws_echo_test.cpp b/beast/wsproto/src/test/beast_wsproto_ws_echo_test.cpp deleted file mode 100644 index 188a8200e3..0000000000 --- a/beast/wsproto/src/test/beast_wsproto_ws_echo_test.cpp +++ /dev/null @@ -1,94 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include -#include -#include - -namespace beast { -namespace wsproto { -namespace test { - -class ws_echo_test : public unit_test::suite -{ -public: - using endpoint_type = boost::asio::ip::tcp::endpoint; - using address_type = boost::asio::ip::address; - - void - run() override - { - async_echo_peer s1(true, endpoint_type{ - address_type::from_string("127.0.0.1"), - 6000 }, *this); - - sync_echo_peer s2(true, endpoint_type{ - address_type::from_string("127.0.0.1"), - 6001 }, *this); - - boost::asio::io_service ios; - boost::asio::signal_set signals( - ios, SIGINT, SIGTERM); - std::mutex m; - bool stop = false; - std::condition_variable cv; - signals.async_wait( - [&](boost::system::error_code const& ec, - int signal_number) - { - std::lock_guard lock(m); - stop = true; - cv.notify_one(); - }); - std::unique_lock lock(m); - cv.wait(lock, [&]{ return stop; }); - } -}; - -class ws_client_test : public unit_test::suite -{ -public: - using endpoint_type = boost::asio::ip::tcp::endpoint; - using address_type = boost::asio::ip::address; - - void - run() override - { - pass(); - { - async_echo_peer s1(false, endpoint_type{ - address_type::from_string("127.0.0.1"), - 9001 }, *this); - } - { - sync_echo_peer s2(false, endpoint_type{ - address_type::from_string("127.0.0.1"), - 9001 }, *this); - } - } -}; - -BEAST_DEFINE_TESTSUITE_MANUAL(ws_echo, asio, beast); -BEAST_DEFINE_TESTSUITE_MANUAL(ws_client, asio, beast); - -} // test -} // wsproto -} // beast diff --git a/beast/wsproto/src/test/beast_wsproto_ws_test.cpp b/beast/wsproto/src/test/beast_wsproto_ws_test.cpp deleted file mode 100644 index 05176ce8f0..0000000000 --- a/beast/wsproto/src/test/beast_wsproto_ws_test.cpp +++ /dev/null @@ -1,362 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace wsproto { - -class ws_test : public unit_test::suite -{ -public: - using error_code = boost::system::error_code; - using endpoint_type = boost::asio::ip::tcp::endpoint; - using address_type = boost::asio::ip::address; - using socket_type = boost::asio::ip::tcp::socket; - using yield_context = boost::asio::yield_context; - - endpoint_type ep_; - - //-------------------------------------------------------------------------- - - // opcodes for creating the test plans - - // concurrent read and write - struct case_1{}; - - // write a bad frame and shut down - struct case_2{}; - - //-------------------------------------------------------------------------- - - class coro_peer - { - error_code ec_; - boost::asio::io_service ios_; - boost::asio::ip::tcp::acceptor acceptor_; - socket_type sock_; - socket ws_; - opcode op_; - beast::streambuf rb_; - beast::streambuf wb_; - yield_context* yield_; - int state_ = 0; - //unit_test::suite& test_; - - public: - coro_peer(coro_peer&&) = default; - coro_peer(coro_peer const&) = delete; - coro_peer& operator=(coro_peer&&) = delete; - coro_peer& operator=(coro_peer const&) = delete; - - template - coro_peer(bool server, endpoint_type ep, - unit_test::suite& test, Ops const&... ops) - : acceptor_(ios_) - , sock_(ios_) - , ws_(sock_) - //, test_(test) - { - if(server) - { - acceptor_.open(ep.protocol()); - acceptor_.bind(ep); - acceptor_.listen( - boost::asio::socket_base::max_connections); - boost::asio::spawn(ios_, - [=](auto yield) - { - yield_ = &yield; - state_ = 10; - acceptor_.async_accept(sock_, (*yield_)[ec_]); - if(ec_) - return this->fail("accept"); - state_ = 20; - ws_.async_accept((*yield_)[ec_]); - if(ec_) - return this->fail("ws.accept"); - this->invoke(ops...); - state_ = -1; - }); - } - else - { - boost::asio::spawn(ios_, - [=](auto yield) - { - yield_ = &yield; - state_ = 30; - sock_.async_connect(ep, (*yield_)[ec_]); - if(ec_) - return this->fail("connect"); - state_ = 40; - ws_.async_handshake(ep.address().to_string() + - std::to_string(ep.port()), "/", (*yield_)[ec_]); - if(ec_) - return this->fail("handshake"); - this->invoke(ops...); - state_ = -1; - }); - } - } - - ~coro_peer() - { - } - - int - state() const - { - return state_; - } - - void - run_one() - { - ios_.run_one(); - } - - void - step_to(int to = 0) - { - while(state_ != to) - ios_.run_one(); - } - - private: - template - void fail(String const& s) - { - } - - void invoke_1(case_1) - { - ws_.async_read(op_, rb_, - [&](auto ec) - { - if(ec) - return this->fail(ec); - rb_.consume(rb_.size()); - }); - state_ = 100; - ws_.async_write( - boost::asio::null_buffers{}, (*yield_)[ec_]); - if(ec_) - return fail("write"); - } - - void invoke_1(case_2) - { - detail::frame_header fh; - fh.op = opcode::rsv5; // bad opcode - fh.fin = true; - fh.mask = true; - fh.rsv1 = false; - fh.rsv2 = false; - fh.rsv3 = false; - fh.len = 0; - fh.key = 0; - detail::write(wb_, fh); - state_ = 200; - boost::asio::async_write( - ws_.next_layer(), wb_.data(), - (*yield_)[ec_]); - if(ec_) - return fail("write"); - ws_.next_layer().shutdown( - socket_type::shutdown_both, ec_); - if(ec_) - return fail("shutdown"); - } - - inline - void - invoke() - { - } - - template - inline - void - invoke(Op op, Ops const&... ops) - { - invoke_1(op); - invoke(ops...); - } - }; - - void - testInvokable() - { - endpoint_type const ep{ - address_type::from_string( - "127.0.0.1"), 6000}; - coro_peer server(true, ep, *this, case_1{}); - coro_peer client(false, ep, *this, case_2{}); - server.step_to(10); // async_accept - client.step_to(30); // async_connect - server.step_to(20); // async_accept(ws) - client.step_to(40); // async_handshake - server.step_to(100); // case_1 - client.step_to(200); // case_2 - client.step_to(-1); - server.step_to(-1); - } - - //-------------------------------------------------------------------------- - - bool - maybe_fail(error_code const& ec, std::string const& what) - { - return expect(! ec, what + ": " + ec.message()); - } - - void - maybe_throw(error_code ec, std::string what) - { - if(ec) - { - maybe_fail(ec, what); - throw ec; - } - } - - template - static - std::string - buffers_to_string(Buffers const& bs) - { - using boost::asio::buffer_cast; - using boost::asio::buffer_size; - std::string s; - s.reserve(buffer_size(bs)); - for(auto const& b : bs) - s.append(buffer_cast(b), - buffer_size(b)); - for(auto i = s.size(); i-- > 0;) - if(s[i] == '\r') - s.replace(i, 1, "\\r"); - else if(s[i] == '\n') - s.replace(i, 1, "\\n\n"); - return s; - } - - int - makeRequest(endpoint_type ep, std::string const& s) - { - using boost::asio::buffer; - boost::asio::io_service ios; - boost::asio::ip::tcp::socket sock(ios); - sock.connect(ep); - write(sock, append_buffers( - buffer(s), buffer("\r\n"))); - - using namespace http; - response resp; - streambuf sb; - read(sock, sb, resp); - return resp.status; - } - - void - expectStatus(endpoint_type ep, - int status, std::string const& s) - { - expect(makeRequest(ep, s) == status); - } - - void - testHandshake(endpoint_type ep) - { - expectStatus(ep, 400, "GET / HTTP/1.0\r\n"); - } - - void - syncEchoClient(endpoint_type ep) - { - using boost::asio::buffer; - error_code ec; - boost::asio::io_service ios; - wsproto::socket ws(ios); - ws.next_layer().connect(ep, ec); - if(! maybe_fail(ec, "connect")) - return; - ws.handshake(ep.address().to_string(), "/", ec); - if(! maybe_fail(ec, "upgrade")) - return; - std::string s(65535, '*'); - ws.write_frame(true, buffer(s), ec); - if(! maybe_fail(ec, "write")) - return; - boost::asio::streambuf sb; - wsproto::opcode op; - ws.read(op, sb, ec); - if(! maybe_fail(ec, "read")) - return; - if(! ec) - expect(op == wsproto::opcode::text); - expect(buffers_to_string(sb.data()) == s); - sb.consume(sb.size()); - ws.close({}, ec); - if(! maybe_fail(ec, "close")) - return; - while(! ec) - { - ws.read(op, sb, ec); - if(! ec) - sb.consume(sb.size()); - } - if(ec != error::closed) - maybe_fail(ec, "teardown"); - } - - void - run() override - { - //testInvokable(); - - { - endpoint_type ep{ - address_type::from_string("127.0.0.1"), 6000}; - testcase("Echo Server"); - test::sync_echo_peer s(true, ep, *this); - //testHandshake(ep); - syncEchoClient(ep); - } - - { - endpoint_type ep{ - address_type::from_string("127.0.0.1"), 6001}; - testcase("Async Echo Server"); - test::async_echo_peer s(true, ep, *this); - //testHandshake(ep); - syncEchoClient(ep); - } - } -}; - -BEAST_DEFINE_TESTSUITE(ws,asio,beast); - -} // wsproto -} // beast diff --git a/beast/wsproto/src/test/sync_echo_peer.h b/beast/wsproto/src/test/sync_echo_peer.h deleted file mode 100644 index 1e8e4377c4..0000000000 --- a/beast/wsproto/src/test/sync_echo_peer.h +++ /dev/null @@ -1,182 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_SYNC_ECHO_PEER_H_INCLUDED -#define BEAST_WSPROTO_SYNC_ECHO_PEER_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace wsproto { -namespace test { - -// Synchronous WebSocket echo client/server -// -class sync_echo_peer -{ -public: - static std::size_t constexpr autobahnCycles = 520; - - using error_code = boost::system::error_code; - using endpoint_type = boost::asio::ip::tcp::endpoint; - using address_type = boost::asio::ip::address; - using socket_type = boost::asio::ip::tcp::socket; - -private: - unit_test::suite& suite_; - boost::asio::io_service ios_; - socket_type sock_; - boost::asio::ip::tcp::acceptor acceptor_; - unit_test::thread thread_; - std::size_t n_ = 0; - -public: - sync_echo_peer(bool server, - endpoint_type ep, unit_test::suite& suite) - : suite_(suite) - , sock_(ios_) - , acceptor_(ios_) - { - error_code ec; - acceptor_.open(ep.protocol(), ec); - maybe_throw(ec, "open"); - acceptor_.bind(ep, ec); - maybe_throw(ec, "bind"); - acceptor_.listen( - boost::asio::socket_base::max_connections, ec); - maybe_throw(ec, "listen"); - acceptor_.async_accept(sock_, - std::bind(&sync_echo_peer::on_accept, this, - beast::asio::placeholders::error)); - thread_ = unit_test::thread(suite_, - [&] - { - ios_.run(); - }); - } - - ~sync_echo_peer() - { - error_code ec; - ios_.dispatch( - [&]{ acceptor_.close(ec); }); - thread_.join(); - } - -private: - void - fail(error_code ec, std::string what) - { - suite_.log << - what << ": " << ec.message(); - } - - void - maybe_throw(error_code ec, std::string what) - { - if(ec) - { - fail(ec, what); - throw ec; - } - } - - void - on_accept(error_code ec) - { - if(ec == boost::asio::error::operation_aborted) - return; - maybe_throw(ec, "accept"); - ++n_; - std::thread{ - [ - this, - sock = std::move(sock_), - work = boost::asio::io_service::work{ios_} - ]() mutable - { - do_peer(std::move(sock)); - }}.detach(); - if(n_ < autobahnCycles) - acceptor_.async_accept(sock_, - std::bind(&sync_echo_peer::on_accept, this, - beast::asio::placeholders::error)); - } - - struct identity - { - template - void - operator()(http::message& req) - { - req.headers.replace("User-Agent", "sync_echo_client"); - } - - template - void - operator()(http::message& resp) - { - resp.headers.replace("Server", "sync_echo_server"); - } - }; - - void - do_peer(socket_type&& sock) - { - wsproto::socket ws(std::move(sock)); - ws.set_option(decorate(identity{})); - ws.set_option(read_message_max(64 * 1024 * 1024)); - //ws.set_option(auto_fragment_size(0)); - error_code ec; - ws.accept(ec); - if(ec) - { - fail(ec, "accept"); - return; - } - for(;;) - { - wsproto::opcode op; - beast::streambuf sb; - ws.read(op, sb, ec); - if(ec) - break; - ws.set_option(wsproto::message_type(op)); - ws.write(sb.data(), ec); - if(ec) - break; - } - if(ec && ec != wsproto::error::closed) - { - fail(ec, "read"); - } - } -}; - -} // test -} // wsproto -} // beast - -#endif diff --git a/beast/xor_shift_engine.h b/beast/xor_shift_engine.h deleted file mode 100644 index 5b917c5feb..0000000000 --- a/beast/xor_shift_engine.h +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2014, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_RANDOM_XOR_SHIFT_ENGINE_H_INCLUDED -#define BEAST_RANDOM_XOR_SHIFT_ENGINE_H_INCLUDED - -#include -#include -#include - -namespace beast { - -namespace detail { - -template -class xor_shift_engine -{ -public: - using result_type = std::uint64_t; - - xor_shift_engine(xor_shift_engine const&) = default; - xor_shift_engine& operator=(xor_shift_engine const&) = default; - - explicit - xor_shift_engine (result_type val = 1977u); - - void - seed (result_type seed); - - result_type - operator()(); - - static - result_type constexpr - min() - { - return std::numeric_limits::min(); - } - - static - result_type constexpr - max() - { - return std::numeric_limits::max(); - } - -private: - result_type s_[2]; - - static - result_type - murmurhash3 (result_type x); -}; - -template -xor_shift_engine<_>::xor_shift_engine ( - result_type val) -{ - seed (val); -} - -template -void -xor_shift_engine<_>::seed (result_type seed) -{ - if (seed == 0) - throw std::domain_error("invalid seed"); - s_[0] = murmurhash3 (seed); - s_[1] = murmurhash3 (s_[0]); -} - -template -auto -xor_shift_engine<_>::operator()() -> - result_type -{ - result_type s1 = s_[0]; - result_type const s0 = s_[1]; - s_[0] = s0; - s1 ^= s1 << 23; - return (s_[1] = (s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26))) + s0; -} - -template -auto -xor_shift_engine<_>::murmurhash3 (result_type x) - -> result_type -{ - x ^= x >> 33; - x *= 0xff51afd7ed558ccdULL; - x ^= x >> 33; - x *= 0xc4ceb9fe1a85ec53ULL; - return x ^= x >> 33; -} - -} // detail - -/** XOR-shift Generator. - - Meets the requirements of UniformRandomNumberGenerator. - - Simple and fast RNG based on: - http://xorshift.di.unimi.it/xorshift128plus.c - does not accept seed==0 -*/ -using xor_shift_engine = detail::xor_shift_engine<>; - -} - -#endif diff --git a/examples/Jamfile b/examples/Jamfile index 10edb82b11..b615209cf8 100644 --- a/examples/Jamfile +++ b/examples/Jamfile @@ -8,17 +8,17 @@ import os ; exe http_crawl : - ../beast/http/src/beast_http_nodejs_parser.cpp + ../src/beast_http_nodejs_parser.cpp http_crawl.cpp urls_large_data.cpp ; exe http_server : - ../beast/http/src/beast_http_nodejs_parser.cpp + ../src/beast_http_nodejs_parser.cpp http_server.cpp ; exe wsproto_echo : - ../beast/http/src/beast_http_nodejs_parser.cpp + ../src/beast_http_nodejs_parser.cpp wsproto_echo.cpp ; diff --git a/examples/file_body.h b/examples/file_body.h index 34fa46e00a..e46cff9ed7 100644 --- a/examples/file_body.h +++ b/examples/file_body.h @@ -20,8 +20,8 @@ #ifndef BEAST_EXAMPLE_FILE_BODY_H_INCLUDED #define BEAST_EXAMPLE_FILE_BODY_H_INCLUDED -#include -#include +#include +#include #include #include #include diff --git a/examples/http_async_server.h b/examples/http_async_server.h index 8bc6ebf2b2..e3ace8e9d5 100644 --- a/examples/http_async_server.h +++ b/examples/http_async_server.h @@ -23,7 +23,7 @@ #include "file_body.h" #include "http_stream.h" -#include +#include #include #include #include diff --git a/examples/http_server_response.h b/examples/http_server_response.h deleted file mode 100644 index 54221aa159..0000000000 --- a/examples/http_server_response.h +++ /dev/null @@ -1,31 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_EXAMPLE_SERVER_RESPONSE_H_INCLUDED -#define BEAST_HTTP_EXAMPLE_SERVER_RESPONSE_H_INCLUDED - -namespace beast { -namespace http { -namespace example { - -} // example -} // http -} // beast - -#endif diff --git a/examples/http_stream.h b/examples/http_stream.h index 9b7a7e1790..d49bbac5a6 100644 --- a/examples/http_stream.h +++ b/examples/http_stream.h @@ -20,8 +20,8 @@ #ifndef BEAST_HTTP_STREAM_H_INCLUDED #define BEAST_HTTP_STREAM_H_INCLUDED -#include -#include +#include +#include #include #include #include diff --git a/examples/http_stream.ipp b/examples/http_stream.ipp index 3432de8f06..fa5fd7ad77 100644 --- a/examples/http_stream.ipp +++ b/examples/http_stream.ipp @@ -20,12 +20,12 @@ #ifndef BEAST_HTTP_STREAM_IPP_INCLUDED #define BEAST_HTTP_STREAM_IPP_INCLUDED -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include namespace beast { diff --git a/examples/http_sync_server.h b/examples/http_sync_server.h index 610e1464de..db72729da7 100644 --- a/examples/http_sync_server.h +++ b/examples/http_sync_server.h @@ -23,7 +23,6 @@ #include "file_body.h" #include "http_stream.h" -#include #include #include #include diff --git a/examples/wsproto_async_echo_peer.h b/examples/wsproto_async_echo_peer.h index 89e51cd882..469e841f4a 100644 --- a/examples/wsproto_async_echo_peer.h +++ b/examples/wsproto_async_echo_peer.h @@ -20,9 +20,9 @@ #ifndef BEAST_WSPROTO_ASYNC_ECHO_PEER_H_INCLUDED #define BEAST_WSPROTO_ASYNC_ECHO_PEER_H_INCLUDED -#include -#include -#include +#include +#include +#include #include #include #include @@ -30,7 +30,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { // Asynchronous WebSocket echo client/server // @@ -94,8 +94,8 @@ private: { int state = 0; boost::optional ep; - wsproto::socket ws; - wsproto::opcode op; + websocket::stream ws; + websocket::opcode op; beast::streambuf sb; int id; @@ -197,13 +197,13 @@ private: // got message case 2: - if(ec == wsproto::error::closed) + if(ec == websocket::error::closed) return; if(ec) return fail(ec, "async_read"); // write message d.state = 1; - d.ws.set_option(wsproto::message_type(d.op)); + d.ws.set_option(websocket::message_type(d.op)); d.ws.async_write(d.sb.data(), std::move(*this)); return; @@ -224,7 +224,7 @@ private: void fail(error_code ec, std::string what) { - if(ec != wsproto::error::closed) + if(ec != websocket::error::closed) std::cerr << "#" << d_->id << " " << what << ": " << ec.message() << std::endl; } @@ -261,7 +261,7 @@ private: } }; -} // wsproto +} // websocket } // beast #endif diff --git a/examples/wsproto_echo.cpp b/examples/wsproto_echo.cpp index 2aa9da0cce..ba85637744 100644 --- a/examples/wsproto_echo.cpp +++ b/examples/wsproto_echo.cpp @@ -19,35 +19,18 @@ #include "wsproto_async_echo_peer.h" #include "wsproto_sync_echo_peer.h" -#include -#include -#include +#include "sig_wait.h" int main() { using endpoint_type = boost::asio::ip::tcp::endpoint; using address_type = boost::asio::ip::address; - beast::wsproto::async_echo_peer s1(true, endpoint_type{ + beast::websocket::async_echo_peer s1(true, endpoint_type{ address_type::from_string("127.0.0.1"), 6000 }, 4); - beast::wsproto::sync_echo_peer s2(true, endpoint_type{ + beast::websocket::sync_echo_peer s2(true, endpoint_type{ address_type::from_string("127.0.0.1"), 6001 }); - boost::asio::io_service ios; - boost::asio::signal_set signals( - ios, SIGINT, SIGTERM); - std::mutex m; - bool stop = false; - std::condition_variable cv; - signals.async_wait( - [&](boost::system::error_code const& ec, - int signal_number) - { - std::lock_guard lock(m); - stop = true; - cv.notify_one(); - }); - std::unique_lock lock(m); - cv.wait(lock, [&]{ return stop; }); + sig_wait(); } diff --git a/examples/wsproto_sync_echo_peer.h b/examples/wsproto_sync_echo_peer.h index 37aa3414e6..991a2d8cb6 100644 --- a/examples/wsproto_sync_echo_peer.h +++ b/examples/wsproto_sync_echo_peer.h @@ -20,8 +20,8 @@ #ifndef BEAST_WSPROTO_SYNC_ECHO_PEER_H_INCLUDED #define BEAST_WSPROTO_SYNC_ECHO_PEER_H_INCLUDED -#include -#include +#include +#include #include #include #include @@ -29,7 +29,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { // Synchronous WebSocket echo client/server // @@ -144,7 +144,7 @@ private: void do_peer(int id, socket_type&& sock) { - wsproto::socket ws(std::move(sock)); + websocket::stream ws(std::move(sock)); ws.set_option(decorate(identity{})); ws.set_option(read_message_max(64 * 1024 * 1024)); error_code ec; @@ -156,24 +156,24 @@ private: } for(;;) { - wsproto::opcode op; + websocket::opcode op; beast::streambuf sb; ws.read(op, sb, ec); if(ec) break; - ws.set_option(wsproto::message_type(op)); + ws.set_option(websocket::message_type(op)); ws.write(sb.data(), ec); if(ec) break; } - if(ec && ec != wsproto::error::closed) + if(ec && ec != websocket::error::closed) { fail(id, ec, "read"); } } }; -} // wsproto +} // websocket } // beast #endif diff --git a/beast/asio/async_completion.h b/include/beast/async_completion.hpp similarity index 65% rename from beast/asio/async_completion.h rename to include/beast/async_completion.hpp index da9493ff1f..d4be5428c4 100644 --- a/beast/asio/async_completion.h +++ b/include/beast/async_completion.hpp @@ -1,26 +1,14 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_ASYNC_COMPLETION_HPP +#define BEAST_ASYNC_COMPLETION_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_ASYNC_COMPLETION_H_INLUDED -#define BEAST_ASIO_ASYNC_COMPLETION_H_INLUDED - -#include +#include #include #include #include diff --git a/beast/asio/basic_streambuf.h b/include/beast/basic_streambuf.hpp similarity index 86% rename from beast/asio/basic_streambuf.h rename to include/beast/basic_streambuf.hpp index e87999d1e7..9a65ce08d2 100644 --- a/beast/asio/basic_streambuf.h +++ b/include/beast/basic_streambuf.hpp @@ -1,26 +1,14 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_BASIC_STREAMBUF_HPP +#define BEAST_BASIC_STREAMBUF_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_BASIC_STREAMBUF_H_INCLUDED -#define BEAST_ASIO_BASIC_STREAMBUF_H_INCLUDED - -#include +#include #include #include #include @@ -42,7 +30,7 @@ namespace beast { template class basic_streambuf #if ! GENERATING_DOCS - : private empty_base_optimization< + : private detail::empty_base_optimization< typename std::allocator_traits:: template rebind_alloc> #endif @@ -345,6 +333,6 @@ to_string(basic_streambuf const& streambuf); } // beast -#include +#include #endif diff --git a/beast/asio/bind_handler.h b/include/beast/bind_handler.hpp similarity index 75% rename from beast/asio/bind_handler.h rename to include/beast/bind_handler.hpp index afa964a907..6cc6225f79 100644 --- a/beast/asio/bind_handler.h +++ b/include/beast/bind_handler.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_BIND_HANDLER_H_INCLUDED -#define BEAST_ASIO_BIND_HANDLER_H_INCLUDED +#ifndef BEAST_BIND_HANDLER_HPP +#define BEAST_BIND_HANDLER_HPP #include #include @@ -31,7 +19,7 @@ namespace beast { namespace detail { -/** Nullary handler that calls Handler with bound arguments. +/* Nullary handler that calls Handler with bound arguments. The bound handler provides the same io_service execution guarantees as the original handler. diff --git a/beast/asio/append_buffers.h b/include/beast/buffer_cat.hpp similarity index 80% rename from beast/asio/append_buffers.h rename to include/beast/buffer_cat.hpp index 297ca41396..40a556fdab 100644 --- a/beast/asio/append_buffers.h +++ b/include/beast/buffer_cat.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_APPEND_BUFFERS_H_INLUDED -#define BEAST_ASIO_APPEND_BUFFERS_H_INLUDED +#ifndef BEAST_BUFFER_CAT_HPP +#define BEAST_BUFFER_CAT_HPP #include #include @@ -33,7 +21,7 @@ namespace beast { namespace detail { template -class append_buffers_helper +class buffer_cat_helper { std::tuple bs_; @@ -42,13 +30,13 @@ public: class const_iterator; - append_buffers_helper(append_buffers_helper&&) = default; - append_buffers_helper(append_buffers_helper const&) = default; - append_buffers_helper& operator=(append_buffers_helper&&) = default; - append_buffers_helper& operator=(append_buffers_helper const&) = default; + buffer_cat_helper(buffer_cat_helper&&) = default; + buffer_cat_helper(buffer_cat_helper const&) = default; + buffer_cat_helper& operator=(buffer_cat_helper&&) = default; + buffer_cat_helper& operator=(buffer_cat_helper const&) = default; explicit - append_buffers_helper(Bs const&... bs) + buffer_cat_helper(Bs const&... bs) : bs_(bs...) { } @@ -77,7 +65,7 @@ max_sizeof() } template -class append_buffers_helper< +class buffer_cat_helper< ValueType, Bs...>::const_iterator { std::size_t n_; @@ -85,7 +73,7 @@ class append_buffers_helper< std::array()> buf_; - friend class append_buffers_helper; + friend class buffer_cat_helper; template using C = std::integral_constant; @@ -349,14 +337,14 @@ private: //------------------------------------------------------------------------------ template -append_buffers_helper:: +buffer_cat_helper:: const_iterator::~const_iterator() { destroy(C<0>{}); } template -append_buffers_helper:: +buffer_cat_helper:: const_iterator::const_iterator() : n_(sizeof...(Bs)) , bs_(nullptr) @@ -364,7 +352,7 @@ const_iterator::const_iterator() } template -append_buffers_helper:: +buffer_cat_helper:: const_iterator::const_iterator( std::tuple const& bs, bool at_end) : bs_(&bs) @@ -376,7 +364,7 @@ const_iterator::const_iterator( } template -append_buffers_helper:: +buffer_cat_helper:: const_iterator::const_iterator(const_iterator&& other) : n_(other.n_) , bs_(other.bs_) @@ -385,7 +373,7 @@ const_iterator::const_iterator(const_iterator&& other) } template -append_buffers_helper:: +buffer_cat_helper:: const_iterator::const_iterator(const_iterator const& other) : n_(other.n_) , bs_(other.bs_) @@ -395,7 +383,7 @@ const_iterator::const_iterator(const_iterator const& other) template auto -append_buffers_helper:: +buffer_cat_helper:: const_iterator::operator=(const_iterator&& other) -> const_iterator& { @@ -410,7 +398,7 @@ const_iterator::operator=(const_iterator&& other) -> template auto -append_buffers_helper:: +buffer_cat_helper:: const_iterator::operator=(const_iterator const& other) -> const_iterator& { @@ -425,7 +413,7 @@ const_iterator& template bool -append_buffers_helper:: +buffer_cat_helper:: const_iterator::operator==(const_iterator const& other) const { if(bs_ != other.bs_) @@ -437,7 +425,7 @@ const_iterator::operator==(const_iterator const& other) const template auto -append_buffers_helper:: +buffer_cat_helper:: const_iterator::operator*() const -> reference { @@ -446,7 +434,7 @@ const_iterator::operator*() const -> template auto -append_buffers_helper:: +buffer_cat_helper:: const_iterator::operator++() -> const_iterator& { @@ -456,7 +444,7 @@ const_iterator::operator++() -> template auto -append_buffers_helper:: +buffer_cat_helper:: const_iterator::operator--() -> const_iterator& { @@ -466,7 +454,7 @@ const_iterator::operator--() -> template auto -append_buffers_helper::begin() const -> +buffer_cat_helper::begin() const -> const_iterator { return const_iterator(bs_, false); @@ -474,7 +462,7 @@ append_buffers_helper::begin() const -> template auto -append_buffers_helper::end() const -> +buffer_cat_helper::end() const -> const_iterator { return const_iterator(bs_, true); @@ -500,14 +488,14 @@ append_buffers_helper::end() const -> #if GENERATING_DOCS template implementation_defined -append_buffers(BufferSequence const&... buffers) +buffer_cat(BufferSequence const&... buffers) #else template auto -append_buffers(B1 const& b1, B2 const& b2, Bn const&... bn) +buffer_cat(B1 const& b1, B2 const& b2, Bn const&... bn) #endif { - return detail::append_buffers_helper< + return detail::buffer_cat_helper< boost::asio::const_buffer, B1, B2, Bn...>(b1, b2, bn...); } diff --git a/beast/asio/buffers_adapter.h b/include/beast/buffers_adapter.hpp similarity index 92% rename from beast/asio/buffers_adapter.h rename to include/beast/buffers_adapter.hpp index a2212a7463..85856b140a 100644 --- a/beast/asio/buffers_adapter.h +++ b/include/beast/buffers_adapter.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_BUFFERS_ADAPTER_H_INLUDED -#define BEAST_ASIO_BUFFERS_ADAPTER_H_INLUDED +#ifndef BEAST_BUFFERS_ADAPTER_HPP +#define BEAST_BUFFERS_ADAPTER_HPP #include #include diff --git a/include/beast/buffers_debug.hpp b/include/beast/buffers_debug.hpp new file mode 100644 index 0000000000..b25349f9d4 --- /dev/null +++ b/include/beast/buffers_debug.hpp @@ -0,0 +1,39 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_BUFFERS_DEBUG_HPP +#define BEAST_BUFFERS_DEBUG_HPP + +#include +#include + +namespace beast { +namespace debug { + +template +std::string +buffers_to_string(Buffers const& bs) +{ + using boost::asio::buffer_cast; + using boost::asio::buffer_size; + std::string s; + s.reserve(buffer_size(bs)); + for(auto const& b : bs) + s.append(buffer_cast(b), + buffer_size(b)); + for(auto i = s.size(); i-- > 0;) + if(s[i] == '\r') + s.replace(i, 1, "\\r"); + else if(s[i] == '\n') + s.replace(i, 1, "\\n\n"); + return s; +} + +} // debug +} // beast + +#endif diff --git a/beast/asio/consuming_buffers.h b/include/beast/consuming_buffers.hpp similarity index 85% rename from beast/asio/consuming_buffers.h rename to include/beast/consuming_buffers.hpp index f20ad7fa7f..57d34f0ee3 100644 --- a/beast/asio/consuming_buffers.h +++ b/include/beast/consuming_buffers.hpp @@ -1,26 +1,14 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_CONSUMING_BUFFERS_HPP +#define BEAST_CONSUMING_BUFFERS_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_CONSUMING_BUFFERS_H_INLUDED -#define BEAST_ASIO_CONSUMING_BUFFERS_H_INLUDED - -#include +#include #include #include #include diff --git a/beast/crypto/base64.h b/include/beast/detail/base64.hpp similarity index 75% rename from beast/crypto/base64.h rename to include/beast/detail/base64.hpp index 4f2ecbba1d..0256aa7d0b 100644 --- a/beast/crypto/base64.h +++ b/include/beast/detail/base64.hpp @@ -1,29 +1,18 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_BASE64_H_INCLUDED -#define BEAST_CRYPTO_BASE64_H_INCLUDED +#ifndef BEAST_DETAIL_BASE64_HPP +#define BEAST_DETAIL_BASE64_HPP #include #include namespace beast { +namespace detail { /* Portions from http://www.adp-gmbh.ch/cpp/common/base64.html @@ -150,7 +139,8 @@ base64_decode(std::string const& data) c4[i++] = data[in_]; in_++; if(i == 4) { for(i = 0; i < 4; i++) - c4[i] = base64_alphabet().find(c4[i]); + c4[i] = static_cast( + base64_alphabet().find(c4[i])); c3[0] = (c4[0] << 2) + ((c4[1] & 0x30) >> 4); c3[1] = ((c4[1] & 0xf) << 4) + ((c4[2] & 0x3c) >> 2); @@ -168,7 +158,8 @@ base64_decode(std::string const& data) c4[j] = 0; for(j = 0; j < 4; j++) - c4[j] = base64_alphabet().find(c4[j]); + c4[j] = static_cast( + base64_alphabet().find(c4[j])); c3[0] = (c4[0] << 2) + ((c4[1] & 0x30) >> 4); c3[1] = ((c4[1] & 0xf) << 4) + ((c4[2] & 0x3c) >> 2); @@ -181,6 +172,7 @@ base64_decode(std::string const& data) return ret; } -} +} // detail +} // beast #endif diff --git a/beast/ci_char_traits.h b/include/beast/detail/ci_char_traits.hpp similarity index 56% rename from beast/ci_char_traits.h rename to include/beast/detail/ci_char_traits.hpp index 9d958a8ebe..0e4d6377e2 100644 --- a/beast/ci_char_traits.h +++ b/include/beast/detail/ci_char_traits.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UTILITY_CI_CHAR_TRAITS_H_INCLUDED -#define BEAST_UTILITY_CI_CHAR_TRAITS_H_INCLUDED +#ifndef BEAST_DETAIL_CI_CHAR_TRAITS_HPP +#define BEAST_DETAIL_CI_CHAR_TRAITS_HPP #include #include @@ -29,6 +17,7 @@ #include namespace beast { +namespace detail { /** Case-insensitive function object for performing less than comparisons. */ struct ci_less @@ -51,8 +40,6 @@ struct ci_less } }; -namespace detail { - inline bool ci_equal(std::pair lhs, @@ -82,19 +69,16 @@ view(std::string const& s) return {s.data(), s.size()}; } -} - /** Returns `true` if strings are case-insensitive equal. */ template inline bool ci_equal(String1 const& lhs, String2 const& rhs) { - using detail::view; - using detail::ci_equal; return ci_equal(view(lhs), view(rhs)); } -} +} // detail +} // beast #endif diff --git a/beast/unit_test/const_container.h b/include/beast/detail/const_container.hpp similarity index 55% rename from beast/unit_test/const_container.h rename to include/beast/detail/const_container.hpp index 2bf093c738..72f2c32bee 100644 --- a/beast/unit_test/const_container.h +++ b/include/beast/detail/const_container.hpp @@ -1,26 +1,15 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_CONST_CONTAINER_H_INCLUDED -#define BEAST_UNIT_TEST_CONST_CONTAINER_H_INCLUDED +#ifndef BEAST_DETAIL_CONST_CONTAINER_HPP +#define BEAST_DETAIL_CONST_CONTAINER_HPP namespace beast { +namespace detail { /** Adapter to constrain a container interface. The interface allows for limited read only operations. Derived classes @@ -94,6 +83,7 @@ public: /** @} */ }; +} // detail } // beast #endif diff --git a/include/beast/detail/empty_base_optimization.hpp b/include/beast/detail/empty_base_optimization.hpp new file mode 100644 index 0000000000..1be8ccde4b --- /dev/null +++ b/include/beast/detail/empty_base_optimization.hpp @@ -0,0 +1,94 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_EMPTY_BASE_OPTIMIZATION_HPP +#define BEAST_DETAIL_EMPTY_BASE_OPTIMIZATION_HPP + +#include +#include + +namespace beast { +namespace detail { + +template +struct empty_base_optimization_decide + : std::integral_constant ::value +#ifdef __clang__ + && !__is_final(T) +#endif + > +{ +}; + +template < + class T, + int UniqueID = 0, + bool ShouldDeriveFrom = + empty_base_optimization_decide::value +> +class empty_base_optimization : private T +{ +public: + empty_base_optimization() = default; + + empty_base_optimization(T const& t) + : T (t) + {} + + empty_base_optimization(T&& t) + : T (std::move (t)) + {} + + T& member() noexcept + { + return *this; + } + + T const& member() const noexcept + { + return *this; + } +}; + +//------------------------------------------------------------------------------ + +template < + class T, + int UniqueID +> +class empty_base_optimization +{ +public: + empty_base_optimization() = default; + + empty_base_optimization(T const& t) + : m_t (t) + {} + + empty_base_optimization(T&& t) + : m_t (std::move (t)) + {} + + T& member() noexcept + { + return m_t; + } + + T const& member() const noexcept + { + return m_t; + } + +private: + T m_t; +}; + +} // detail +} // beast + +#endif diff --git a/beast/is_call_possible.h b/include/beast/detail/is_call_possible.hpp similarity index 57% rename from beast/is_call_possible.h rename to include/beast/detail/is_call_possible.hpp index 5c18bc3b1f..c14dbd3482 100644 --- a/beast/is_call_possible.h +++ b/include/beast/detail/is_call_possible.hpp @@ -1,29 +1,16 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_IS_CALL_POSSIBLE_H_INCLUDED -#define BEAST_IS_CALL_POSSIBLE_H_INCLUDED +#ifndef BEAST_DETAIL_IS_CALL_POSSIBLE_HPP +#define BEAST_DETAIL_IS_CALL_POSSIBLE_HPP #include namespace beast { - namespace detail { template @@ -38,8 +25,6 @@ template std::false_type is_call_possible_test(C&& c, long, A&& ...a); -} // detail - /** Metafunction returns `true` if F callable as R(A...) Example: is_call_possible @@ -53,7 +38,7 @@ struct is_call_possible template struct is_call_possible - : decltype(detail::is_call_possible_test( + : decltype(is_call_possible_test( std::declval(), 1, std::declval()...)) { }; @@ -96,8 +81,10 @@ static_assert(is_call_possible< static_assert(! is_call_possible< is_call_possible_udt3 const, int(int)>::value, ""); -} -} +} // test + +} // detail +} // beast #endif diff --git a/beast/crypto/detail/sha_context.h b/include/beast/detail/sha1.hpp similarity index 86% rename from beast/crypto/detail/sha_context.h rename to include/beast/detail/sha1.hpp index 482df01d82..c34b1bb8bc 100644 --- a/beast/crypto/detail/sha_context.h +++ b/include/beast/detail/sha1.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_CRYPTO_SHA_CONTEXT_H_INCLUDED -#define BEAST_CRYPTO_SHA_CONTEXT_H_INCLUDED +#ifndef BEAST_DETAIL_SHA1_HPP +#define BEAST_DETAIL_SHA1_HPP #include #include @@ -228,7 +216,7 @@ transform( } // sha1 -struct sha_context +struct sha1_context { static unsigned int const block_size = sha1::BLOCK_BYTES; static unsigned int const digest_size = 20; @@ -241,7 +229,7 @@ struct sha_context template void -init(sha_context& ctx) noexcept +init(sha1_context& ctx) noexcept { ctx.buflen = 0; ctx.digest[0] = 0x67452301; @@ -254,7 +242,7 @@ init(sha_context& ctx) noexcept template void -update(sha_context& ctx, +update(sha1_context& ctx, void const* message, std::size_t size) noexcept { auto p = reinterpret_cast< @@ -279,7 +267,7 @@ update(sha_context& ctx, template void -finish(sha_context& ctx, void* digest) noexcept +finish(sha1_context& ctx, void* digest) noexcept { using sha1::BLOCK_INTS; using sha1::BLOCK_BYTES; diff --git a/include/beast/detail/stream/abstract_ostream.hpp b/include/beast/detail/stream/abstract_ostream.hpp new file mode 100644 index 0000000000..43a3c22373 --- /dev/null +++ b/include/beast/detail/stream/abstract_ostream.hpp @@ -0,0 +1,22 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_STREAM_ABSTRACT_OSTREAM_HPP +#define BEAST_DETAIL_STREAM_ABSTRACT_OSTREAM_HPP + +#include + +namespace beast { +namespace detail { + +/** An abstract ostream for `char`. */ +using abstract_ostream = basic_abstract_ostream ; + +} // detail +} // beast + +#endif diff --git a/beast/streams/basic_abstract_ostream.h b/include/beast/detail/stream/basic_abstract_ostream.hpp similarity index 55% rename from beast/streams/basic_abstract_ostream.h rename to include/beast/detail/stream/basic_abstract_ostream.hpp index 82341b7880..098886a2a8 100644 --- a/beast/streams/basic_abstract_ostream.h +++ b/include/beast/detail/stream/basic_abstract_ostream.hpp @@ -1,32 +1,20 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STREAMS_BASIC_ABSTRACT_OSTREAM_H_INCLUDED -#define BEAST_STREAMS_BASIC_ABSTRACT_OSTREAM_H_INCLUDED - -#include +#ifndef BEAST_DETAIL_STREAM_BASIC_ABSTRACT_OSTREAM_HPP +#define BEAST_DETAIL_STREAM_BASIC_ABSTRACT_OSTREAM_HPP +#include #include #include #include namespace beast { +namespace detail { /** Abstraction for an output stream similar to std::basic_ostream. */ template < @@ -93,6 +81,7 @@ public: } }; -} +} // detail +} // beast #endif diff --git a/beast/streams/basic_scoped_ostream.h b/include/beast/detail/stream/basic_scoped_ostream.hpp similarity index 69% rename from beast/streams/basic_scoped_ostream.h rename to include/beast/detail/stream/basic_scoped_ostream.hpp index e645334ac5..fcd34d6b61 100644 --- a/beast/streams/basic_scoped_ostream.h +++ b/include/beast/detail/stream/basic_scoped_ostream.hpp @@ -1,26 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_STREAMS_BASIC_SCOPED_OSTREAM_H_INCLUDED -#define BEAST_STREAMS_BASIC_SCOPED_OSTREAM_H_INCLUDED - -#include +#ifndef BEAST_DETAIL_STREAM_BASIC_SCOPED_OSTREAM_HPP +#define BEAST_DETAIL_STREAM_BASIC_SCOPED_OSTREAM_HPP #include #include @@ -38,6 +24,7 @@ #endif namespace beast { +namespace detail { template < class CharT, @@ -145,6 +132,7 @@ public: } }; -} +} // detail +} // beast #endif diff --git a/include/beast/detail/stream/basic_std_ostream.hpp b/include/beast/detail/stream/basic_std_ostream.hpp new file mode 100644 index 0000000000..9173421214 --- /dev/null +++ b/include/beast/detail/stream/basic_std_ostream.hpp @@ -0,0 +1,62 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_STREAM_BASIC_STD_OSTREAM_H_INCLUDED +#define BEAST_DETAIL_STREAM_BASIC_STD_OSTREAM_H_INCLUDED + +#include +#include + +namespace beast { +namespace detail { + +/** Wraps an existing std::basic_ostream as an abstract_ostream. */ +template < + class CharT, + class Traits = std::char_traits +> +class basic_std_ostream + : public basic_abstract_ostream +{ +private: + using typename basic_abstract_ostream ::string_type; + + std::reference_wrapper m_stream; + +public: + explicit basic_std_ostream ( + std::basic_ostream & stream) + : m_stream (stream) + { + } + + void + write (string_type const& s) override + { + m_stream.get() << s << std::endl; + } +}; + +using std_ostream = basic_std_ostream ; + +//------------------------------------------------------------------------------ + +/** Returns a basic_std_ostream using template argument deduction. */ +template < + class CharT, + class Traits = std::char_traits +> +basic_std_ostream +make_std_ostream (std::basic_ostream & stream) +{ + return basic_std_ostream (stream); +} + +} // detail +} // beast + +#endif diff --git a/include/beast/detail/stream/debug_ostream.hpp b/include/beast/detail/stream/debug_ostream.hpp new file mode 100644 index 0000000000..1f3bc4653e --- /dev/null +++ b/include/beast/detail/stream/debug_ostream.hpp @@ -0,0 +1,80 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_STREAM_DEBUG_OSTREAM_HPP +#define BEAST_DETAIL_STREAM_DEBUG_OSTREAM_HPP + +#include +#include + +#ifdef _MSC_VER +# ifndef WIN32_LEAN_AND_MEAN // VC_EXTRALEAN +# define WIN32_LEAN_AND_MEAN +#include +# undef WIN32_LEAN_AND_MEAN +# else +#include +# endif +# ifdef min +# undef min +# endif +# ifdef max +# undef max +# endif +#endif + +namespace beast { +namespace detail { + +#ifdef _MSC_VER +/** A basic_abstract_ostream that redirects output to an attached debugger. */ +class debug_ostream + : public abstract_ostream +{ +private: + bool m_debugger; + +public: + debug_ostream() + : m_debugger (IsDebuggerPresent() != FALSE) + { + // Note that the check for an attached debugger is made only + // during construction time, for efficiency. A stream created before + // the debugger is attached will not have output redirected. + } + + void + write (string_type const& s) override + { + if (m_debugger) + { + OutputDebugStringA ((s + "\n").c_str()); + return; + } + + std::cout << s << std::endl; + } +}; + +#else +class debug_ostream + : public abstract_ostream +{ +public: + void + write (string_type const& s) override + { + std::cout << s << std::endl; + } +}; + +#endif + +} // detail +} // beast + +#endif diff --git a/beast/unit_test/temp_dir.h b/include/beast/detail/temp_dir.hpp similarity index 51% rename from beast/unit_test/temp_dir.h rename to include/beast/detail/temp_dir.hpp index 030dcfcbe6..54a0d905a0 100644 --- a/beast/unit_test/temp_dir.h +++ b/include/beast/detail/temp_dir.hpp @@ -1,29 +1,18 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNITTEST_TEMP_DIR_H_INCLUDED -#define BEAST_UNITTEST_TEMP_DIR_H_INCLUDED +#ifndef BEAST_DETAIL_TEMP_DIR_H_INCLUDED +#define BEAST_DETAIL_TEMP_DIR_H_INCLUDED #include #include namespace beast { +namespace detail { /** RAII temporary directory. @@ -78,6 +67,7 @@ public: } }; +} // detail } // beast #endif diff --git a/include/beast/detail/unit_test.h b/include/beast/detail/unit_test.h new file mode 100644 index 0000000000..a53379e0ba --- /dev/null +++ b/include/beast/detail/unit_test.h @@ -0,0 +1,23 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_UNIT_TEST_H_INCLUDED +#define BEAST_DETAIL_UNIT_TEST_H_INCLUDED + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif diff --git a/include/beast/detail/unit_test/amount.hpp b/include/beast/detail/unit_test/amount.hpp new file mode 100644 index 0000000000..c07b4cad0e --- /dev/null +++ b/include/beast/detail/unit_test/amount.hpp @@ -0,0 +1,59 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_UNIT_TEST_AMOUNT_HPP +#define BEAST_DETAIL_UNIT_TEST_AMOUNT_HPP + +#include +#include +#include + +namespace beast { +namespace detail { + +inline +namespace unit_test { + +/** Utility for producing nicely composed output of amounts with units. */ +class amount +{ +private: + std::size_t n_; + std::string const& what_; + +public: + amount (amount const&) = default; + amount& operator= (amount const&) = delete; + + template + amount (std::size_t n, std::string const& what); + + friend + std::ostream& + operator<< (std::ostream& s, amount const& t); +}; + +template +amount::amount (std::size_t n, std::string const& what) + : n_ (n) + , what_ (what) +{ +} + +inline +std::ostream& +operator<< (std::ostream& s, amount const& t) +{ + s << t.n_ << " " << t.what_ << ((t.n_ != 1) ? "s" : ""); + return s; +} + +} // unit_test +} // detail +} // beast + +#endif diff --git a/beast/unit_test/define_print.cpp b/include/beast/detail/unit_test/define_print.cpp similarity index 52% rename from beast/unit_test/define_print.cpp rename to include/beast/detail/unit_test/define_print.cpp index 27e2c2d7a7..6540d4dcac 100644 --- a/beast/unit_test/define_print.cpp +++ b/include/beast/detail/unit_test/define_print.cpp @@ -1,30 +1,21 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include +#include +#include +#include #include // Include this .cpp in your project to gain access to the printing suite namespace beast { +namespace detail { + +inline namespace unit_test { namespace detail { @@ -93,6 +84,7 @@ print_test::print (suite_list &c) BEAST_DEFINE_TESTSUITE_MANUAL(print,unit_test,beast); -} -} -} +} // detail +} // unit_test +} // detail +} // beast diff --git a/include/beast/detail/unit_test/global_suites.hpp b/include/beast/detail/unit_test/global_suites.hpp new file mode 100644 index 0000000000..c7a7d8a376 --- /dev/null +++ b/include/beast/detail/unit_test/global_suites.hpp @@ -0,0 +1,60 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_UNIT_TEST_GLOBAL_SUITES_HPP +#define BEAST_DETAIL_UNIT_TEST_GLOBAL_SUITES_HPP + +#include + +namespace beast { +namespace detail { + +inline +namespace unit_test { + +namespace detail { + +template +suite_list& +global_suites() +{ + static suite_list s; + return s; +} + +template +struct insert_suite +{ + template + insert_suite (char const* name, char const* module, + char const* library, bool manual); +}; + +template +template +insert_suite::insert_suite (char const* name, + char const* module, char const* library, bool manual) +{ + global_suites().insert ( + name, module, library, manual); +} + +} // detail + +/** Holds suites registered during static initialization. */ +inline +suite_list const& +global_suites() +{ + return detail::global_suites(); +} + +} // unit_test +} // detail +} // beast + +#endif diff --git a/beast/unit_test/match.h b/include/beast/detail/unit_test/match.hpp similarity index 73% rename from beast/unit_test/match.h rename to include/beast/detail/unit_test/match.hpp index cc9b2b0140..664bae8a1f 100644 --- a/beast/unit_test/match.h +++ b/include/beast/detail/unit_test/match.hpp @@ -1,28 +1,20 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_MATCH_HPP +#define BEAST_DETAIL_UNIT_TEST_MATCH_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_MATCH_H_INCLUDED -#define BEAST_UNIT_TEST_MATCH_H_INCLUDED - -#include +#include +#include namespace beast { +namespace detail { + +inline namespace unit_test { // Predicate for implementing matches @@ -179,6 +171,7 @@ match_library (std::string const& name) } } // unit_test +} // detail } // beast #endif diff --git a/include/beast/detail/unit_test/print.hpp b/include/beast/detail/unit_test/print.hpp new file mode 100644 index 0000000000..04957db594 --- /dev/null +++ b/include/beast/detail/unit_test/print.hpp @@ -0,0 +1,71 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_DETAIL_UNIT_TEST_PRINT_H_INCLUDED +#define BEAST_DETAIL_UNIT_TEST_PRINT_H_INCLUDED + +#include +#include +#include +#include + +#include +#include + +namespace beast { +namespace detail { + +inline +namespace unit_test { + +/** Write test results to the specified output stream. */ +/** @{ */ +template +void +print (results const& r, beast::detail::abstract_ostream& stream) +{ + for (auto const& s : r) + { + for (auto const& c : s) + { + stream << + s.name() << + (c.name().empty() ? "" : ("." + c.name())); + + std::size_t i (1); + for (auto const& t : c.tests) + { + if (! t.pass) + stream << + "#" << i << + " failed: " << t.reason; + ++i; + } + } + } + + stream << + amount (r.size(), "suite") << ", " << + amount (r.cases(), "case") << ", " << + amount (r.total(), "test") << " total, " << + amount (r.failed(), "failure") + ; +} + +template +void +print (results const& r, std::ostream& stream = std::cout) +{ + auto s (make_std_ostream (stream)); + print (r, s); +} + +} // unit_test +} // detail +} // beast + +#endif diff --git a/beast/unit_test/recorder.h b/include/beast/detail/unit_test/recorder.hpp similarity index 52% rename from beast/unit_test/recorder.h rename to include/beast/detail/unit_test/recorder.hpp index b066e0cffc..8c711cf8c1 100644 --- a/beast/unit_test/recorder.h +++ b/include/beast/detail/unit_test/recorder.hpp @@ -1,29 +1,20 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_RECORDER_HPP +#define BEAST_DETAIL_UNIT_TEST_RECORDER_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_RECORDER_H_INCLUDED -#define BEAST_UNIT_TEST_RECORDER_H_INCLUDED - -#include -#include +#include +#include namespace beast { +namespace detail { + +inline namespace unit_test { /** A test runner that stores the results. */ @@ -99,6 +90,7 @@ private: }; } // unit_test +} // detail } // beast #endif diff --git a/beast/unit_test/reporter.h b/include/beast/detail/unit_test/reporter.hpp similarity index 80% rename from beast/unit_test/reporter.h rename to include/beast/detail/unit_test/reporter.hpp index e9952058e8..93a0f9606b 100644 --- a/beast/unit_test/reporter.h +++ b/include/beast/detail/unit_test/reporter.hpp @@ -1,29 +1,17 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_REPORTER_HPP +#define BEAST_DETAIL_UNIT_TEST_REPORTER_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_REPORTER_H_INCLUDED -#define BEAST_UNIT_TEST_REPORTER_H_INCLUDED - -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include @@ -35,6 +23,9 @@ #include namespace beast { +namespace detail { + +inline namespace unit_test { namespace detail { @@ -96,7 +87,7 @@ private: }; boost::optional std_ostream_; - std::reference_wrapper stream_; + std::reference_wrapper stream_; results results_; suite_results suite_results_; case_results case_results_; @@ -111,7 +102,7 @@ public: reporter (std::ostream& stream = std::cout); explicit - reporter (abstract_ostream& stream); + reporter (beast::detail::abstract_ostream& stream); private: static @@ -238,7 +229,7 @@ reporter<_>::~reporter() template reporter<_>::reporter ( - abstract_ostream& stream) + beast::detail::abstract_ostream& stream) : stream_ (stream) { } @@ -327,6 +318,7 @@ reporter<_>::on_log ( using reporter = detail::reporter<>; } // unit_test +} // detail } // beast #endif diff --git a/beast/unit_test/results.h b/include/beast/detail/unit_test/results.hpp similarity index 79% rename from beast/unit_test/results.h rename to include/beast/detail/unit_test/results.hpp index 125b897020..75231fa806 100644 --- a/beast/unit_test/results.h +++ b/include/beast/detail/unit_test/results.hpp @@ -1,31 +1,22 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_RESULTS_HPP +#define BEAST_DETAIL_UNIT_TEST_RESULTS_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_RESULTS_H_INCLUDED -#define BEAST_UNIT_TEST_RESULTS_H_INCLUDED - -#include +#include #include #include namespace beast { +namespace detail { + +inline namespace unit_test { /** Holds a set of test condition outcomes in a testcase. */ @@ -249,6 +240,7 @@ public: }; } // unit_test +} // detail } // beast #endif diff --git a/beast/unit_test/runner.h b/include/beast/detail/unit_test/runner.hpp similarity index 83% rename from beast/unit_test/runner.h rename to include/beast/detail/unit_test/runner.hpp index 164770f628..6f46774557 100644 --- a/beast/unit_test/runner.h +++ b/include/beast/detail/unit_test/runner.hpp @@ -1,32 +1,23 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_RUNNER_H_INCLUDED +#define BEAST_DETAIL_UNIT_TEST_RUNNER_H_INCLUDED - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_RUNNER_H_INCLUDED -#define BEAST_UNIT_TEST_RUNNER_H_INCLUDED - -#include -#include +#include +#include #include #include #include namespace beast { +namespace detail { + +inline namespace unit_test { /** Unit test runner interface. @@ -37,7 +28,7 @@ class runner { private: // Reroutes log output to the runner - class stream_t : public abstract_ostream + class stream_t : public beast::detail::abstract_ostream { private: runner& owner_; @@ -341,6 +332,7 @@ runner::log (std::string const& s) } } // unit_test +} // detail } // beast #endif diff --git a/beast/unit_test/suite.h b/include/beast/detail/unit_test/suite.hpp similarity index 90% rename from beast/unit_test/suite.h rename to include/beast/detail/unit_test/suite.hpp index f3e0aa585c..3732224ed3 100644 --- a/beast/unit_test/suite.h +++ b/include/beast/detail/unit_test/suite.hpp @@ -1,30 +1,21 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_SUITE_HPP +#define BEAST_DETAIL_UNIT_TEST_SUITE_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_SUITE_H_INCLUDED -#define BEAST_UNIT_TEST_SUITE_H_INCLUDED - -#include +#include #include #include namespace beast { +namespace detail { + +inline namespace unit_test { class thread; @@ -546,6 +537,7 @@ suite::run (runner& r) } } // unit_test +} // detail } // beast //------------------------------------------------------------------------------ @@ -553,7 +545,7 @@ suite::run (runner& r) // detail: // This inserts the suite with the given manual flag #define BEAST_DEFINE_TESTSUITE_INSERT(Class,Module,Library,manual) \ - static beast::unit_test::detail::insert_suite \ + static beast::detail::unit_test::detail::insert_suite \ Library ## Module ## Class ## _test_instance ( \ #Class, #Module, #Library, manual); @@ -601,7 +593,7 @@ suite::run (runner& r) #define BEAST_DEFINE_TESTSUITE(Class,Module,Library) #else -#include +#include #define BEAST_DEFINE_TESTSUITE(Class,Module,Library) \ BEAST_DEFINE_TESTSUITE_INSERT(Class,Module,Library,false) #define BEAST_DEFINE_TESTSUITE_MANUAL(Class,Module,Library) \ diff --git a/beast/unit_test/suite_info.h b/include/beast/detail/unit_test/suite_info.hpp similarity index 64% rename from beast/unit_test/suite_info.h rename to include/beast/detail/unit_test/suite_info.hpp index 94ba5cc8c1..2176bb829f 100644 --- a/beast/unit_test/suite_info.h +++ b/include/beast/detail/unit_test/suite_info.hpp @@ -1,30 +1,21 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_SUITE_INFO_H_INCLUDED -#define BEAST_UNIT_TEST_SUITE_INFO_H_INCLUDED +#ifndef BEAST_DETAIL_UNIT_TEST_SUITE_INFO_HPP +#define BEAST_DETAIL_UNIT_TEST_SUITE_INFO_HPP #include #include #include namespace beast { +namespace detail { + +inline namespace unit_test { class runner; @@ -122,6 +113,7 @@ make_suite_info (std::string const& name, std::string const& module, } } // unit_test +} // detail } // beast #endif diff --git a/beast/unit_test/suite_list.h b/include/beast/detail/unit_test/suite_list.hpp similarity index 51% rename from beast/unit_test/suite_list.h rename to include/beast/detail/unit_test/suite_list.hpp index b552d4e36c..1393d406ad 100644 --- a/beast/unit_test/suite_list.h +++ b/include/beast/detail/unit_test/suite_list.hpp @@ -1,33 +1,24 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_SUITE_LIST_HPP +#define BEAST_DETAIL_UNIT_TEST_SUITE_LIST_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_SUITE_LIST_H_INCLUDED -#define BEAST_UNIT_TEST_SUITE_LIST_H_INCLUDED - -#include -#include +#include +#include #include #include #include #include namespace beast { +namespace detail { + +inline namespace unit_test { /** A container of test suites. */ @@ -77,6 +68,7 @@ suite_list::insert (char const* name, char const* module, char const* library, } } // unit_test +} // detail } // beast #endif diff --git a/beast/unit_test/thread.h b/include/beast/detail/unit_test/thread.hpp similarity index 63% rename from beast/unit_test/thread.h rename to include/beast/detail/unit_test/thread.hpp index 90e6fb3d2b..a684abd3b6 100644 --- a/beast/unit_test/thread.h +++ b/include/beast/detail/unit_test/thread.hpp @@ -1,31 +1,22 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_DETAIL_UNIT_TEST_THREAD_HPP +#define BEAST_DETAIL_UNIT_TEST_THREAD_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_UNIT_TEST_THREAD_H_INCLUDED -#define BEAST_UNIT_TEST_THREAD_H_INCLUDED - -#include +#include #include #include #include namespace beast { +namespace detail { + +inline namespace unit_test { /** Replacement for std::thread that handles exceptions in unit tests. */ @@ -131,6 +122,7 @@ private: }; } // unit_test +} // detail } // beast #endif diff --git a/beast/asio/handler_alloc.h b/include/beast/handler_alloc.hpp similarity index 70% rename from beast/asio/handler_alloc.h rename to include/beast/handler_alloc.hpp index d76f62d993..afde93e9df 100644 --- a/beast/asio/handler_alloc.h +++ b/include/beast/handler_alloc.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_HANDLER_ALLOC_H_INCLUDED -#define BEAST_ASIO_HANDLER_ALLOC_H_INCLUDED +#ifndef BEAST_HANDLER_ALLOC_HPP +#define BEAST_HANDLER_ALLOC_HPP #include #include diff --git a/include/beast/http.hpp b/include/beast/http.hpp new file mode 100644 index 0000000000..591c32bb05 --- /dev/null +++ b/include/beast/http.hpp @@ -0,0 +1,29 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_HTTP_HPP_INCLUDED +#define BEAST_HTTP_HPP_INCLUDED + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif diff --git a/beast/http/basic_headers.h b/include/beast/http/basic_headers.hpp similarity index 86% rename from beast/http/basic_headers.h rename to include/beast/http/basic_headers.hpp index b10390e8eb..cf1f775306 100644 --- a/beast/http/basic_headers.h +++ b/include/beast/http/basic_headers.hpp @@ -1,29 +1,17 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_BASIC_HEADERS_HPP +#define BEAST_HTTP_BASIC_HEADERS_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_BASIC_HEADERS_H_INCLUDED -#define BEAST_HTTP_BASIC_HEADERS_H_INCLUDED - -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include @@ -32,7 +20,7 @@ #include #include #include -#include // +#include #include namespace beast { @@ -92,7 +80,7 @@ protected: } }; - struct less : private ci_less + struct less : private beast::detail::ci_less { template bool @@ -111,7 +99,7 @@ protected: bool operator()(element const& lhs, element const& rhs) const { - return beast::ci_less::operator()( + return ci_less::operator()( lhs.data.first, rhs.data.first); } }; @@ -257,7 +245,7 @@ public: template class basic_headers #if ! GENERATING_DOCS - : private empty_base_optimization< + : private beast::detail::empty_base_optimization< typename std::allocator_traits:: template rebind_alloc< detail::basic_headers_base::element>> diff --git a/beast/http/basic_parser.h b/include/beast/http/basic_parser.hpp similarity index 89% rename from beast/http/basic_parser.h rename to include/beast/http/basic_parser.hpp index 85301a5beb..494083ce26 100644 --- a/beast/http/basic_parser.h +++ b/include/beast/http/basic_parser.hpp @@ -1,33 +1,21 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_BASIC_PARSER_HPP +#define BEAST_HTTP_BASIC_PARSER_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_BASIC_PARSER_H_INCLUDED -#define BEAST_HTTP_BASIC_PARSER_H_INCLUDED - -#include -#include -#include +#include +#include +#include #include #include #include #include -#include // +#include namespace beast { namespace http { @@ -265,7 +253,7 @@ private: }; template using has_on_start = - std::bool_constant::value>; + std::integral_constant::value>; void call_on_start(std::true_type) @@ -295,7 +283,7 @@ private: }; template using has_on_field = - std::bool_constant::value>; + std::integral_constant::value>; void call_on_field(std::string const& field, @@ -325,7 +313,7 @@ private: }; template using has_on_headers_complete = - std::bool_constant::value>; + std::integral_constant::value>; void call_on_headers_complete(error_code& ec, std::true_type) @@ -356,7 +344,7 @@ private: }; template using has_on_request = - std::bool_constant::value>; + std::integral_constant::value>; void call_on_request(method_t method, std::string url, @@ -396,7 +384,7 @@ private: }; template using has_on_response = - std::bool_constant::value>; + std::integral_constant::value>; bool call_on_response(int status, std::string text, @@ -431,7 +419,7 @@ private: }; template using has_on_body = - std::bool_constant::value>; + std::integral_constant::value>; void call_on_body(void const* data, std::size_t bytes, @@ -460,7 +448,7 @@ private: }; template using has_on_complete = - std::bool_constant::value>; + std::integral_constant::value>; void call_on_complete(std::true_type) diff --git a/beast/http/chunk_encode.h b/include/beast/http/chunk_encode.hpp similarity index 85% rename from beast/http/chunk_encode.h rename to include/beast/http/chunk_encode.hpp index 608dad32d2..15ae2a427a 100644 --- a/beast/http/chunk_encode.h +++ b/include/beast/http/chunk_encode.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_CHUNK_ENCODE_H_INCLUDED -#define BEAST_HTTP_CHUNK_ENCODE_H_INCLUDED +#ifndef BEAST_HTTP_CHUNK_ENCODE_HPP +#define BEAST_HTTP_CHUNK_ENCODE_HPP #include #include diff --git a/beast/http/detail/error.h b/include/beast/http/detail/error.hpp similarity index 50% rename from beast/http/detail/error.h rename to include/beast/http/detail/error.hpp index 39918f910d..a1543d9884 100644 --- a/beast/http/detail/error.h +++ b/include/beast/http/detail/error.hpp @@ -1,26 +1,14 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_DETAIL_ERROR_HPP +#define BEAST_HTTP_DETAIL_ERROR_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_DETAIL_ERROR_H_INCLUDED -#define BEAST_HTTP_DETAIL_ERROR_H_INCLUDED - -#include +#include #include namespace beast { diff --git a/beast/http/detail/write_preparation.h b/include/beast/http/detail/write_preparation.hpp similarity index 67% rename from beast/http/detail/write_preparation.h rename to include/beast/http/detail/write_preparation.hpp index f7bfd2916a..5456eb2ffb 100644 --- a/beast/http/detail/write_preparation.h +++ b/include/beast/http/detail/write_preparation.hpp @@ -1,26 +1,14 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Copyright 2013, Vinnie Falco - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_DETAIL_WRITE_PREPARATION_HPP +#define BEAST_HTTP_DETAIL_WRITE_PREPARATION_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_WRITE_PREPARATION_H_INCLUDED -#define BEAST_HTTP_WRITE_PREPARATION_H_INCLUDED - -#include +#include namespace beast { namespace http { diff --git a/beast/http/detail/writes.h b/include/beast/http/detail/writes.hpp similarity index 52% rename from beast/http/detail/writes.h rename to include/beast/http/detail/writes.hpp index efeff68cd0..d887a95c02 100644 --- a/beast/http/detail/writes.h +++ b/include/beast/http/detail/writes.hpp @@ -1,26 +1,14 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_DETAIL_WRITES_HPP +#define BEAST_HTTP_DETAIL_WRITES_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_WRITES_H_INCLUDED -#define BEAST_HTTP_WRITES_H_INCLUDED - -#include +#include #include #include #include diff --git a/include/beast/http/empty_body.hpp b/include/beast/http/empty_body.hpp new file mode 100644 index 0000000000..d1d076fe48 --- /dev/null +++ b/include/beast/http/empty_body.hpp @@ -0,0 +1,75 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_HTTP_EMPTY_BODY_HPP +#define BEAST_HTTP_EMPTY_BODY_HPP + +#include +#include +#include +#include +#include +#include + +namespace beast { +namespace http { + +/** An empty content-body. +*/ +struct empty_body +{ + struct value_type + { + }; + + struct reader + { + template + explicit + reader(message&) + { + } + + void + write(void const*, std::size_t, error_code&) + { + } + }; + + struct writer + { + template + explicit + writer(message const& m) + { + } + + void + init(error_code& ec) + { + } + + std::size_t + content_length() const + { + return 0; + } + + template + boost::tribool + operator()(resume_context&&, error_code&, Write&& write) + { + write(boost::asio::null_buffers{}); + return true; + } + }; +}; + +} // http +} // beast + +#endif diff --git a/test/temp_buffer.cpp b/include/beast/http/error.hpp similarity index 53% rename from test/temp_buffer.cpp rename to include/beast/http/error.hpp index 536cf776f3..d82d45bd36 100644 --- a/test/temp_buffer.cpp +++ b/include/beast/http/error.hpp @@ -5,5 +5,17 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -// Test that header file is self-contained. -#include +#ifndef BEAST_HTTP_ERROR_HPP +#define BEAST_HTTP_ERROR_HPP + +#include + +namespace beast { +namespace http { + +using error_code = boost::system::error_code; + +} // http +} // beast + +#endif diff --git a/beast/http/fields.h b/include/beast/http/fields.hpp similarity index 100% rename from beast/http/fields.h rename to include/beast/http/fields.hpp diff --git a/include/beast/http/headers.hpp b/include/beast/http/headers.hpp new file mode 100644 index 0000000000..9b919071d9 --- /dev/null +++ b/include/beast/http/headers.hpp @@ -0,0 +1,26 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_HTTP_HEADERS_HPP +#define BEAST_HTTP_HEADERS_HPP + +#include +#include + +namespace beast { +namespace http { + +template +using headers = basic_headers; + +using http_headers = + basic_headers>; + +} // http +} // beast + +#endif diff --git a/beast/http/impl/basic_headers.ipp b/include/beast/http/impl/basic_headers.ipp similarity index 81% rename from beast/http/impl/basic_headers.ipp rename to include/beast/http/impl/basic_headers.ipp index 0c4ec1e518..45a42322d7 100644 --- a/beast/http/impl/basic_headers.ipp +++ b/include/beast/http/impl/basic_headers.ipp @@ -1,27 +1,15 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_IMPL_BASIC_HEADERS_IPP +#define BEAST_HTTP_IMPL_BASIC_HEADERS_IPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_BASIC_HEADERS_IPP_INCLUDED -#define BEAST_HTTP_BASIC_HEADERS_IPP_INCLUDED - -#include -#include +#include +#include namespace beast { namespace http { @@ -138,7 +126,7 @@ basic_headers:: template basic_headers:: basic_headers(Allocator const& alloc) - : empty_base_optimization< + : beast::detail::empty_base_optimization< alloc_type>(alloc) { } @@ -146,7 +134,7 @@ basic_headers(Allocator const& alloc) template basic_headers:: basic_headers(basic_headers&& other) - : empty_base_optimization( + : beast::detail::empty_base_optimization( std::move(other.member())) , detail::basic_headers_base( std::move(other.set_), std::move(other.list_)) diff --git a/beast/http/impl/basic_parser.ipp b/include/beast/http/impl/basic_parser.ipp similarity index 65% rename from beast/http/impl/basic_parser.ipp rename to include/beast/http/impl/basic_parser.ipp index 9642d21f5a..15b624d849 100644 --- a/beast/http/impl/basic_parser.ipp +++ b/include/beast/http/impl/basic_parser.ipp @@ -1,29 +1,83 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_IMPL_BASIC_PARSER_IPP +#define BEAST_HTTP_IMPL_BASIC_PARSER_IPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include +#include +#include +#include namespace beast { namespace http { +namespace detail { + +inline +beast::http::method_t +convert_http_method(http_method m) +{ + using namespace beast; + switch (m) + { + case HTTP_DELETE: return http::method_t::http_delete; + case HTTP_GET: return http::method_t::http_get; + case HTTP_HEAD: return http::method_t::http_head; + case HTTP_POST: return http::method_t::http_post; + case HTTP_PUT: return http::method_t::http_put; + + // pathological + case HTTP_CONNECT: return http::method_t::http_connect; + case HTTP_OPTIONS: return http::method_t::http_options; + case HTTP_TRACE: return http::method_t::http_trace; + + // webdav + case HTTP_COPY: return http::method_t::http_copy; + case HTTP_LOCK: return http::method_t::http_lock; + case HTTP_MKCOL: return http::method_t::http_mkcol; + case HTTP_MOVE: return http::method_t::http_move; + case HTTP_PROPFIND: return http::method_t::http_propfind; + case HTTP_PROPPATCH: return http::method_t::http_proppatch; + case HTTP_SEARCH: return http::method_t::http_search; + case HTTP_UNLOCK: return http::method_t::http_unlock; + case HTTP_BIND: return http::method_t::http_bind; + case HTTP_REBIND: return http::method_t::http_rebind; + case HTTP_UNBIND: return http::method_t::http_unbind; + case HTTP_ACL: return http::method_t::http_acl; + + // subversion + case HTTP_REPORT: return http::method_t::http_report; + case HTTP_MKACTIVITY: return http::method_t::http_mkactivity; + case HTTP_CHECKOUT: return http::method_t::http_checkout; + case HTTP_MERGE: return http::method_t::http_merge; + + // upnp + case HTTP_MSEARCH: return http::method_t::http_msearch; + case HTTP_NOTIFY: return http::method_t::http_notify; + case HTTP_SUBSCRIBE: return http::method_t::http_subscribe; + case HTTP_UNSUBSCRIBE: return http::method_t::http_unsubscribe; + + // RFC-5789 + case HTTP_PATCH: return http::method_t::http_patch; + case HTTP_PURGE: return http::method_t::http_purge; + + // CalDav + case HTTP_MKCALENDAR: return http::method_t::http_mkcalendar; + + // RFC-2068, section 19.6.1.2 + case HTTP_LINK: return http::method_t::http_link; + case HTTP_UNLINK: return http::method_t::http_unlink; + }; + + return http::method_t::http_get; +} + +} // detail + template basic_parser:: basic_parser(basic_parser&& other) @@ -207,7 +261,7 @@ basic_parser::cb_headers_complete(http_parser* p) http_should_keep_alive(p) != 0; if(p->type == http_parser_type::HTTP_REQUEST) { - t.call_on_request(convert_http_method( + t.call_on_request(detail::convert_http_method( http_method(p->method)), t.url_, p->http_major, p->http_minor, keep_alive, p->upgrade, has_on_request{}); @@ -258,3 +312,5 @@ basic_parser::cb_chunk_complete(http_parser*) } // http } // beast + +#endif diff --git a/beast/http/impl/http-parser/http_parser.h b/include/beast/http/impl/http_parser.h similarity index 97% rename from beast/http/impl/http-parser/http_parser.h rename to include/beast/http/impl/http_parser.h index ffbfd99799..105ae510a8 100644 --- a/beast/http/impl/http-parser/http_parser.h +++ b/include/beast/http/impl/http_parser.h @@ -18,17 +18,16 @@ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ -#ifndef BEAST_HTTP_HTTP_PARSER_HTTP_PARSER_H_INCLUDED -#define BEAST_HTTP_HTTP_PARSER_HTTP_PARSER_H_INCLUDED - +#ifndef http_parser_h +#define http_parser_h #ifdef __cplusplus extern "C" { #endif /* Also update SONAME in the Makefile whenever you change these. */ #define HTTP_PARSER_VERSION_MAJOR 2 -#define HTTP_PARSER_VERSION_MINOR 6 -#define HTTP_PARSER_VERSION_PATCH 1 +#define HTTP_PARSER_VERSION_MINOR 7 +#define HTTP_PARSER_VERSION_PATCH 0 #include #if defined(_WIN32) && !defined(__MINGW32__) && \ @@ -78,6 +77,11 @@ typedef struct http_parser_settings http_parser_settings; * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding: * chunked' headers that indicate the presence of a body. * + * Returning `2` from on_headers_complete will tell parser that it should not + * expect neither a body nor any futher responses on this connection. This is + * useful for handling responses to a CONNECT request which may not contain + * `Upgrade` or `Connection: upgrade` headers. + * * http_data_cb does not return data chunks. It will be called arbitrarily * many times for each string. E.G. you might get 10 callbacks for "on_url" * each providing just a few characters more data. diff --git a/beast/http/impl/message.ipp b/include/beast/http/impl/message.ipp similarity index 85% rename from beast/http/impl/message.ipp rename to include/beast/http/impl/message.ipp index ccb72bef8f..f9dcb36711 100644 --- a/beast/http/impl/message.ipp +++ b/include/beast/http/impl/message.ipp @@ -1,30 +1,18 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_IMPL_MESSAGE_IPP +#define BEAST_HTTP_IMPL_MESSAGE_IPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_MESSAGE_IPP_INCLUDED -#define BEAST_HTTP_MESSAGE_IPP_INCLUDED - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include diff --git a/beast/http/impl/read.ipp b/include/beast/http/impl/read.ipp similarity index 84% rename from beast/http/impl/read.ipp rename to include/beast/http/impl/read.ipp index bc45cda6f0..0022f184df 100644 --- a/beast/http/impl/read.ipp +++ b/include/beast/http/impl/read.ipp @@ -1,29 +1,17 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_IMPL_READ_IPP_HPP +#define BEAST_HTTP_IMPL_READ_IPP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_READ_IPP_H_INCLUDED -#define BEAST_HTTP_READ_IPP_H_INCLUDED - -#include -#include -#include -#include +#include +#include +#include +#include #include namespace beast { diff --git a/beast/http/impl/write.ipp b/include/beast/http/impl/write.ipp similarity index 84% rename from beast/http/impl/write.ipp rename to include/beast/http/impl/write.ipp index 5a06575abc..30852e2ef7 100644 --- a/beast/http/impl/write.ipp +++ b/include/beast/http/impl/write.ipp @@ -1,41 +1,29 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Copyright 2013, Vinnie Falco - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_IMPL_WRITE_IPP +#define BEAST_HTTP_IMPL_WRITE_IPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_WRITE_IPP_INCLUDED -#define BEAST_HTTP_WRITE_IPP_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include #include -#include // +#include namespace beast { namespace http { @@ -174,12 +162,12 @@ operator()(error_code ec, std::size_t, bool again) // write headers and body if(d.wp.chunked) boost::asio::async_write(d.s, - append_buffers(d.wp.sb.data(), + buffer_cat(d.wp.sb.data(), chunk_encode(buffers)), std::move(*this)); else boost::asio::async_write(d.s, - append_buffers(d.wp.sb.data(), + buffer_cat(d.wp.sb.data(), buffers), std::move(*this)); }); if(ec) @@ -304,10 +292,10 @@ write(SyncWriteStream& stream, { // write headers and body if(wp.chunked) - boost::asio::write(stream, append_buffers( + boost::asio::write(stream, buffer_cat( wp.sb.data(), chunk_encode(buffers)), ec); else - boost::asio::write(stream, append_buffers( + boost::asio::write(stream, buffer_cat( wp.sb.data(), buffers), ec); }); if(ec) diff --git a/include/beast/http/message.hpp b/include/beast/http/message.hpp new file mode 100644 index 0000000000..e1756a395b --- /dev/null +++ b/include/beast/http/message.hpp @@ -0,0 +1,170 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_HTTP_MESSAGE_HPP +#define BEAST_HTTP_MESSAGE_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace beast { +namespace http { + +namespace detail { + +struct request_fields +{ + http::method_t method; + std::string url; +}; + +struct response_fields +{ + int status; + std::string reason; +}; + +} // detail + +struct request_params +{ + http::method_t method; + std::string url; + int version; +}; + +struct response_params +{ + int status; + std::string reason; + int version; +}; + +/** A HTTP message. + + A message can be a request or response, depending on the `isRequest` + template argument value. Requests and responses have different types, + so functions may be overloaded on them if desired. + + The `Body` template argument type determines the model used + to read or write the content body of the message. + + @tparam isRequest `true` if this is a request. + + @tparam Body A type meeting the requirements of Body. + + @tparam Headers A type meeting the requirements of Headers. +*/ +template +struct message + : std::conditional_t +{ + /** The trait type characterizing the body. + + The body member will be of type body_type::value_type. + */ + using body_type = Body; + using headers_type = Headers; + + using is_request = + std::integral_constant; + + int version; // 10 or 11 + headers_type headers; + typename Body::value_type body; + + message(); + message(message&&) = default; + message(message const&) = default; + message& operator=(message&&) = default; + message& operator=(message const&) = default; + + /** Construct a HTTP request. + */ + explicit + message(request_params params); + + /** Construct a HTTP response. + */ + explicit + message(response_params params); + + /// Serialize the request or response line to a Streambuf. + template + void + write_firstline(Streambuf& streambuf) const + { + write_firstline(streambuf, + std::integral_constant{}); + } + + /// Diagnostics only + template + friend + std::ostream& + operator<<(std::ostream& os, + message const& m); + +private: + template + void + write_firstline(Streambuf& streambuf, + std::true_type) const; + + template + void + write_firstline(Streambuf& streambuf, + std::false_type) const; +}; + +#if ! GENERATING_DOCS + +/// A typical HTTP request +template>> +using request = message; + +/// A typical HTTP response +template>> +using response = message; + +#endif + +// For diagnostic output only +template +std::ostream& +operator<<(std::ostream& os, + message const& m); + +/// Write a FieldSequence to a Streambuf. +template +void +write_fields(Streambuf& streambuf, FieldSequence const& fields); + +/// Returns `true` if a message indicates a keep alive +template +bool +is_keep_alive(message const& msg); + +/// Returns `true` if a message indicates a HTTP Upgrade request or response +template +bool +is_upgrade(message const& msg); + +} // http +} // beast + +#include + +#endif diff --git a/beast/http/method.h b/include/beast/http/method.hpp similarity index 79% rename from beast/http/method.h rename to include/beast/http/method.hpp index bc58af68af..0c1acf045e 100644 --- a/beast/http/method.h +++ b/include/beast/http/method.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_METHOD_H_INCLUDED -#define BEAST_HTTP_METHOD_H_INCLUDED +#ifndef BEAST_HTTP_METHOD_HPP +#define BEAST_HTTP_METHOD_HPP #include #include diff --git a/include/beast/http/parser.hpp b/include/beast/http/parser.hpp new file mode 100644 index 0000000000..fd4f4eaab9 --- /dev/null +++ b/include/beast/http/parser.hpp @@ -0,0 +1,155 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_HTTP_PARSER_HPP +#define BEAST_HTTP_PARSER_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace beast { +namespace http { + +/** A HTTP parser. + + The parser may only be used once. +*/ +template +class parser + : public basic_parser> +{ + using message_type = + message; + + message_type m_; + typename message_type::body_type::reader r_; + bool started_ = false; + +public: + parser(parser&&) = default; + + parser() + : http::basic_parser(isRequest) + , r_(m_) + { + } + + /// Returns `true` if at least one byte has been processed + bool + started() + { + return started_; + } + + message_type + release() + { + return std::move(m_); + } + +private: + friend class http::basic_parser; + + void + on_start() + { + started_ = true; + } + + void + on_field(std::string const& field, std::string const& value) + { + m_.headers.insert(field, value); + } + + void + on_headers_complete(error_code&) + { + // vFALCO TODO Decode the Content-Length and + // Transfer-Encoding, see if we can reserve the buffer. + // + // r_.reserve(content_length) + } + + bool + on_request(http::method_t method, std::string const& url, + int major, int minor, bool keep_alive, bool upgrade, + std::true_type) + { + m_.method = method; + m_.url = url; + m_.version = major * 10 + minor; + return true; + } + + bool + on_request(http::method_t, std::string const&, + int, int, bool, bool, + std::false_type) + { + return true; + } + + bool + on_request(http::method_t method, std::string const& url, + int major, int minor, bool keep_alive, bool upgrade) + { + return on_request(method, url, + major, minor, keep_alive, upgrade, + typename message_type::is_request{}); + } + + bool + on_response(int status, std::string const& reason, + int major, int minor, bool keep_alive, bool upgrade, + std::true_type) + { + m_.status = status; + m_.reason = reason; + m_.version = major * 10 + minor; + // VFALCO TODO return expect_body_ + return true; + } + + bool + on_response(int, std::string const&, int, int, bool, bool, + std::false_type) + { + return true; + } + + bool + on_response(int status, std::string const& reason, + int major, int minor, bool keep_alive, bool upgrade) + { + return on_response( + status, reason, major, minor, keep_alive, upgrade, + std::integral_constant{}); + } + + void + on_body(void const* data, + std::size_t size, error_code& ec) + { + r_.write(data, size, ec); + } + + void + on_complete() + { + } +}; + +} // http +} // beast + +#endif diff --git a/beast/http/read.h b/include/beast/http/read.hpp similarity index 70% rename from beast/http/read.h rename to include/beast/http/read.hpp index 6707831675..9532cdee08 100644 --- a/beast/http/read.h +++ b/include/beast/http/read.hpp @@ -1,28 +1,16 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_READ_HPP +#define BEAST_HTTP_READ_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_READ_H_INCLUDED -#define BEAST_HTTP_READ_H_INCLUDED - -#include -#include -#include +#include +#include +#include #include #include diff --git a/beast/http/reason.h b/include/beast/http/reason.hpp similarity index 62% rename from beast/http/reason.h rename to include/beast/http/reason.hpp index 7d97809125..ab3b51b741 100644 --- a/beast/http/reason.h +++ b/include/beast/http/reason.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_REASON_H_INCLUDED -#define BEAST_HTTP_REASON_H_INCLUDED +#ifndef BEAST_HTTP_REASON_HPP +#define BEAST_HTTP_REASON_HPP namespace beast { namespace http { diff --git a/include/beast/http/resume_context.hpp b/include/beast/http/resume_context.hpp new file mode 100644 index 0000000000..67c8d513a5 --- /dev/null +++ b/include/beast/http/resume_context.hpp @@ -0,0 +1,34 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_HTTP_RESUME_CONTEXT_HPP +#define BEAST_HTTP_RESUME_CONTEXT_HPP + +#include + +namespace beast { +namespace http { + +/** A functor that resumes a write operation. + + An rvalue reference to an object of this type is provided by the + write implementation to the `writer` associated with the body of + a message being sent. + + If it is desired that the `writer` suspend the write operation (for + example, to wait until data is ready), it can take ownership of + the resume context using a move. Then, it returns `boost::indeterminate` + to indicate that the write operation should suspend. Later, the calling + code invokes the resume function and the write operation continues + from where it left off. +*/ +using resume_context = std::function; + +} // http +} // beast + +#endif diff --git a/beast/http/rfc2616.h b/include/beast/http/rfc2616.hpp similarity index 89% rename from beast/http/rfc2616.h rename to include/beast/http/rfc2616.hpp index 053c3109ef..ea43016c76 100644 --- a/beast/http/rfc2616.h +++ b/include/beast/http/rfc2616.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_RFC2616_H_INCLUDED -#define BEAST_HTTP_RFC2616_H_INCLUDED +#ifndef BEAST_HTTP_RFC2616_HPP +#define BEAST_HTTP_RFC2616_HPP #include #include diff --git a/beast/http/streambuf_body.h b/include/beast/http/streambuf_body.hpp similarity index 55% rename from beast/http/streambuf_body.h rename to include/beast/http/streambuf_body.hpp index e89a48a1d7..7b2fe581e9 100644 --- a/beast/http/streambuf_body.h +++ b/include/beast/http/streambuf_body.hpp @@ -1,29 +1,17 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_STREAMBUF_BODY_HPP +#define BEAST_HTTP_STREAMBUF_BODY_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_STREAMBUF_BODY_H_INCLUDED -#define BEAST_HTTP_STREAMBUF_BODY_H_INCLUDED - -#include -#include -#include -#include +#include +#include +#include +#include #include #include diff --git a/beast/http/string_body.h b/include/beast/http/string_body.hpp similarity index 50% rename from beast/http/string_body.h rename to include/beast/http/string_body.hpp index c00326ab7d..19f9822636 100644 --- a/beast/http/string_body.h +++ b/include/beast/http/string_body.hpp @@ -1,30 +1,18 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_STRING_BODY_HPP +#define BEAST_HTTP_STRING_BODY_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_STRING_BODY_H_INCLUDED -#define BEAST_HTTP_STRING_BODY_H_INCLUDED - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include diff --git a/include/beast/http/type_check.hpp b/include/beast/http/type_check.hpp new file mode 100644 index 0000000000..a5192bd445 --- /dev/null +++ b/include/beast/http/type_check.hpp @@ -0,0 +1,72 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_HTTP_TYPE_CHECK_HPP +#define BEAST_HTTP_TYPE_CHECK_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace beast { +namespace http { + +#if GENERATING_DOCS +namespace detail { +#else +namespace concept { +#endif + +struct Reader +{ + template + Reader(message&) noexcept; + void write(void const*, std::size_t, error_code&) noexcept; +}; + +} // concept + +/// Evaluates to std::true_type if `T` models Body +template +struct is_Body : std::true_type +{ +}; + +/// Evalulates to std::true_type if Body has a reader +template +struct is_ReadableBody : std::true_type +{ +}; + +/// Evalulates to std::true_type if Body has a writer +template +struct is_WritableBody : std::true_type +{ +}; + +/// Evaluates to std::true_type if `T` models HTTPMessage +template +struct is_HTTPMessage : std::false_type +{ +}; + +/// Evaluates to std::true_type if `HTTPMessage` is a request +template +struct is_HTTPRequest : std::true_type +{ +}; + +} // http +} // beast + +#endif diff --git a/beast/http/write.h b/include/beast/http/write.hpp similarity index 63% rename from beast/http/write.h rename to include/beast/http/write.hpp index bafa2ec655..9544687b2c 100644 --- a/beast/http/write.h +++ b/include/beast/http/write.hpp @@ -1,27 +1,15 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_HTTP_WRITE_HPP +#define BEAST_HTTP_WRITE_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_HTTP_WRITE_H_INCLUDED -#define BEAST_HTTP_WRITE_H_INCLUDED - -#include -#include +#include +#include #include #include diff --git a/beast/asio/impl/basic_streambuf.ipp b/include/beast/impl/basic_streambuf.ipp similarity index 94% rename from beast/asio/impl/basic_streambuf.ipp rename to include/beast/impl/basic_streambuf.ipp index afec27bf7e..46ec6ab288 100644 --- a/beast/asio/impl/basic_streambuf.ipp +++ b/include/beast/impl/basic_streambuf.ipp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_BASIC_STREAMBUF_IPP_INCLUDED -#define BEAST_ASIO_BASIC_STREAMBUF_IPP_INCLUDED +#ifndef BEAST_IMPL_BASIC_STREAMBUF_IPP +#define BEAST_IMPL_BASIC_STREAMBUF_IPP #include #include @@ -358,7 +346,7 @@ basic_streambuf::~basic_streambuf() template basic_streambuf:: basic_streambuf(basic_streambuf&& other) - : empty_base_optimization( + : detail::empty_base_optimization( std::move(other.member())) , alloc_size_(other.alloc_size_) , in_size_(other.in_size_) @@ -476,7 +464,7 @@ basic_streambuf::operator=( template basic_streambuf::basic_streambuf( std::size_t alloc_size, Allocator const& alloc) - : empty_base_optimization(alloc) + : detail::empty_base_optimization(alloc) , out_(list_.end()) , alloc_size_(alloc_size) { diff --git a/beast/asio/impl/streambuf_readstream.ipp b/include/beast/impl/streambuf_readstream.ipp similarity index 83% rename from beast/asio/impl/streambuf_readstream.ipp rename to include/beast/impl/streambuf_readstream.ipp index fd1e8d9147..9c52df4112 100644 --- a/beast/asio/impl/streambuf_readstream.ipp +++ b/include/beast/impl/streambuf_readstream.ipp @@ -1,29 +1,17 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_IMPL_STREAMBUF_READSTREAM_IPP +#define BEAST_IMPL_STREAMBUF_READSTREAM_IPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_STREAMBUF_READSTREAM_IPP_INLUDED -#define BEAST_ASIO_STREAMBUF_READSTREAM_IPP_INLUDED - -#include -#include -#include -#include +#include +#include +#include +#include namespace beast { diff --git a/include/beast/placeholders.hpp b/include/beast/placeholders.hpp new file mode 100644 index 0000000000..2ba1a7af37 --- /dev/null +++ b/include/beast/placeholders.hpp @@ -0,0 +1,29 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_PLACEHOLDERS_HPP +#define BEAST_PLACEHOLDERS_HPP + +#include + +namespace beast { +namespace asio { + +namespace placeholders { +// asio placeholders that work with std::bind +namespace { +static auto const error (std::placeholders::_1); +static auto const bytes_transferred (std::placeholders::_2); +static auto const iterator (std::placeholders::_2); +static auto const signal_number (std::placeholders::_2); +} +} + +} +} + +#endif diff --git a/beast/asio/prepare_buffers.h b/include/beast/prepare_buffers.hpp similarity index 87% rename from beast/asio/prepare_buffers.h rename to include/beast/prepare_buffers.hpp index 724e56b26e..e2009bc003 100644 --- a/beast/asio/prepare_buffers.h +++ b/include/beast/prepare_buffers.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_PREPARE_BUFFERS_H_INLUDED -#define BEAST_ASIO_PREPARE_BUFFERS_H_INLUDED +#ifndef BEAST_PREPARE_BUFFERS_HPP +#define BEAST_PREPARE_BUFFERS_HPP #include #include diff --git a/beast/asio/static_streambuf.h b/include/beast/static_streambuf.hpp similarity index 89% rename from beast/asio/static_streambuf.h rename to include/beast/static_streambuf.hpp index 349998d39e..65d6df9569 100644 --- a/beast/asio/static_streambuf.h +++ b/include/beast/static_streambuf.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_STATIC_STREAMBUF_H_INLUDED -#define BEAST_ASIO_STATIC_STREAMBUF_H_INLUDED +#ifndef BEAST_STATIC_STREAMBUF_HPP +#define BEAST_STATIC_STREAMBUF_HPP #include #include diff --git a/test/asio.cpp b/include/beast/streambuf.hpp similarity index 55% rename from test/asio.cpp rename to include/beast/streambuf.hpp index 880a574428..04ab4b3e0a 100644 --- a/test/asio.cpp +++ b/include/beast/streambuf.hpp @@ -5,5 +5,15 @@ // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // -// Test that header file is self-contained. -#include +#ifndef BEAST_STREAMBUF_HPP +#define BEAST_STREAMBUF_HPP + +#include + +namespace beast { + +using streambuf = basic_streambuf>; + +} // beast + +#endif diff --git a/beast/asio/streambuf_readstream.h b/include/beast/streambuf_readstream.hpp similarity index 84% rename from beast/asio/streambuf_readstream.h rename to include/beast/streambuf_readstream.hpp index 78b6db7815..8b5bb77057 100644 --- a/beast/asio/streambuf_readstream.h +++ b/include/beast/streambuf_readstream.hpp @@ -1,26 +1,14 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_STREAMBUF_READSTREAM_HPP +#define BEAST_STREAMBUF_READSTREAM_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_STREAMBUF_READSTREAM_H_INLUDED -#define BEAST_ASIO_STREAMBUF_READSTREAM_H_INLUDED - -#include +#include #include #include #include @@ -254,6 +242,6 @@ public: } // beast -#include +#include #endif diff --git a/beast/asio/type_check.h b/include/beast/type_check.hpp similarity index 81% rename from beast/asio/type_check.h rename to include/beast/type_check.hpp index 00d0276171..16dfa8c843 100644 --- a/beast/asio/type_check.h +++ b/include/beast/type_check.hpp @@ -1,31 +1,19 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_TYPE_CHECK_HPP +#define BEAST_TYPE_CHECK_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_ASIO_TYPE_CHECK_H_INCLUDED -#define BEAST_ASIO_TYPE_CHECK_H_INCLUDED - -#include +#include #include #include #include #include -#include +#include #include namespace beast { @@ -297,22 +285,53 @@ struct is_Stream }; /// Determine if `T` meets the requirements of `Streambuf`. -template -struct is_Streambuf : std::false_type {}; -template -struct is_Streambuf().prepare(1))>::value>, - std::integral_constant().data())>::value>, - decltype(std::declval().commit(1), std::true_type{}), - decltype(std::declval().consume(1), std::true_type{}), - std::is_same().size()), std::size_t> ->>:std::true_type{}; +template +class is_Streambuf +{ + template().prepare(1))>::value>> + static R check1(int); + template + static std::false_type check1(...); + using type1 = decltype(check1(0)); + + template().data())>::value>> + static R check2(int); + template + static std::false_type check2(...); + using type2 = decltype(check2(0)); + + template().commit(1), std::true_type{})> + static R check3(int); + template + static std::false_type check3(...); + using type3 = decltype(check3(0)); + + template().consume(1), std::true_type{})> + static R check4(int); + template + static std::false_type check4(...); + using type4 = decltype(check4(0)); + + template().size()), std::size_t>> + static R check5(int); + template + static std::false_type check5(...); + using type5 = decltype(check5(0)); + +public: + /// `true` if `T` meets the requirements. + static bool const value = + type1::value && type2::value && + type3::value && type4::value && + type5::value; +}; #if ! GENERATING_DOCS @@ -320,7 +339,7 @@ struct is_Streambuf using is_Handler = std::integral_constant>::value && - is_call_possible::value>; + detail::is_call_possible::value>; #endif diff --git a/beast/http/error.h b/include/beast/websocket.hpp similarity index 78% rename from beast/http/error.h rename to include/beast/websocket.hpp index 3a101c551b..2baebdfc14 100644 --- a/beast/http/error.h +++ b/include/beast/websocket.hpp @@ -17,17 +17,14 @@ */ //============================================================================== -#ifndef BEAST_HTTP_ERROR_H_INCLUDED -#define BEAST_HTTP_ERROR_H_INCLUDED +#ifndef BEAST_WEBSOCKET_HPP +#define BEAST_WEBSOCKET_HPP -#include - -namespace beast { -namespace http { - -using error_code = boost::system::error_code; - -} // http -} // beast +#include +#include +#include +#include +#include +#include #endif diff --git a/beast/wsproto/detail/debug.h b/include/beast/websocket/detail/debug.hpp similarity index 99% rename from beast/wsproto/detail/debug.h rename to include/beast/websocket/detail/debug.hpp index a3696c9ff2..91de367bdd 100644 --- a/beast/wsproto/detail/debug.h +++ b/include/beast/websocket/detail/debug.hpp @@ -27,7 +27,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { template diff --git a/beast/wsproto/detail/decorator.h b/include/beast/websocket/detail/decorator.hpp similarity index 51% rename from beast/wsproto/detail/decorator.h rename to include/beast/websocket/detail/decorator.hpp index 7078849cfd..c0492477bb 100644 --- a/beast/wsproto/detail/decorator.h +++ b/include/beast/websocket/detail/decorator.hpp @@ -1,32 +1,20 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_DETAIL_DECORATOR_HPP +#define BEAST_WEBSOCKET_DETAIL_DECORATOR_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_DECORATOR_H_INCLUDED -#define BEAST_WSPROTO_DECORATOR_H_INCLUDED - -#include -#include -#include +#include +#include +#include #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { using request_type = http::request; @@ -106,7 +94,7 @@ using decorator_type = std::unique_ptr; } // detail -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/detail/error.h b/include/beast/websocket/detail/error.hpp similarity index 61% rename from beast/wsproto/detail/error.h rename to include/beast/websocket/detail/error.hpp index f19e1bc03e..0495a9ae87 100644 --- a/beast/wsproto/detail/error.h +++ b/include/beast/websocket/detail/error.hpp @@ -1,31 +1,19 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_DETAIL_ERROR_HPP +#define BEAST_WEBSOCKET_DETAIL_ERROR_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_DETAIL_ERROR_H_INCLUDED -#define BEAST_WSPROTO_DETAIL_ERROR_H_INCLUDED - -#include +#include namespace boost { namespace system { template<> -struct is_error_code_enum +struct is_error_code_enum { static bool const value = true; }; @@ -33,7 +21,7 @@ struct is_error_code_enum } // boost namespace beast { -namespace wsproto { +namespace websocket { namespace detail { class error_category : public boost::system::error_category @@ -98,7 +86,7 @@ get_error_category() } } // detail -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/detail/frame.h b/include/beast/websocket/detail/frame.hpp similarity index 84% rename from beast/wsproto/detail/frame.h rename to include/beast/websocket/detail/frame.hpp index cd9db07805..3ec1bfc635 100644 --- a/beast/wsproto/detail/frame.h +++ b/include/beast/websocket/detail/frame.hpp @@ -1,37 +1,25 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_DETAIL_FRAME_HPP +#define BEAST_WEBSOCKET_DETAIL_FRAME_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_FRAME_H_INCLUDED -#define BEAST_WSPROTO_FRAME_H_INCLUDED - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { // Contents of a WebSocket frame header @@ -369,7 +357,7 @@ read(close_reason& cr, } } // detail -} // wsproto +} // websocket } // beast #endif diff --git a/include/beast/websocket/detail/hybi13.hpp b/include/beast/websocket/detail/hybi13.hpp new file mode 100644 index 0000000000..831469c80d --- /dev/null +++ b/include/beast/websocket/detail/hybi13.hpp @@ -0,0 +1,57 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_WEBSOCKET_DETAIL_HYBI13_HPP +#define BEAST_WEBSOCKET_DETAIL_HYBI13_HPP + +#include +#include +#include +#include +#include +#include + +namespace beast { +namespace websocket { +namespace detail { + +template +std::string +make_sec_ws_key(Gen& g) +{ + union U + { + std::array a4; + std::array a16; + }; + U u; + for(int i = 0; i < 4; ++i) + u.a4[i] = g(); + return beast::detail::base64_encode(u.a16.data(), u.a16.size()); +} + +template +std::string +make_sec_ws_accept(boost::string_ref const& key) +{ + std::string s(key.data(), key.size()); + s += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + beast::detail::sha1_context ctx; + beast::detail::init(ctx); + beast::detail::update(ctx, s.data(), s.size()); + std::array digest; + beast::detail::finish(ctx, digest.data()); + return beast::detail::base64_encode( + digest.data(), digest.size()); +} + +} // detail +} // websocket +} // beast + +#endif diff --git a/beast/wsproto/detail/invokable.h b/include/beast/websocket/detail/invokable.hpp similarity index 69% rename from beast/wsproto/detail/invokable.h rename to include/beast/websocket/detail/invokable.hpp index 140246893d..37053fc8fa 100644 --- a/beast/wsproto/detail/invokable.h +++ b/include/beast/websocket/detail/invokable.hpp @@ -1,24 +1,12 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_INVOKABLE_H_INCLUDED -#define BEAST_WSPROTO_INVOKABLE_H_INCLUDED +#ifndef BEAST_WEBSOCKET_DETAIL_INVOKABLE_HPP +#define BEAST_WEBSOCKET_DETAIL_INVOKABLE_HPP #include #include @@ -27,7 +15,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { // "Parks" a composed operation, to invoke later @@ -162,7 +150,7 @@ invokable::emplace(F&& f) } } // detail -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/detail/mask.h b/include/beast/websocket/detail/mask.hpp similarity index 98% rename from beast/wsproto/detail/mask.h rename to include/beast/websocket/detail/mask.hpp index 220268665d..f5ebaddd71 100644 --- a/beast/wsproto/detail/mask.h +++ b/include/beast/websocket/detail/mask.hpp @@ -17,8 +17,8 @@ */ //============================================================================== -#ifndef BEAST_WSPROTO_DETAIL_MASKGEN_H_INCLUDED -#define BEAST_WSPROTO_DETAIL_MASKGEN_H_INCLUDED +#ifndef BEAST_WEBSOCKETDETAIL_MASKGEN_HPP +#define BEAST_WEBSOCKETDETAIL_MASKGEN_HPP #include #include @@ -28,7 +28,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { // Pseudo-random source of mask keys @@ -383,7 +383,7 @@ mask_inplace( } } // detail -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/detail/socket_base.h b/include/beast/websocket/detail/stream_base.hpp similarity index 60% rename from beast/wsproto/detail/socket_base.h rename to include/beast/websocket/detail/stream_base.hpp index 11abd8b5fc..42eab6890c 100644 --- a/beast/wsproto/detail/socket_base.h +++ b/include/beast/websocket/detail/stream_base.hpp @@ -1,36 +1,24 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_DETAIL_STREAM_BASE_HPP +#define BEAST_WEBSOCKET_DETAIL_STREAM_BASE_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_SOCKET_BASE_H_INCLUDED -#define BEAST_WSPROTO_SOCKET_BASE_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -39,7 +27,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { template @@ -73,7 +61,7 @@ clamp(UInt x, std::size_t limit) //------------------------------------------------------------------------------ -struct socket_base +struct stream_base { protected: struct op {}; @@ -108,16 +96,16 @@ protected: invokable wr_op_; // invoked after read completes close_reason cr_; // set from received close frame - socket_base() + stream_base() : d_(std::make_unique< decorator>()) { } - socket_base(socket_base&&) = default; - socket_base(socket_base const&) = delete; - socket_base& operator=(socket_base&&) = default; - socket_base& operator=(socket_base const&) = delete; + stream_base(stream_base&&) = default; + stream_base(stream_base const&) = delete; + stream_base& operator=(stream_base&&) = default; + stream_base& operator=(stream_base const&) = delete; template void @@ -135,7 +123,7 @@ protected: }; } // detail -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/detail/utf8_checker.h b/include/beast/websocket/detail/utf8_checker.hpp similarity index 80% rename from beast/wsproto/detail/utf8_checker.h rename to include/beast/websocket/detail/utf8_checker.hpp index 7d35134c42..e9a673bbef 100644 --- a/beast/wsproto/detail/utf8_checker.h +++ b/include/beast/websocket/detail/utf8_checker.hpp @@ -1,31 +1,19 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_UTF8_CHECKER_H_INCLUDED -#define BEAST_WSPROTO_UTF8_CHECKER_H_INCLUDED +#ifndef BEAST_WEBSOCKET_DETAIL_UTF8_CHECKER_HPP +#define BEAST_WEBSOCKET_DETAIL_UTF8_CHECKER_HPP #include #include #include // DEPRECATED namespace beast { -namespace wsproto { +namespace websocket { namespace detail { // Code adapted from @@ -178,7 +166,7 @@ check_utf8(char const* p, std::size_t n) } } // detail -} // wsproto +} // websocket } // beast #endif diff --git a/include/beast/websocket/error.hpp b/include/beast/websocket/error.hpp new file mode 100644 index 0000000000..0283483f67 --- /dev/null +++ b/include/beast/websocket/error.hpp @@ -0,0 +1,60 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_WEBSOCKET_ERROR_HPP +#define BEAST_WEBSOCKET_ERROR_HPP + +#include + +namespace beast { +namespace websocket { + +using error_code = boost::system::error_code; + +/// Error values +enum class error +{ + /// Both sides performed a WebSocket close + closed = 1, + + /// WebSocket connection failed, protocol violation + failed, + + /// Upgrade request failed, connection is closed + handshake_failed, + + /// Upgrade request failed, but connection is still open + keep_alive, + + /// HTTP response is malformed + response_malformed, + + /// HTTP response failed the upgrade + response_failed, + + /// Upgrade request denied for invalid fields. + response_denied, + + /// Upgrade request is malformed + request_malformed, + + /// Upgrade request fields incorrect + request_invalid, + + /// Upgrade request denied + request_denied +}; + +error_code +make_error_code(error e); + +} // websocket +} // beast + +#include + +#endif diff --git a/beast/wsproto/impl/accept_op.ipp b/include/beast/websocket/impl/accept_op.ipp similarity index 63% rename from beast/wsproto/impl/accept_op.ipp rename to include/beast/websocket/impl/accept_op.ipp index c82e24cd1a..ff8b03d1d9 100644 --- a/beast/wsproto/impl/accept_op.ipp +++ b/include/beast/websocket/impl/accept_op.ipp @@ -1,56 +1,44 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_ACCEPT_OP_HPP +#define BEAST_WEBSOCKET_IMPL_ACCEPT_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_ACCEPT_OP_H_INCLUDED -#define BEAST_WSPROTO_ACCEPT_OP_H_INCLUDED - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include namespace beast { -namespace wsproto { +namespace websocket { // read and respond to an upgrade request // -template +template template -class socket::accept_op +class stream::accept_op { using alloc_type = handler_alloc; struct data { - socket& ws; + stream& ws; http::request req; Handler h; bool cont; int state = 0; template - data(DeducedHandler&& h_, socket& ws_, + data(DeducedHandler&& h_, stream& ws_, Buffers const& buffers) : ws(ws_) , h(std::forward(h_)) @@ -73,7 +61,7 @@ public: template accept_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::allocate_shared(alloc_type{h}, std::forward(h), ws, std::forward(args)...)) @@ -120,10 +108,10 @@ public: } }; -template +template template void -socket::accept_op:: +stream::accept_op:: operator()(error_code const& ec, std::size_t bytes_transferred, bool again) { @@ -152,7 +140,7 @@ operator()(error_code const& ec, d.h(ec); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/close_op.ipp b/include/beast/websocket/impl/close_op.ipp similarity index 71% rename from beast/wsproto/impl/close_op.ipp rename to include/beast/websocket/impl/close_op.ipp index f17e050ead..1b558686a6 100644 --- a/beast/wsproto/impl/close_op.ipp +++ b/include/beast/websocket/impl/close_op.ipp @@ -1,37 +1,25 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_CLOSE_OP_HPP +#define BEAST_WEBSOCKET_IMPL_CLOSE_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_CLOSE_OP_H_INCLUDED -#define BEAST_WSPROTO_CLOSE_OP_H_INCLUDED - -#include -#include +#include +#include #include namespace beast { -namespace wsproto { +namespace websocket { // send the close message and wait for the response // -template +template template -class socket::close_op +class stream::close_op { using alloc_type = handler_alloc; @@ -42,7 +30,7 @@ class socket::close_op struct data : op { - socket& ws; + stream& ws; close_reason cr; Handler h; fb_type fb; @@ -51,7 +39,7 @@ class socket::close_op int state = 0; template - data(DeducedHandler&& h_, socket& ws_, + data(DeducedHandler&& h_, stream& ws_, close_reason const& cr_) : ws(ws_) , cr(cr_) @@ -72,7 +60,7 @@ public: template close_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::allocate_shared(alloc_type{h}, std::forward(h), ws, std::forward(args)...)) @@ -127,10 +115,10 @@ public: } }; -template +template template void -socket::close_op::operator()( +stream::close_op::operator()( error_code ec, std::size_t bytes_transferred, bool again) { auto& d = *d_; @@ -192,7 +180,7 @@ socket::close_op::operator()( d.ws.rd_op_.maybe_invoke(); } -} // wsproto +} // websocket } // beast #endif diff --git a/include/beast/websocket/impl/error.ipp b/include/beast/websocket/impl/error.ipp new file mode 100644 index 0000000000..b4c2910228 --- /dev/null +++ b/include/beast/websocket/impl/error.ipp @@ -0,0 +1,27 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef BEAST_WEBSOCKET_IMPL_ERROR_IPP_HPP +#define BEAST_WEBSOCKET_IMPL_ERROR_IPP_HPP + +#include + +namespace beast { +namespace websocket { + +inline +error_code +make_error_code(error e) +{ + return error_code( + static_cast(e), detail::get_error_category()); +} + +} // websocket +} // beast + +#endif diff --git a/beast/wsproto/impl/handshake_op.ipp b/include/beast/websocket/impl/handshake_op.ipp similarity index 66% rename from beast/wsproto/impl/handshake_op.ipp rename to include/beast/websocket/impl/handshake_op.ipp index 2f6538fb76..a3cd9e552a 100644 --- a/beast/wsproto/impl/handshake_op.ipp +++ b/include/beast/websocket/impl/handshake_op.ipp @@ -1,48 +1,36 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_HANDSHAKE_OP_HPP +#define BEAST_WEBSOCKET_IMPL_HANDSHAKE_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_HANDSHAKE_OP_H_INCLUDED -#define BEAST_WSPROTO_HANDSHAKE_OP_H_INCLUDED - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include namespace beast { -namespace wsproto { +namespace websocket { // send the upgrade request and process the response // -template +template template -class socket::handshake_op +class stream::handshake_op { using alloc_type = handler_alloc; struct data { - socket& ws; + stream& ws; Handler h; std::string key; http::request req; @@ -51,7 +39,7 @@ class socket::handshake_op int state = 0; template - data(DeducedHandler&& h_, socket& ws_, + data(DeducedHandler&& h_, stream& ws_, boost::string_ref const& host, boost::string_ref const& resource) : ws(ws_) @@ -71,7 +59,7 @@ public: template handshake_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::allocate_shared(alloc_type{h}, std::forward(h), ws, std::forward(args)...)) @@ -118,10 +106,10 @@ public: } }; -template +template template void -socket::handshake_op< +stream::handshake_op< Handler>::operator()(error_code ec, std::size_t bytes_transferred, bool again) { @@ -164,7 +152,7 @@ socket::handshake_op< d.h(ec); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/read_frame_op.ipp b/include/beast/websocket/impl/read_frame_op.ipp similarity index 89% rename from beast/wsproto/impl/read_frame_op.ipp rename to include/beast/websocket/impl/read_frame_op.ipp index 9c3d1f017c..e29feda006 100644 --- a/beast/wsproto/impl/read_frame_op.ipp +++ b/include/beast/websocket/impl/read_frame_op.ipp @@ -1,41 +1,29 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_READ_FRAME_OP_HPP +#define BEAST_WEBSOCKET_IMPL_READ_FRAME_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_READ_FRAME_OP_H_INCLUDED -#define BEAST_WSPROTO_READ_FRAME_OP_H_INCLUDED - -#include -#include -#include -#include +#include +#include +#include +#include #include #include namespace beast { -namespace wsproto { +namespace websocket { // Reads a single message frame, // processes any received control frames. // -template +template template -class socket::read_frame_op +class stream::read_frame_op { using alloc_type = handler_alloc; @@ -51,7 +39,7 @@ class socket::read_frame_op struct data : op { - socket& ws; + stream& ws; frame_info& fi; Streambuf& sb; smb_type smb; @@ -62,7 +50,7 @@ class socket::read_frame_op int state = 0; template - data(DeducedHandler&& h_, socket& ws_, + data(DeducedHandler&& h_, stream& ws_, frame_info& fi_, Streambuf& sb_) : ws(ws_) , fi(fi_) @@ -82,7 +70,7 @@ public: template read_frame_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::allocate_shared(alloc_type{h}, std::forward(h), ws, std::forward(args)...)) @@ -136,10 +124,10 @@ public: } }; -template +template template void -socket::read_frame_op:: +stream::read_frame_op:: operator()(error_code ec,std::size_t bytes_transferred, bool again) { auto& d = *d_; @@ -513,7 +501,7 @@ operator()(error_code ec,std::size_t bytes_transferred, bool again) d.ws.wr_op_.maybe_invoke(); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/read_op.ipp b/include/beast/websocket/impl/read_op.ipp similarity index 62% rename from beast/wsproto/impl/read_op.ipp rename to include/beast/websocket/impl/read_op.ipp index 895a91514b..b42c401b0b 100644 --- a/beast/wsproto/impl/read_op.ipp +++ b/include/beast/websocket/impl/read_op.ipp @@ -1,43 +1,31 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_READ_OP_HPP +#define BEAST_WEBSOCKET_IMPL_READ_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_READ_OP_H_INCLUDED -#define BEAST_WSPROTO_READ_OP_H_INCLUDED - -#include +#include #include namespace beast { -namespace wsproto { +namespace websocket { // read an entire message // -template +template template -class socket::read_op +class stream::read_op { using alloc_type = handler_alloc; struct data { - socket& ws; + stream& ws; opcode& op; Streambuf& sb; Handler h; @@ -47,7 +35,7 @@ class socket::read_op template data(DeducedHandler&& h_, - socket& ws_, opcode& op_, + stream& ws_, opcode& op_, Streambuf& sb_) : ws(ws_) , op(op_) @@ -67,7 +55,7 @@ public: template read_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::allocate_shared(alloc_type{h}, std::forward(h), ws, std::forward(args)...)) @@ -109,10 +97,10 @@ public: } }; -template +template template void -socket::read_op:: +stream::read_op:: operator()(error_code const& ec, bool again) { auto& d = *d_; @@ -138,7 +126,7 @@ operator()(error_code const& ec, bool again) d.h(ec); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/response_op.ipp b/include/beast/websocket/impl/response_op.ipp similarity index 62% rename from beast/wsproto/impl/response_op.ipp rename to include/beast/websocket/impl/response_op.ipp index ff7e6f7f7f..9351c2b27e 100644 --- a/beast/wsproto/impl/response_op.ipp +++ b/include/beast/websocket/impl/response_op.ipp @@ -1,44 +1,32 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_RESPONSE_OP_HPP +#define BEAST_WEBSOCKET_IMPL_RESPONSE_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_RESPONSE_OP_H_INCLUDED -#define BEAST_WSPROTO_RESPONSE_OP_H_INCLUDED - -#include -#include -#include +#include +#include +#include #include namespace beast { -namespace wsproto { +namespace websocket { // Respond to an upgrade HTTP request -template +template template -class socket::response_op +class stream::response_op { using alloc_type = handler_alloc; struct data { - socket& ws; + stream& ws; http::response resp; Handler h; error_code final_ec; @@ -47,7 +35,7 @@ class socket::response_op template - data(DeducedHandler&& h_, socket& ws_, + data(DeducedHandler&& h_, stream& ws_, http::message const& req, bool cont_) : ws(ws_) @@ -68,7 +56,7 @@ public: template response_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::allocate_shared(alloc_type{h}, std::forward(h), ws, std::forward(args)...)) @@ -110,10 +98,10 @@ public: } }; -template +template template void -socket::response_op:: +stream::response_op:: operator()(error_code ec, bool again) { auto& d = *d_; @@ -141,7 +129,7 @@ operator()(error_code ec, bool again) d.h(ec); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/socket.ipp b/include/beast/websocket/impl/socket.ipp similarity index 84% rename from beast/wsproto/impl/socket.ipp rename to include/beast/websocket/impl/socket.ipp index 50607f9a85..6d437540d2 100644 --- a/beast/wsproto/impl/socket.ipp +++ b/include/beast/websocket/impl/socket.ipp @@ -1,46 +1,34 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_SOCKET_IPP +#define BEAST_WEBSOCKET_IMPL_SOCKET_IPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_IMPL_SOCKET_IPP_INCLUDED -#define BEAST_WSPROTO_IMPL_SOCKET_IPP_INCLUDED - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -48,13 +36,13 @@ #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { template void -socket_base::prepare_fh(close_code& code) +stream_base::prepare_fh(close_code& code) { // continuation without an active message if(! rd_cont_ && rd_fh_.op == opcode::cont) @@ -100,7 +88,7 @@ socket_base::prepare_fh(close_code& code) template void -socket_base::write_close( +stream_base::write_close( Streambuf& sb, close_reason const& cr) { using namespace boost::endian; @@ -146,7 +134,7 @@ socket_base::write_close( template void -socket_base::write_ping(Streambuf& sb, +stream_base::write_ping(Streambuf& sb, opcode op, ping_payload_type const& data) { frame_header fh; @@ -177,9 +165,9 @@ socket_base::write_ping(Streambuf& sb, //------------------------------------------------------------------------------ -template +template template -socket::socket(Args&&... args) +stream::stream(Args&&... args) : next_layer_(std::forward(args)...) , stream_(next_layer_) { @@ -187,26 +175,26 @@ socket::socket(Args&&... args) "Stream requirements not met"); } -template +template void -socket::accept(error_code& ec) +stream::accept(error_code& ec) { accept(boost::asio::null_buffers{}, ec); } -template +template template auto -socket::async_accept(AcceptHandler&& handler) +stream::async_accept(AcceptHandler&& handler) { return async_accept(boost::asio::null_buffers{}, std::forward(handler)); } -template +template template void -socket::accept( +stream::accept( ConstBufferSequence const& buffers) { static_assert(is_ConstBufferSequence< @@ -217,10 +205,10 @@ socket::accept( detail::maybe_throw(ec, "accept"); } -template +template template void -socket::accept( +stream::accept( ConstBufferSequence const& buffers, error_code& ec) { static_assert(beast::is_ConstBufferSequence< @@ -238,10 +226,10 @@ socket::accept( accept(m, ec); } -template +template template auto -socket::async_accept( +stream::async_accept( ConstBufferSequence const& bs, AcceptHandler&& handler) { static_assert(beast::is_ConstBufferSequence< @@ -255,10 +243,10 @@ socket::async_accept( return completion.result.get(); } -template +template template void -socket::accept( +stream::accept( http::message const& request) { error_code ec; @@ -266,10 +254,10 @@ socket::accept( detail::maybe_throw(ec, "accept"); } -template +template template void -socket::accept( +stream::accept( http::message const& req, error_code& ec) { @@ -285,10 +273,10 @@ socket::accept( role_ = role_type::server; } -template +template template auto -socket::async_accept( +stream::async_accept( http::message const& req, AcceptHandler&& handler) { @@ -302,9 +290,9 @@ socket::async_accept( return completion.result.get(); } -template +template void -socket::handshake(boost::string_ref const& host, +stream::handshake(boost::string_ref const& host, boost::string_ref const& resource, error_code& ec) { std::string key; @@ -319,10 +307,10 @@ socket::handshake(boost::string_ref const& host, do_response(resp, key, ec); } -template +template template auto -socket::async_handshake(boost::string_ref const& host, +stream::async_handshake(boost::string_ref const& host, boost::string_ref const& resource, HandshakeHandler&& handler) { beast::async_completion< @@ -333,9 +321,9 @@ socket::async_handshake(boost::string_ref const& host, return completion.result.get(); } -template +template void -socket::close( +stream::close( close_reason const& cr, error_code& ec) { assert(! wr_close_); @@ -346,10 +334,10 @@ socket::close( error_ = ec != 0; } -template +template template auto -socket::async_close( +stream::async_close( close_reason const& cr, CloseHandler&& handler) { beast::async_completion< @@ -360,10 +348,10 @@ socket::async_close( return completion.result.get(); } -template +template template void -socket:: +stream:: read(opcode& op, Streambuf& streambuf, error_code& ec) { frame_info fi; @@ -378,10 +366,10 @@ read(opcode& op, Streambuf& streambuf, error_code& ec) } } -template +template template auto -socket:: +stream:: async_read(opcode& op, Streambuf& streambuf, ReadHandler&& handler) { @@ -395,10 +383,10 @@ async_read(opcode& op, return completion.result.get(); } -template +template template void -socket::read_frame(frame_info& fi, +stream::read_frame(frame_info& fi, Streambuf& streambuf, error_code& ec) { close_code code{}; @@ -531,10 +519,10 @@ socket::read_frame(frame_info& fi, error_ = ec != 0; } -template +template template auto -socket::async_read_frame(frame_info& fi, +stream::async_read_frame(frame_info& fi, Streambuf& streambuf, ReadHandler&& handler) { static_assert(beast::is_Streambuf::value, @@ -546,10 +534,10 @@ socket::async_read_frame(frame_info& fi, return completion.result.get(); } -template +template template void -socket::write( +stream::write( ConstBufferSequence const& bs, error_code& ec) { static_assert(beast::is_ConstBufferSequence< @@ -573,10 +561,10 @@ socket::write( } } -template +template template auto -socket::async_write( +stream::async_write( ConstBufferSequence const& bs, WriteHandler&& handler) { static_assert(beast::is_ConstBufferSequence< @@ -589,10 +577,10 @@ socket::async_write( return completion.result.get(); } -template +template template void -socket::write_frame(bool fin, +stream::write_frame(bool fin, ConstBufferSequence const& bs, error_code& ec) { static_assert(beast::is_ConstBufferSequence< @@ -617,7 +605,7 @@ socket::write_frame(bool fin, { // send header and payload boost::asio::write(stream_, - append_buffers(fh_buf.data(), bs), ec); + buffer_cat(fh_buf.data(), bs), ec); error_ = ec != 0; return; } @@ -640,7 +628,7 @@ socket::write_frame(bool fin, detail::mask_inplace(mb, key); // send header and payload boost::asio::write(stream_, - append_buffers(fh_buf.data(), mb), ec); + buffer_cat(fh_buf.data(), mb), ec); if(ec) { error_ = ec != 0; @@ -666,10 +654,10 @@ socket::write_frame(bool fin, } } -template +template template auto -socket::async_write_frame(bool fin, +stream::async_write_frame(bool fin, ConstBufferSequence const& bs, WriteHandler&& handler) { static_assert(beast::is_ConstBufferSequence< @@ -686,9 +674,9 @@ socket::async_write_frame(bool fin, //------------------------------------------------------------------------------ -template +template http::request -socket::build_request(boost::string_ref const& host, +stream::build_request(boost::string_ref const& host, boost::string_ref const& resource, std::string& key) { http::request req; @@ -705,10 +693,10 @@ socket::build_request(boost::string_ref const& host, return req; } -template +template template http::response -socket::build_response( +stream::build_response( http::message const& req) { auto err = @@ -757,10 +745,10 @@ socket::build_response( return resp; } -template +template template void -socket::do_response( +stream::do_response( http::message const& resp, boost::string_ref const& key, error_code& ec) { @@ -781,9 +769,9 @@ socket::do_response( role_ = role_type::client; } -template +template void -socket::do_read_fh( +stream::do_read_fh( detail::frame_streambuf& fb, close_code& code, error_code& ec) { @@ -809,7 +797,7 @@ socket::do_read_fh( prepare_fh(code); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/ssl.ipp b/include/beast/websocket/impl/ssl.ipp similarity index 72% rename from beast/wsproto/impl/ssl.ipp rename to include/beast/websocket/impl/ssl.ipp index ec465db639..4e9440a8a3 100644 --- a/beast/wsproto/impl/ssl.ipp +++ b/include/beast/websocket/impl/ssl.ipp @@ -1,30 +1,18 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_SSL_IPP_INCLUDED +#define BEAST_WEBSOCKET_IMPL_SSL_IPP_INCLUDED - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_SSL_IPP_INCLUDED -#define BEAST_WSPROTO_SSL_IPP_INCLUDED - -#include -#include +#include +#include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { @@ -164,7 +152,7 @@ async_teardown( handler), stream}; } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/teardown.ipp b/include/beast/websocket/impl/teardown.ipp similarity index 72% rename from beast/wsproto/impl/teardown.ipp rename to include/beast/websocket/impl/teardown.ipp index 92e50fd0f4..e11992a6a7 100644 --- a/beast/wsproto/impl/teardown.ipp +++ b/include/beast/websocket/impl/teardown.ipp @@ -1,31 +1,19 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_TEARDOWN_IPP +#define BEAST_WEBSOCKET_IMPL_TEARDOWN_IPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_TEARDOWN_IPP_INCLUDED -#define BEAST_WSPROTO_TEARDOWN_IPP_INCLUDED - -#include -#include +#include +#include #include namespace beast { -namespace wsproto { +namespace websocket { namespace detail { @@ -177,7 +165,7 @@ async_teardown( TeardownHandler>(handler), socket}; } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/write_frame_op.ipp b/include/beast/websocket/impl/write_frame_op.ipp similarity index 78% rename from beast/wsproto/impl/write_frame_op.ipp rename to include/beast/websocket/impl/write_frame_op.ipp index a374157094..3d0f72a188 100644 --- a/beast/wsproto/impl/write_frame_op.ipp +++ b/include/beast/websocket/impl/write_frame_op.ipp @@ -1,50 +1,38 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_WRITE_FRAME_OP_HPP +#define BEAST_WEBSOCKET_IMPL_WRITE_FRAME_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_WRITE_FRAME_OP_H_INCLUDED -#define BEAST_WSPROTO_WRITE_FRAME_OP_H_INCLUDED - -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include #include namespace beast { -namespace wsproto { +namespace websocket { // write a frame // -template +template template -class socket::write_frame_op +class stream::write_frame_op { using alloc_type = handler_alloc; struct data : op { - socket& ws; + stream& ws; consuming_buffers cb; Handler h; detail::frame_header fh; @@ -57,7 +45,7 @@ class socket::write_frame_op int state = 0; template - data(DeducedHandler&& h_, socket& ws_, + data(DeducedHandler&& h_, stream& ws_, bool fin, Buffers const& bs) : ws(ws_) , cb(bs) @@ -106,7 +94,7 @@ public: template write_frame_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::make_shared( std::forward(h), ws, std::forward(args)...)) @@ -155,10 +143,10 @@ public: } }; -template +template template void -socket:: +stream:: write_frame_op:: operator()( error_code ec, std::size_t bytes_transferred, bool again) @@ -214,7 +202,7 @@ operator()( assert(! d.ws.wr_block_); d.ws.wr_block_ = &d; boost::asio::async_write(d.ws.stream_, - append_buffers(d.fh_buf.data(), d.cb), + buffer_cat(d.fh_buf.data(), d.cb), std::move(*this)); return; } @@ -230,7 +218,7 @@ operator()( assert(! d.ws.wr_block_); d.ws.wr_block_ = &d; boost::asio::async_write(d.ws.stream_, - append_buffers(d.fh_buf.data(), + buffer_cat(d.fh_buf.data(), mb), std::move(*this)); return; } @@ -271,7 +259,7 @@ operator()( d.ws.rd_op_.maybe_invoke(); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/impl/write_op.ipp b/include/beast/websocket/impl/write_op.ipp similarity index 61% rename from beast/wsproto/impl/write_op.ipp rename to include/beast/websocket/impl/write_op.ipp index 24e48dd4d0..50fa14d43c 100644 --- a/beast/wsproto/impl/write_op.ipp +++ b/include/beast/websocket/impl/write_op.ipp @@ -1,49 +1,36 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_IMPL_WRITE_OP_HPP +#define BEAST_WEBSOCKET_IMPL_WRITE_OP_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_WRITE_OP_H_INCLUDED -#define BEAST_WSPROTO_WRITE_OP_H_INCLUDED - -#include -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include namespace beast { -namespace wsproto { +namespace websocket { // write a message // -template +template template -class socket::write_op +class stream::write_op { using alloc_type = handler_alloc; struct data : op { - socket& ws; + stream& ws; consuming_buffers cb; Handler h; std::size_t remain; @@ -52,7 +39,7 @@ class socket::write_op template data(DeducedHandler&& h_, - socket& ws_, Buffers const& bs) + stream& ws_, Buffers const& bs) : ws(ws_) , cb(bs) , h(std::forward(h_)) @@ -72,7 +59,7 @@ public: template explicit write_op(DeducedHandler&& h, - socket& ws, Args&&... args) + stream& ws, Args&&... args) : d_(std::allocate_shared(alloc_type{h}, std::forward(h), ws, std::forward(args)...)) @@ -113,10 +100,10 @@ public: } }; -template +template template void -socket:: +stream:: write_op:: operator()(error_code ec, bool again) { @@ -144,7 +131,7 @@ operator()(error_code ec, bool again) d.h(ec); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/option.h b/include/beast/websocket/option.hpp similarity index 84% rename from beast/wsproto/option.h rename to include/beast/websocket/option.hpp index f2fbb7b1fb..3f872f6507 100644 --- a/beast/wsproto/option.h +++ b/include/beast/websocket/option.hpp @@ -1,33 +1,21 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_OPTION_HPP +#define BEAST_WEBSOCKET_OPTION_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_OPTION_H_INCLUDED -#define BEAST_WSPROTO_OPTION_H_INCLUDED - -#include +#include #include #include #include #include namespace beast { -namespace wsproto { +namespace websocket { /** Automatic fragmentation size option. @@ -47,7 +35,7 @@ namespace wsproto { Setting the automatic fragmentation size option: @code ... - wsproto::socket stream(ios); + websocket::stream stream(ios); stream.set_option(auto_fragment_size{8192}); @endcode */ @@ -299,7 +287,7 @@ struct write_buffer_size }; #endif -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/rfc6455.h b/include/beast/websocket/rfc6455.hpp similarity index 69% rename from beast/wsproto/rfc6455.h rename to include/beast/websocket/rfc6455.hpp index 84700f426a..3290b369fc 100644 --- a/beast/wsproto/rfc6455.h +++ b/include/beast/websocket/rfc6455.hpp @@ -1,32 +1,20 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_RFC6455_HPP +#define BEAST_WEBSOCKET_RFC6455_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_RFC6455_H_INCLUDED -#define BEAST_WSPROTO_RFC6455_H_INCLUDED - -#include +#include #include #include #include namespace beast { -namespace wsproto { +namespace websocket { /** WebSocket frame header opcodes. */ enum class opcode : std::uint8_t @@ -157,7 +145,7 @@ enum class role_type #endif -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/ssl.h b/include/beast/websocket/ssl.hpp similarity index 61% rename from beast/wsproto/ssl.h rename to include/beast/websocket/ssl.hpp index e99faec6b5..8d7606b330 100644 --- a/beast/wsproto/ssl.h +++ b/include/beast/websocket/ssl.hpp @@ -1,32 +1,20 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_SSL_HPP +#define BEAST_WEBSOCKET_SSL_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_SSL_H_INCLUDED -#define BEAST_WSPROTO_SSL_H_INCLUDED - -#include +#include #include #include #include namespace beast { -namespace wsproto { +namespace websocket { /** Tear down a `boost::asio::ssl::stream`. @@ -78,9 +66,9 @@ async_teardown( boost::asio::ssl::stream& stream, TeardownHandler&& handler); -} // wsproto +} // websocket } // beast -#include +#include #endif diff --git a/beast/wsproto/static_string.h b/include/beast/websocket/static_string.hpp similarity index 98% rename from beast/wsproto/static_string.h rename to include/beast/websocket/static_string.hpp index 45eb085897..6cddcdc5cb 100644 --- a/beast/wsproto/static_string.h +++ b/include/beast/websocket/static_string.hpp @@ -17,8 +17,8 @@ */ //============================================================================== -#ifndef BEAST_WSPROTO_STATIC_STRING_H_INCLUDED -#define BEAST_WSPROTO_STATIC_STRING_H_INCLUDED +#ifndef BEAST_WEBSOCKET_STATIC_STRING_HPP +#define BEAST_WEBSOCKET_STATIC_STRING_HPP #include #include @@ -28,7 +28,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { /** A string with a fixed-size storage area. @@ -331,7 +331,7 @@ assign(CharT const* s) std::copy(s, s+n, s_.begin()); } -} // wsproto +} // websocket } // beast #endif diff --git a/beast/wsproto/socket.h b/include/beast/websocket/stream.hpp similarity index 90% rename from beast/wsproto/socket.h rename to include/beast/websocket/stream.hpp index d6f83ea7fd..537242aa8a 100644 --- a/beast/wsproto/socket.h +++ b/include/beast/websocket/stream.hpp @@ -1,30 +1,18 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. +#ifndef BEAST_WEBSOCKET_STREAM_HPP +#define BEAST_WEBSOCKET_STREAM_HPP - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#ifndef BEAST_WSPROTO_SOCKET_H_INCLUDED -#define BEAST_WSPROTO_SOCKET_H_INCLUDED - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include @@ -32,7 +20,7 @@ #include namespace beast { -namespace wsproto { +namespace websocket { /** Information about a WebSocket frame. @@ -52,7 +40,7 @@ struct frame_info /** Provides message-oriented functionality using WebSocket. - The socket class template provides asynchronous and blocking + The stream class template provides asynchronous and blocking message-oriented functionality necessary for clients and servers to utilize the WebSocket protocol. @@ -64,37 +52,40 @@ struct frame_info @par Example - To use the WebSocket socket template with an + To use the WebSocket stream template with an ip::tcp::socket, you would write: @code - wsproto::socket ws(io_service); + websocket::stream ws(io_service); @endcode Alternatively, you can write: @code ip::tcp::socket sock(io_service); - wsproto::socket ws(sock); + websocket::stream ws(sock); @endcode - @note A socket object must not be destroyed while there are + @tparam NextLayer An object meeting the requirements of ReadStream, + WriteStream, AsyncReadStream, and AsyncWriteStream. + + @note A stream object must not be destroyed while there are pending asynchronous operations associated with it. @par Concepts AsyncReadStream, AsyncWriteStream, Decorator, Streambuf, SyncReadStream, SyncWriteStream. */ -template -class socket : public detail::socket_base +template +class stream : public detail::stream_base { friend class ws_test; - Stream next_layer_; - streambuf_readstream stream_; + NextLayer next_layer_; + streambuf_readstream stream_; public: /// The type of the next layer. using next_layer_type = - std::remove_reference_t; + std::remove_reference_t; /// The type of the lowest layer. using lowest_layer_type = @@ -113,42 +104,42 @@ public: typename protocol_type::resolver; /// Move constructor. - socket(socket&&) = default; + stream(stream&&) = default; /** Move assignment. Undefined behavior if operations are active or pending. */ - socket& operator=(socket&&) = default; + stream& operator=(stream&&) = default; - /** Construct a websocket. + /** Construct a WebSocket stream. - This constructor creates a websocket and initialises the - underlying stream object. + This constructor creates a websocket stream and initialises + the next layer object. - @throws Any exceptions thrown by the Stream constructor. + @throws Any exceptions thrown by the NextLayer constructor. @param args The arguments to be passed to initialise the - underlying stream object. The arguments are forwarded - to the stream's constructor. + next layer object. The arguments are forwarded to the next + layer's constructor. */ template explicit - socket(Args&&... args); + stream(Args&&... args); /** Destructor. A stream object must not be destroyed while there are pending asynchronous operations associated with it. */ - ~socket() = default; + ~stream() = default; - /** Set options on the socket. + /** Set options on the stream. The application must ensure that calls to set options are performed within the same implicit or explicit strand. - @param args One or more socket options to set. + @param args One or more stream options to set. */ #if GENERATING_DOCS template @@ -212,13 +203,13 @@ public: stream_.reserve(o.value); } - /** Get the io_service associated with the socket. + /** Get the io_service associated with the stream. This function may be used to obtain the io_service object - that the socket uses to dispatch handlers for asynchronous + that the stream uses to dispatch handlers for asynchronous operations. - @return A reference to the io_service object that the socket + @return A reference to the io_service object that the stream will use to dispatch handlers. Ownership is not transferred to the caller. */ @@ -300,7 +291,7 @@ public: Upgrade request and send the HTTP response. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -310,7 +301,7 @@ public: The call blocks until one of the following conditions is true: - @li An error occurs on the socket. + @li An error occurs on the stream. @li The entire HTTP response has been sent. @@ -330,7 +321,7 @@ public: Upgrade request and send the HTTP response. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -339,7 +330,7 @@ public: The call blocks until one of the following conditions is true: - @li An error occurs on the socket. + @li An error occurs on the stream. @li The entire HTTP response has been sent. @@ -355,7 +346,7 @@ public: always returns immediately. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -383,7 +374,7 @@ public: Upgrade request and send the HTTP response. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -392,13 +383,13 @@ public: The call blocks until one of the following conditions is true: - @li An error occurs on the socket. + @li An error occurs on the stream. @li The entire HTTP response has been sent. @param buffers Caller provide data that has already been - received on the socket. This may be used for implementations - allowing multiple protocols on the same socket. The + received on the stream. This may be used for implementations + allowing multiple protocols on the same stream. The buffered data will first be applied to the handshake, and then to received WebSocket frames. The implementation will copy the caller provided data before the function returns. @@ -415,7 +406,7 @@ public: Upgrade request and send the HTTP response. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -424,13 +415,13 @@ public: The call blocks until one of the following conditions is true: - @li An error occurs on the socket. + @li An error occurs on the stream. @li The entire HTTP response has been sent. @param buffers Caller provide data that has already been - received on the socket. This may be used for implementations - allowing multiple protocols on the same socket. The + received on the stream. This may be used for implementations + allowing multiple protocols on the same stream. The buffered data will first be applied to the handshake, and then to received WebSocket frames. The implementation will copy the caller provided data before the function returns. @@ -448,7 +439,7 @@ public: always returns immediately. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -456,8 +447,8 @@ public: code (typically 400, "Bad Request"). @param buffers Caller provide data that has already been - received on the socket. This may be used for implementations - allowing multiple protocols on the same socket. The + received on the stream. This may be used for implementations + allowing multiple protocols on the same stream. The buffered data will first be applied to the handshake, and then to received WebSocket frames. The implementation will copy the caller provided data before the function returns. @@ -484,7 +475,7 @@ public: to a HTTP WebSocket Upgrade request. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -493,7 +484,7 @@ public: The call blocks until one of the following conditions is true: - @li An error occurs on the socket. + @li An error occurs on the stream. @li The entire HTTP response has been sent. @@ -515,7 +506,7 @@ public: to a HTTP WebSocket Upgrade request. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -524,7 +515,7 @@ public: The call blocks until one of the following conditions is true: - @li An error occurs on the socket. + @li An error occurs on the stream. @li The entire HTTP response has been sent. @@ -546,7 +537,7 @@ public: always returns immediately. If the contents of the request are valid, the HTTP response - indicates a successful upgrade and the socket is then ready + indicates a successful upgrade and the stream is then ready to send and receive WebSocket protocol frames and messages. If the WebSocket HTTP Upgrade request cannot be satisfied, @@ -579,7 +570,7 @@ public: upgrade HTTP request. The call blocks until one of the following conditions is true: - @li An error occurs on the socket + @li An error occurs on the stream @li A complete HTTP response with the result of the upgrade request is received. @@ -594,7 +585,7 @@ public: @par Example @code - wsproto::socket ws(io_service); + websocket::stream ws(io_service); ... try { @@ -621,7 +612,7 @@ public: upgrade HTTP request. The call blocks until one of the following conditions is true: - @li An error occurs on the socket + @li An error occurs on the stream. @li A complete HTTP response with the result of the upgrade request is received. @@ -636,7 +627,7 @@ public: @par Example @code - wsproto::socket ws(io_service); + websocket::stream ws(io_service); ... error_code ec; ws.upgrade(host, resource, ec); @@ -975,7 +966,7 @@ public: @throws boost::system::system_error Thrown on failure. @note This function always sends an entire message. To - send a message in fragments, use `socket::write`. + send a message in fragments, use `write_frame`. */ template void @@ -1010,7 +1001,7 @@ public: until the completion handler is called. @note This function always sends an entire message. To - send a message in fragments, use `socket::write`. + send a message in fragments, use `write_frame`. */ template void @@ -1182,9 +1173,9 @@ private: close_code& code, error_code& ec); }; -} // wsproto +} // websocket } // beast -#include +#include #endif diff --git a/beast/wsproto/teardown.h b/include/beast/websocket/teardown.hpp similarity index 93% rename from beast/wsproto/teardown.h rename to include/beast/websocket/teardown.hpp index f184f9e63f..2bbc6e2437 100644 --- a/beast/wsproto/teardown.h +++ b/include/beast/websocket/teardown.hpp @@ -17,15 +17,15 @@ */ //============================================================================== -#ifndef BEAST_WSPROTO_TEARDOWN_H_INCLUDED -#define BEAST_WSPROTO_TEARDOWN_H_INCLUDED +#ifndef BEAST_WEBSOCKET_TEARDOWN_HPP +#define BEAST_WEBSOCKET_TEARDOWN_HPP -#include +#include #include #include namespace beast { -namespace wsproto { +namespace websocket { /** Tear down a connection. @@ -122,7 +122,7 @@ async_teardown( boost::asio::ip::tcp::socket& socket, TeardownHandler&& handler); -} // wsproto +} // websocket //------------------------------------------------------------------------------ @@ -136,9 +136,9 @@ namespace wsproto_helpers { template inline void -call_teardown(Socket& socket, wsproto::error_code& ec) +call_teardown(Socket& socket, websocket::error_code& ec) { - using wsproto::teardown; + using websocket::teardown; teardown(socket, ec); } @@ -147,15 +147,15 @@ inline void call_async_teardown(Socket& socket, TeardownHandler&& handler) { - using wsproto::async_teardown; + using websocket::async_teardown; async_teardown(socket, std::forward(handler)); } -} // wsproto_helpers +} // websocket_helpers } // beast -#include +#include #endif diff --git a/site_scons/Beast.py b/site_scons/Beast.py deleted file mode 100644 index 5b2fe849a4..0000000000 --- a/site_scons/Beast.py +++ /dev/null @@ -1,188 +0,0 @@ -# Beast.py -# Copyright 2014 by: -# Vinnie Falco -# Tom Ritchford -# Nik Bougalis -# This file is part of Beast: http://github.com/vinniefalco/Beast - -from __future__ import absolute_import, division, print_function, unicode_literals - -import os -import platform -import subprocess -import sys -import SCons.Node -import SCons.Util - -#------------------------------------------------------------------------------- -# -# Environment -# -#------------------------------------------------------------------------------- - -def _execute(args, include_errors=True, **kwds): - """Execute a shell command and return the value. If args is a string, - it's split on spaces - if some of your arguments contain spaces, args should - instead be a list of arguments.""" - def single_line(line, report_errors=True, joiner='+'): - """Force a string to be a single line with no carriage returns, and report - a warning if there was more than one line.""" - lines = line.strip().splitlines() - if report_errors and len(lines) > 1: - print('multiline result:', lines) - return joiner.join(lines) - def is_string(s): - """Is s a string? - in either Python 2.x or 3.x.""" - return isinstance(s, (str, unicode)) - if is_string(args): - args = args.split() - stderr = subprocess.STDOUT if include_errors else None - return single_line(subprocess.check_output(args, stderr=stderr, **kwds)) - -class __System(object): - """Provides information about the host platform""" - def __init__(self): - self.name = platform.system() - self.linux = self.name == 'Linux' - self.osx = self.name == 'Darwin' - self.windows = self.name == 'Windows' - self.distro = None - self.version = None - - # True if building under the Travis CI (http://travis-ci.org) - self.travis = ( - os.environ.get('TRAVIS', '0') == 'true') and ( - os.environ.get('CI', '0') == 'true') - - if self.linux: - self.distro, self.version, _ = platform.linux_distribution() - self.__display = '%s %s (%s)' % (self.distro, self.version, self.name) - - elif self.osx: - parts = platform.mac_ver()[0].split('.') - while len(parts) < 3: - parts.append('0') - self.__display = '%s %s' % (self.name, '.'.join(parts)) - elif self.windows: - release, version, csd, ptype = platform.win32_ver() - self.__display = '%s %s %s (%s)' % (self.name, release, version, ptype) - - else: - raise Exception('Unknown system platform "' + self.name + '"') - - self.platform = self.distro or self.name - - def __str__(self): - return self.__display - -class Git(object): - """Provides information about git and the repository we are called from""" - def __init__(self, env): - self.tags = self.branch = self.user = '' - self.exists = env.Detect('git') - if self.exists: - try: - self.tags = _execute('git describe --tags') - self.branch = _execute('git rev-parse --abbrev-ref HEAD') - remote = _execute('git config remote.origin.url') - self.user = remote.split(':')[1].split('/')[0] - except: - self.exists = False - -system = __System() - -#------------------------------------------------------------------------------- - -def printChildren(target): - def doPrint(tgt, level, found): - for item in tgt: - if SCons.Util.is_List(item): - doPrint(item, level, found) - else: - if item.abspath in found: - continue - found[item.abspath] = False - print('\t'*level + item.path) - #DoPrint(item.children(scan=1), level+1, found) - item.scan() - doPrint(item.all_children(), level+1, found) - doPrint(target, 0, {}) - -def variantFile(path, variant_dirs): - '''Returns the path to the corresponding dict entry in variant_dirs''' - path = str(path) - for dest, source in variant_dirs.iteritems(): - common = os.path.commonprefix([path, source]) - if common == source: - return os.path.join(dest, path[len(common)+1:]) - return path - -def variantFiles(files, variant_dirs): - '''Returns a list of files remapped to their variant directories''' - result = [] - for path in files: - result.append(variantFile(path, variant_dirs)) - return result - -def printEnv(env, keys): - if type(keys) != list: - keys = list(keys) - s = '' - for key in keys: - if key in env: - value = env[key] - else: - value = '' - s+=('%s=%s, ' % (key, value)) - print('[' + s + ']') - -#------------------------------------------------------------------------------- -# -# Output -# -#------------------------------------------------------------------------------- - -# See https://stackoverflow.com/questions/7445658/how-to-detect-if-the-console-does-support-ansi-escape-codes-in-python -CAN_CHANGE_COLOR = ( - hasattr(sys.stderr, "isatty") - and sys.stderr.isatty() - and not system.windows - and not os.environ.get('INSIDE_EMACS') - ) - -# See https://en.wikipedia.org/wiki/ANSI_escape_code -BLUE = 94 -GREEN = 92 -RED = 91 -YELLOW = 93 - -def add_mode(text, *modes): - if CAN_CHANGE_COLOR: - modes = ';'.join(str(m) for m in modes) - return '\033[%sm%s\033[0m' % (modes, text) - else: - return text - -def blue(text): - return add_mode(text, BLUE) - -def green(text): - return add_mode(text, GREEN) - -def red(text): - return add_mode(text, RED) - -def yellow(text): - return add_mode(text, YELLOW) - -def warn(text, print=print): - print('%s %s' % (red('WARNING:'), text)) - -# Prints command lines using environment substitutions -def print_coms(coms, env): - if type(coms) is str: - coms=list(coms) - for key in coms: - cmdline = env.subst(env[key], 0, - env.File(''), env.File('')) - print (green(cmdline)) diff --git a/site_scons/site_tools/Protoc.py b/site_scons/site_tools/Protoc.py deleted file mode 100644 index 32d77f3a4c..0000000000 --- a/site_scons/site_tools/Protoc.py +++ /dev/null @@ -1,97 +0,0 @@ -# -# Copyright (c) 2009 Scott Stafford -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be included -# in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY -# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# - -# Author : Scott Stafford -# Date : 2009-12-09 20:36:14 -# -# Changes : Vinnie Falco -# Date : 2014--4-25 - -""" -Protoc.py: Protoc Builder for SCons - -This Builder invokes protoc to generate C++ and Python from a .proto file. - -NOTE: Java is not currently supported. -""" - -__author__ = "Scott Stafford" - -import SCons.Action -import SCons.Builder -import SCons.Defaults -import SCons.Node.FS -import SCons.Util - -from SCons.Script import File, Dir - -import os.path - -protocs = 'protoc' - -ProtocAction = SCons.Action.Action('$PROTOCCOM', '$PROTOCCOMSTR') - -def ProtocEmitter(target, source, env): - PROTOCOUTDIR = env['PROTOCOUTDIR'] - PROTOCPYTHONOUTDIR = env['PROTOCPYTHONOUTDIR'] - for source_path in [str(x) for x in source]: - base = os.path.splitext(os.path.basename(source_path))[0] - if PROTOCOUTDIR: - target.extend([os.path.join(PROTOCOUTDIR, base + '.pb.cc'), - os.path.join(PROTOCOUTDIR, base + '.pb.h')]) - if PROTOCPYTHONOUTDIR: - target.append(os.path.join(PROTOCPYTHONOUTDIR, base + '_pb2.py')) - - try: - target.append(env['PROTOCFDSOUT']) - except KeyError: - pass - - #print "PROTOC SOURCE:", [str(s) for s in source] - #print "PROTOC TARGET:", [str(s) for s in target] - - return target, source - -ProtocBuilder = SCons.Builder.Builder( - action = ProtocAction, - emitter = ProtocEmitter, - srcsuffix = '$PROTOCSRCSUFFIX') - -def generate(env): - """Add Builders and construction variables for protoc to an Environment.""" - try: - bld = env['BUILDERS']['Protoc'] - except KeyError: - bld = ProtocBuilder - env['BUILDERS']['Protoc'] = bld - - env['PROTOC'] = env.Detect(protocs) or 'protoc' - env['PROTOCFLAGS'] = SCons.Util.CLVar('') - env['PROTOCPROTOPATH'] = SCons.Util.CLVar('') - env['PROTOCCOM'] = '$PROTOC ${["-I%s"%x for x in PROTOCPROTOPATH]} $PROTOCFLAGS --cpp_out=$PROTOCCPPOUTFLAGS$PROTOCOUTDIR ${PROTOCPYTHONOUTDIR and ("--python_out="+PROTOCPYTHONOUTDIR) or ""} ${PROTOCFDSOUT and ("-o"+PROTOCFDSOUT) or ""} ${SOURCES}' - env['PROTOCOUTDIR'] = '${SOURCE.dir}' - env['PROTOCPYTHONOUTDIR'] = "python" - env['PROTOCSRCSUFFIX'] = '.proto' - -def exists(env): - return env.Detect(protocs) \ No newline at end of file diff --git a/site_scons/site_tools/VSProject.py b/site_scons/site_tools/VSProject.py deleted file mode 100644 index 6a8ebe2e6d..0000000000 --- a/site_scons/site_tools/VSProject.py +++ /dev/null @@ -1,894 +0,0 @@ -# Copyright 2014 Vinnie Falco (vinnie.falco@gmail.com) -# Portions Copyright The SCons Foundation -# Portions Copyright Google, Inc. -# This file is part of beast - -""" -A SCons tool to provide a family of scons builders that -generate Visual Studio project files -""" - -import collections -import hashlib -import io -import itertools -import ntpath -import os -import pprint -import random -import re - -import SCons.Builder -import SCons.Node.FS -import SCons.Node -import SCons.Script.Main -import SCons.Util - -#------------------------------------------------------------------------------- - -# Adapted from msvs.py - -UnicodeByteMarker = '\xEF\xBB\xBF' - -V14DSPHeader = """\ -\r -\r -""" - -V14DSPProjectConfiguration = """\ - \r - %(variant)s\r - %(platform)s\r - \r -""" - -V14DSPGlobals = """\ - \r - %(project_guid)s\r - Win32Proj\r - %(name)s\r - true\r - \r -""" - -V14DSPPropertyGroup = """\ - \r - MultiByte\r - Application\r - v140\r - False\r - %(use_debug_libs)s\r - False\r - false\r - %(int_dir)s\r - %(out_dir)s\r - \r -""" - -V14DSPImportGroup= """\ - \r - \r - \r -""" - -V14DSPItemDefinitionGroup= """\ - \r -""" - -V14CustomBuildProtoc= """\ - Document\r - protoc --cpp_out=%(cpp_out)s --proto_path=%%(RelativeDir) %%(Identity)\r - %(base_out)s.pb.h;%(base_out)s.pb.cc\r - protoc --cpp_out=%(cpp_out)s --proto_path=%%(RelativeDir) %%(Identity)\r - false\r -""" - -V14DSPFiltersHeader = ( -'''\r -\r -''') - -#------------------------------------------------------------------------------- - -def is_subdir(child, parent): - '''Determine if child is a subdirectory of parent''' - return os.path.commonprefix([parent, child]) == parent - -def _key(item): - if isinstance(item, (str, unicode)): - return ('s', item.upper(), item) - elif isinstance(item, (int, long, float)): - return ('n', item) - elif isinstance(item, (list, tuple)): - return ('l', map(_key, item)) - elif isinstance(item, dict): - return ('d', xsorted(item.keys()), xsorted(item.values())) - elif isinstance(item, Configuration): - return ('c', _key(item.name), _key(item.target), _key(item.variant), _key(item.platform)) - elif isinstance(item, Item): - return ('i', _key(winpath(item.path())), _key(item.is_compiled()), _key(item.builder()), _key(item.tag()), _key(item.is_excluded())) - elif isinstance(item, SCons.Node.FS.File): - return ('f', _key(item.name), _key(item.suffix)) - else: - return ('x', item) - -def xsorted(tosort, **kwargs): - '''Performs sorted in a deterministic manner.''' - if 'key' in kwargs: - map(kwargs['key'], tosort) - kwargs['key'] = _key - return sorted(tosort, **kwargs) - -def itemList(items, sep): - if type(items) == str: # Won't work in Python 3. - return items - def gen(): - for item in xsorted(items): - if isinstance(item, dict): - for k, v in xsorted(item.items()): - yield k + '=' + v - elif isinstance(item, (tuple, list)): - assert len(item) == 2, "Item shoud have exactly two elements: " + str(item) - yield '%s=%s' % tuple(item) - else: - yield item - yield sep - return ''.join(gen()) - -#------------------------------------------------------------------------------- - -class SwitchConverter(object): - '''Converts command line switches to MSBuild XML, using tables''' - - def __init__(self, table, booltable, retable=None): - self.table = {} - for key in table: - self.table[key] = table[key] - for key in booltable: - value = booltable[key] - self.table[key] = [value[0], 'True'] - self.table[key + '-'] = [value[0], 'False'] - if retable != None: - self.retable = retable - else: - self.retable = [] - - def getXml(self, switches, prefix = ''): - switches = list(set(switches)) # Filter dupes because on windows platforms, /nologo is added automatically to the environment. - xml = [] - for regex, tag in self.retable: - matches = [] - for switch in switches[:]: - match = regex.match(switch) - if None != match: - matches.append(match.group(1)) - switches.remove(switch) - if len(matches) > 0: - xml.append ( - '%s<%s>%s\r\n' % ( - prefix, tag, ';'.join(matches), tag)) - unknown = [] - for switch in switches: - try: - value = self.table[switch] - xml.append ( - '%s<%s>%s\r\n' % ( - prefix, value[0], value[1], value[0])) - except: - unknown.append(switch) - if unknown: - s = itemList(unknown, ' ') - tag = 'AdditionalOptions' - xml.append('%(prefix)s<%(tag)s>%(s)s%%(%(tag)s)\r\n' % locals()) - if xml: - return ''.join(xml) - return '' - -class ClSwitchConverter(SwitchConverter): - def __init__(self): - booltable = { - '/C' : ['KeepComments'], - '/doc' : ['GenerateXMLDocumentationFiles'], - '/FAu' : ['UseUnicodeForAssemblerListing'], - '/FC' : ['UseFullPaths'], - '/FR' : ['BrowseInformation'], - '/Fr' : ['BrowseInformation'], - '/Fx' : ['ExpandAttributedSource'], - '/GF' : ['StringPooling'], - '/GL' : ['WholeProgramOptimization'], - '/Gm' : ['MinimalRebuild'], - '/GR' : ['RuntimeTypeInfo'], - '/GS' : ['BufferSecurityCheck'], - '/GT' : ['EnableFiberSafeOptimizations'], - '/Gy' : ['FunctionLevelLinking'], - '/MP' : ['MultiProcessorCompilation'], - '/Oi' : ['IntrinsicFunctions'], - '/Oy' : ['OmitFramePointers'], - '/RTCc' : ['SmallerTypeCheck'], - '/u' : ['UndefineAllPreprocessorDefinitions'], - '/X' : ['IgnoreStandardIncludePath'], - '/WX' : ['TreatWarningAsError'], - '/Za' : ['DisableLanguageExtensions'], - '/Zl' : ['OmitDefaultLibName'], - '/fp:except' : ['FloatingPointExceptions'], - '/hotpatch' : ['CreateHotpatchableImage'], - '/nologo' : ['SuppressStartupBanner'], - '/openmp' : ['OpenMPSupport'], - '/showIncludes' : ['ShowIncludes'], - '/Zc:forScope' : ['ForceConformanceInForLoopScope'], - '/Zc:wchar_t' : ['TreatWChar_tAsBuiltInType'], - } - table = { - '/EHsc' : ['ExceptionHandling', 'Sync'], - '/EHa' : ['ExceptionHandling', 'Async'], - '/EHs' : ['ExceptionHandling', 'SyncCThrow'], - '/FA' : ['AssemblerOutput', 'AssemblyCode'], - '/FAcs' : ['AssemblerOutput', 'All'], - '/FAc' : ['AssemblerOutput', 'AssemblyAndMachineCode'], - '/FAs' : ['AssemblerOutput', 'AssemblyAndSourceCode'], - '/Gd' : ['CallingConvention', 'Cdecl'], - '/Gr' : ['CallingConvention', 'FastCall'], - '/Gz' : ['CallingConvention', 'StdCall'], - '/MT' : ['RuntimeLibrary', 'MultiThreaded'], - '/MTd' : ['RuntimeLibrary', 'MultiThreadedDebug'], - '/MD' : ['RuntimeLibrary', 'MultiThreadedDLL'], - '/MDd' : ['RuntimeLibrary', 'MultiThreadedDebugDLL'], - '/Od' : ['Optimization', 'Disabled'], - '/O1' : ['Optimization', 'MinSpace'], - '/O2' : ['Optimization', 'MaxSpeed'], - '/Ox' : ['Optimization', 'Full'], - '/Ob1' : ['InlineFunctionExpansion', 'OnlyExplicitInline'], - '/Ob2' : ['InlineFunctionExpansion', 'AnySuitable'], - '/Ot' : ['FavorSizeOrSpeed', 'Speed'], - '/Os' : ['FavorSizeOrSpeed', 'Size'], - '/RTCs' : ['BasicRuntimeChecks', 'StackFrameRuntimeCheck'], - '/RTCu' : ['BasicRuntimeChecks', 'UninitializedLocalUsageCheck'], - '/RTC1' : ['BasicRuntimeChecks', 'EnableFastChecks'], - '/TC' : ['CompileAs', 'CompileAsC'], - '/TP' : ['CompileAs', 'CompileAsCpp'], - '/W0' : [ 'WarningLevel', 'TurnOffAllWarnings'], - '/W1' : [ 'WarningLevel', 'Level1'], - '/W2' : [ 'WarningLevel', 'Level2'], - '/W3' : [ 'WarningLevel', 'Level3'], - '/W4' : [ 'WarningLevel', 'Level4'], - '/Wall' : [ 'WarningLevel', 'EnableAllWarnings'], - '/Yc' : ['PrecompiledHeader', 'Create'], - '/Yu' : ['PrecompiledHeader', 'Use'], - '/Z7' : ['DebugInformationFormat', 'OldStyle'], - '/Zi' : ['DebugInformationFormat', 'ProgramDatabase'], - '/ZI' : ['DebugInformationFormat', 'EditAndContinue'], - '/Zp1' : ['StructMemberAlignment', '1Byte'], - '/Zp2' : ['StructMemberAlignment', '2Bytes'], - '/Zp4' : ['StructMemberAlignment', '4Bytes'], - '/Zp8' : ['StructMemberAlignment', '8Bytes'], - '/Zp16' : ['StructMemberAlignment', '16Bytes'], - '/arch:IA32' : ['EnableEnhancedInstructionSet', 'NoExtensions'], - '/arch:SSE' : ['EnableEnhancedInstructionSet', 'StreamingSIMDExtensions'], - '/arch:SSE2' : ['EnableEnhancedInstructionSet', 'StreamingSIMDExtensions2'], - '/arch:AVX' : ['EnableEnhancedInstructionSet', 'AdvancedVectorExtensions'], - '/clr' : ['CompileAsManaged', 'True'], - '/clr:pure' : ['CompileAsManaged', 'Pure'], - '/clr:safe' : ['CompileAsManaged', 'Safe'], - '/clr:oldSyntax' : ['CompileAsManaged', 'OldSyntax'], - '/fp:fast' : ['FloatingPointModel', 'Fast'], - '/fp:precise' : ['FloatingPointModel', 'Precise'], - '/fp:strict' : ['FloatingPointModel', 'Strict'], - '/errorReport:none' : ['ErrorReporting', 'None'], - '/errorReport:prompt' : ['ErrorReporting', 'Prompt'], - '/errorReport:queue' : ['ErrorReporting', 'Queue'], - '/errorReport:send' : ['ErrorReporting', 'Send'], - } - retable = [ - (re.compile(r'/wd\"(\d+)\"'), 'DisableSpecificWarnings'), - ] - # Ideas from Google's Generate Your Project - ''' - _Same(_compile, 'AdditionalIncludeDirectories', _folder_list) # /I - - _Same(_compile, 'PreprocessorDefinitions', _string_list) # /D - _Same(_compile, 'ProgramDataBaseFileName', _file_name) # /Fd - - _Same(_compile, 'AdditionalOptions', _string_list) - _Same(_compile, 'AdditionalUsingDirectories', _folder_list) # /AI - _Same(_compile, 'AssemblerListingLocation', _file_name) # /Fa - _Same(_compile, 'BrowseInformationFile', _file_name) - _Same(_compile, 'ForcedIncludeFiles', _file_list) # /FI - _Same(_compile, 'ForcedUsingFiles', _file_list) # /FU - _Same(_compile, 'UndefinePreprocessorDefinitions', _string_list) # /U - _Same(_compile, 'XMLDocumentationFileName', _file_name) - '' : ['EnablePREfast', _boolean) # /analyze Visible='false' - _Renamed(_compile, 'ObjectFile', 'ObjectFileName', _file_name) # /Fo - _Renamed(_compile, 'PrecompiledHeaderThrough', 'PrecompiledHeaderFile', - _file_name) # Used with /Yc and /Yu - _Renamed(_compile, 'PrecompiledHeaderFile', 'PrecompiledHeaderOutputFile', - _file_name) # /Fp - _ConvertedToAdditionalOption(_compile, 'DefaultCharIsUnsigned', '/J') - _MSBuildOnly(_compile, 'ProcessorNumber', _integer) # the number of processors - _MSBuildOnly(_compile, 'TrackerLogDirectory', _folder_name) - _MSBuildOnly(_compile, 'TreatSpecificWarningsAsErrors', _string_list) # /we - _MSBuildOnly(_compile, 'PreprocessOutputPath', _string) # /Fi - ''' - SwitchConverter.__init__(self, table, booltable, retable) - -class LinkSwitchConverter(SwitchConverter): - def __init__(self): - # Based on code in Generate Your Project - booltable = { - '/DEBUG' : ['GenerateDebugInformation'], - '/DYNAMICBASE' : ['RandomizedBaseAddress'], - '/NOLOGO' : ['SuppressStartupBanner'], - '/nologo' : ['SuppressStartupBanner'], - } - table = { - '/ERRORREPORT:NONE' : ['ErrorReporting', 'NoErrorReport'], - '/ERRORREPORT:PROMPT' : ['ErrorReporting', 'PromptImmediately'], - '/ERRORREPORT:QUEUE' : ['ErrorReporting', 'QueueForNextLogin'], - '/ERRORREPORT:SEND' : ['ErrorReporting', 'SendErrorReport'], - '/MACHINE:X86' : ['TargetMachine', 'MachineX86'], - '/MACHINE:ARM' : ['TargetMachine', 'MachineARM'], - '/MACHINE:EBC' : ['TargetMachine', 'MachineEBC'], - '/MACHINE:IA64' : ['TargetMachine', 'MachineIA64'], - '/MACHINE:MIPS' : ['TargetMachine', 'MachineMIPS'], - '/MACHINE:MIPS16' : ['TargetMachine', 'MachineMIPS16'], - '/MACHINE:MIPSFPU' : ['TargetMachine', 'MachineMIPSFPU'], - '/MACHINE:MIPSFPU16' : ['TargetMachine', 'MachineMIPSFPU16'], - '/MACHINE:SH4' : ['TargetMachine', 'MachineSH4'], - '/MACHINE:THUMB' : ['TargetMachine', 'MachineTHUMB'], - '/MACHINE:X64' : ['TargetMachine', 'MachineX64'], - '/NXCOMPAT' : ['DataExecutionPrevention', 'true'], - '/NXCOMPAT:NO' : ['DataExecutionPrevention', 'false'], - '/SUBSYSTEM:CONSOLE' : ['SubSystem', 'Console'], - '/SUBSYSTEM:WINDOWS' : ['SubSystem', 'Windows'], - '/SUBSYSTEM:NATIVE' : ['SubSystem', 'Native'], - '/SUBSYSTEM:EFI_APPLICATION' : ['SubSystem', 'EFI Application'], - '/SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER' : ['SubSystem', 'EFI Boot Service Driver'], - '/SUBSYSTEM:EFI_ROM' : ['SubSystem', 'EFI ROM'], - '/SUBSYSTEM:EFI_RUNTIME_DRIVER' : ['SubSystem', 'EFI Runtime'], - '/SUBSYSTEM:WINDOWSCE' : ['SubSystem', 'WindowsCE'], - '/SUBSYSTEM:POSIX' : ['SubSystem', 'POSIX'], - } - ''' - /TLBID:1 /MANIFEST /MANIFESTUAC:level='asInvoker' uiAccess='false' - - _Same(_link, 'AllowIsolation', _boolean) # /ALLOWISOLATION - _Same(_link, 'CLRUnmanagedCodeCheck', _boolean) # /CLRUNMANAGEDCODECHECK - _Same(_link, 'DelaySign', _boolean) # /DELAYSIGN - _Same(_link, 'EnableUAC', _boolean) # /MANIFESTUAC - _Same(_link, 'GenerateMapFile', _boolean) # /MAP - _Same(_link, 'IgnoreAllDefaultLibraries', _boolean) # /NODEFAULTLIB - _Same(_link, 'IgnoreEmbeddedIDL', _boolean) # /IGNOREIDL - _Same(_link, 'MapExports', _boolean) # /MAPINFO:EXPORTS - _Same(_link, 'StripPrivateSymbols', _file_name) # /PDBSTRIPPED - _Same(_link, 'PerUserRedirection', _boolean) - _Same(_link, 'Profile', _boolean) # /PROFILE - _Same(_link, 'RegisterOutput', _boolean) - _Same(_link, 'SetChecksum', _boolean) # /RELEASE - _Same(_link, 'SupportUnloadOfDelayLoadedDLL', _boolean) # /DELAY:UNLOAD - - _Same(_link, 'SwapRunFromCD', _boolean) # /SWAPRUN:CD - _Same(_link, 'TurnOffAssemblyGeneration', _boolean) # /NOASSEMBLY - _Same(_link, 'UACUIAccess', _boolean) # /uiAccess='true' - _Same(_link, 'EnableCOMDATFolding', _newly_boolean) # /OPT:ICF - _Same(_link, 'FixedBaseAddress', _newly_boolean) # /FIXED - _Same(_link, 'LargeAddressAware', _newly_boolean) # /LARGEADDRESSAWARE - _Same(_link, 'OptimizeReferences', _newly_boolean) # /OPT:REF - _Same(_link, 'TerminalServerAware', _newly_boolean) # /TSAWARE - - _Same(_link, 'AdditionalDependencies', _file_list) - _Same(_link, 'AdditionalLibraryDirectories', _folder_list) # /LIBPATH - _Same(_link, 'AdditionalManifestDependencies', _file_list) # /MANIFESTDEPENDENCY: - _Same(_link, 'AdditionalOptions', _string_list) - _Same(_link, 'AddModuleNamesToAssembly', _file_list) # /ASSEMBLYMODULE - _Same(_link, 'AssemblyLinkResource', _file_list) # /ASSEMBLYLINKRESOURCE - _Same(_link, 'BaseAddress', _string) # /BASE - _Same(_link, 'DelayLoadDLLs', _file_list) # /DELAYLOAD - _Same(_link, 'EmbedManagedResourceFile', _file_list) # /ASSEMBLYRESOURCE - _Same(_link, 'EntryPointSymbol', _string) # /ENTRY - _Same(_link, 'ForceSymbolReferences', _file_list) # /INCLUDE - _Same(_link, 'FunctionOrder', _file_name) # /ORDER - _Same(_link, 'HeapCommitSize', _string) - _Same(_link, 'HeapReserveSize', _string) # /HEAP - _Same(_link, 'ImportLibrary', _file_name) # /IMPLIB - _Same(_link, 'KeyContainer', _file_name) # /KEYCONTAINER - _Same(_link, 'KeyFile', _file_name) # /KEYFILE - _Same(_link, 'ManifestFile', _file_name) # /ManifestFile - _Same(_link, 'MapFileName', _file_name) - _Same(_link, 'MergedIDLBaseFileName', _file_name) # /IDLOUT - _Same(_link, 'MergeSections', _string) # /MERGE - _Same(_link, 'MidlCommandFile', _file_name) # /MIDL - _Same(_link, 'ModuleDefinitionFile', _file_name) # /DEF - _Same(_link, 'OutputFile', _file_name) # /OUT - _Same(_link, 'ProfileGuidedDatabase', _file_name) # /PGD - _Same(_link, 'ProgramDatabaseFile', _file_name) # /PDB - _Same(_link, 'StackCommitSize', _string) - _Same(_link, 'StackReserveSize', _string) # /STACK - _Same(_link, 'TypeLibraryFile', _file_name) # /TLBOUT - _Same(_link, 'TypeLibraryResourceID', _integer) # /TLBID - _Same(_link, 'Version', _string) # /VERSION - - - _Same(_link, 'AssemblyDebug', - _Enumeration(['', - 'true', # /ASSEMBLYDEBUG - 'false'])) # /ASSEMBLYDEBUG:DISABLE - _Same(_link, 'CLRImageType', - _Enumeration(['Default', - 'ForceIJWImage', # /CLRIMAGETYPE:IJW - 'ForcePureILImage', # /Switch="CLRIMAGETYPE:PURE - 'ForceSafeILImage'])) # /Switch="CLRIMAGETYPE:SAFE - _Same(_link, 'CLRThreadAttribute', - _Enumeration(['DefaultThreadingAttribute', # /CLRTHREADATTRIBUTE:NONE - 'MTAThreadingAttribute', # /CLRTHREADATTRIBUTE:MTA - 'STAThreadingAttribute'])) # /CLRTHREADATTRIBUTE:STA - _Same(_link, 'Driver', - _Enumeration(['NotSet', - 'Driver', # /Driver - 'UpOnly', # /DRIVER:UPONLY - 'WDM'])) # /DRIVER:WDM - _Same(_link, 'LinkTimeCodeGeneration', - _Enumeration(['Default', - 'UseLinkTimeCodeGeneration', # /LTCG - 'PGInstrument', # /LTCG:PGInstrument - 'PGOptimization', # /LTCG:PGOptimize - 'PGUpdate'])) # /LTCG:PGUpdate - _Same(_link, 'ShowProgress', - _Enumeration(['NotSet', - 'LinkVerbose', # /VERBOSE - 'LinkVerboseLib'], # /VERBOSE:Lib - new=['LinkVerboseICF', # /VERBOSE:ICF - 'LinkVerboseREF', # /VERBOSE:REF - 'LinkVerboseSAFESEH', # /VERBOSE:SAFESEH - 'LinkVerboseCLR'])) # /VERBOSE:CLR - _Same(_link, 'UACExecutionLevel', - _Enumeration(['AsInvoker', # /level='asInvoker' - 'HighestAvailable', # /level='highestAvailable' - 'RequireAdministrator'])) # /level='requireAdministrator' - _Same(_link, 'MinimumRequiredVersion', _string) - _Same(_link, 'TreatLinkerWarningAsErrors', _boolean) # /WX - - - # Options found in MSVS that have been renamed in MSBuild. - _Renamed(_link, 'IgnoreDefaultLibraryNames', 'IgnoreSpecificDefaultLibraries', - _file_list) # /NODEFAULTLIB - _Renamed(_link, 'ResourceOnlyDLL', 'NoEntryPoint', _boolean) # /NOENTRY - _Renamed(_link, 'SwapRunFromNet', 'SwapRunFromNET', _boolean) # /SWAPRUN:NET - - _Moved(_link, 'GenerateManifest', '', _boolean) - _Moved(_link, 'IgnoreImportLibrary', '', _boolean) - _Moved(_link, 'LinkIncremental', '', _newly_boolean) - _Moved(_link, 'LinkLibraryDependencies', 'ProjectReference', _boolean) - _Moved(_link, 'UseLibraryDependencyInputs', 'ProjectReference', _boolean) - - # MSVS options not found in MSBuild. - _MSVSOnly(_link, 'OptimizeForWindows98', _newly_boolean) - _MSVSOnly(_link, 'UseUnicodeResponseFiles', _boolean) - - # MSBuild options not found in MSVS. - _MSBuildOnly(_link, 'BuildingInIDE', _boolean) - _MSBuildOnly(_link, 'ImageHasSafeExceptionHandlers', _boolean) # /SAFESEH - _MSBuildOnly(_link, 'LinkDLL', _boolean) # /DLL Visible='false' - _MSBuildOnly(_link, 'LinkStatus', _boolean) # /LTCG:STATUS - _MSBuildOnly(_link, 'PreventDllBinding', _boolean) # /ALLOWBIND - _MSBuildOnly(_link, 'SupportNobindOfDelayLoadedDLL', _boolean) # /DELAY:NOBIND - _MSBuildOnly(_link, 'TrackerLogDirectory', _folder_name) - _MSBuildOnly(_link, 'MSDOSStubFileName', _file_name) # /STUB Visible='false' - _MSBuildOnly(_link, 'SectionAlignment', _integer) # /ALIGN - _MSBuildOnly(_link, 'SpecifySectionAttributes', _string) # /SECTION - _MSBuildOnly(_link, 'ForceFileOutput', - _Enumeration([], new=['Enabled', # /FORCE - # /FORCE:MULTIPLE - 'MultiplyDefinedSymbolOnly', - 'UndefinedSymbolOnly'])) # /FORCE:UNRESOLVED - _MSBuildOnly(_link, 'CreateHotPatchableImage', - _Enumeration([], new=['Enabled', # /FUNCTIONPADMIN - 'X86Image', # /FUNCTIONPADMIN:5 - 'X64Image', # /FUNCTIONPADMIN:6 - 'ItaniumImage'])) # /FUNCTIONPADMIN:16 - _MSBuildOnly(_link, 'CLRSupportLastError', - _Enumeration([], new=['Enabled', # /CLRSupportLastError - 'Disabled', # /CLRSupportLastError:NO - # /CLRSupportLastError:SYSTEMDLL - 'SystemDlls'])) - - ''' - SwitchConverter.__init__(self, table, booltable) - -CLSWITCHES = ClSwitchConverter() -LINKSWITCHES = LinkSwitchConverter() - -#------------------------------------------------------------------------------- - -# Return a Windows path from a native path -def winpath(path): - drive, rest = ntpath.splitdrive(path) - result = [] - while rest and rest != ntpath.sep: - rest, part = ntpath.split(rest) - result.insert(0, part) - if rest: - result.insert(0, rest) - return ntpath.join(drive.upper(), *result) - -def makeList(x): - if not x: - return [] - if type(x) is not list: - return [x] - return x - -#------------------------------------------------------------------------------- - -class Configuration(object): - def __init__(self, variant, platform, target, env): - self.name = '%s|%s' % (variant, platform) - self.variant = variant - self.platform = platform - self.target = target - self.env = env - -#------------------------------------------------------------------------------- - -class Item(object): - '''Represents a file item in the Solution Explorer''' - def __init__(self, path, builder): - self._path = path - self._builder = builder - self.node = dict() - - if builder == 'Object': - self._tag = 'ClCompile' - self._excluded = False - elif builder == 'Protoc': - self._tag = 'CustomBuild' - self._excluded = False - else: - ext = os.path.splitext(self._path)[1] - if ext in ['.c', '.cc', '.cpp']: - self._tag = 'ClCompile' - self._excluded = True - else: - if ext in ['.h', '.hpp', '.hxx', '.inl', '.inc']: - self._tag = 'ClInclude' - else: - self._tag = 'None' - self._excluded = False; - - def __repr__(self): - return '' % ( - self.path, self.tag, str(self.node)) - - def path(self): - return self._path - - def tag(self): - return self._tag - - def builder(self): - return self._builder - - def is_compiled(self): - return self._builder == 'Object' - - def is_excluded(self): - return self._excluded - -#------------------------------------------------------------------------------- - -def _guid(seed, name = None): - m = hashlib.md5() - m.update(seed) - if name: - m.update(name) - d = m.hexdigest().upper() - guid = "{%s-%s-%s-%s-%s}" % (d[:8], d[8:12], d[12:16], d[16:20], d[20:32]) - return guid - -class _ProjectGenerator(object): - '''Generates a project file for Visual Studio 2013''' - - def __init__(self, project_node, filters_node, env): - try: - self.configs = xsorted(env['VSPROJECT_CONFIGS']) - except KeyError: - raise ValueError ('Missing VSPROJECT_CONFIGS') - self.root_dir = os.getcwd() - self.root_dirs = [os.path.abspath(x) for x in makeList(env['VSPROJECT_ROOT_DIRS'])] - self.project_dir = os.path.dirname(os.path.abspath(str(project_node))) - self.project_node = project_node - self.project_file = None - self.filters_node = filters_node - self.filters_file = None - self.guid = _guid(os.path.basename(str(self.project_node))) - self.buildItemList(env) - - def buildItemList(self, env): - '''Build the Item set associated with the configurations''' - items = {} - def _walk(target, items, prefix=''): - if os.path.isabs(str(target)): - return - if target.has_builder(): - builder = target.get_builder().get_name(env) - bsources = target.get_binfo().bsources - if builder == 'Program': - for child in bsources: - _walk(child, items, prefix+' ') - else: - for child in bsources: - item = items.setdefault(str(child), Item(str(child), builder=builder)) - item.node[config] = target - _walk(child, items, prefix+' ') - for child in target.children(scan=1): - if not os.path.isabs(str(child)): - item = items.setdefault(str(child), Item(str(child), builder=None)) - _walk(child, items, prefix+' ') - for config in self.configs: - targets = config.target - for target in targets: - _walk(target, items) - self.items = xsorted(items.values()) - - def makeListTag(self, items, prefix, tag, attrs, inherit=True): - '''Builds an XML tag string from a list of items. If items is - empty, then the returned string is empty.''' - if not items: - return '' - s = '%(prefix)s<%(tag)s%(attrs)s>' % locals() - s += ';'.join(items) - if inherit: - s += ';%%(%(tag)s)' % locals() - s += '\r\n' % locals() - return s - - def relPaths(self, paths): - items = [] - for path in paths: - if not os.path.isabs(path): - items.append(winpath(os.path.relpath(path, self.project_dir))) - return items - - def extraRelPaths(self, paths, base): - extras = [] - for path in paths: - if not path in base: - extras.append(path) - return self.relPaths(extras) - - def writeHeader(self): - global clSwitches - - encoding = 'utf-8' - project_guid = self.guid - name = os.path.splitext(os.path.basename(str(self.project_node)))[0] - - f = self.project_file - f.write(UnicodeByteMarker) - f.write(V14DSPHeader % locals()) - f.write(V14DSPGlobals % locals()) - f.write(' \r\n') - for config in self.configs: - variant = config.variant - platform = config.platform - f.write(V14DSPProjectConfiguration % locals()) - f.write(' \r\n') - - f.write(' \r\n') - for config in self.configs: - variant = config.variant - platform = config.platform - use_debug_libs = variant == 'Debug' - variant_dir = os.path.relpath(os.path.dirname( - config.target[0].get_abspath()), self.project_dir) - out_dir = winpath(variant_dir) + ntpath.sep - int_dir = winpath(ntpath.join(variant_dir, 'src')) + ntpath.sep - f.write(V14DSPPropertyGroup % locals()) - - f.write(' \r\n') - f.write(' \r\n') - for config in self.configs: - variant = config.variant - platform = config.platform - f.write(V14DSPImportGroup % locals()) - - f.write(' \r\n') - for config in self.configs: - variant = config.variant - platform = config.platform - f.write(V14DSPItemDefinitionGroup % locals()) - # Cl options - f.write(' \r\n') - f.write( - ' %s%%(PreprocessorDefinitions)\r\n' % ( - itemList(config.env['CPPDEFINES'], ';'))) - props = '' - props += self.makeListTag(self.relPaths(xsorted(config.env['CPPPATH'])), - ' ', 'AdditionalIncludeDirectories', '', True) - f.write(props) - f.write(CLSWITCHES.getXml(xsorted(config.env['CCFLAGS']), ' ')) - f.write(' \r\n') - - f.write(' \r\n') - props = '' - props += self.makeListTag(xsorted(config.env['LIBS']), - ' ', 'AdditionalDependencies', '', True) - try: - props += self.makeListTag(self.relPaths(xsorted(config.env['LIBPATH'])), - ' ', 'AdditionalLibraryDirectories', '', True) - except: - pass - f.write(props) - f.write(LINKSWITCHES.getXml(xsorted(config.env['LINKFLAGS']), ' ')) - f.write(' \r\n') - - f.write(' \r\n') - - def writeProject(self): - self.writeHeader() - - f = self.project_file - self.project_file.write(' \r\n') - for item in self.items: - path = winpath(os.path.relpath(item.path(), self.project_dir)) - tag = item.tag() - props = '' - if item.builder() == 'Object': - props = '' - for config in self.configs: - name = config.name - variant = config.variant - platform = config.platform - if not config in item.node: - props += \ - ''' True\r\n''' % locals() - for config, output in xsorted(item.node.items()): - name = config.name - env = output.get_build_env() - variant = config.variant - platform = config.platform - props += self.makeListTag(self.extraRelPaths(xsorted(env['CPPPATH']), config.env['CPPPATH']), - ' ', 'AdditionalIncludeDirectories', - ''' Condition="'$(Configuration)|$(Platform)'=='%(variant)s|%(platform)s'"''' % locals(), - True) - elif item.is_excluded(): - props = ' True\r\n' - elif item.builder() == 'Protoc': - for config, output in xsorted(item.node.items()): - name = config.name - out_dir = os.path.relpath(os.path.dirname(str(output)), self.project_dir) - cpp_out = winpath(out_dir) - out_parts = out_dir.split(os.sep) - out_parts.append(os.path.splitext(os.path.basename(item.path()))[0]) - base_out = ntpath.join(*out_parts) - props += V14CustomBuildProtoc % locals() - - f.write(' <%(tag)s Include="%(path)s">\r\n' % locals()) - f.write(props) - f.write(' \r\n' % locals()) - f.write(' \r\n') - - f.write( - ' \r\n' - ' \r\n' - ' \r\n' - '\r\n') - - def writeFilters(self): - def getGroup(abspath): - abspath = os.path.dirname(abspath) - for d in self.root_dirs: - common = os.path.commonprefix([abspath, d]) - if common == d: - return winpath(os.path.relpath(abspath, common)) - return winpath(os.path.split(abspath)[1]) - - f = self.filters_file - f.write(UnicodeByteMarker) - f.write(V14DSPFiltersHeader) - - f.write(' \r\n') - groups = set() - for item in self.items: - group = getGroup(os.path.abspath(item.path())) - while group != '': - groups.add(group) - group = ntpath.split(group)[0] - for group in xsorted(groups): - guid = _guid(self.guid, group) - f.write( - ' \r\n' - ' %(guid)s\r\n' - ' \r\n' % locals()) - f.write(' \r\n') - - f.write(' \r\n') - for item in self.items: - path = os.path.abspath(item.path()) - group = getGroup(path) - path = winpath(os.path.relpath(path, self.project_dir)) - tag = item.tag() - f.write ( - ' <%(tag)s Include="%(path)s">\r\n' - ' %(group)s\r\n' - ' \r\n' % locals()) - f.write(' \r\n') - f.write('\r\n') - - def build(self): - try: - self.project_file = open(str(self.project_node), 'wb') - except IOError, detail: - raise SCons.Errors.InternalError('Unable to open "' + - str(self.project_node) + '" for writing:' + str(detail)) - try: - self.filters_file = open(str(self.filters_node), 'wb') - except IOError, detail: - raise SCons.Errors.InternalError('Unable to open "' + - str(self.filters_node) + '" for writing:' + str(detail)) - self.writeProject() - self.writeFilters() - self.project_file.close() - self.filters_file.close() - -#------------------------------------------------------------------------------- - -class _SolutionGenerator(object): - def __init__(self, slnfile, projfile, env): - pass - - def build(self): - pass - -#------------------------------------------------------------------------------- - -# Generate the VS2013 project -def buildProject(target, source, env): - if env.get('auto_build_solution', 1): - if len(target) != 3: - raise ValueError ("Unexpected len(target) != 3") - if not env.get('auto_build_solution', 1): - if len(target) != 2: - raise ValueError ("Unexpected len(target) != 2") - - g = _ProjectGenerator (target[0], target[1], env) - g.build() - - if env.get('auto_build_solution', 1): - g = _SolutionGenerator (target[2], target[0], env) - g.build() - -def projectEmitter(target, source, env): - if len(target) != 1: - raise ValueError ("Exactly one target must be specified") - - # If source is unspecified this condition will be true - if not source or source[0] == target[0]: - source = [] - - outputs = [] - for node in list(target): - path = env.GetBuildPath(node) - outputs.extend([ - path + '.vcxproj', - path + '.vcxproj.filters']) - if env.get('auto_build_solution', 1): - outputs.append(path + '.sln') - return outputs, source - -projectBuilder = SCons.Builder.Builder( - action = SCons.Action.Action(buildProject, "Building ${TARGET}"), - emitter = projectEmitter) - -def createConfig(self, variant, platform, target, env): - return Configuration(variant, platform, target, env) - -def generate(env): - '''Add Builders and construction variables for Microsoft Visual - Studio project files to an Environment.''' - try: - env['BUILDERS']['VSProject'] - except KeyError: - env['BUILDERS']['VSProject'] = projectBuilder - env.AddMethod(createConfig, 'VSProjectConfig') - -def exists(env): - return True diff --git a/src/beast_http_nodejs_parser.cpp b/src/beast_http_nodejs_parser.cpp new file mode 100644 index 0000000000..cb1dccf905 --- /dev/null +++ b/src/beast_http_nodejs_parser.cpp @@ -0,0 +1,17 @@ +// +// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifdef _MSC_VER +# pragma warning (push) +# pragma warning (disable: 4127) // conditional expression is constant +# pragma warning (disable: 4244) // integer conversion, possible loss of data +#endif +#include "http-parser/http_parser.c" +#ifdef _MSC_VER +# pragma warning (pop) +#endif + diff --git a/beast/http/impl/http-parser/AUTHORS b/src/http-parser/AUTHORS similarity index 100% rename from beast/http/impl/http-parser/AUTHORS rename to src/http-parser/AUTHORS diff --git a/beast/http/impl/http-parser/LICENSE-MIT b/src/http-parser/LICENSE-MIT similarity index 100% rename from beast/http/impl/http-parser/LICENSE-MIT rename to src/http-parser/LICENSE-MIT diff --git a/beast/http/impl/http-parser/README.md b/src/http-parser/README.md similarity index 100% rename from beast/http/impl/http-parser/README.md rename to src/http-parser/README.md diff --git a/beast/http/impl/http-parser/http_parser.c b/src/http-parser/http_parser.c similarity index 99% rename from beast/http/impl/http-parser/http_parser.c rename to src/http-parser/http_parser.c index d0c77ea73a..278d4b2077 100644 --- a/beast/http/impl/http-parser/http_parser.c +++ b/src/http-parser/http_parser.c @@ -21,7 +21,7 @@ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ -#include "http_parser.h" +#include "../../include/beast/http/impl/http_parser.h" #include #include #include @@ -123,7 +123,7 @@ do { \ FOR##_mark = NULL; \ } \ } while (0) - + /* Run the data callback FOR and consume the current byte */ #define CALLBACK_DATA(FOR) \ CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) @@ -440,7 +440,7 @@ enum http_host_state * character or %x80-FF **/ #define IS_HEADER_CHAR(ch) \ - (ch == CR || ch == LF || ch == 9 || (ch > 31 && ch != 127)) + (ch == CR || ch == LF || ch == 9 || ((unsigned char)ch > 31 && ch != 127)) #define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) @@ -1812,6 +1812,9 @@ reexecute: case 0: break; + case 2: + parser->upgrade = 1; + case 1: parser->flags |= F_SKIPBODY; break; diff --git a/test/Jamfile b/test/Jamfile index e407b93a0b..6b7870df07 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -7,24 +7,27 @@ import os ; -path-constant test_main : ../beast/unit_test/src/main.cpp ; - unit-test all : - append_buffers.cpp - asio.cpp + ../src/beast_http_nodejs_parser.cpp async_completion.cpp + base64.cpp basic_streambuf.cpp basic_headers.cpp bind_handler.cpp + buffer_cat.cpp buffers_adapter.cpp buffers_debug.cpp + chunk_encode.cpp consuming_buffers.cpp + empty_base_optimization.cpp handler_alloc.cpp + message.cpp placeholders.cpp prepare_buffers.cpp + rfc2616.cpp static_streambuf.cpp streambuf.cpp streambuf_readstream.cpp type_check.cpp - $(test_main) + main.cpp ; diff --git a/test/async_completion.cpp b/test/async_completion.cpp index 1118ab8044..6dd0636fe8 100644 --- a/test/async_completion.cpp +++ b/test/async_completion.cpp @@ -6,4 +6,4 @@ // // Test that header file is self-contained. -#include +#include diff --git a/beast/crypto/tests/beast_base64_test.cpp b/test/base64.cpp similarity index 84% rename from beast/crypto/tests/beast_base64_test.cpp rename to test/base64.cpp index d42a82802d..68d7d02829 100644 --- a/beast/crypto/tests/beast_base64_test.cpp +++ b/test/base64.cpp @@ -17,20 +17,21 @@ */ //============================================================================== -#include -#include +#include +#include namespace beast { +namespace test { -class base64_test : public unit_test::suite +class base64_test : public detail::unit_test::suite { public: void check (std::string const& in, std::string const& out) { - auto const encoded = base64_encode (in); + auto const encoded = detail::base64_encode (in); expect (encoded == out); - expect (base64_decode (encoded) == in); + expect (detail::base64_decode (encoded) == in); } void @@ -48,4 +49,6 @@ public: BEAST_DEFINE_TESTSUITE(base64,crypto,beast); -} +} // test +} // beast + diff --git a/test/basic_headers.cpp b/test/basic_headers.cpp index ece03c32af..fc78890e57 100644 --- a/test/basic_headers.cpp +++ b/test/basic_headers.cpp @@ -6,15 +6,15 @@ // // Test that header file is self-contained. -#include +#include -#include +#include namespace beast { namespace http { namespace test { -class basic_headers_test : public unit_test::suite +class basic_headers_test : public beast::detail::unit_test::suite { public: template diff --git a/test/basic_streambuf.cpp b/test/basic_streambuf.cpp index afe91596fa..f82d53854e 100644 --- a/test/basic_streambuf.cpp +++ b/test/basic_streambuf.cpp @@ -6,4 +6,4 @@ // // Test that header file is self-contained. -#include +#include diff --git a/test/beast_wsproto_ws_test.cpp b/test/beast_wsproto_ws_test.cpp deleted file mode 100644 index 8bddcd57a1..0000000000 --- a/test/beast_wsproto_ws_test.cpp +++ /dev/null @@ -1,358 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include -#include -#include -#include - -namespace beast { -namespace wsproto { - -class ws_test : public unit_test::suite -{ -public: - using error_code = boost::system::error_code; - using endpoint_type = boost::asio::ip::tcp::endpoint; - using address_type = boost::asio::ip::address; - using socket_type = boost::asio::ip::tcp::socket; - using yield_context = boost::asio::yield_context; - - endpoint_type ep_; - - //-------------------------------------------------------------------------- - - // opcodes for creating the test plans - - // concurrent read and write - struct case_1{}; - - // write a bad frame and shut down - struct case_2{}; - - //-------------------------------------------------------------------------- - - class coro_peer - { - error_code ec_; - boost::asio::io_service ios_; - boost::asio::ip::tcp::acceptor acceptor_; - socket_type sock_; - socket ws_; - opcode::value op_; - beast::streambuf rb_; - beast::streambuf wb_; - yield_context* yield_; - int state_ = 0; - //unit_test::suite& test_; - - public: - coro_peer(coro_peer&&) = default; - coro_peer(coro_peer const&) = delete; - coro_peer& operator=(coro_peer&&) = delete; - coro_peer& operator=(coro_peer const&) = delete; - - template - coro_peer(bool server, endpoint_type ep, - unit_test::suite& test, Ops const&... ops) - : acceptor_(ios_) - , sock_(ios_) - , ws_(sock_) - //, test_(test) - { - if(server) - { - acceptor_.open(ep.protocol()); - acceptor_.bind(ep); - acceptor_.listen( - boost::asio::socket_base::max_connections); - boost::asio::spawn(ios_, - [=](auto yield) - { - yield_ = &yield; - state_ = 10; - acceptor_.async_accept(sock_, (*yield_)[ec_]); - if(ec_) - return this->fail("accept"); - state_ = 20; - ws_.async_accept((*yield_)[ec_]); - if(ec_) - return this->fail("ws.accept"); - this->invoke(ops...); - state_ = -1; - }); - } - else - { - boost::asio::spawn(ios_, - [=](auto yield) - { - yield_ = &yield; - state_ = 30; - sock_.async_connect(ep, (*yield_)[ec_]); - if(ec_) - return this->fail("connect"); - state_ = 40; - ws_.async_handshake(ep.address().to_string() + - std::to_string(ep.port()), "/", (*yield_)[ec_]); - if(ec_) - return this->fail("handshake"); - this->invoke(ops...); - state_ = -1; - }); - } - } - - ~coro_peer() - { - } - - int - state() const - { - return state_; - } - - void - run_one() - { - ios_.run_one(); - } - - void - step_to(int to = 0) - { - while(state_ != to) - ios_.run_one(); - } - - private: - template - void fail(String const& s) - { - } - - void invoke_1(case_1) - { - async_read(ws_, op_, rb_, - [&](auto ec) - { - if(ec) - return this->fail(ec); - rb_.consume(rb_.size()); - }); - state_ = 100; - async_write(ws_, opcode::text, - boost::asio::null_buffers{}, (*yield_)[ec_]); - if(ec_) - return fail("write"); - } - - void invoke_1(case_2) - { - detail::frame_header fh; - fh.op = opcode::rsv5; // bad opcode - fh.fin = true; - fh.mask = true; - fh.rsv1 = false; - fh.rsv2 = false; - fh.rsv3 = false; - fh.len = 0; - fh.key = 0; - detail::write(wb_, fh); - state_ = 200; - boost::asio::async_write( - ws_.next_layer(), wb_.data(), - (*yield_)[ec_]); - if(ec_) - return fail("write"); - ws_.next_layer().shutdown( - socket_type::shutdown_both, ec_); - if(ec_) - return fail("shutdown"); - } - - inline - void - invoke() - { - } - - template - inline - void - invoke(Op op, Ops const&... ops) - { - invoke_1(op); - invoke(ops...); - } - }; - - void - testInvokable() - { - endpoint_type const ep{ - address_type::from_string( - "127.0.0.1"), 6000}; - coro_peer server(true, ep, *this, case_1{}); - coro_peer client(false, ep, *this, case_2{}); - server.step_to(10); // async_accept - client.step_to(30); // async_connect - server.step_to(20); // async_accept(ws) - client.step_to(40); // async_handshake - server.step_to(100); // case_1 - client.step_to(200); // case_2 - client.step_to(-1); - server.step_to(-1); - } - - //-------------------------------------------------------------------------- - - void - maybe_fail(error_code const& ec, std::string const& what) - { - expect(! ec, what + ": " + ec.message()); - } - - void - maybe_throw(error_code ec, std::string what) - { - if(ec) - { - maybe_fail(ec, what); - throw ec; - } - } - - template - static - std::string - buffers_to_string(Buffers const& bs) - { - using boost::asio::buffer_cast; - using boost::asio::buffer_size; - std::string s; - s.reserve(buffer_size(bs)); - for(auto const& b : bs) - s.append(buffer_cast(b), - buffer_size(b)); - for(auto i = s.size(); i-- > 0;) - if(s[i] == '\r') - s.replace(i, 1, "\\r"); - else if(s[i] == '\n') - s.replace(i, 1, "\\n\n"); - return s; - } - - int - makeRequest(endpoint_type ep, std::string const& s) - { - using boost::asio::buffer; - boost::asio::io_service ios; - boost::asio::ip::tcp::socket sock(ios); - sock.connect(ep); - write(sock, append_buffers( - buffer(s), buffer("\r\n"))); - - using namespace http; - parsed_response m; - streambuf sb; - read(sock, sb, m); - return m.status; - } - - void - expectStatus(endpoint_type ep, - int status, std::string const& s) - { - expect(makeRequest(ep, s) == status); - } - - void - testHandshake(endpoint_type ep) - { - expectStatus(ep, 400, "GET / HTTP/1.0\r\n"); - } - - void - syncEchoClient(endpoint_type ep) - { - using boost::asio::buffer; - error_code ec; - boost::asio::io_service ios; - wsproto::socket ws(ios); - ws.next_layer().connect(ep, ec); - maybe_fail(ec, "connect"); - ws.handshake(ep.address().to_string(), "/", ec); - maybe_fail(ec, "upgrade"); - std::string const s = "Hello, world!"; - ws.write(wsproto::opcode::text, true, buffer(s), ec); - maybe_fail(ec, "write"); - boost::asio::streambuf sb; - wsproto::opcode::value op; - read(ws, op, sb, ec); - maybe_fail(ec, "read"); - if(! ec) - expect(op == wsproto::opcode::text); - expect(buffers_to_string(sb.data()) == s); - sb.consume(sb.size()); - ws.close({}, ec); - maybe_fail(ec, "close"); - while(! ec) - { - read(ws, op, sb, ec); - if(! ec) - sb.consume(sb.size()); - } - if(ec != error::closed) - maybe_fail(ec, "teardown"); - } - - void - run() override - { - //testInvokable(); - -#if 0 - { - endpoint_type ep{ - address_type::from_string("127.0.0.1"), 6000}; - testcase("Echo Server"); - test::sync_echo_peer s(true, ep, *this); - testHandshake(ep); - syncEchoClient(ep); - } -#endif - { - endpoint_type ep{ - address_type::from_string("127.0.0.1"), 6001}; - testcase("Async Echo Server"); - test::async_echo_peer s(true, ep, *this); - //testHandshake(ep); - syncEchoClient(ep); - } - } -}; - -BEAST_DEFINE_TESTSUITE(ws,asio,beast); - -} // wsproto -} // beast diff --git a/test/bind_handler.cpp b/test/bind_handler.cpp index 540efa5164..4bd49738cc 100644 --- a/test/bind_handler.cpp +++ b/test/bind_handler.cpp @@ -6,6 +6,32 @@ // // Test that header file is self-contained. -#include +#include -#include +#include +#include + +namespace beast { +namespace test { + +class bind_handler_test : public detail::unit_test::suite +{ +public: + static void foo (int) + { + } + + void run() + { + auto f (bind_handler ( + std::bind (&foo, std::placeholders::_1), + 42)); + f(); + pass(); + } +}; + +BEAST_DEFINE_TESTSUITE(bind_handler,asio,beast); + +} // test +} // beast diff --git a/test/append_buffers.cpp b/test/buffer_cat.cpp similarity index 81% rename from test/append_buffers.cpp rename to test/buffer_cat.cpp index 468b8622a3..88cb5004c0 100644 --- a/test/append_buffers.cpp +++ b/test/buffer_cat.cpp @@ -6,9 +6,9 @@ // // Test that header file is self-contained. -#include +#include -#include +#include #include #include #include @@ -16,14 +16,13 @@ #include namespace beast { -namespace asio { namespace test { -class append_buffers_test : public unit_test::suite +class buffer_cat_test : public detail::unit_test::suite { public: - void testAppendBuffers() + void testBufferCat() { using boost::asio::buffer_size; using boost::asio::const_buffer; @@ -40,7 +39,7 @@ public: std::list b5{ const_buffer{buf+9, 1}}; std::list b6; - auto bs = append_buffers( + auto bs = buffer_cat( b1, b2, b3, b4, b5, b6); expect(buffer_size(bs) == 10); std::vector v; @@ -54,23 +53,22 @@ public: bs3 = std::move(bs2); { boost::asio::streambuf sb1, sb2; - expect(buffer_size(append_buffers( + expect(buffer_size(buffer_cat( sb1.prepare(5), sb2.prepare(7))) == 12); sb1.commit(5); sb2.commit(7); - expect(buffer_size(append_buffers( + expect(buffer_size(buffer_cat( sb1.data(), sb2.data())) == 12); } } void run() override { - testAppendBuffers(); + testBufferCat(); } }; -BEAST_DEFINE_TESTSUITE(append_buffers,asio,beast); +BEAST_DEFINE_TESTSUITE(buffer_cat,asio,beast); } // test -} // asio } // beast diff --git a/test/buffers_adapter.cpp b/test/buffers_adapter.cpp index d2f3d73cf6..b70c545497 100644 --- a/test/buffers_adapter.cpp +++ b/test/buffers_adapter.cpp @@ -6,18 +6,17 @@ // // Test that header file is self-contained. -#include +#include -#include +#include #include #include #include namespace beast { -namespace asio { namespace test { -class buffers_adapter_test : public unit_test::suite +class buffers_adapter_test : public detail::unit_test::suite { public: template @@ -120,5 +119,4 @@ public: BEAST_DEFINE_TESTSUITE(buffers_adapter,asio,beast); } // test -} // asio } // beast diff --git a/test/buffers_debug.cpp b/test/buffers_debug.cpp index 231c49b499..cd420b8617 100644 --- a/test/buffers_debug.cpp +++ b/test/buffers_debug.cpp @@ -6,4 +6,4 @@ // // Test that header file is self-contained. -#include +#include diff --git a/beast/http/src/test/beast_http_chunked_encoder_test.cpp b/test/chunk_encode.cpp similarity index 96% rename from beast/http/src/test/beast_http_chunked_encoder_test.cpp rename to test/chunk_encode.cpp index 9684131e30..31ba7bc1c0 100644 --- a/beast/http/src/test/beast_http_chunked_encoder_test.cpp +++ b/test/chunk_encode.cpp @@ -17,15 +17,15 @@ */ //============================================================================== -#include -#include -#include +#include +#include +#include namespace beast { namespace http { namespace test { -class chunk_encode_test : public unit_test::suite +class chunk_encode_test : public beast::detail::unit_test::suite { public: // Convert CR LF to printables for display diff --git a/test/consuming_buffers.cpp b/test/consuming_buffers.cpp index c38355117b..9b3ce35345 100644 --- a/test/consuming_buffers.cpp +++ b/test/consuming_buffers.cpp @@ -6,17 +6,16 @@ // // Test that header file is self-contained. -#include +#include -#include +#include #include #include namespace beast { -namespace asio { namespace test { -class consuming_buffers_test : public unit_test::suite +class consuming_buffers_test : public beast::detail::unit_test::suite { public: template @@ -93,5 +92,4 @@ public: BEAST_DEFINE_TESTSUITE(consuming_buffers,asio,beast); } // test -} // asio } // beast diff --git a/beast/test/beast_empty_base_optimization_test.cpp b/test/empty_base_optimization.cpp similarity index 90% rename from beast/test/beast_empty_base_optimization_test.cpp rename to test/empty_base_optimization.cpp index c21ca370da..6e885aae3e 100644 --- a/beast/test/beast_empty_base_optimization_test.cpp +++ b/test/empty_base_optimization.cpp @@ -21,21 +21,22 @@ #include #endif -#include +#include -#include +#include namespace beast { +namespace test { class empty_base_optimization_test - : public unit_test::suite + : public beast::detail::unit_test::suite { public: template class test1 - : private empty_base_optimization + : private detail::empty_base_optimization { - using Base = empty_base_optimization; + using Base = detail::empty_base_optimization; void* m_p; public: explicit test1 (T const& t) @@ -104,4 +105,5 @@ public: BEAST_DEFINE_TESTSUITE(empty_base_optimization,utility,beast); +} // test } // beast diff --git a/test/handler_alloc.cpp b/test/handler_alloc.cpp index f90587b1dd..f27a1943a1 100644 --- a/test/handler_alloc.cpp +++ b/test/handler_alloc.cpp @@ -6,4 +6,4 @@ // // Test that header file is self-contained. -#include +#include diff --git a/beast/unit_test/src/main.cpp b/test/main.cpp similarity index 88% rename from beast/unit_test/src/main.cpp rename to test/main.cpp index 589012a9bb..22efdfcc4f 100644 --- a/beast/unit_test/src/main.cpp +++ b/test/main.cpp @@ -17,8 +17,9 @@ */ //============================================================================== -#include -#include +#include +#include +#include #ifdef _MSC_VER # ifndef WIN32_LEAN_AND_MEAN // VC_EXTRALEAN @@ -36,7 +37,7 @@ // alone executables that run unit tests. int main() { - using namespace beast::unit_test; + using namespace beast::detail::unit_test; #ifdef _MSC_VER { @@ -47,7 +48,7 @@ int main() #endif { - beast::debug_ostream s; + beast::detail::debug_ostream s; reporter r (s); bool failed (r.run_each (global_suites())); if (failed) diff --git a/beast/http/src/test/beast_http_message_test.cpp b/test/message.cpp similarity index 88% rename from beast/http/src/test/beast_http_message_test.cpp rename to test/message.cpp index 7266f7ef9f..ee6aee614f 100644 --- a/beast/http/src/test/beast_http_message_test.cpp +++ b/test/message.cpp @@ -17,13 +17,15 @@ */ //============================================================================== -#include -#include -#include -#include -#include -#include -#include +// Test that header file is self-contained. +#include + +#include +#include +#include +#include +#include +#include #include namespace beast { @@ -39,15 +41,15 @@ public: using socket_type = boost::asio::ip::tcp::socket; private: - unit_test::suite& suite_; + beast::detail::unit_test::suite& suite_; boost::asio::io_service ios_; socket_type sock_; boost::asio::ip::tcp::acceptor acceptor_; - unit_test::thread thread_; + beast::detail::unit_test::thread thread_; public: sync_echo_http_server( - endpoint_type ep, unit_test::suite& suite) + endpoint_type ep, beast::detail::unit_test::suite& suite) : suite_(suite) , sock_(ios_) , acceptor_(ios_) @@ -63,7 +65,7 @@ public: acceptor_.async_accept(sock_, std::bind(&sync_echo_http_server::on_accept, this, beast::asio::placeholders::error)); - thread_ = unit_test::thread(suite_, + thread_ = beast::detail::unit_test::thread(suite_, [&] { ios_.run(); @@ -132,7 +134,7 @@ private: } }; -class http_message_test : public unit_test::suite +class message_test : public beast::detail::unit_test::suite { public: using error_code = boost::system::error_code; @@ -174,12 +176,12 @@ public: void run() override { - testAsio(); + //testAsio(); pass(); } }; -BEAST_DEFINE_TESTSUITE_MANUAL(http_message,http,beast); +BEAST_DEFINE_TESTSUITE(message,http,beast); } // test } // http diff --git a/test/placeholders.cpp b/test/placeholders.cpp index b3df0f30e1..d16718b842 100644 --- a/test/placeholders.cpp +++ b/test/placeholders.cpp @@ -6,4 +6,4 @@ // // Test that header file is self-contained. -#include +#include diff --git a/test/prepare_buffers.cpp b/test/prepare_buffers.cpp index 842ec85f0a..8ec75ccf99 100644 --- a/test/prepare_buffers.cpp +++ b/test/prepare_buffers.cpp @@ -6,18 +6,17 @@ // // Test that header file is self-contained. -#include +#include -#include -#include +#include +#include #include #include namespace beast { -namespace asio { namespace test { -class prepare_buffers_test : public unit_test::suite +class prepare_buffers_test : public beast::detail::unit_test::suite { public: template @@ -83,7 +82,7 @@ public: cb.consume(1); expect(buffer_size(cb) == 0); expect(buffer_copy(cb, pb1) == 0); - + auto pbc = prepare_buffers(2, cb); expect(buffer_size(pbc) == 0); expect(buffer_copy(pbc, cb) == 0); @@ -99,5 +98,4 @@ public: BEAST_DEFINE_TESTSUITE(prepare_buffers,asio,beast); } // test -} // asio } // beast diff --git a/beast/http/src/test/beast_http_rfc2616_test.cpp b/test/rfc2616.cpp similarity index 96% rename from beast/http/src/test/beast_http_rfc2616_test.cpp rename to test/rfc2616.cpp index 54c220e5fe..c095bc3fb4 100644 --- a/beast/http/src/test/beast_http_rfc2616_test.cpp +++ b/test/rfc2616.cpp @@ -17,17 +17,16 @@ */ //============================================================================== -#include -#include +#include +#include #include #include - namespace beast { namespace rfc2616 { namespace test { -class rfc2616_test : public beast::unit_test::suite +class rfc2616_test : public beast::detail::unit_test::suite { public: void diff --git a/test/ssl_error.cpp b/test/ssl_error.cpp deleted file mode 100644 index d750c5de70..0000000000 --- a/test/ssl_error.cpp +++ /dev/null @@ -1,43 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of Beast: https://github.com/vinniefalco/Beast - Copyright 2013, Vinnie Falco - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ -//============================================================================== - -#include -#include -#include - -namespace beast { - -class ssl_error_test : public unit_test::suite -{ -public: - void run() - { - { - boost::system::error_code ec = - boost::system::error_code (335544539, - boost::asio::error::get_ssl_category ()); - std::string const s = beast::error_message_with_ssl(ec); - expect(s == " (20,0,219) error:140000DB:SSL routines:SSL routines:short read"); - } - } -}; - -BEAST_DEFINE_TESTSUITE(ssl_error,asio,beast); - -} // beast diff --git a/test/static_streambuf.cpp b/test/static_streambuf.cpp index ce97965d58..22c7bcc2b5 100644 --- a/test/static_streambuf.cpp +++ b/test/static_streambuf.cpp @@ -6,17 +6,16 @@ // // Test that header file is self-contained. -#include +#include -#include +#include #include #include namespace beast { -namespace asio { namespace test { -class static_streambuf_test : public unit_test::suite +class static_streambuf_test : public beast::detail::unit_test::suite { public: template @@ -109,5 +108,4 @@ public: BEAST_DEFINE_TESTSUITE(static_streambuf,asio,beast); } // test -} // asio -} // beast +} // beastp diff --git a/test/streambuf.cpp b/test/streambuf.cpp index 248771940c..8f7bc414a6 100644 --- a/test/streambuf.cpp +++ b/test/streambuf.cpp @@ -6,16 +6,15 @@ // // Test that header file is self-contained. -#include +#include -#include +#include #include #include #include #include namespace beast { -namespace asio { namespace test { struct test_allocator_info @@ -135,7 +134,7 @@ public: } }; -class streambuf_test : public unit_test::suite +class streambuf_test : public beast::detail::unit_test::suite { public: template @@ -287,5 +286,4 @@ public: BEAST_DEFINE_TESTSUITE(streambuf,asio,beast); } // test -} // asio } // beast diff --git a/test/streambuf_readstream.cpp b/test/streambuf_readstream.cpp index e35f5bfd8a..80d34f6b14 100644 --- a/test/streambuf_readstream.cpp +++ b/test/streambuf_readstream.cpp @@ -6,4 +6,4 @@ // // Test that header file is self-contained. -#include +#include diff --git a/test/type_check.cpp b/test/type_check.cpp index f25a3b3627..2bdde9a937 100644 --- a/test/type_check.cpp +++ b/test/type_check.cpp @@ -6,4 +6,4 @@ // // Test that header file is self-contained. -#include +#include