summaryrefslogtreecommitdiffhomepage
path: root/tests/test-webserver.cpp
blob: de38cf3d164ca1fd3281ce432090ecd71394a642 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// Main unit test compilation unit
// boost mandates that exactly one compilation unit contains the following two lines:
#define BOOST_TEST_MODULE webserver_test
#include <boost/test/included/unit_test.hpp>

// Support both boost in Debian unstable (BOOST_LATEST) and in stable (boost 1.67)
#if BOOST_VERSION >= 107100
#define BOOST_LATEST
#endif

#include <boost/test/data/dataset.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>

#include <boost/algorithm/string.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#ifdef BOOST_LATEST
#include <boost/beast/ssl.hpp>
#endif
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include <fmt/core.h>

#include <chrono>
#include <filesystem>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include <ext/stdio_filebuf.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>

#include <libreichwein/file.h>

#include "webserver.h"

using namespace std::string_literals;
namespace fs = std::filesystem;
namespace pt = boost::property_tree;
using namespace boost::unit_test;
using namespace Reichwein;

class WebserverProcess
{
public:
 const fs::path testConfigFilename{"./webserver.conf"};
 WebserverProcess(): m_pid{}
 {
  File::setFile(testConfigFilename, R"CONFIG(<webserver>
 <user>www-data</user>
 <group>www-data</group>
 <threads>10</threads>
 <plugin-directory>../plugins</plugin-directory>
 <sites>
  <site>
   <name>localhost</name>
   <host>ip6-localhost</host>
   <host>localhost</host>
   <host>127.0.0.1</host>
   <host>[::1]</host>
   <path requested="/">
    <plugin>static-files</plugin>
    <target>.</target>
   </path>
   <certpath>../fullchain.pem</certpath>
   <keypath>../privkey.pem</keypath>
  </site>
 </sites>
 <sockets>
  <socket>
   <address>127.0.0.1</address>
   <port>8080</port>
   <protocol>http</protocol>
   <site>localhost</site>
  </socket>
  <socket>
   <address>::1</address>
   <port>8080</port>
   <protocol>http</protocol>
   <site>localhost</site>
  </socket>
  <socket>
   <address>127.0.0.1</address>
   <port>8081</port>
   <protocol>https</protocol>
   <site>localhost</site>
  </socket>
  <socket>
   <address>::1</address>
   <port>8081</port>
   <protocol>https</protocol>
   <site>localhost</site>
  </socket>
 </sockets>
</webserver>

)CONFIG");

  start();
 }

 ~WebserverProcess()
 {
  stop();
  fs::remove(testConfigFilename);
 }

 void start()
 {
  if (m_pid != 0)
   throw std::runtime_error("Process already running, so it can't be started");

  // connect stdout of new child process to stream of parent, via pipe
  int filedes[2];
  if (pipe(filedes) == -1)
   throw std::runtime_error("Pipe error");

  m_pid = fork();
  if (m_pid < 0)
   throw std::runtime_error("Fork unsuccessful.");

  if (m_pid == 0) { // child process branch
                    //
   if (close(filedes[0]) == -1)
    throw std::runtime_error("Child can't close read end of pipe");

   // Replace stdout of child with pipe input (next 2 commands)
   if (close(1) == -1)
    throw std::runtime_error("Child can't close stdout");
   if (dup(filedes[1]) == -1)
    throw std::runtime_error("Child replace stdout w/ pipe input");

   char* argv[] = {(char*)"webserver", (char*)"-c", (char*)"./webserver.conf"};
   webserver(sizeof(argv) / sizeof(char*), argv);
   exit(0);
  }

  if (close(filedes[1]) == -1)
   throw std::runtime_error("Parent can't close read end of pipe");
  m_filebuf = std::make_shared<__gnu_cxx::stdio_filebuf<char>>(filedes[0], std::ios::in);
  m_is = std::make_shared<std::istream>(&(*m_filebuf));

  // wait for server to start up
  std::this_thread::sleep_for(std::chrono::milliseconds(100));
 }

