Truncate history, version 1.0.0-b2

This commit is contained in:
Vinnie Falco committed 2017-07-20 08:01:46 -07:00
commit 9a3a42a644
204 files changed
+46608

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
# Part of Beast
GroupSources(include/beast)
GroupSources(test)
set(CORE_TESTS_SRCS
main.cpp
async_completion.cpp
basic_streambuf.cpp
bind_handler.cpp
buffer_cat.cpp
buffers_adapter.cpp
buffers_debug.cpp
consuming_buffers.cpp
handler_alloc.cpp
placeholders.cpp
prepare_buffers.cpp
static_streambuf.cpp
streambuf.cpp
streambuf_readstream.cpp
type_check.cpp
detail/base64.cpp
detail/empty_base_optimization.cpp
)
add_executable (core-tests
${BEAST_INCLUDES}
${CORE_TESTS_SRCS}
)
set(HTTP_TESTS_SRCS
main.cpp
http/basic_headers.cpp
http/basic_parser.cpp
http/chunk_encode.cpp
http/empty_body.cpp
http/error.cpp
http/headers.cpp
http/message.cpp
http/method.cpp
http/parse_error.cpp
http/parser.cpp
http/read.cpp
http/reason.cpp
http/resume_context.cpp
http/rfc2616.cpp
http/rfc7230.cpp
http/streambuf_body.cpp
http/string_body.cpp
http/write.cpp
)
add_executable (http-tests
${BEAST_INCLUDES}
${HTTP_TESTS_SRCS}
)
set(WEBSOCKET_TESTS_SRCS
main.cpp
websocket/error.cpp
websocket/option.cpp
websocket/rfc6455.cpp
websocket/static_string.cpp
websocket/teardown.cpp
websocket/utf8_checker.cpp
)
add_executable (websocket-tests
${BEAST_INCLUDES}
${WEBSOCKET_TESTS_SRCS}
)
set(PARSER_BENCH_SRCS
main.cpp
http/nodejs_parser.cpp
http/parser_bench.cpp
)
add_executable (parser-bench
${BEAST_INCLUDES}
${PARSER_BENCH_SRCS}
)
+66
View File
@@ -0,0 +1,66 @@
#
# 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)
#
import os ;
unit-test core-tests :
main.cpp
async_completion.cpp
basic_streambuf.cpp
bind_handler.cpp
buffer_cat.cpp
buffers_adapter.cpp
buffers_debug.cpp
consuming_buffers.cpp
handler_alloc.cpp
placeholders.cpp
prepare_buffers.cpp
static_streambuf.cpp
streambuf.cpp
streambuf_readstream.cpp
type_check.cpp
detail/base64.cpp
detail/empty_base_optimization.cpp
;
unit-test http-tests :
main.cpp
http/basic_headers.cpp
http/basic_parser.cpp
http/chunk_encode.cpp
http/empty_body.cpp
http/error.cpp
http/headers.cpp
http/message.cpp
http/method.cpp
http/parse_error.cpp
http/parser.cpp
http/read.cpp
http/reason.cpp
http/resume_context.cpp
http/rfc2616.cpp
http/rfc7230.cpp
http/streambuf_body.cpp
http/string_body.cpp
http/write.cpp
;
unit-test websocket-tests :
main.cpp
websocket/error.cpp
websocket/option.cpp
websocket/rfc6455.cpp
websocket/static_string.cpp
websocket/teardown.cpp
websocket/utf8_checker.cpp
;
unit-test parser-bench :
main.cpp
http/nodejs_parser.cpp
http/parser_bench.cpp
;
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/async_completion.hpp>
+301
View File
@@ -0,0 +1,301 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/basic_streambuf.hpp>
#include <beast/streambuf.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/asio/buffer.hpp>
#include <atomic>
#include <memory>
#include <string>
namespace beast {
namespace test {
struct test_allocator_info
{
std::size_t ncopy = 0;
std::size_t nmove = 0;
std::size_t nselect = 0;
};
template<class T,
bool Assign, bool Move, bool Swap, bool Select>
class test_allocator;
template<class T,
bool Assign, bool Move, bool Swap, bool Select>
struct test_allocator_base
{
};
template<class T,
bool Assign, bool Move, bool Swap>
struct test_allocator_base<T, Assign, Move, Swap, true>
{
static
test_allocator<T, Assign, Move, Swap, true>
select_on_container_copy_construction(
test_allocator<T, Assign, Move, Swap, true> const& a)
{
return test_allocator<T, Assign, Move, Swap, true>{};
}
};
template<class T,
bool Assign, bool Move, bool Swap, bool Select>
class test_allocator : public test_allocator_base<
T, Assign, Move, Swap, Select>
{
std::size_t id_;
std::shared_ptr<test_allocator_info> info_;
template<class, bool, bool, bool, bool>
friend class test_allocator;
public:
using value_type = T;
using propagate_on_container_copy_assignment =
std::integral_constant<bool, Assign>;
using propagate_on_container_move_assignment =
std::integral_constant<bool, Move>;
using propagate_on_container_swap =
std::integral_constant<bool, Swap>;
template<class U>
struct rebind
{
using other = test_allocator<
U, Assign, Move, Swap, Select>;
};
test_allocator()
: id_([]
{
static std::atomic<
std::size_t> sid(0);
return ++sid;
}())
, info_(std::make_shared<test_allocator_info>())
{
}
test_allocator(test_allocator const& u) noexcept
: id_(u.id_)
, info_(u.info_)
{
++info_->ncopy;
}
template<class U>
test_allocator(test_allocator<
U, Assign, Move, Swap, Select> const& u) noexcept
: id_(u.id_)
, info_(u.info_)
{
++info_->ncopy;
}
test_allocator(test_allocator&& t)
: id_(t.id_)
, info_(t.info_)
{
++info_->nmove;
}
value_type*
allocate(std::size_t n)
{
return static_cast<value_type*>(
::operator new (n*sizeof(value_type)));
}
void
deallocate(value_type* p, std::size_t) noexcept
{
::operator delete(p);
}
std::size_t
id() const
{
return id_;
}
test_allocator_info const*
operator->() const
{
return info_.get();
}
};
class basic_streambuf_test : public beast::detail::unit_test::suite
{
public:
template<class ConstBufferSequence>
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<char const*>(b),
buffer_size(b));
return s;
}
void
testPrepare()
{
using boost::asio::buffer_size;
streambuf sb(2);
expect(buffer_size(sb.prepare(5)) == 5);
expect(buffer_size(sb.prepare(8)) == 8);
expect(buffer_size(sb.prepare(7)) == 7);
}
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);
}
}}}}}
}
template<class Alloc1, class Alloc2>
static
bool
eq(basic_streambuf<Alloc1> const& sb1,
basic_streambuf<Alloc2> const& sb2)
{
return to_string(sb1.data()) == to_string(sb2.data());
}
void testSpecial()
{
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) {
std::size_t z = s.size() - (x + y);
{
streambuf sb(i);
sb.commit(buffer_copy(sb.prepare(x), buffer(s.data(), x)));
sb.commit(buffer_copy(sb.prepare(y), buffer(s.data()+x, y)));
sb.commit(buffer_copy(sb.prepare(z), buffer(s.data()+x+y, z)));
expect(to_string(sb.data()) == s);
{
streambuf sb2(sb);
expect(eq(sb, sb2));
}
{
streambuf sb2;
sb2 = sb;
expect(eq(sb, sb2));
}
{
streambuf sb2(std::move(sb));
expect(to_string(sb2.data()) == s);
expect(buffer_size(sb.data()) == 0);
sb = std::move(sb2);
expect(to_string(sb.data()) == s);
expect(buffer_size(sb2.data()) == 0);
}
}
}}}
}
void testAllocator()
{
{
using alloc_type =
test_allocator<char, false, false, false, false>;
using sb_type = basic_streambuf<alloc_type>;
sb_type sb;
expect(sb.get_allocator().id() == 1);
}
{
using alloc_type =
test_allocator<char, false, false, false, false>;
using sb_type = basic_streambuf<alloc_type>;
sb_type sb;
expect(sb.get_allocator().id() == 2);
sb_type sb2(sb);
expect(sb2.get_allocator().id() == 2);
sb_type sb3(sb, alloc_type{});
//expect(sb3.get_allocator().id() == 3);
}
}
void run() override
{
testPrepare();
testStreambuf();
testSpecial();
testAllocator();
}
};
BEAST_DEFINE_TESTSUITE(basic_streambuf,core,beast);
} // test
} // beast
+37
View File
@@ -0,0 +1,37 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/bind_handler.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <functional>
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,core,beast);
} // test
} // beast
+81
View File
@@ -0,0 +1,81 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/buffer_cat.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/streambuf.hpp>
#include <iterator>
#include <list>
#include <vector>
namespace beast {
namespace test {
class buffer_cat_test : public detail::unit_test::suite
{
public:
template< class Iterator >
static
std::reverse_iterator<Iterator>
make_reverse_iterator( Iterator i )
{
return std::reverse_iterator<Iterator>(i);
}
void testBufferCat()
{
using boost::asio::buffer_size;
using boost::asio::const_buffer;
char buf[10];
std::list<const_buffer> b1;
std::vector<const_buffer> b2{
const_buffer{buf+0, 1},
const_buffer{buf+1, 2}};
std::list<const_buffer> b3;
std::array<const_buffer, 3> b4{{
const_buffer{buf+3, 1},
const_buffer{buf+4, 2},
const_buffer{buf+6, 3}}};
std::list<const_buffer> b5{
const_buffer{buf+9, 1}};
std::list<const_buffer> b6;
auto bs = buffer_cat(
b1, b2, b3, b4, b5, b6);
expect(buffer_size(bs) == 10);
std::vector<const_buffer> v;
for(auto iter = make_reverse_iterator(bs.end());
iter != 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);
{
boost::asio::streambuf sb1, sb2;
expect(buffer_size(buffer_cat(
sb1.prepare(5), sb2.prepare(7))) == 12);
sb1.commit(5);
sb2.commit(7);
expect(buffer_size(buffer_cat(
sb1.data(), sb2.data())) == 12);
}
}
void run() override
{
testBufferCat();
}
};
BEAST_DEFINE_TESTSUITE(buffer_cat,core,beast);
} // test
} // beast
+122
View File
@@ -0,0 +1,122 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/buffers_adapter.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/streambuf.hpp>
#include <iterator>
namespace beast {
namespace test {
class buffers_adapter_test : public detail::unit_test::suite
{
public:
template<class ConstBufferSequence>
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<char const*>(b),
buffer_size(b));
return s;
}
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<mutable_buffer, 3> bs{{
mutable_buffer{&buf[0], i},
mutable_buffer{&buf[i], j},
mutable_buffer{&buf[i+j], k}}};
buffers_adapter<decltype(bs)> 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 run() override
{
testBuffersAdapter();
}
};
BEAST_DEFINE_TESTSUITE(buffers_adapter,core,beast);
} // test
} // beast
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/buffers_debug.hpp>
+95
View File
@@ -0,0 +1,95 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/consuming_buffers.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/asio/buffer.hpp>
#include <string>
namespace beast {
namespace test {
class consuming_buffers_test : public beast::detail::unit_test::suite
{
public:
template<class ConstBufferSequence>
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<char const*>(b),
buffer_size(b));
return s;
}
void testBuffers()
{
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<const_buffer, 3> bs{{
const_buffer{&buf[0], i},
const_buffer{&buf[i], j},
const_buffer{&buf[i+j], k}}};
consuming_buffers<decltype(bs)> 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 testNullBuffers()
{
using boost::asio::buffer_copy;
using boost::asio::buffer_size;
using boost::asio::null_buffers;
consuming_buffers<null_buffers> cb(
null_buffers{});
expect(buffer_size(cb) == 0);
consuming_buffers<null_buffers> cb2(
null_buffers{});
expect(buffer_copy(cb2, cb) == 0);
}
void run() override
{
testBuffers();
testNullBuffers();
}
};
BEAST_DEFINE_TESTSUITE(consuming_buffers,asio,beast);
} // test
} // beast
+54
View File
@@ -0,0 +1,54 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
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 <beast/detail/base64.hpp>
#include <beast/detail/unit_test/suite.hpp>
namespace beast {
namespace test {
class base64_test : public detail::unit_test::suite
{
public:
void
check (std::string const& in, std::string const& out)
{
auto const encoded = detail::base64_encode (in);
expect (encoded == out);
expect (detail::base64_decode (encoded) == in);
}
void
run()
{
check ("", "");
check ("f", "Zg==");
check ("fo", "Zm8=");
check ("foo", "Zm9v");
check ("foob", "Zm9vYg==");
check ("fooba", "Zm9vYmE=");
check ("foobar", "Zm9vYmFy");
}
};
BEAST_DEFINE_TESTSUITE(base64,detail,beast);
} // test
} // beast
+109
View File
@@ -0,0 +1,109 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2014, Howard Hinnant <howard.hinnant@gmail.com>
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 <beast/detail/empty_base_optimization.hpp>
#include <beast/detail/unit_test/suite.hpp>
namespace beast {
namespace test {
class empty_base_optimization_test
: public beast::detail::unit_test::suite
{
public:
template <class T>
class test1
: private detail::empty_base_optimization<T>
{
using Base = detail::empty_base_optimization<T>;
void* m_p;
public:
explicit test1 (T const& t)
: Base (t)
{}
T& member() {return Base::member();}
T const& member() const {return Base::member();}
};
template <class T>
class test2
{
void* m_p;
T m_t;
public:
explicit test2 (T const& t)
: m_t (t)
{}
T& member() {return m_t;}
T const& member() const {return m_t;}
};
struct Empty
{
operator bool() {return true;}
};
static
bool
test_one ()
{
test1<int> t1(1);
test2<int> t2(2);
static_assert(sizeof(t1) == sizeof(t2), "don't optimize for int");
if (t1.member() != 1)
return false;
if (t2.member() != 2)
return false;
return true;
}
static
bool
test_two ()
{
test1<Empty> t1((Empty()));
test2<Empty> t2((Empty()));
static_assert(sizeof(t1) < sizeof(t2), "do optimize for Empty");
if (t1.member() != true)
return false;
if (t2.member() != true)
return false;
return true;
}
void
run ()
{
expect (test_one());
expect (test_two());
pass ();
}
};
BEAST_DEFINE_TESTSUITE(empty_base_optimization,detail,beast);
} // test
} // beast
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/handler_alloc.hpp>
+63
View File
@@ -0,0 +1,63 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/basic_headers.hpp>
#include <beast/detail/unit_test/suite.hpp>
namespace beast {
namespace http {
namespace test {
class basic_headers_test : public beast::detail::unit_test::suite
{
public:
template<class Allocator>
using bha = basic_headers<Allocator>;
using bh = basic_headers<std::allocator<char>>;
template<class Allocator>
static
void
fill(std::size_t n, basic_headers<Allocator>& h)
{
for(std::size_t i = 1; i<= n; ++i)
h.insert(std::to_string(i), i);
}
void testHeaders()
{
bh h1;
expect(h1.empty());
fill(1, h1);
expect(h1.size() == 1);
bh h2;
h2 = h1;
expect(h2.size() == 1);
h2.insert("2", "2");
expect(std::distance(h2.begin(), h2.end()) == 2);
h1 = std::move(h2);
expect(h1.size() == 2);
expect(h2.size() == 0);
bh h3(std::move(h1));
expect(h3.size() == 2);
expect(h1.size() == 0);
}
void run() override
{
testHeaders();
}
};
BEAST_DEFINE_TESTSUITE(basic_headers,http,beast);
} // test
} // asio
} // beast
+636
View File
@@ -0,0 +1,636 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/basic_parser.hpp>
#include "message_fuzz.hpp"
#include <beast/streambuf.hpp>
#include <beast/buffers_debug.hpp>
#include <beast/write_streambuf.hpp>
#include <beast/http/error.hpp>
#include <beast/http/rfc2616.hpp>
#include <beast/detail/ci_char_traits.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/utility/string_ref.hpp>
#include <cassert>
#include <climits>
#include <map>
#include <new>
#include <random>
#include <type_traits>
namespace beast {
namespace http {
class basic_parser_test : public beast::detail::unit_test::suite
{
std::mt19937 rng_;
public:
struct cb_req_checker
{
bool method = false;
bool uri = false;
bool request = false;
};
struct cb_res_checker
{
bool reason = false;
bool response = false;
};
template<bool isRequest>
struct cb_checker
: public basic_parser<isRequest, cb_checker<isRequest>>
, std::conditional<isRequest,
cb_req_checker, cb_res_checker>::type
{
bool field = false;
bool value = false;
bool headers = false;
bool body = false;
bool complete = false;
private:
friend class basic_parser<isRequest, cb_checker<isRequest>>;
void on_method(boost::string_ref const&, error_code&)
{
this->method = true;
}
void on_uri(boost::string_ref const&, error_code&)
{
this->uri = true;
}
void on_reason(boost::string_ref const&, error_code&)
{
this->reason = true;
}
void on_request(error_code&)
{
this->request = true;
}
void on_response(error_code&)
{
this->response = true;
}
void on_field(boost::string_ref const&, error_code&)
{
field = true;
}
void on_value(boost::string_ref const&, error_code&)
{
value = true;
}
int on_headers(error_code&)
{
headers = true;
return 0;
}
void on_body(boost::string_ref const&, error_code&)
{
body = true;
}
void on_complete(error_code&)
{
complete = true;
}
};
//--------------------------------------------------------------------------
static
std::string
escaped_string(boost::string_ref const& s)
{
std::string out;
out.reserve(s.size());
char const* p = s.data();
while(p != s.end())
{
if(*p == '\r')
out.append("\\r");
else if(*p == '\n')
out.append("\\n");
else if (*p == '\t')
out.append("\\t");
else
out.append(p, 1);
++p;
}
return out;
}
template<bool isRequest>
struct null_parser : basic_parser<isRequest, null_parser<isRequest>>
{
};
template<bool isRequest>
class test_parser :
public basic_parser<isRequest, test_parser<isRequest>>
{
std::string field_;
std::string value_;
void check()
{
if(! value_.empty())
{
rfc2616::trim_right_in_place(value_);
fields.emplace(field_, value_);
field_.clear();
value_.clear();
}
}
public:
std::map<std::string, std::string,
beast::detail::ci_less> fields;
std::string body;
void on_field(boost::string_ref const& s, error_code&)
{
check();
field_.append(s.data(), s.size());
}
void on_value(boost::string_ref const& s, error_code&)
{
value_.append(s.data(), s.size());
}
int on_headers(error_code&)
{
check();
return 0;
}
void on_body(boost::string_ref const& s, error_code&)
{
body.append(s.data(), s.size());
}
};
void
testCallbacks()
{
{
cb_checker<true> p;
error_code ec;
std::string const s =
"GET / HTTP/1.1\r\n"
"User-Agent: test\r\n"
"Content-Length: 1\r\n"
"\r\n"
"*";
p.write(s.data(), s.size(), ec);
if( expect(! ec))
{
expect(p.method);
expect(p.uri);
expect(p.request);
expect(p.field);
expect(p.value);
expect(p.headers);
expect(p.body);
expect(p.complete);
}
}
{
cb_checker<false> p;
error_code ec;
std::string const s =
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Content-Length: 1\r\n"
"\r\n"
"*";
p.write(s.data(), s.size(), ec);
if( expect(! ec))
{
expect(p.reason);
expect(p.response);
expect(p.field);
expect(p.value);
expect(p.headers);
expect(p.body);
expect(p.complete);
}
}
}
// Parse the entire input buffer as a valid message,
// then parse in two pieces of all possible lengths.
//
template<class Parser, class F>
void
parse(boost::string_ref const& m, F&& f)
{
{
error_code ec;
Parser p;
p.write(m.data(), m.size(), ec);
if(expect(p.complete()))
if(expect(! ec, ec.message()))
f(p);
}
for(std::size_t i = 1; i < m.size() - 1; ++i)
{
error_code ec;
Parser p;
p.write(&m[0], i, ec);
if(! expect(! ec, ec.message()))
continue;
if(p.complete())
{
f(p);
}
else
{
p.write(&m[i], m.size() - i, ec);
if(! expect(! ec, ec.message()))
continue;
expect(p.complete());
f(p);
}
}
}
// Parse with an expected error code
//
template<bool isRequest>
void
parse_ev(boost::string_ref const& m, parse_error ev)
{
{
error_code ec;
null_parser<isRequest> p;
p.write(m.data(), m.size(), ec);
if(expect(! p.complete()))
expect(ec == ev, ec.message());
}
for(std::size_t i = 1; i < m.size() - 1; ++i)
{
error_code ec;
null_parser<isRequest> p;
p.write(&m[0], i, ec);
if(! expect(! p.complete()))
continue;
if(ec)
{
expect(ec == ev, ec.message());
continue;
}
p.write(&m[i], m.size() - i, ec);
if(! expect(! p.complete()))
continue;
if(! expect(ec == ev, ec.message()))
continue;
}
}
//--------------------------------------------------------------------------
template<class UInt = std::size_t>
UInt
rand(std::size_t n)
{
return static_cast<UInt>(
std::uniform_int_distribution<
std::size_t>{0, n-1}(rng_));
}
//--------------------------------------------------------------------------
// Parse a valid message with expected version
//
template<bool isRequest>
void
version(boost::string_ref const& m,
unsigned major, unsigned minor)
{
parse<null_parser<isRequest>>(m,
[&](null_parser<isRequest> const& p)
{
expect(p.http_major() == major);
expect(p.http_minor() == minor);
});
}
// Parse a valid message with expected flags mask
//
void
checkf(boost::string_ref const& m, std::uint8_t mask)
{
parse<null_parser<true>>(m,
[&](null_parser<true> const& p)
{
expect(p.flags() & mask);
});
}
void
testVersion()
{
version<true>("GET / HTTP/0.0\r\n\r\n", 0, 0);
version<true>("GET / HTTP/0.1\r\n\r\n", 0, 1);
version<true>("GET / HTTP/0.9\r\n\r\n", 0, 9);
version<true>("GET / HTTP/1.0\r\n\r\n", 1, 0);
version<true>("GET / HTTP/1.1\r\n\r\n", 1, 1);
version<true>("GET / HTTP/9.9\r\n\r\n", 9, 9);
version<true>("GET / HTTP/999.999\r\n\r\n", 999, 999);
parse_ev<true>("GET / HTTP/1000.0\r\n\r\n", parse_error::bad_version);
parse_ev<true>("GET / HTTP/0.1000\r\n\r\n", parse_error::bad_version);
parse_ev<true>("GET / HTTP/99999999999999999999.0\r\n\r\n", parse_error::bad_version);
parse_ev<true>("GET / HTTP/0.99999999999999999999\r\n\r\n", parse_error::bad_version);
}
void
testConnection(std::string const& token,
std::uint8_t flag)
{
checkf("GET / HTTP/1.1\r\nConnection:" + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: " + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection:\t" + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: \t" + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: " + token + " \r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: " + token + "\t\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: " + token + " \t\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: " + token + "\t \r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: \r\n" " " + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection:\t\r\n" " " + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: \r\n" "\t" + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection:\t\r\n" "\t" + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: X," + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: X, " + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: X,\t" + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: X,\t " + token + "\r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: X," + token + " \r\n\r\n", flag);
checkf("GET / HTTP/1.1\r\nConnection: X," + token + "\t\r\n\r\n", flag);
}
void
testContentLength()
{
std::size_t const length = 0;
std::string const length_s =
std::to_string(length);
checkf("GET / HTTP/1.1\r\nContent-Length:"+ length_s + "\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + "\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length:\t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: \t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + " \r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + "\t\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + " \t\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: "+ length_s + "\t \r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: \r\n" " "+ length_s + "\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length:\t\r\n" " "+ length_s + "\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length: \r\n" "\t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
checkf("GET / HTTP/1.1\r\nContent-Length:\t\r\n" "\t"+ length_s + "\r\n\r\n", parse_flag::contentlength);
}
void
testTransferEncoding()
{
checkf("GET / HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding:\tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: \tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked \r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\t\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked \t\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\t \r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: \r\n" " chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding:\t\r\n" " chunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding: \r\n" "\tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked);
checkf("GET / HTTP/1.1\r\nTransfer-Encoding:\t\r\n" "\tchunked\r\n\r\n0\r\n\r\n", parse_flag::chunked );
}
void
testFlags()
{
testConnection("keep-alive",
parse_flag::connection_keep_alive);
testConnection("close",
parse_flag::connection_close);
testConnection("upgrade",
parse_flag::connection_upgrade);
testContentLength();
testTransferEncoding();
checkf(
"GET / HTTP/1.1\r\n"
"Upgrade: x\r\n"
"\r\n",
parse_flag::upgrade
);
parse_ev<true>(
"GET / HTTP/1.1\r\n"
"Transfer-Encoding:chunked\r\n"
"Content-Length: 0\r\n"
"\r\n", parse_error::illegal_content_length);
}
void
testUpgrade()
{
null_parser<true> p;
boost::string_ref s =
"GET / HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: WebSocket\r\n\r\n";
error_code ec;
p.write(s.data(), s.size(), ec);
if(! expect(! ec, ec.message()))
return;
expect(p.complete());
expect(p.upgrade());
}
void testBad()
{
parse_ev<true>(" ", parse_error::bad_method);
parse_ev<true>(" G", parse_error::bad_method);
parse_ev<true>("G:", parse_error::bad_request);
parse_ev<true>("GET /", parse_error::bad_uri);
parse_ev<true>("GET / X", parse_error::bad_version);
parse_ev<true>("GET / HX", parse_error::bad_version);
parse_ev<true>("GET / HTTX", parse_error::bad_version);
parse_ev<true>("GET / HTTPX", parse_error::bad_version);
parse_ev<true>("GET / HTTP/.", parse_error::bad_version);
parse_ev<true>("GET / HTTP/1000", parse_error::bad_version);
parse_ev<true>("GET / HTTP/1. ", parse_error::bad_version);
parse_ev<true>("GET / HTTP/1.1000", parse_error::bad_version);
parse_ev<true>("GET / HTTP/1.1\r ", parse_error::bad_crlf);
parse_ev<true>("GET / HTTP/1.1\r\nf :", parse_error::bad_field);
}
void
testRandomReq(std::size_t N)
{
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
message_fuzz mg;
for(std::size_t i = 0; i < N; ++i)
{
std::string s;
{
streambuf sb;
mg.request(sb);
s.reserve(buffer_size(sb.data()));
for(auto const& b : sb.data())
s.append(buffer_cast<char const*>(b),
buffer_size(b));
}
null_parser<true> p;
for(std::size_t j = 1; j < s.size() - 1; ++j)
{
error_code ec;
p.write(&s[0], j, ec);
if(! expect(! ec, ec.message()))
{
log << escaped_string(s);
break;
}
if(! p.complete())
{
p.write(&s[j], s.size() - j, ec);
if(! expect(! ec, ec.message()))
{
log << escaped_string(s);
break;
}
}
if(! expect(p.complete()))
break;
if(! p.keep_alive())
{
p.~null_parser();
new(&p) null_parser<true>{};
}
}
}
}
void
testRandomResp(std::size_t N)
{
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
message_fuzz mg;
for(std::size_t i = 0; i < N; ++i)
{
std::string s;
{
streambuf sb;
mg.response(sb);
s.reserve(buffer_size(sb.data()));
for(auto const& b : sb.data())
s.append(buffer_cast<char const*>(b),
buffer_size(b));
}
null_parser<false> p;
for(std::size_t j = 1; j < s.size() - 1; ++j)
{
error_code ec;
p.write(&s[0], j, ec);
if(! expect(! ec, ec.message()))
{
log << escaped_string(s);
break;
}
if(! p.complete())
{
p.write(&s[j], s.size() - j, ec);
if(! expect(! ec, ec.message()))
{
log << escaped_string(s);
break;
}
}
if(! expect(p.complete()))
break;
if(! p.keep_alive())
{
p.~null_parser();
new(&p) null_parser<false>{};
}
}
}
}
void testBody()
{
auto match =
[&](std::string const& body)
{
return
[&](test_parser<true> const& p)
{
expect(p.body == body);
};
};
parse<test_parser<true>>(
"GET / HTTP/1.1\r\nContent-Length: 1\r\n\r\n123", match("1"));
parse<test_parser<true>>(
"GET / HTTP/1.1\r\nContent-Length: 3\r\n\r\n123", match("123"));
parse<test_parser<true>>(
"GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n", match(""));
parse<test_parser<true>>(
"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
"1\r\n"
"a\r\n"
"0\r\n"
"\r\n", match("a"));
parse<test_parser<true>>(
"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
"2\r\n"
"ab\r\n"
"0\r\n"
"\r\n", match("ab"));
parse<test_parser<true>>(
"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
"2\r\n"
"ab\r\n"
"1\r\n"
"c\r\n"
"0\r\n"
"\r\n", match("abc"));
parse<test_parser<true>>(
"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
"10\r\n"
"1234567890123456\r\n"
"0\r\n"
"\r\n", match("1234567890123456"));
}
void run() override
{
testCallbacks();
testVersion();
testFlags();
testUpgrade();
testBad();
testRandomReq(100);
testRandomResp(100);
testBody();
}
};
BEAST_DEFINE_TESTSUITE(basic_parser,http,beast);
} // http
} // beast
+154
View File
@@ -0,0 +1,154 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
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 <beast/streambuf.hpp>
#include <beast/http/chunk_encode.hpp>
#include <beast/detail/unit_test/suite.hpp>
namespace beast {
namespace http {
namespace test {
class chunk_encode_test : public beast::detail::unit_test::suite
{
public:
// Convert CR LF to printables for display
static
std::string
encode (std::string const& s)
{
std::string result;
for(auto const c : s)
{
if (c == '\r')
result += "\\r";
else if (c== '\n')
result += "\\n";
else
result += c;
}
return result;
}
// Print the contents of a ConstBufferSequence to the log
template <class ConstBufferSequence, class Log>
static
void
print (ConstBufferSequence const& buffers, Log log)
{
for(auto const& buf : buffers)
log << encode (std::string(
boost::asio::buffer_cast<char const*>(buf),
boost::asio::buffer_size(buf)));
}
// Convert a ConstBufferSequence to a string
template <class ConstBufferSequence>
static
std::string
buffer_to_string (ConstBufferSequence const& b)
{
std::string s;
auto const n = boost::asio::buffer_size(b);
s.resize(n);
boost::asio::buffer_copy(
boost::asio::buffer(&s[0], n), b);
return s;
}
// Append a ConstBufferSequence to an existing string
template <class ConstBufferSequence>
static
void
buffer_append (std::string& s, ConstBufferSequence const& b)
{
s += buffer_to_string(b);
}
// Convert the input sequence of the stream to a
// chunked-encoded string. The input sequence is consumed.
template <class Streambuf>
static
std::string
streambuf_to_string (Streambuf& sb,
bool final_chunk = false)
{
std::string s;
buffer_append(s, chunk_encode(sb.data(), final_chunk));
return s;
}
// Check an input against the correct chunk encoded version
void
check (std::string const& in, std::string const& answer,
bool final_chunk = true)
{
streambuf sb(3);
sb << in;
auto const out = streambuf_to_string (sb, final_chunk);
if (! expect (out == answer))
log << "expected\n" << encode(answer) <<
"\ngot\n" << encode(out);
}
void testStreambuf()
{
streambuf sb(3);
std::string const s =
"0123456789012345678901234567890123456789012345678901234567890123456789"
"0123456789012345678901234567890123456789012345678901234567890123456789"
"0123456789012345678901234567890123456789012345678901234567890123456789";
sb << s;
expect(buffer_to_string(sb.data()) == s);
}
void
testEncoder()
{
check("", "0\r\n\r\n");
check("x", "1\r\nx\r\n0\r\n\r\n");
check("abcd", "4\r\nabcd\r\n0\r\n\r\n");
check("x", "1\r\nx\r\n", false);
check(
"0123456789012345678901234567890123456789012345678901234567890123456789"
"0123456789012345678901234567890123456789012345678901234567890123456789"
"0123456789012345678901234567890123456789012345678901234567890123456789"
,
"d2\r\n"
"0123456789012345678901234567890123456789012345678901234567890123456789"
"0123456789012345678901234567890123456789012345678901234567890123456789"
"0123456789012345678901234567890123456789012345678901234567890123456789"
"\r\n"
"0\r\n\r\n");
}
void
run()
{
testStreambuf();
testEncoder();
}
};
BEAST_DEFINE_TESTSUITE(chunk_encode,http,beast);
} // test
} // http
} // beast
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/empty_body.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/error.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/headers.hpp>
+188
View File
@@ -0,0 +1,188 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
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.
*/
//==============================================================================
// Test that header file is self-contained.
#include <beast/http/message.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <beast/detail/unit_test/thread.hpp>
#include <beast/buffers_debug.hpp>
#include <beast/placeholders.hpp>
#include <beast/streambuf.hpp>
#include <beast/http.hpp>
#include <boost/asio.hpp>
namespace beast {
namespace http {
namespace test {
class sync_echo_http_server
{
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;
private:
beast::detail::unit_test::suite& suite_;
boost::asio::io_service ios_;
socket_type sock_;
boost::asio::ip::tcp::acceptor acceptor_;
beast::detail::unit_test::thread thread_;
public:
sync_echo_http_server(
endpoint_type ep, beast::detail::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_http_server::on_accept, this,
beast::asio::placeholders::error));
thread_ = beast::detail::unit_test::thread(suite_,
[&]
{
ios_.run();
});
}
~sync_echo_http_server()
{
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 &&
ec != boost::asio::error::operation_aborted)
{
fail(ec, what);
throw ec;
}
}
void
on_accept(error_code ec)
{
if(ec == boost::asio::error::operation_aborted)
return;
maybe_throw(ec, "accept");
std::thread{&sync_echo_http_server::do_client, this,
std::move(sock_), boost::asio::io_service::work{
sock_.get_io_service()}}.detach();
acceptor_.async_accept(sock_,
std::bind(&sync_echo_http_server::on_accept, this,
beast::asio::placeholders::error));
}
void
do_client(socket_type sock, boost::asio::io_service::work)
{
error_code ec;
streambuf rb;
for(;;)
{
request<string_body> req;
read(sock, rb, req, ec);
if(ec)
break;
response<string_body> resp(
{100, "OK", req.version});
resp.body = "Completed successfully.";
write(sock, resp, ec);
if(ec)
break;
}
}
};
class message_test : public beast::detail::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;
void
syncEcho(endpoint_type ep)
{
boost::asio::io_service ios;
socket_type sock(ios);
sock.connect(ep);
streambuf rb;
{
request<string_body> req(
{beast::http::method_t::http_get, "/", 11});
req.body = "Beast.HTTP";
req.headers.replace("Host",
ep.address().to_string() + ":" +
std::to_string(ep.port()));
write(sock, req);
}
{
response<string_body> m;
read(sock, rb, m);
}
}
void
testAsio()
{
endpoint_type ep{
address_type::from_string("127.0.0.1"), 6000};
sync_echo_http_server s(ep, *this);
syncEcho(ep);
}
void run() override
{
//testAsio();
pass();
}
};
BEAST_DEFINE_TESTSUITE(message,http,beast);
} // test
} // http
} // beast
+562
View File
@@ -0,0 +1,562 @@
//
// 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_TEST_MESSAGE_FUZZ_HPP
#define BEAST_HTTP_TEST_MESSAGE_FUZZ_HPP
#include <beast/http/detail/basic_parser.hpp>
#include <beast/write_streambuf.hpp>
#include <cstdint>
#include <random>
#include <string>
namespace beast {
namespace http {
template<class = void>
std::string
escaped_string(boost::string_ref const& s)
{
std::string out;
out.reserve(s.size());
char const* p = s.data();
while(p != s.end())
{
if(*p == '\r')
out.append("\\r");
else if(*p == '\n')
out.append("\\n");
else if (*p == '\t')
out.append("\\t");
else
out.append(p, 1);
++p;
}
return out;
}
// Produces random HTTP messages
//
template<class = void>
class message_fuzz_t
{
std::mt19937 rng_;
static
std::string
to_hex(std::size_t v)
{
if(! v)
return "0";
std::string s;
while(v > 0)
{
s.insert(s.begin(),
"0123456789abcdef"[v&0xf]);
v >>= 4;
}
return s;
}
public:
template<class UInt = std::size_t>
UInt
rand(std::size_t n)
{
return static_cast<UInt>(
std::uniform_int_distribution<
std::size_t>{0, n-1}(rng_));
}
std::string
method()
{
#if 0
// All IANA registered methods
static char const* const list[39] = {
"ACL", "BASELINE-CONTROL", "BIND", "CHECKIN", "CHECKOUT", "CONNECT",
"COPY", "DELETE", "GET", "HEAD", "LABEL", "LINK", "LOCK", "MERGE",
"MKACTIVITY", "MKCALENDAR", "MKCOL", "MKREDIRECTREF", "MKWORKSPACE",
"MOVE", "OPTIONS", "ORDERPATCH", "PATCH", "POST", "PRI", "PROPFIND",
"PROPPATCH", "PUT", "REBIND", "REPORT", "SEARCH", "TRACE", "UNBIND",
"UNCHECKOUT", "UNLINK", "UNLOCK", "UPDATE", "UPDATEREDIRECTREF",
"VERSION-CONTROL"
};
return list[rand(39)];
#else
// methods parsed by nodejs-http-parser
static char const* const list[33] = {
"ACL", "BIND", "CHECKOUT", "CONNECT", "COPY", "DELETE", "HEAD", "GET",
"LINK", "LOCK", "MERGE", "MKCOL", "MKCALENDAR", "MKACTIVITY", "M-SEARCH",
"MOVE", "NOTIFY", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH",
"PURGE", "PUT", "REBIND", "REPORT", "SEARCH", "SUBSCRIBE", "TRACE",
"UNBIND", "UNLINK", "UNLOCK", "UNSUBSCRIBE"
};
return list[rand(33)];
#endif
}
std::string
scheme()
{
static char const* const list[241] = {
"aaa", "aaas", "about", "acap", "acct", "acr", "adiumxtra", "afp", "afs",
"aim", "appdata", "apt", "attachment", "aw", "barion", "beshare", "bitcoin",
"blob", "bolo", "callto", "cap", "chrome", "chrome-extension", "cid",
"coap", "coaps", "com-eventbrite-attendee", "content", "crid", "cvs",
"data", "dav", "dict", "dis", "dlna-playcontainer", "dlna-playsingle",
"dns", "dntp", "dtn", "dvb", "ed2k", "example", "facetime", "fax", "feed",
"feedready", "file", "filesystem", "finger", "fish", "ftp", "geo", "gg",
"git", "gizmoproject", "go", "gopher", "gtalk", "h323", "ham", "hcp",
"http", "https", "iax", "icap", "icon", "im", "imap", "info", "iotdisco",
"ipn", "ipp", "ipps", "irc", "irc6", "ircs", "iris", "iris.beep",
"iris.lwz", "iris.xpc", "iris.xpcs", "isostore", "itms", "jabber", "jar",
"jms", "keyparc", "lastfm", "ldap", "ldaps", "magnet", "mailserver",
"mailto", "maps", "market", "message", "mid", "mms",
"modem", "ms-access", "ms-drive-to", "ms-enrollment", "ms-excel",
"ms-getoffice", "ms-help", "ms-infopath", "ms-media-stream-id", "ms-project",
"ms-powerpoint", "ms-publisher", "ms-search-repair",
"ms-secondary-screen-controller", "ms-secondary-screen-setup",
"ms-settings", "ms-settings-airplanemode", "ms-settings-bluetooth",
"ms-settings-camera", "ms-settings-cellular", "ms-settings-cloudstorage",
"ms-settings-emailandaccounts", "ms-settings-language", "ms-settings-location",
"ms-settings-lock", "ms-settings-nfctransactions", "ms-settings-notifications",
"ms-settings-power", "ms-settings-privacy", "ms-settings-proximity",
"ms-settings-screenrotation", "ms-settings-wifi", "ms-settings-workplace",
"ms-spd", "ms-transit-to", "ms-visio", "ms-walk-to", "ms-word", "msnim",
"msrp", "msrps", "mtqp", "mumble", "mupdate", "mvn", "news", "nfs", "ni",
"nih", "nntp", "notes", "oid", "opaquelocktoken", "pack", "palm", "paparazzi",
"pkcs11", "platform", "pop", "pres", "prospero", "proxy", "psyc", "query",
"redis", "rediss", "reload", "res", "resource", "rmi", "rsync", "rtmfp",
"rtmp", "rtsp", "rtsps", "rtspu", "secondlife", "service", "session", "sftp",
"sgn", "shttp", "sieve", "sip", "sips", "skype", "smb", "sms", "smtp",
"snews", "snmp", "soap.beep", "soap.beeps", "soldat", "spotify", "ssh",
"steam", "stun", "stuns", "submit", "svn", "tag", "teamspeak", "tel",
"teliaeid", "telnet", "tftp", "things", "thismessage", "tip", "tn3270",
"tool", "turn", "turns", "tv", "udp", "unreal", "urn", "ut2004", "v-event",
"vemmi", "ventrilo", "videotex", "vnc", "view-source", "wais", "webcal",
"wpid", "ws", "wss", "wtai", "wyciwyg", "xcon", "xcon-userid", "xfire",
"xmlrpc.beep", "xmlrpc.beeps", "xmpp", "xri", "ymsgr", "z39.50", "z39.50r",
"z39.50s:"
};
return list[rand(241)];
}
std::string
pchar()
{
if(rand(4))
return std::string(1,
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
":@&=+$,"[rand(69)]);
std::string s = "%";
s += "0123456789abcdef"[rand(16)];
s += "0123456789abcdef"[rand(16)];
return s;
}
char
uric()
{
return 'a';
}
char
uric_no_slash()
{
return 'a';
}
std::string
param()
{
std::string s;
while(rand(2))
s += pchar();
return s;
}
std::string
query()
{
std::string s;
while(rand(2))
s += uric();
return s;
}
std::string
userinfo()
{
std::string s;
while(rand(2))
s += "a";
return s;
}
/* authority = server | reg_name
reg_name = 1*( unreserved | escaped | "$" | "," |
";" | ":" | "@" | "&" | "=" | "+" )
server = [ [ userinfo "@" ] hostport ]
userinfo = *( unreserved | escaped |
";" | ":" | "&" | "=" | "+" | "$" | "," )
hostport = host [ ":" port ]
host = hostname | IPv4address
hostname = *( domainlabel "." ) toplabel [ "." ]
domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
toplabel = alpha | alpha *( alphanum | "-" ) alphanum
IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit
port = *digit
*/
std::string
server()
{
std::string s;
if(rand(2))
s += userinfo() + "@";
return s;
}
std::string
reg_name()
{
std::string s;
s = "a";
while(rand(2))
s += "a";
return s;
}
std::string
authority()
{
if(rand(2))
return server();
return reg_name();
}
std::string
opaque_part()
{
std::string s;
s += uric_no_slash();
while(rand(2))
s += uric();
return s;
}
/* abs_path = "/" path_segments
path_segments = segment *( "/" segment )
segment = *pchar *( ";" param )
param = *pchar
pchar = unreserved | escaped |
":" | "@" | "&" | "=" | "+" | "$" | ","
*/
std::string
abs_path()
{
std::string s = "/";
for(;;)
{
while(rand(2))
s += pchar();
while(rand(2))
s += ";" + param();
if(rand(2))
break;
s.append("/");
}
return s;
}
/* net_path = "//" authority [ abs_path ]
*/
std::string
net_path()
{
std::string s = "//";
s += authority();
if(rand(2))
s += abs_path();
return s;
}
/* absoluteURI = scheme ":" ( hier_part | opaque_part )
scheme = alpha *( alpha | digit | "+" | "-" | "." )
hier_part = ( net_path | abs_path ) [ "?" query ]
abs_path = "/" path_segments
query = *uric
opaque_part = uric_no_slash *uric
*/
std::string
abs_uri()
{
std::string s;
s = scheme() + ":";
if(rand(2))
{
if(rand(2))
s += net_path();
else
s += abs_path();
if(rand(2))
s += "?" + query();
}
else
{
s += opaque_part();
}
return s;
}
std::string
uri()
{
//switch(rand(4))
switch(1)
{
case 0: return abs_uri();
case 1: return abs_path();
case 2: return authority();
default:
case 3: break;
}
return "*";
}
std::string
token()
{
static char constexpr valid[78] =
"!#$%&\'*+-." "0123456789" "ABCDEFGHIJ" "KLMNOPQRST"
"UVWXYZ^_`a" "bcdefghijk" "lmnopqrstu" "vwxyz|~";
std::string s;
s.append(1, valid[rand(77)]);
while(rand(4))
s.append(1, valid[rand(77)]);
return s;
}
#if 0
std::string
uri()
{
static char constexpr alpha[63] =
"0123456789" "ABCDEFGHIJ" "KLMNOPQRST"
"UVWXYZabcd" "efghijklmn" "opqrstuvwx" "yz";
std::string s;
s = "/";
while(rand(4))
s.append(1, alpha[rand(62)]);
return s;
}
#endif
std::string
field()
{ static char const* const list[289] =
{
"A-IM",
"Accept", "Accept-Additions", "Accept-Charset", "Accept-Datetime", "Accept-Encoding",
"Accept-Features", "Accept-Language", "Accept-Patch", "Accept-Ranges", "Age", "Allow",
"ALPN", "Also-Control", "Alt-Svc", "Alt-Used", "Alternate-Recipient", "Alternates",
"Apply-To-Redirect-Ref", "Approved", "Archive", "Archived-At", "Article-Names",
"Article-Updates", "Authentication-Info", "Authentication-Results", "Authorization",
"Auto-Submitted", "Autoforwarded", "Autosubmitted", "Base", "Bcc", "Body", "C-Ext",
"C-Man", "C-Opt", "C-PEP", "C-PEP-Info", "Cache-Control",
"CalDAV-Timezones", "Cc", "Close", "Comments", /*"Connection",*/ "Content-Alternative",
"Content-Base", "Content-Description", "Content-Disposition", "Content-Duration",
"Content-Encoding", "Content-features", "Content-ID", "Content-Identifier",
"Content-Language", /*"Content-Length",*/ "Content-Location", "Content-MD5",
"Content-Range", "Content-Return", "Content-Script-Type", "Content-Style-Type",
"Content-Transfer-Encoding", "Content-Type", "Content-Version", "Control", "Conversion",
"Conversion-With-Loss", "Cookie", "Cookie2", "DASL", "DAV", "DL-Expansion-History", "Date",
"Date-Received", "Default-Style", "Deferred-Delivery", "Delivery-Date", "Delta-Base",
"Depth", "Derived-From", "Destination", "Differential-ID", "Digest",
"Discarded-X400-IPMS-Extensions", "Discarded-X400-MTS-Extensions", "Disclose-Recipients",
"Disposition-Notification-Options", "Disposition-Notification-To", "Distribution",
"DKIM-Signature", "Downgraded-Bcc", "Downgraded-Cc", "Downgraded-Disposition-Notification-To",
"Downgraded-Final-Recipient", "Downgraded-From", "Downgraded-In-Reply-To",
"Downgraded-Mail-From", "Downgraded-Message-Id", "Downgraded-Original-Recipient",
"Downgraded-Rcpt-To", "Downgraded-References", "Downgraded-Reply-To", "Downgraded-Resent-Bcc",
"Downgraded-Resent-Cc", "Downgraded-Resent-From", "Downgraded-Resent-Reply-To",
"Downgraded-Resent-Sender", "Downgraded-Resent-To", "Downgraded-Return-Path",
"Downgraded-Sender", "Downgraded-To", "Encoding", "Encrypted", "ETag", "Expect",
"Expires", "Expiry-Date", "Ext", "Followup-To", "Forwarded", "From",
"Generate-Delivery-Report", "GetProfile", "Hobareg", "Host", "HTTP2-Settings", "IM", "If",
"If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Schedule-Tag-Match",
"If-Unmodified-Since", "Importance", "In-Reply-To", "Incomplete-Copy", "Injection-Date",
"Injection-Info", "Keep-Alive", "Keywords", "Label", "Language", "Last-Modified",
"Latest-Delivery-Time", "Lines", "Link", "List-Archive", "List-Help", "List-ID",
"List-Owner", "List-Post", "List-Subscribe", "List-Unsubscribe", "Location", "Lock-Token",
"Man", "Max-Forwards", "Memento-Datetime", "Message-Context", "Message-ID", "Message-Type",
"Meter", "MIME-Version", "MMHS-Exempted-Address", "MMHS-Extended-Authorisation-Info",
"MMHS-Subject-Indicator-Codes", "MMHS-Handling-Instructions", "MMHS-Message-Instructions",
"MMHS-Codress-Message-Indicator", "MMHS-Originator-Reference", "MMHS-Primary-Precedence",
"MMHS-Copy-Precedence", "MMHS-Message-Type", "MMHS-Other-Recipients-Indicator-To",
"MMHS-Other-Recipients-Indicator-CC", "MMHS-Acp127-Message-Identifier", "MMHS-Originator-PLAD",
"MT-Priority", "Negotiate", "Newsgroups", "NNTP-Posting-Date", "NNTP-Posting-Host",
"Obsoletes", "Opt", "Ordering-Type", "Organization", "Origin",
"Original-Encoded-Information-Types", "Original-From", "Original-Message-ID",
"Original-Recipient", "Original-Sender", "Originator-Return-Address", "Original-Subject",
"Overwrite", "P3P", "Path", "PEP", "PICS-Label", "Pep-Info", "Position", "Posting-Version",
"Pragma", "Prefer", "Preference-Applied", "Prevent-NonDelivery-Report", "Priority",
"ProfileObject", "Protocol", "Protocol-Info", "Protocol-Query", "Protocol-Request",
"Proxy-Authenticate", "Proxy-Authentication-Info", "Proxy-Authorization", "Proxy-Features",
"Proxy-Instruction", "Public", "Public-Key-Pins", "Public-Key-Pins-Report-Only", "Range",
"Received", "Received-SPF", "Redirect-Ref", "References", "Referer", "Relay-Version",
"Reply-By", "Reply-To", "Require-Recipient-Valid-Since", "Resent-Bcc", "Resent-Cc",
"Resent-Date", "Resent-From", "Resent-Message-ID", "Resent-Reply-To", "Resent-Sender",
"Resent-To", "Retry-After", "Return-Path", "Safe", "Schedule-Reply", "Schedule-Tag",
"Sec-WebSocket-Accept", "Sec-WebSocket-Extensions", "Sec-WebSocket-Key",
"Sec-WebSocket-Protocol", "Sec-WebSocket-Version", "Security-Scheme", "See-Also", "Sender",
"Sensitivity", "Server", "Set-Cookie", "Set-Cookie2",
"SetProfile", "SLUG", "SoapAction", "Solicitation", "Status-URI", "Strict-Transport-Security",
"Subject", "Summary", "Supersedes", "Surrogate-Capability", "Surrogate-Control", "TCN",
"TE", "Timeout", "To", "Trailer", /*"Transfer-Encoding",*/ "URI", /*"Upgrade",*/ "User-Agent",
"Variant-Vary", "Vary", "VBR-Info", "Via", "WWW-Authenticate", "Want-Digest", "Warning",
"X400-Content-Identifier", "X400-Content-Return", "X400-Content-Type", "X400-MTS-Identifier",
"X400-Originator", "X400-Received", "X400-Recipients", "X400-Trace", "X-Frame-Options", "Xref"
};
return list[rand(289)];
}
std::string
text()
{
std::string s;
while(rand(3))
{
for(;;)
{
char c = rand<char>(256);
if(detail::is_text(c))
{
s.append(1, c);
break;
}
}
}
return s;
}
std::string
value()
{
std::string s;
while(rand(3))
{
if(rand(5))
{
s.append(text());
}
else
{
// LWS
if(! rand(4))
s.append("\r\n");
s.append(1, rand(2) ? ' ' : '\t');
while(rand(2))
s.append(1, rand(2) ? ' ' : '\t');
}
}
return s;
}
template<class Streambuf>
void
headers(Streambuf& sb)
{
while(rand(6))
{
write(sb, field());
write(sb, rand(4) ? ": " : ":");
write(sb, value());
write(sb, "\r\n");
}
}
template<class Streambuf>
void
body(Streambuf& sb)
{
if(! rand(4))
{
write(sb, "Content-Length: 0\r\n\r\n");
return;
}
if(rand(2))
{
auto const len = rand(500);
write(sb, "Content-Length: ", len, "\r\n\r\n");
for(auto const& b : sb.prepare(len))
{
auto p = boost::asio::buffer_cast<char*>(b);
auto n = boost::asio::buffer_size(b);
while(n--)
*p++ = static_cast<char>(32 + rand(26+26+10+6));
}
sb.commit(len);
}
else
{
auto len = rand(500);
write(sb, "Transfer-Encoding: chunked\r\n\r\n");
while(len > 0)
{
auto n = std::min(1 + rand(300), len);
len -= n;
write(sb, to_hex(n), "\r\n");
for(auto const& b : sb.prepare(n))
{
auto p = boost::asio::buffer_cast<char*>(b);
auto m = boost::asio::buffer_size(b);
while(m--)
*p++ = static_cast<char>(32 + rand(26+26+10+6));
}
sb.commit(n);
write(sb, "\r\n");
}
write(sb, "0\r\n\r\n");
}
}
template<class Streambuf>
void
request(Streambuf& sb)
{
write(sb, method(), " ", uri(), " HTTP/1.1\r\n");
headers(sb);
body(sb);
}
template<class Streambuf>
void
response(Streambuf& sb)
{
write(sb, "HTTP/1.");
write(sb, rand(2) ? "0" : "1");
write(sb, " ", 100 + rand(401), " ");
write(sb, token());
write(sb, "\r\n");
headers(sb);
body(sb);
write(sb, "\r\n");
}
};
using message_fuzz = message_fuzz_t<>;
} // http
} // beast
#endif
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/method.hpp>
+68
View File
@@ -0,0 +1,68 @@
# Authors ordered by first contribution.
Ryan Dahl <ry@tinyclouds.org>
Jeremy Hinegardner <jeremy@hinegardner.org>
Sergey Shepelev <temotor@gmail.com>
Joe Damato <ice799@gmail.com>
tomika <tomika_nospam@freemail.hu>
Phoenix Sol <phoenix@burninglabs.com>
Cliff Frey <cliff@meraki.com>
Ewen Cheslack-Postava <ewencp@cs.stanford.edu>
Santiago Gala <sgala@apache.org>
Tim Becker <tim.becker@syngenio.de>
Jeff Terrace <jterrace@gmail.com>
Ben Noordhuis <info@bnoordhuis.nl>
Nathan Rajlich <nathan@tootallnate.net>
Mark Nottingham <mnot@mnot.net>
Aman Gupta <aman@tmm1.net>
Tim Becker <tim.becker@kuriositaet.de>
Sean Cunningham <sean.cunningham@mandiant.com>
Peter Griess <pg@std.in>
Salman Haq <salman.haq@asti-usa.com>
Cliff Frey <clifffrey@gmail.com>
Jon Kolb <jon@b0g.us>
Fouad Mardini <f.mardini@gmail.com>
Paul Querna <pquerna@apache.org>
Felix Geisendörfer <felix@debuggable.com>
koichik <koichik@improvement.jp>
Andre Caron <andre.l.caron@gmail.com>
Ivo Raisr <ivosh@ivosh.net>
James McLaughlin <jamie@lacewing-project.org>
David Gwynne <loki@animata.net>
Thomas LE ROUX <thomas@november-eleven.fr>
Randy Rizun <rrizun@ortivawireless.com>
Andre Louis Caron <andre.louis.caron@usherbrooke.ca>
Simon Zimmermann <simonz05@gmail.com>
Erik Dubbelboer <erik@dubbelboer.com>
Martell Malone <martellmalone@gmail.com>
Bertrand Paquet <bpaquet@octo.com>
BogDan Vatra <bogdan@kde.org>
Peter Faiman <peter@thepicard.org>
Corey Richardson <corey@octayn.net>
Tóth Tamás <tomika_nospam@freemail.hu>
Cam Swords <cam.swords@gmail.com>
Chris Dickinson <christopher.s.dickinson@gmail.com>
Uli Köhler <ukoehler@btronik.de>
Charlie Somerville <charlie@charliesomerville.com>
Patrik Stutz <patrik.stutz@gmail.com>
Fedor Indutny <fedor.indutny@gmail.com>
runner <runner.mei@gmail.com>
Alexis Campailla <alexis@janeasystems.com>
David Wragg <david@wragg.org>
Vinnie Falco <vinnie.falco@gmail.com>
Alex Butum <alexbutum@linux.com>
Rex Feng <rexfeng@gmail.com>
Alex Kocharin <alex@kocharin.ru>
Mark Koopman <markmontymark@yahoo.com>
Helge Heß <me@helgehess.eu>
Alexis La Goutte <alexis.lagoutte@gmail.com>
George Miroshnykov <george.miroshnykov@gmail.com>
Maciej Małecki <me@mmalecki.com>
Marc O'Morain <github.com@marcomorain.com>
Jeff Pinner <jpinner@twitter.com>
Timothy J Fontaine <tjfontaine@gmail.com>
Akagi201 <akagi201@gmail.com>
Romain Giraud <giraud.romain@gmail.com>
Jay Satiro <raysatiro@yahoo.com>
Arne Steen <Arne.Steen@gmx.de>
Kjell Schubert <kjell.schubert@gmail.com>
Olivier Mengué <dolmen@cpan.org>
+23
View File
@@ -0,0 +1,23 @@
http_parser.c is 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.
+246
View File
@@ -0,0 +1,246 @@
HTTP Parser
===========
[![Build Status](https://api.travis-ci.org/nodejs/http-parser.svg?branch=master)](https://travis-ci.org/nodejs/http-parser)
This is a parser for HTTP messages written in C. It parses both requests and
responses. The parser is designed to be used in performance HTTP
applications. It does not make any syscalls nor allocations, it does not
buffer data, it can be interrupted at anytime. Depending on your
architecture, it only requires about 40 bytes of data per message
stream (in a web server that is per connection).
Features:
* No dependencies
* Handles persistent streams (keep-alive).
* Decodes chunked encoding.
* Upgrade support
* Defends against buffer overflow attacks.
The parser extracts the following information from HTTP messages:
* Header fields and values
* Content-Length
* Request method
* Response status code
* Transfer-Encoding
* HTTP version
* Request URL
* Message body
Usage
-----
One `http_parser` object is used per TCP connection. Initialize the struct
using `http_parser_init()` and set the callbacks. That might look something
like this for a request parser:
```c
http_parser_settings settings;
settings.on_url = my_url_callback;
settings.on_header_field = my_header_field_callback;
/* ... */
http_parser *parser = malloc(sizeof(http_parser));
http_parser_init(parser, HTTP_REQUEST);
parser->data = my_socket;
```
When data is received on the socket execute the parser and check for errors.
```c
size_t len = 80*1024, nparsed;
char buf[len];
ssize_t recved;
recved = recv(fd, buf, len, 0);
if (recved < 0) {
/* Handle error. */
}
/* Start up / continue the parser.
* Note we pass recved==0 to signal that EOF has been received.
*/
nparsed = http_parser_execute(parser, &settings, buf, recved);
if (parser->upgrade) {
/* handle new protocol */
} else if (nparsed != recved) {
/* Handle error. Usually just close the connection. */
}
```
HTTP needs to know where the end of the stream is. For example, sometimes
servers send responses without Content-Length and expect the client to
consume input (for the body) until EOF. To tell http_parser about EOF, give
`0` as the fourth parameter to `http_parser_execute()`. Callbacks and errors
can still be encountered during an EOF, so one must still be prepared
to receive them.
Scalar valued message information such as `status_code`, `method`, and the
HTTP version are stored in the parser structure. This data is only
temporally stored in `http_parser` and gets reset on each new message. If
this information is needed later, copy it out of the structure during the
`headers_complete` callback.
The parser decodes the transfer-encoding for both requests and responses
transparently. That is, a chunked encoding is decoded before being sent to
the on_body callback.
The Special Problem of Upgrade
------------------------------
HTTP supports upgrading the connection to a different protocol. An
increasingly common example of this is the WebSocket protocol which sends
a request like
GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
WebSocket-Protocol: sample
followed by non-HTTP data.
(See [RFC6455](https://tools.ietf.org/html/rfc6455) for more information the
WebSocket protocol.)
To support this, the parser will treat this as a normal HTTP message without a
body, issuing both on_headers_complete and on_message_complete callbacks. However
http_parser_execute() will stop parsing at the end of the headers and return.
The user is expected to check if `parser->upgrade` has been set to 1 after
`http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied
offset by the return value of `http_parser_execute()`.
Callbacks
---------
During the `http_parser_execute()` call, the callbacks set in
`http_parser_settings` will be executed. The parser maintains state and
never looks behind, so buffering the data is not necessary. If you need to
save certain data for later usage, you can do that from the callbacks.
There are two types of callbacks:
* notification `typedef int (*http_cb) (http_parser*);`
Callbacks: on_message_begin, on_headers_complete, on_message_complete.
* data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);`
Callbacks: (requests only) on_url,
(common) on_header_field, on_header_value, on_body;
Callbacks must return 0 on success. Returning a non-zero value indicates
error to the parser, making it exit immediately.
For cases where it is necessary to pass local information to/from a callback,
the `http_parser` object's `data` field can be used.
An example of such a case is when using threads to handle a socket connection,
parse a request, and then give a response over that socket. By instantiation
of a thread-local struct containing relevant data (e.g. accepted socket,
allocated memory for callbacks to write into, etc), a parser's callbacks are
able to communicate data between the scope of the thread and the scope of the
callback in a threadsafe manner. This allows http-parser to be used in
multi-threaded contexts.
Example:
```
typedef struct {
socket_t sock;
void* buffer;
int buf_len;
} custom_data_t;
int my_url_callback(http_parser* parser, const char *at, size_t length) {
/* access to thread local custom_data_t struct.
Use this access save parsed data for later use into thread local
buffer, or communicate over socket
*/
parser->data;
...
return 0;
}
...
void http_parser_thread(socket_t sock) {
int nparsed = 0;
/* allocate memory for user data */
custom_data_t *my_data = malloc(sizeof(custom_data_t));
/* some information for use by callbacks.
* achieves thread -> callback information flow */
my_data->sock = sock;
/* instantiate a thread-local parser */
http_parser *parser = malloc(sizeof(http_parser));
http_parser_init(parser, HTTP_REQUEST); /* initialise parser */
/* this custom data reference is accessible through the reference to the
parser supplied to callback functions */
parser->data = my_data;
http_parser_settings settings; / * set up callbacks */
settings.on_url = my_url_callback;
/* execute parser */
nparsed = http_parser_execute(parser, &settings, buf, recved);
...
/* parsed information copied from callback.
can now perform action on data copied into thread-local memory from callbacks.
achieves callback -> thread information flow */
my_data->buffer;
...
}
```
In case you parse HTTP message in chunks (i.e. `read()` request line
from socket, parse, read half headers, parse, etc) your data callbacks
may be called more than once. Http-parser guarantees that data pointer is only
valid for the lifetime of callback. You can also `read()` into a heap allocated
buffer to avoid copying memory around if this fits your application.
Reading headers may be a tricky task if you read/parse headers partially.
Basically, you need to remember whether last header callback was field or value
and apply the following logic:
(on_header_field and on_header_value shortened to on_h_*)
------------------------ ------------ --------------------------------------------
| State (prev. callback) | Callback | Description/action |
------------------------ ------------ --------------------------------------------
| nothing (first call) | on_h_field | Allocate new buffer and copy callback data |
| | | into it |
------------------------ ------------ --------------------------------------------
| value | on_h_field | New header started. |
| | | Copy current name,value buffers to headers |
| | | list and allocate new buffer for new name |
------------------------ ------------ --------------------------------------------
| field | on_h_field | Previous name continues. Reallocate name |
| | | buffer and append callback data to it |
------------------------ ------------ --------------------------------------------
| field | on_h_value | Value for current header started. Allocate |
| | | new buffer and copy callback data to it |
------------------------ ------------ --------------------------------------------
| value | on_h_value | Value continues. Reallocate value buffer |
| | | and append callback data to it |
------------------------ ------------ --------------------------------------------
Parsing URLs
------------
A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`.
Users of this library may wish to use it to parse URLs constructed from
consecutive `on_url` callbacks.
See examples of reading in headers:
* [partial example](http://gist.github.com/155877) in C
* [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C
* [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript
File diff suppressed because it is too large. Load diff
+362
View File
@@ -0,0 +1,362 @@
/* 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.
*/
#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 7
#define HTTP_PARSER_VERSION_PATCH 0
#include <sys/types.h>
#if defined(_WIN32) && !defined(__MINGW32__) && \
(!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
#include <BaseTsd.h>
#include <stddef.h>
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
* faster
*/
#ifndef HTTP_PARSER_STRICT
# define HTTP_PARSER_STRICT 1
#endif
/* Maximium header size allowed. If the macro is not defined
* before including this header then the default is used. To
* change the maximum header size, define the macro in the build
* environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
* the effective limit on the size of the header, define the macro
* to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
*/
#ifndef HTTP_MAX_HEADER_SIZE
# define HTTP_MAX_HEADER_SIZE (80*1024)
#endif
typedef struct http_parser http_parser;
typedef struct http_parser_settings http_parser_settings;
/* Callbacks should return non-zero to indicate an error. The parser will
* then halt execution.
*
* The one exception is on_headers_complete. In a HTTP_RESPONSE parser
* returning '1' from on_headers_complete will tell the parser that it
* should not expect a body. This is used when receiving a response to a
* 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.
*/
typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
typedef int (*http_cb) (http_parser*);
/* Request Methods */
#define HTTP_METHOD_MAP(XX) \
XX(0, DELETE, DELETE) \
XX(1, GET, GET) \
XX(2, HEAD, HEAD) \
XX(3, POST, POST) \
XX(4, PUT, PUT) \
/* pathological */ \
XX(5, CONNECT, CONNECT) \
XX(6, OPTIONS, OPTIONS) \
XX(7, TRACE, TRACE) \
/* WebDAV */ \
XX(8, COPY, COPY) \
XX(9, LOCK, LOCK) \
XX(10, MKCOL, MKCOL) \
XX(11, MOVE, MOVE) \
XX(12, PROPFIND, PROPFIND) \
XX(13, PROPPATCH, PROPPATCH) \
XX(14, SEARCH, SEARCH) \
XX(15, UNLOCK, UNLOCK) \
XX(16, BIND, BIND) \
XX(17, REBIND, REBIND) \
XX(18, UNBIND, UNBIND) \
XX(19, ACL, ACL) \
/* subversion */ \
XX(20, REPORT, REPORT) \
XX(21, MKACTIVITY, MKACTIVITY) \
XX(22, CHECKOUT, CHECKOUT) \
XX(23, MERGE, MERGE) \
/* upnp */ \
XX(24, MSEARCH, M-SEARCH) \
XX(25, NOTIFY, NOTIFY) \
XX(26, SUBSCRIBE, SUBSCRIBE) \
XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \
/* RFC-5789 */ \
XX(28, PATCH, PATCH) \
XX(29, PURGE, PURGE) \
/* CalDAV */ \
XX(30, MKCALENDAR, MKCALENDAR) \
/* RFC-2068, section 19.6.1.2 */ \
XX(31, LINK, LINK) \
XX(32, UNLINK, UNLINK) \
enum http_method
{
#define XX(num, name, string) HTTP_##name = num,
HTTP_METHOD_MAP(XX)
#undef XX
};
enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
/* Flag values for http_parser.flags field */
enum flags
{ F_CHUNKED = 1 << 0
, F_CONNECTION_KEEP_ALIVE = 1 << 1
, F_CONNECTION_CLOSE = 1 << 2
, F_CONNECTION_UPGRADE = 1 << 3
, F_TRAILING = 1 << 4
, F_UPGRADE = 1 << 5
, F_SKIPBODY = 1 << 6
, F_CONTENTLENGTH = 1 << 7
};
/* Map for errno-related constants
*
* The provided argument should be a macro that takes 2 arguments.
*/
#define HTTP_ERRNO_MAP(XX) \
/* No error */ \
XX(OK, "success") \
\
/* Callback-related errors */ \
XX(CB_message_begin, "the on_message_begin callback failed") \
XX(CB_url, "the on_url callback failed") \
XX(CB_header_field, "the on_header_field callback failed") \
XX(CB_header_value, "the on_header_value callback failed") \
XX(CB_headers_complete, "the on_headers_complete callback failed") \
XX(CB_body, "the on_body callback failed") \
XX(CB_message_complete, "the on_message_complete callback failed") \
XX(CB_status, "the on_status callback failed") \
XX(CB_chunk_header, "the on_chunk_header callback failed") \
XX(CB_chunk_complete, "the on_chunk_complete callback failed") \
\
/* Parsing-related errors */ \
XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
XX(HEADER_OVERFLOW, \
"too many header bytes seen; overflow detected") \
XX(CLOSED_CONNECTION, \
"data received after completed connection: close message") \
XX(INVALID_VERSION, "invalid HTTP version") \
XX(INVALID_STATUS, "invalid HTTP status code") \
XX(INVALID_METHOD, "invalid HTTP method") \
XX(INVALID_URL, "invalid URL") \
XX(INVALID_HOST, "invalid host") \
XX(INVALID_PORT, "invalid port") \
XX(INVALID_PATH, "invalid path") \
XX(INVALID_QUERY_STRING, "invalid query string") \
XX(INVALID_FRAGMENT, "invalid fragment") \
XX(LF_EXPECTED, "LF character expected") \
XX(INVALID_HEADER_TOKEN, "invalid character in header") \
XX(INVALID_CONTENT_LENGTH, \
"invalid character in content-length header") \
XX(UNEXPECTED_CONTENT_LENGTH, \
"unexpected content-length header") \
XX(INVALID_CHUNK_SIZE, \
"invalid character in chunk size header") \
XX(INVALID_CONSTANT, "invalid constant string") \
XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
XX(STRICT, "strict mode assertion failed") \
XX(PAUSED, "parser is paused") \
XX(UNKNOWN, "an unknown error occurred")
/* Define HPE_* values for each errno value above */
#define HTTP_ERRNO_GEN(n, s) HPE_##n,
enum http_errno {
HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
};
#undef HTTP_ERRNO_GEN
/* Get an http_errno value from an http_parser */
#define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno)
struct http_parser {
/** PRIVATE **/
unsigned int type : 2; /* enum http_parser_type */
unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */
unsigned int state : 7; /* enum state from http_parser.c */
unsigned int header_state : 7; /* enum header_state from http_parser.c */
unsigned int index : 7; /* index into current matcher */
unsigned int lenient_http_headers : 1;
uint32_t nread; /* # bytes read in various scenarios */
uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
/** READ-ONLY **/
unsigned short http_major;
unsigned short http_minor;
unsigned int status_code : 16; /* responses only */
unsigned int method : 8; /* requests only */
unsigned int http_errno : 7;
/* 1 = Upgrade header was present and the parser has exited because of that.
* 0 = No upgrade header present.
* Should be checked when http_parser_execute() returns in addition to
* error checking.
*/
unsigned int upgrade : 1;
/** PUBLIC **/
void *data; /* A pointer to get hook to the "connection" or "socket" object */
};
struct http_parser_settings {
http_cb on_message_begin;
http_data_cb on_url;
http_data_cb on_status;
http_data_cb on_header_field;
http_data_cb on_header_value;
http_cb on_headers_complete;
http_data_cb on_body;
http_cb on_message_complete;
/* When on_chunk_header is called, the current chunk length is stored
* in parser->content_length.
*/
http_cb on_chunk_header;
http_cb on_chunk_complete;
};
enum http_parser_url_fields
{ UF_SCHEMA = 0
, UF_HOST = 1
, UF_PORT = 2
, UF_PATH = 3
, UF_QUERY = 4
, UF_FRAGMENT = 5
, UF_USERINFO = 6
, UF_MAX = 7
};
/* Result structure for http_parser_parse_url().
*
* Callers should index into field_data[] with UF_* values iff field_set
* has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
* because we probably have padding left over), we convert any port to
* a uint16_t.
*/
struct http_parser_url {
uint16_t field_set; /* Bitmask of (1 << UF_*) values */
uint16_t port; /* Converted UF_PORT string */
struct {
uint16_t off; /* Offset into buffer in which field starts */
uint16_t len; /* Length of run in buffer */
} field_data[UF_MAX];
};
/* Returns the library version. Bits 16-23 contain the major version number,
* bits 8-15 the minor version number and bits 0-7 the patch level.
* Usage example:
*
* unsigned long version = http_parser_version();
* unsigned major = (version >> 16) & 255;
* unsigned minor = (version >> 8) & 255;
* unsigned patch = version & 255;
* printf("http_parser v%u.%u.%u\n", major, minor, patch);
*/
unsigned long http_parser_version(void);
void http_parser_init(http_parser *parser, enum http_parser_type type);
/* Initialize http_parser_settings members to 0
*/
void http_parser_settings_init(http_parser_settings *settings);
/* Executes the parser. Returns number of parsed bytes. Sets
* `parser->http_errno` on error. */
size_t http_parser_execute(http_parser *parser,
const http_parser_settings *settings,
const char *data,
size_t len);
/* If http_should_keep_alive() in the on_headers_complete or
* on_message_complete callback returns 0, then this should be
* the last message on the connection.
* If you are the server, respond with the "Connection: close" header.
* If you are the client, close the connection.
*/
int http_should_keep_alive(const http_parser *parser);
/* Returns a string version of the HTTP method. */
const char *http_method_str(enum http_method m);
/* Return a string name of the given error */
const char *http_errno_name(enum http_errno err);
/* Return a string description of the given error */
const char *http_errno_description(enum http_errno err);
/* Initialize all http_parser_url members to 0 */
void http_parser_url_init(struct http_parser_url *u);
/* Parse a URL; return nonzero on failure */
int http_parser_parse_url(const char *buf, size_t buflen,
int is_connect,
struct http_parser_url *u);
/* Pause or un-pause the parser; a nonzero value pauses */
void http_parser_pause(http_parser *parser, int paused);
/* Checks if this is the final chunk of the body. */
int http_body_is_final(const http_parser *parser);
#ifdef __cplusplus
}
#endif
#endif
+17
View File
@@ -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 "nodejs-parser/http_parser.c"
#ifdef _MSC_VER
# pragma warning (pop)
#endif
+881
View File
@@ -0,0 +1,881 @@
//
// 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_NODEJS_PARSER_HPP
#define BEAST_HTTP_NODEJS_PARSER_HPP
#include "nodejs-parser/http_parser.h"
#include <beast/http/method.hpp>
#include <beast/http/basic_parser.hpp>
#include <beast/http/rfc2616.hpp>
#include <beast/type_check.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/system/error_code.hpp>
#include <cstdint>
#include <string>
#include <type_traits>
namespace beast {
namespace http {
namespace detail {
class nodejs_message_category
: public boost::system::error_category
{
public:
const char*
name() const noexcept override
{
return "nodejs-http-error";
}
std::string
message(int ev) const override
{
return http_errno_description(
static_cast<http_errno>(ev));
}
boost::system::error_condition
default_error_condition(int ev) const noexcept override
{
return boost::system::error_condition{ev, *this};
}
bool
equivalent(int ev,
boost::system::error_condition const& condition
) const noexcept override
{
return condition.value() == ev &&
&condition.category() == this;
}
bool
equivalent(boost::system::error_code const& error,
int ev) const noexcept override
{
return error.value() == ev &&
&error.category() == this;
}
};
template<class = void>
boost::system::error_code
make_nodejs_error(int http_errno)
{
static nodejs_message_category const mc{};
return boost::system::error_code{http_errno, mc};
}
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<class Derived>
class nodejs_basic_parser
{
http_parser state_;
boost::system::error_code* ec_;
bool complete_ = false;
std::string url_;
std::string status_;
std::string field_;
std::string value_;
public:
using error_code = boost::system::error_code;
nodejs_basic_parser(nodejs_basic_parser&& other);
nodejs_basic_parser&
operator=(nodejs_basic_parser&& other);
nodejs_basic_parser(nodejs_basic_parser const& other);
nodejs_basic_parser& operator=(nodejs_basic_parser const& other);
explicit
nodejs_basic_parser(bool request) noexcept;
bool
complete() const noexcept
{
return complete_;
}
std::size_t
write(void const* data, std::size_t size)
{
error_code ec;
auto const used = write(data, size, ec);
if(ec)
throw boost::system::system_error{ec};
return used;
}
std::size_t
write(void const* data, std::size_t size,
error_code& ec);
template<class ConstBufferSequence>
std::size_t
write(ConstBufferSequence const& buffers)
{
error_code ec;
auto const used = write(buffers, ec);
if(ec)
throw boost::system::system_error{ec};
return used;
}
template<class ConstBufferSequence>
std::size_t
write(ConstBufferSequence const& buffers,
error_code& ec);
void
write_eof()
{
error_code ec;
write_eof(ec);
if(ec)
throw boost::system::system_error{ec};
}
void
write_eof(error_code& ec);
private:
Derived&
impl()
{
return *static_cast<Derived*>(this);
}
template<class C>
class has_on_start_t
{
template<class T, class R =
decltype(std::declval<T>().on_start(), std::true_type{})>
static R check(int);
template <class>
static std::false_type check(...);
using type = decltype(check<C>(0));
public:
static bool const value = type::value;
};
template<class C>
using has_on_start =
std::integral_constant<bool, has_on_start_t<C>::value>;
void
call_on_start(std::true_type)
{
impl().on_start();
}
void
call_on_start(std::false_type)
{
}
template<class C>
class has_on_field_t
{
template<class T, class R =
decltype(std::declval<T>().on_field(
std::declval<std::string const&>(),
std::declval<std::string const&>()),
std::true_type{})>
static R check(int);
template <class>
static std::false_type check(...);
using type = decltype(check<C>(0));
public:
static bool const value = type::value;
};
template<class C>
using has_on_field =
std::integral_constant<bool, has_on_field_t<C>::value>;
void
call_on_field(std::string const& field,
std::string const& value, std::true_type)
{
impl().on_field(field, value);
}
void
call_on_field(std::string const&, std::string const&,
std::false_type)
{
}
template<class C>
class has_on_headers_complete_t
{
template<class T, class R =
decltype(std::declval<T>().on_headers_complete(
std::declval<error_code&>()), std::true_type{})>
static R check(int);
template <class>
static std::false_type check(...);
using type = decltype(check<C>(0));
public:
static bool const value = type::value;
};
template<class C>
using has_on_headers_complete =
std::integral_constant<bool, has_on_headers_complete_t<C>::value>;
void
call_on_headers_complete(error_code& ec, std::true_type)
{
impl().on_headers_complete(ec);
}
void
call_on_headers_complete(error_code&, std::false_type)
{
}
template<class C>
class has_on_request_t
{
template<class T, class R =
decltype(std::declval<T>().on_request(
std::declval<method_t>(), std::declval<std::string>(),
std::declval<int>(), std::declval<int>(),
std::declval<bool>(), std::declval<bool>()),
std::true_type{})>
static R check(int);
template <class>
static std::false_type check(...);
using type = decltype(check<C>(0));
public:
static bool const value = type::value;
};
template<class C>
using has_on_request =
std::integral_constant<bool, has_on_request_t<C>::value>;
void
call_on_request(method_t method, std::string url,
int major, int minor, bool keep_alive, bool upgrade,
std::true_type)
{
impl().on_request(
method, url, major, minor, keep_alive, upgrade);
}
void
call_on_request(method_t, std::string, int, int, bool, bool,
std::false_type)
{
}
template<class C>
class has_on_response_t
{
template<class T, class R =
decltype(std::declval<T>().on_response(
std::declval<int>(), std::declval<std::string>,
std::declval<int>(), std::declval<int>(),
std::declval<bool>(), std::declval<bool>()),
std::true_type{})>
static R check(int);
template <class>
static std::false_type check(...);
#if 0
using type = decltype(check<C>(0));
#else
// VFALCO Trait seems broken for http::parser
using type = std::true_type;
#endif
public:
static bool const value = type::value;
};
template<class C>
using has_on_response =
std::integral_constant<bool, has_on_response_t<C>::value>;
bool
call_on_response(int status, std::string text,
int major, int minor, bool keep_alive, bool upgrade,
std::true_type)
{
return impl().on_response(
status, text, major, minor, keep_alive, upgrade);
}
bool
call_on_response(int, std::string, int, int, bool, bool,
std::false_type)
{
// VFALCO Certainly incorrect
return true;
}
template<class C>
class has_on_body_t
{
template<class T, class R =
decltype(std::declval<T>().on_body(
std::declval<void const*>(), std::declval<std::size_t>(),
std::declval<error_code&>()), std::true_type{})>
static R check(int);
template <class>
static std::false_type check(...);
using type = decltype(check<C>(0));
public:
static bool const value = type::value;
};
template<class C>
using has_on_body =
std::integral_constant<bool, has_on_body_t<C>::value>;
void
call_on_body(void const* data, std::size_t bytes,
error_code& ec, std::true_type)
{
impl().on_body(data, bytes, ec);
}
void
call_on_body(void const*, std::size_t,
error_code&, std::false_type)
{
}
template<class C>
class has_on_complete_t
{
template<class T, class R =
decltype(std::declval<T>().on_complete(), std::true_type{})>
static R check(int);
template <class>
static std::false_type check(...);
using type = decltype(check<C>(0));
public:
static bool const value = type::value;
};
template<class C>
using has_on_complete =
std::integral_constant<bool, has_on_complete_t<C>::value>;
void
call_on_complete(std::true_type)
{
impl().on_complete();
}
void
call_on_complete(std::false_type)
{
}
void
check_header();
static int cb_message_start(http_parser*);
static int cb_url(http_parser*, char const*, std::size_t);
static int cb_status(http_parser*, char const*, std::size_t);
static int cb_header_field(http_parser*, char const*, std::size_t);
static int cb_header_value(http_parser*, char const*, std::size_t);
static int cb_headers_complete(http_parser*);
static int cb_body(http_parser*, char const*, std::size_t);
static int cb_message_complete(http_parser*);
static int cb_chunk_header(http_parser*);
static int cb_chunk_complete(http_parser*);
struct hooks_t : http_parser_settings
{
hooks_t()
{
http_parser_settings_init(this);
on_message_begin = &nodejs_basic_parser::cb_message_start;
on_url = &nodejs_basic_parser::cb_url;
on_status = &nodejs_basic_parser::cb_status;
on_header_field = &nodejs_basic_parser::cb_header_field;
on_header_value = &nodejs_basic_parser::cb_header_value;
on_headers_complete = &nodejs_basic_parser::cb_headers_complete;
on_body = &nodejs_basic_parser::cb_body;
on_message_complete = &nodejs_basic_parser::cb_message_complete;
on_chunk_header = &nodejs_basic_parser::cb_chunk_header;
on_chunk_complete = &nodejs_basic_parser::cb_chunk_complete;
}
};
static
http_parser_settings const*
hooks();
};
template<class Derived>
template<class ConstBufferSequence>
std::size_t
nodejs_basic_parser<Derived>::write(
ConstBufferSequence const& buffers, error_code& ec)
{
static_assert(beast::is_ConstBufferSequence<
ConstBufferSequence>::value,
"ConstBufferSequence requirements not met");
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
std::size_t bytes_used = 0;
for (auto const& buffer : buffers)
{
auto const n = write(
buffer_cast<void const*>(buffer),
buffer_size(buffer), ec);
if(ec)
return 0;
bytes_used += n;
if(complete())
break;
}
return bytes_used;
}
template<class Derived>
http_parser_settings const*
nodejs_basic_parser<Derived>::hooks()
{
static hooks_t const h;
return &h;
}
template<class Derived>
nodejs_basic_parser<Derived>::
nodejs_basic_parser(nodejs_basic_parser&& other)
{
state_ = other.state_;
state_.data = this;
complete_ = other.complete_;
url_ = std::move(other.url_);
status_ = std::move(other.status_);
field_ = std::move(other.field_);
value_ = std::move(other.value_);
}
template<class Derived>
auto
nodejs_basic_parser<Derived>::operator=(nodejs_basic_parser&& other) ->
nodejs_basic_parser&
{
state_ = other.state_;
state_.data = this;
complete_ = other.complete_;
url_ = std::move(other.url_);
status_ = std::move(other.status_);
field_ = std::move(other.field_);
value_ = std::move(other.value_);
return *this;
}
template<class Derived>
nodejs_basic_parser<Derived>::
nodejs_basic_parser(nodejs_basic_parser const& other)
{
state_ = other.state_;
state_.data = this;
complete_ = other.complete_;
url_ = other.url_;
status_ = other.status_;
field_ = other.field_;
value_ = other.value_;
}
template<class Derived>
auto
nodejs_basic_parser<Derived>::
operator=(nodejs_basic_parser const& other) ->
nodejs_basic_parser&
{
state_ = other.state_;
state_.data = this;
complete_ = other.complete_;
url_ = other.url_;
status_ = other.status_;
field_ = other.field_;
value_ = other.value_;
return *this;
}
template<class Derived>
nodejs_basic_parser<Derived>::nodejs_basic_parser(bool request) noexcept
{
state_.data = this;
http_parser_init(&state_, request
? http_parser_type::HTTP_REQUEST
: http_parser_type::HTTP_RESPONSE);
}
template<class Derived>
std::size_t
nodejs_basic_parser<Derived>::write(void const* data,
std::size_t size, error_code& ec)
{
ec_ = &ec;
auto const n = http_parser_execute(
&state_, hooks(),
static_cast<const char*>(data), size);
if(! ec)
ec = detail::make_nodejs_error(
static_cast<int>(state_.http_errno));
if(ec)
return 0;
return n;
}
template<class Derived>
void
nodejs_basic_parser<Derived>::write_eof(error_code& ec)
{
ec_ = &ec;
http_parser_execute(
&state_, hooks(), nullptr, 0);
if(! ec)
ec = detail::make_nodejs_error(
static_cast<int>(state_.http_errno));
}
template<class Derived>
void
nodejs_basic_parser<Derived>::check_header()
{
if (! value_.empty())
{
rfc2616::trim_right_in_place(value_);
call_on_field(field_, value_,
has_on_field<Derived>{});
field_.clear();
value_.clear();
}
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_message_start(http_parser* p)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.complete_ = false;
t.url_.clear();
t.status_.clear();
t.field_.clear();
t.value_.clear();
t.call_on_start(has_on_start<Derived>{});
return 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_url(http_parser* p,
char const* in, std::size_t bytes)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.url_.append(in, bytes);
return 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_status(http_parser* p,
char const* in, std::size_t bytes)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.status_.append(in, bytes);
return 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_header_field(http_parser* p,
char const* in, std::size_t bytes)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.check_header();
t.field_.append(in, bytes);
return 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_header_value(http_parser* p,
char const* in, std::size_t bytes)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.value_.append(in, bytes);
return 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_headers_complete(http_parser* p)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.check_header();
t.call_on_headers_complete(*t.ec_,
has_on_headers_complete<Derived>{});
if(*t.ec_)
return 1;
bool const keep_alive =
http_should_keep_alive(p) != 0;
if(p->type == http_parser_type::HTTP_REQUEST)
{
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<Derived>{});
return 0;
}
return t.call_on_response(p->status_code, t.status_,
p->http_major, p->http_minor, keep_alive,
p->upgrade, has_on_response<Derived>{}) ? 0 : 1;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_body(http_parser* p,
char const* in, std::size_t bytes)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.call_on_body(in, bytes, *t.ec_, has_on_body<Derived>{});
return *t.ec_ ? 1 : 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_message_complete(http_parser* p)
{
auto& t = *reinterpret_cast<nodejs_basic_parser*>(p->data);
t.complete_ = true;
t.call_on_complete(has_on_complete<Derived>{});
return 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_chunk_header(http_parser*)
{
return 0;
}
template<class Derived>
int
nodejs_basic_parser<Derived>::cb_chunk_complete(http_parser*)
{
return 0;
}
} // http
} // beast
#include <beast/http/error.hpp>
#include <beast/http/message.hpp>
#include <boost/optional.hpp>
#include <functional>
#include <type_traits>
#include <utility>
namespace beast {
namespace http {
/** A HTTP parser.
The parser may only be used once.
*/
template<bool isRequest, class Body, class Headers>
class nodejs_parser
: public nodejs_basic_parser<nodejs_parser<isRequest, Body, Headers>>
{
using message_type =
message<isRequest, Body, Headers>;
message_type m_;
typename message_type::body_type::reader r_;
bool started_ = false;
public:
nodejs_parser(nodejs_parser&&) = default;
nodejs_parser()
: http::nodejs_basic_parser<nodejs_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::nodejs_basic_parser<nodejs_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<bool, ! message_type::is_request::value>{});
}
void
on_body(void const* data,
std::size_t size, error_code& ec)
{
r_.write(data, size, ec);
}
void
on_complete()
{
}
};
} // http
} // beast
#endif
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/parse_error.hpp>
+69
View File
@@ -0,0 +1,69 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/parser.hpp>
#include <beast/http/headers.hpp>
#include <beast/http/string_body.hpp>
#include <beast/detail/unit_test/suite.hpp>
namespace beast {
namespace http {
class parser_test : public beast::detail::unit_test::suite
{
public:
void run() override
{
{
error_code ec;
parser<true, string_body,
basic_headers<std::allocator<char>>> p;
std::string const s =
"GET / HTTP/1.1\r\n"
"User-Agent: test\r\n"
"Content-Length: 1\r\n"
"\r\n"
"*";
p.write(s.data(), s.size(), ec);
expect(! ec);
expect(p.complete());
auto m = p.release();
expect(m.method == method_t::http_get);
expect(m.url == "/");
expect(m.version == 11);
expect(m.headers["User-Agent"] == "test");
expect(m.body == "*");
}
{
error_code ec;
parser<false, string_body,
basic_headers<std::allocator<char>>> p;
std::string const s =
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Content-Length: 1\r\n"
"\r\n"
"*";
p.write(s.data(), s.size(), ec);
expect(! ec);
expect(p.complete());
auto m = p.release();
expect(m.status == 200);
expect(m.reason == "OK");
expect(m.version == 11);
expect(m.headers["Server"] == "test");
expect(m.body == "*");
}
}
};
BEAST_DEFINE_TESTSUITE(parser,http,beast);
} // http
} // beast
+155
View File
@@ -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)
//
#include "nodejs_parser.hpp"
#include "message_fuzz.hpp"
#include <beast/http.hpp>
#include <beast/streambuf.hpp>
#include <beast/buffers_debug.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <chrono>
#include <iostream>
#include <vector>
namespace beast {
namespace http {
class parser_bench_test : public beast::detail::unit_test::suite
{
public:
static std::size_t constexpr N = 2000;
using corpus = std::vector<streambuf>;
corpus creq_;
corpus cres_;
std::size_t size_ = 0;
parser_bench_test()
{
creq_ = build_corpus(N/2, std::true_type{});
cres_ = build_corpus(N/2, std::false_type{});
}
corpus
build_corpus(std::size_t n, std::true_type)
{
corpus v;
v.resize(N);
message_fuzz mg;
for(std::size_t i = 0; i < n; ++i)
{
mg.request(v[i]);
size_ += v[i].size();
}
return v;
}
corpus
build_corpus(std::size_t n, std::false_type)
{
corpus v;
v.resize(N);
message_fuzz mg;
for(std::size_t i = 0; i < n; ++i)
{
mg.response(v[i]);
size_ += v[i].size();
}
return v;
}
template<class Parser>
void
testParser(std::size_t repeat, corpus const& v)
{
while(repeat--)
for(auto const& sb : v)
{
Parser p;
error_code ec;
p.write(sb.data(), ec);
if(! expect(! ec, ec.message()))
log << debug::buffers_to_string(
sb.data()) << std::endl;
}
}
template<class Function>
void
timedTest(std::size_t repeat, std::string const& name, Function&& f)
{
using namespace std::chrono;
using clock_type = std::chrono::high_resolution_clock;
log << name;
for(std::size_t trial = 1; trial <= repeat; ++trial)
{
auto const t0 = clock_type::now();
f();
auto const elapsed = clock_type::now() - t0;
log <<
"Trial " << trial << ": " <<
duration_cast<milliseconds>(elapsed).count() << " ms";
}
}
template<bool isRequest>
struct null_parser : basic_parser<isRequest, null_parser<isRequest>>
{
};
void
testSpeed()
{
static std::size_t constexpr Trials = 3;
static std::size_t constexpr Repeat = 50;
log << "sizeof(request parser) == " <<
sizeof(basic_parser<true, null_parser<true>>);
log << "sizeof(response parser) == " <<
sizeof(basic_parser<false, null_parser<true>>);
testcase << "Parser speed test, " <<
((Repeat * size_ + 512) / 1024) << "KB in " <<
(Repeat * (creq_.size() + cres_.size())) << " messages";
timedTest(Trials, "nodejs_parser",
[&]
{
testParser<nodejs_parser<
true, streambuf_body, http_headers>>(
Repeat, creq_);
testParser<nodejs_parser<
false, streambuf_body, http_headers>>(
Repeat, cres_);
});
timedTest(Trials, "http::basic_parser",
[&]
{
testParser<parser<
true, streambuf_body, http_headers>>(
Repeat, creq_);
testParser<parser<
false, streambuf_body, http_headers>>(
Repeat, cres_);
});
pass();
}
void run() override
{
pass();
testSpeed();
}
};
BEAST_DEFINE_TESTSUITE(parser_bench,http,beast);
} // http
} // beast
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/read.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/reason.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/resume_context.hpp>
+115
View File
@@ -0,0 +1,115 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/rfc2616.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <string>
#include <vector>
namespace beast {
namespace rfc2616 {
namespace test {
class rfc2616_test : public beast::detail::unit_test::suite
{
public:
void
checkSplit(std::string const& s,
std::vector <std::string> const& expected)
{
auto const parsed = split_commas(s.begin(), s.end());
expect (parsed == expected);
}
void testSplit()
{
checkSplit("", {});
checkSplit(" ", {});
checkSplit(" ", {});
checkSplit("\t", {});
checkSplit(" \t ", {});
checkSplit(",", {});
checkSplit(",,", {});
checkSplit(" ,", {});
checkSplit(" , ,", {});
checkSplit("x", {"x"});
checkSplit(" x", {"x"});
checkSplit(" \t x", {"x"});
checkSplit("x ", {"x"});
checkSplit("x \t", {"x"});
checkSplit(" \t x \t ", {"x"});
checkSplit("\"\"", {});
checkSplit(" \"\"", {});
checkSplit("\"\" ", {});
checkSplit("\"x\"", {"x"});
checkSplit("\" \"", {" "});
checkSplit("\" x\"", {" x"});
checkSplit("\"x \"", {"x "});
checkSplit("\" x \"", {" x "});
checkSplit("\"\tx \"", {"\tx "});
checkSplit("x,y", {"x", "y"});
checkSplit("x ,\ty ", {"x", "y"});
checkSplit("x, y, z", {"x","y","z"});
checkSplit("x, \"y\", z", {"x","y","z"});
checkSplit(",,x,,\"y\",,", {"x","y"});
}
void
checkIter(std::string const& s,
std::vector<std::string> const& expected)
{
std::vector<std::string> got;
for(auto const& v : make_list(s))
got.emplace_back(v);
expect(got == expected);
}
void
testIter()
{
checkIter("x", {"x"});
checkIter(" x", {"x"});
checkIter("x\t", {"x"});
checkIter("\tx ", {"x"});
checkIter(",x", {"x"});
checkIter("x,", {"x"});
checkIter(",x,", {"x"});
checkIter(" , x\t,\t", {"x"});
checkIter("x,y", {"x", "y"});
checkIter("x, ,y ", {"x", "y"});
checkIter("\"x\"", {"x"});
}
void
testList()
{
expect(token_in_list("x", "x"));
expect(token_in_list("x,y", "x"));
expect(token_in_list("x,y", "y"));
expect(token_in_list("x, y ", "y"));
expect(token_in_list("x", "X"));
expect(token_in_list("Y", "y"));
expect(token_in_list("close, keepalive", "close"));
expect(token_in_list("close, keepalive", "keepalive"));
}
void
run()
{
testSplit();
testIter();
testList();
}
};
BEAST_DEFINE_TESTSUITE(rfc2616,http,beast);
} // test
} // rfc2616
} // beast
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/rfc7230.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/streambuf_body.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/string_body.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/http/write.hpp>
+58
View File
@@ -0,0 +1,58 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
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 <beast/detail/unit_test/reporter.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <beast/detail/stream/debug_ostream.hpp>
#ifdef _MSC_VER
# ifndef WIN32_LEAN_AND_MEAN // VC_EXTRALEAN
# define WIN32_LEAN_AND_MEAN
#include <windows.h>
# undef WIN32_LEAN_AND_MEAN
# else
#include <windows.h>
# endif
#endif
#include <cstdlib>
// Simple main used to produce stand
// alone executables that run unit tests.
int main()
{
using namespace beast::detail::unit_test;
#ifdef _MSC_VER
{
int flags = _CrtSetDbgFlag (_CRTDBG_REPORT_FLAG);
flags |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag (flags);
}
#endif
{
beast::detail::debug_ostream s;
reporter r (s);
bool failed (r.run_each (global_suites()));
if (failed)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
}
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/placeholders.hpp>
+101
View File
@@ -0,0 +1,101 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/prepare_buffers.hpp>
#include <beast/consuming_buffers.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/asio/buffer.hpp>
#include <string>
namespace beast {
namespace test {
class prepare_buffers_test : public beast::detail::unit_test::suite
{
public:
template<class ConstBufferSequence>
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<char const*>(b),
buffer_size(b));
return s;
}
void testBuffers()
{
using boost::asio::buffer_size;
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<const_buffer, 3> 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)
{
auto pb = prepare_buffers(i, bs);
expect(to_string(pb) == s.substr(0, i));
auto pb2 = pb;
expect(to_string(pb2) == to_string(pb));
pb = prepare_buffers(0, bs);
pb2 = pb;
expect(buffer_size(pb2) == 0);
pb2 = prepare_buffers(i, bs);
expect(to_string(pb2) == s.substr(0, i));
}
}
}}
}
void testNullBuffers()
{
using boost::asio::buffer_copy;
using boost::asio::buffer_size;
using boost::asio::null_buffers;
auto pb0 = prepare_buffers(0, null_buffers{});
expect(buffer_size(pb0) == 0);
auto pb1 = prepare_buffers(1, null_buffers{});
expect(buffer_size(pb1) == 0);
expect(buffer_copy(pb0, pb1) == 0);
using pb_type = decltype(pb0);
consuming_buffers<pb_type> cb(pb0);
expect(buffer_size(cb) == 0);
expect(buffer_copy(cb, pb1) == 0);
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);
}
void run() override
{
testBuffers();
testNullBuffers();
}
};
BEAST_DEFINE_TESTSUITE(prepare_buffers,asio,beast);
} // test
} // beast
+111
View File
@@ -0,0 +1,111 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/static_streambuf.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <boost/asio/buffer.hpp>
#include <string>
namespace beast {
namespace test {
class static_streambuf_test : public beast::detail::unit_test::suite
{
public:
template<class ConstBufferSequence>
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<char const*>(b),
buffer_size(b));
return s;
}
void testStaticStreambuf()
{
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<sizeof(buf)> 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 run() override
{
testStaticStreambuf();
}
};
BEAST_DEFINE_TESTSUITE(static_streambuf,asio,beast);
} // test
} // beastp
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/streambuf.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/streambuf_readstream.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/type_check.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/websocket/error.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/websocket/option.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/websocket/rfc6455.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/websocket/static_string.hpp>
+9
View File
@@ -0,0 +1,9 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/websocket/teardown.hpp>
+264
View File
@@ -0,0 +1,264 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/websocket/detail/utf8_checker.hpp>
#include <beast/streambuf.hpp>
#include <beast/detail/unit_test/suite.hpp>
#include <array>
namespace beast {
namespace websocket {
class utf8_checker_test : public beast::detail::unit_test::suite
{
public:
void
testOneByteSequence()
{
detail::utf8_checker utf8;
std::array<std::uint8_t, 256> const buf =
([]()
{
std::array<std::uint8_t, 256> values;
std::uint8_t i = 0;
for (auto& c : values)
c = i++;
return values;
})();
// Valid range 0-127
expect(utf8.write(buf.data(), 128));
expect(utf8.finish());
// Invalid range 128-193
for (auto it = std::next(buf.begin(), 128);
it != std::next(buf.begin(), 194); ++it)
expect(! utf8.write(&(*it), 1));
// Invalid range 245-255
for (auto it = std::next(buf.begin(), 245);
it != buf.end(); ++it)
expect(! utf8.write(&(*it), 1));
}
void
testTwoByteSequence()
{
detail::utf8_checker utf8;
std::uint8_t buf[2];
for(auto i = 194; i <= 223; ++i)
{
// First byte valid range 194-223
buf[0] = static_cast<std::uint8_t>(i);
for (auto j = 128; j <= 191; ++j)
{
// Second byte valid range 128-191
buf[1] = static_cast<std::uint8_t>(j);
expect(utf8.write(buf, 2));
expect(utf8.finish());
}
for (auto j = 0; j <= 127; ++j)
{
// Second byte invalid range 0-127
buf[1] = static_cast<std::uint8_t>(j);
expect(! utf8.write(buf, 2));
}
for (auto j = 192; j <= 255; ++j)
{
// Second byte invalid range 192-255
buf[1] = static_cast<std::uint8_t>(j);
expect(! utf8.write(buf, 2));
}
}
}
void
testThreeByteSequence()
{
detail::utf8_checker utf8;
std::uint8_t buf[3];
for (auto i = 224; i <= 239; ++i)
{
// First byte valid range 224-239
buf[0] = static_cast<std::uint8_t>(i);
std::int32_t const b = (i == 224 ? 160 : 128);
std::int32_t const e = (i == 237 ? 159 : 191);
for (auto j = b; j <= e; ++j)
{
// Second byte valid range 128-191 or 160-191 or 128-159
buf[1] = static_cast<std::uint8_t>(j);
for (auto k = 128; k <= 191; ++k)
{
// Third byte valid range 128-191
buf[2] = static_cast<std::uint8_t>(k);
expect(utf8.write(buf, 3));
expect(utf8.finish());
}
for (auto k = 0; k <= 127; ++k)
{
// Third byte invalid range 0-127
buf[2] = static_cast<std::uint8_t>(k);
expect(! utf8.write(buf, 3));
}
for (auto k = 192; k <= 255; ++k)
{
// Third byte invalid range 192-255
buf[2] = static_cast<std::uint8_t>(k);
expect(! utf8.write(buf, 3));
}
}
for (auto j = 0; j < b; ++j)
{
// Second byte invalid range 0-127 or 0-159
buf[1] = static_cast<std::uint8_t>(j);
expect(! utf8.write(buf, 3));
}
for (auto j = e + 1; j <= 255; ++j)
{
// Second byte invalid range 160-255 or 192-255
buf[1] = static_cast<std::uint8_t>(j);
expect(! utf8.write(buf, 3));
}
}
}
void
testFourByteSequence()
{
detail::utf8_checker utf8;
std::uint8_t buf[4];
for (auto i = 240; i <= 244; ++i)
{
// First byte valid range 240-244
buf[0] = static_cast<std::uint8_t>(i);
std::int32_t const b = (i == 240 ? 144 : 128);
std::int32_t const e = (i == 244 ? 143 : 191);
for (auto j = b; j <= e; ++j)
{
// Second byte valid range 128-191 or 144-191 or 128-143
buf[1] = static_cast<std::uint8_t>(j);
for (auto k = 128; k <= 191; ++k)
{
// Third byte valid range 128-191
buf[2] = static_cast<std::uint8_t>(k);
for (auto n = 128; n <= 191; ++n)
{
// Fourth byte valid range 128-191
buf[3] = static_cast<std::uint8_t>(n);
expect(utf8.write(buf, 4));
expect(utf8.finish());
}
for (auto n = 0; n <= 127; ++n)
{
// Fourth byte invalid range 0-127
buf[3] = static_cast<std::uint8_t>(n);
expect(! utf8.write(buf, 4));
}
for (auto n = 192; n <= 255; ++n)
{
// Fourth byte invalid range 192-255
buf[3] = static_cast<std::uint8_t>(n);
expect(! utf8.write(buf, 4));
}
}
for (auto k = 0; k <= 127; ++k)
{
// Third byte invalid range 0-127
buf[2] = static_cast<std::uint8_t>(k);
expect(! utf8.write(buf, 4));
}
for (auto k = 192; k <= 255; ++k)
{
// Third byte invalid range 192-255
buf[2] = static_cast<std::uint8_t>(k);
expect(! utf8.write(buf, 4));
}
}
for (auto j = 0; j < b; ++j)
{
// Second byte invalid range 0-127 or 0-143
buf[1] = static_cast<std::uint8_t>(j);
expect(! utf8.write(buf, 3));
}
for (auto j = e + 1; j <= 255; ++j)
{
// Second byte invalid range 144-255 or 192-255
buf[1] = static_cast<std::uint8_t>(j);
expect(! utf8.write(buf, 3));
}
}
}
void
testWithStreamBuffer()
{
using namespace boost::asio;
// Valid UTF8 encoded text
std::vector<std::vector<std::uint8_t>> const data{
{0x48,0x65,0x69,0x7A,0xC3,0xB6,0x6C,0x72,0xC3,0xBC,0x63,0x6B,
0x73,0x74,0x6F,0xC3,0x9F,0x61,0x62,0x64,0xC3,0xA4,0x6D,0x70,
0x66,0x75,0x6E,0x67},
{0xCE,0x93,0xCE,0xB1,0xCE,0xB6,0xCE,0xAD,0xCE,0xB5,0xCF,0x82,
0x20,0xCE,0xBA,0xCE,0xB1,0xE1,0xBD,0xB6,0x20,0xCE,0xBC,0xCF,
0x85,0xCF,0x81,0xCF,0x84,0xCE,0xB9,0xE1,0xBD,0xB2,0xCF,0x82,
0x20,0xCE,0xB4,0xE1,0xBD,0xB2,0xCE,0xBD,0x20,0xCE,0xB8,0xE1,
0xBD,0xB0,0x20,0xCE,0xB2,0xCF,0x81,0xE1,0xBF,0xB6,0x20,0xCF,
0x80,0xCE,0xB9,0xE1,0xBD,0xB0,0x20,0xCF,0x83,0xCF,0x84,0xE1,
0xBD,0xB8,0x20,0xCF,0x87,0xCF,0x81,0xCF,0x85,0xCF,0x83,0xCE,
0xB1,0xCF,0x86,0xE1,0xBD,0xB6,0x20,0xCE,0xBE,0xCE,0xAD,0xCF,
0x86,0xCF,0x89,0xCF,0x84,0xCE,0xBF},
{0xC3,0x81,0x72,0x76,0xC3,0xAD,0x7A,0x74,0xC5,0xB1,0x72,0xC5,
0x91,0x20,0x74,0xC3,0xBC,0x6B,0xC3,0xB6,0x72,0x66,0xC3,0xBA,
0x72,0xC3,0xB3,0x67,0xC3,0xA9,0x70}
};
detail::utf8_checker utf8;
for(auto const& s : data)
{
beast::streambuf sb(
s.size() / 4); // Force split across blocks
sb.commit(buffer_copy(
sb.prepare(s.size()),
const_buffer(s.data(), s.size())));
expect(utf8.write(sb.data()));
expect(utf8.finish());
}
}
void run() override
{
testOneByteSequence();
testTwoByteSequence();
testThreeByteSequence();
testFourByteSequence();
testWithStreamBuffer();
}
};
BEAST_DEFINE_TESTSUITE(utf8_checker,websocket,beast);
} // websocket
} // beast
+35
View File
@@ -0,0 +1,35 @@
//
// 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)
//
// Test that header file is self-contained.
#include <beast/write_streambuf.hpp>
#include <beast/streambuf.hpp>
#include <beast/detail/unit_test/suite.hpp>
namespace beast {
class write_streambuf_test : public beast::detail::unit_test::suite
{
public:
void run() override
{
streambuf sb;
std::string s;
write(sb, boost::asio::const_buffer{"", 0});
write(sb, boost::asio::mutable_buffer{nullptr, 0});
write(sb, boost::asio::null_buffers{});
write(sb, boost::asio::const_buffers_1{"", 0});
write(sb, boost::asio::mutable_buffers_1{nullptr, 0});
write(sb, s);
write(sb, 23);
pass();
}
};
BEAST_DEFINE_TESTSUITE(write_streambuf,core,beast);
} // beast