 void stop()
 {
  if (m_pid == 0)
   throw std::runtime_error("Process not running, so it can't be stopped");
  
  if (kill(m_pid, SIGTERM) != 0)
   throw std::runtime_error("Unable to kill process");

  if (int result = waitpid(m_pid, NULL, 0); result != m_pid)
   throw std::runtime_error("waitpid returned "s + std::to_string(result));

  m_pid = 0;
  m_is = 0;
  m_filebuf = 0;
 }

 bool isRunning()
 {
  if (m_pid == 0)
   return false;

  fs::path pid_file{fmt::format("/proc/{}/stat", m_pid)};
  if (!fs::exists(pid_file))
   return false;

  std::string s{File::getFile(pid_file)};

  auto pos0{s.find(' ', 0)};
  pos0 = s.find(' ', pos0 + 1);
  pos0++;

  auto pos1{s.find(' ', pos0 + 1)};

  std::string state{s.substr(pos0, pos1 - pos0)};

  return state == "R" || state == "S";
 }

 std::string output()
 {
  if (!isRunning())
   throw std::runtime_error("No output/stdout available from webserver since it is not running");

  if (!m_is)
   throw std::runtime_error("Webserver stdout stream not initialized.");

  std::stringstream result;
  std::string buffer(static_cast<std::string::size_type>(1024), '\0');
  int size{};
  while ((size = m_is->readsome(buffer.data(), buffer.size())) > 0)
   result << buffer.substr(0, size);
  return result.str();
 }

private:
 pid_t m_pid;

 // child stdout
 std::shared_ptr<__gnu_cxx::stdio_filebuf<char>> m_filebuf;
 std::shared_ptr<std::istream> m_is;
};

std::pair<std::string,std::string> HTTPGet(const std::string& target, bool ipv6 = true, bool HTTP11 = true)
{
 auto const host = ipv6 ? "::1" : "127.0.0.1"; 
 auto const port = "8080";
 int version = HTTP11 ? 11 : 10;

 // The io_context is required for all I/O
 boost::asio::io_context ioc;

 // These objects perform our I/O
 boost::asio::ip::tcp::resolver resolver(ioc);
 boost::beast::tcp_stream stream(ioc);

 // Look up the domain name
 auto const results = resolver.resolve(host, port);

 // Make the connection on the IP address we get from a lookup
 stream.connect(results);

 // Set up an HTTP GET request message
 boost::beast::http::request<boost::beast::http::string_body> req{boost::beast::http::verb::get, target, version};
 req.set(boost::beast::http::field::host, ipv6 && host == "::1"s ? "["s + host + "]"s : host);
 req.set(boost::beast::http::field::user_agent, "Webserver Testsuite");

 // Send the HTTP request to the remote host
 boost::beast::http::write(stream, req);

 // This buffer is used for reading and must be persisted
 boost::beast::flat_buffer buffer;

 // Declare a container to hold the response
 boost::beast::http::response<boost::beast::http::dynamic_body> res;

 // Receive the HTTP response
 boost::beast::http::read(stream, buffer, res);

 // Return value
 std::ostringstream header_stream;
 header_stream << res.base();
 std::ostringstream body_stream;
 body_stream << boost::beast::buffers_to_string(res.body().data());

 // Gracefully close the socket
 boost::beast::error_code ec;
 stream.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);

 // not_connected happens sometimes
 // so don't bother reporting it.
 //
 if (ec && ec != boost::beast::errc::not_connected)
     throw boost::beast::system_error{ec};

 return {header_stream.str(), body_stream.str()};
}

std::pair<std::string,std::string> HTTPSGet(const std::string& target, bool ipv6 = true, bool HTTP11 = true)
{
 auto const host = ipv6 ? "::1" : "127.0.0.1"; 
 auto const port = "8081";
 int version = HTTP11 ? 11 : 10;

 // The io_context is required for all I/O
 boost::asio::io_context ioc;

 // The SSL context is required, and holds certificates
 boost::asio::ssl::context ctx(
#ifdef BOOST_LATEST
                               boost::asio::ssl::context::tlsv13_client
#else
                               boost::asio::ssl::context::tlsv12_client
#endif
                               );

 // This holds the root certificate used for verification
 //load_root_certificates(ctx);

 // Verify the remote server's certificate
 ctx.set_verify_mode(boost::asio::ssl::verify_none); // TODO: ssl::verify_peer w/ load_root_certificates() (above)

 // These objects perform our I/O
 boost::asio::ip::tcp::resolver resolver(ioc);
 boost::beast::ssl_stream<boost::beast::tcp_stream> stream(ioc, ctx);

 // Set SNI Hostname (many hosts need this to handshake successfully)
 if (!SSL_set_tlsext_host_name(stream.native_handle(), host))
 {
  boost::beast::error_code ec{static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};
  throw boost::beast::system_error{ec};
 }

 // Look up the domain name
 auto const results = resolver.resolve(host, port);

 // Make the connection on the IP address we get from a lookup
 boost::beast::get_lowest_layer(stream).connect(results);

 // Perform the SSL handshake
 stream.handshake(boost::asio::ssl::stream_base::client);

 // Set up an HTTP GET request message
 boost::beast::http::request<boost::beast::http::string_body> req{boost::beast::http::verb::get, target, version};
 req.set(boost::beast::http::field::host,  ipv6 && host == "::1"s ? "["s + host + "]"s : host);
 req.set(boost::beast::http::field::user_agent, "Webserver Testsuite");

 // Send the HTTP request to the remote host
 boost::beast::http::write(stream, req);

 // This buffer is used for reading and must be persisted
 boost::beast::flat_buffer buffer;

 // Declare a container to hold the response
 boost::beast::http::response<boost::beast::http::dynamic_body> res;

 // Receive the HTTP response
 boost::beast::http::read(stream, buffer, res);

 // Return value
 std::ostringstream header_stream;
 header_stream << res.base();
 std::ostringstream body_stream;
 body_stream << boost::beast::buffers_to_string(res.body().data());

 // Gracefully close the stream
 boost::beast::error_code ec;
 stream.shutdown(ec);
 if (ec == boost::asio::error::eof)
 {
  // Rationale:
  // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
  ec = {};
 }
 if (ec)
  throw boost::beast::system_error{ec};
 
 return {header_stream.str(), body_stream.str()};
}

class Fixture
{
public:
 Fixture(){}
 ~Fixture(){}
};

BOOST_DATA_TEST_CASE_F(Fixture, http_get, data::make({false, true}) * data::make({false, true}) * data::make({false, true}), ipv6, http11, https)
{
 WebserverProcess serverProcess;

 BOOST_REQUIRE(serverProcess.isRunning());
 auto response{(https ? HTTPSGet("/webserver.conf") : HTTPGet("/webserver.conf"))};
 BOOST_REQUIRE(serverProcess.isRunning());
 BOOST_REQUIRE_EQUAL(response.first, "HTTP/1.1 200 OK\r\nServer: Reichwein.IT Webserver " VERSION "\r\nContent-Type: application/text\r\nContent-Length: 1021\r\n\r\n");
 BOOST_REQUIRE_EQUAL(response.second, File::getFile(serverProcess.testConfigFilename));
 auto output{serverProcess.output()};
 BOOST_REQUIRE_MESSAGE(boost::algorithm::contains(output, "Serving"), "Bad output: "s + output);
}

BOOST_DATA_TEST_CASE_F(Fixture, http_get_file_not_found, data::make({false, true}) * data::make({false, true}) * data::make({false, true}), ipv6, http11, https)
{
 WebserverProcess serverProcess;

 BOOST_REQUIRE(serverProcess.isRunning());
 BOOST_REQUIRE(!fs::exists("./webserver.confSUFFIX"));
 auto response{(https ? HTTPSGet("/webserver.confSUFFIX") : HTTPGet("/webserver.confSUFFIX"))};
 BOOST_REQUIRE(serverProcess.isRunning());
 BOOST_REQUIRE_EQUAL(response.first, "HTTP/1.1 404 Not Found\r\nServer: Reichwein.IT Webserver " VERSION "\r\nContent-Type: text/html\r\nContent-Length: 36\r\n\r\n");
 BOOST_REQUIRE_EQUAL(response.second, "404 Not found: /webserver.confSUFFIX");
 auto output{serverProcess.output()};
 BOOST_REQUIRE_MESSAGE(boost::algorithm::contains(output, "Serving"), "Bad output: "s + output);
}