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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649 | // Copyright (C) 2017-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef TEST_HTTP_CLIENT_H
#define TEST_HTTP_CLIENT_H
#include <cc/data.h>
#include <http/client.h>
#include <http/http_types.h>
#include <http/response_parser.h>
#include <boost/asio/read.hpp><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/asio/buffer.hpp><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/asio/ip/tcp.hpp><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/enable_shared_from_this.hpp><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <gtest/gtest.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
using namespace boost::asio::ip;
using namespace isc::asiolink;
using namespace isc::http;
/// @brief Sending chuck size.
const size_t TEST_HTTP_CHUCK_SIZE = 8 * 1024;
/// @brief Common base for test HTTP/HTTPS clients.
class BaseTestHttpClient : public boost::noncopyable {
public:
/// @brief Destructor.
virtual ~BaseTestHttpClient() = default;<--- Virtual destructor in base class<--- Virtual destructor in base class
/// @brief Send HTTP request specified in textual format.
///
/// @param request HTTP request in the textual format.
virtual void startRequest(const std::string& request) = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Send HTTP request.
///
/// @param request HTTP request in the textual format.
virtual void sendRequest(const std::string& request) = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Send part of the HTTP request.
///
/// @param request part of the HTTP request to be sent.
virtual void sendPartialRequest(std::string request) = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Receive response from the server.
virtual void receivePartialResponse() = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Checks if the TCP connection is still open.
///
/// Tests the TCP connection by trying to read from the socket.
/// Unfortunately expected failure depends on a race between the read
/// and the other side close so to check if the connection is closed
/// please use @c isConnectionClosed instead.
///
/// @return true if the TCP connection is open.
virtual bool isConnectionAlive() = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Checks if the TCP connection is already closed.
///
/// Tests the TCP connection by trying to read from the socket.
/// The read can block so this must be used to check if a connection
/// is alive so to check if the connection is alive please always
/// use @c isConnectionAlive.
///
/// @return true if the TCP connection is closed.
virtual bool isConnectionClosed() = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Close connection.
virtual void close() = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Returns the HTTP response string.
///
/// @return string containing the response.
virtual std::string getResponse() const = 0;<--- Virtual function in base class<--- Virtual function in base class
/// @brief Returns true if the receive completed without error.
///
/// @return True if the receive completed successfully, false
/// otherwise.
virtual bool receiveDone() const = 0;<--- Virtual function in base class<--- Virtual function in base class
};
/// @brief Entity which can connect to the HTTP server endpoint.
class TestHttpClient : public BaseTestHttpClient,
public boost::enable_shared_from_this<TestHttpClient> {
public:
/// @brief Constructor.
///
/// This constructor creates new socket instance. It doesn't connect. Call
/// connect() to connect to the server.
///
/// @param io_service IO service to be stopped on error or completion.
/// @param server_address string containing the IP address of the server.
/// @param port port number of the server.
explicit TestHttpClient(const IOServicePtr& io_service,
const std::string& server_address = "127.0.0.1",
uint16_t port = 18123)
: io_service_(io_service), socket_(io_service_->getInternalIOService()),
buf_(), response_(), server_address_(server_address),
server_port_(port), receive_done_(false) {
}
/// @brief Destructor.
///
/// Closes the underlying socket if it is open.
virtual ~TestHttpClient() {<--- Destructor in derived class
close();<--- Calling close
}
/// @brief Send HTTP request specified in textual format.
///
/// @param request HTTP request in the textual format.
virtual void startRequest(const std::string& request) {<--- Function in derived class
tcp::endpoint endpoint(address::from_string(server_address_), server_port_);
auto ref = shared_from_this();
socket_.async_connect(endpoint,
[this, ref, request](const boost::system::error_code& ec) {
receive_done_ = false;
if (ec) {
// One would expect that async_connect wouldn't return
// EINPROGRESS error code, but simply wait for the connection
// to get established before the handler is invoked. It turns out,
// however, that on some OSes the connect handler may receive this
// error code which doesn't necessarily indicate a problem.
// Making an attempt to write and read from this socket will
// typically succeed. So, we ignore this error.
if (ec.value() != boost::asio::error::in_progress) {
ADD_FAILURE() << "error occurred while connecting: "
<< ec.message();
io_service_->stop();
return;
}
}
sendRequest(request);
});
}
/// @brief Send HTTP request.
///
/// @param request HTTP request in the textual format.
virtual void sendRequest(const std::string& request) {<--- Function in derived class
sendPartialRequest(request);
}
/// @brief Send part of the HTTP request.
///
/// @param request part of the HTTP request to be sent.
virtual void sendPartialRequest(std::string request) {<--- Function in derived class
size_t chuck_size = std::min(TEST_HTTP_CHUCK_SIZE, request.size());
auto ref = shared_from_this();
socket_.async_send(boost::asio::buffer(request.data(), chuck_size),
[this, ref, request](const boost::system::error_code& ec,
std::size_t bytes_transferred) mutable {
if (ec) {
if (ec.value() == boost::asio::error::operation_aborted) {
return;
} else if ((ec.value() == boost::asio::error::try_again) ||
(ec.value() == boost::asio::error::would_block)) {
// If we should try again make sure there is no garbage in the
// bytes_transferred.
bytes_transferred = 0;
} else {
ADD_FAILURE() << "error occurred while connecting: "
<< ec.message();
io_service_->stop();
return;
}
}
// Remove the part of the request which has been sent.
request.erase(0, bytes_transferred);
// Continue sending request data if there are still some data to be
// sent.
if (!request.empty()) {
sendPartialRequest(request);
} else {
// Request has been sent. Start receiving response.
response_.clear();
receivePartialResponse();
}
});
}
/// @brief Receive response from the server.
virtual void receivePartialResponse() {<--- Function in derived class
auto ref = shared_from_this();
socket_.async_read_some(boost::asio::buffer(ref->buf_.data(), ref->buf_.size()),
[this, ref](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
if (ec) {
// IO service stopped so simply return.
if (ec.value() == boost::asio::error::operation_aborted) {
return;
} else if ((ec.value() == boost::asio::error::try_again) ||
(ec.value() == boost::asio::error::would_block)) {
// If we should try again, make sure that there is no garbage
// in the bytes_transferred.
bytes_transferred = 0;
} else {
// Error occurred, bail...
ADD_FAILURE() << "error occurred while receiving HTTP"
" response from the server: " << ec.message();
io_service_->stop();
}
}
if (bytes_transferred > 0) {
response_.insert(response_.end(), buf_.data(),
buf_.data() + bytes_transferred);
}
// Two consecutive new lines end the part of the response we're
// expecting.
bool need_data(true);
if (response_.find("\r\n\r\n", 0) != std::string::npos) {
// Try to parse the response.
try {
HttpResponse hr;
HttpResponseParser parser(hr);
parser.initModel();
parser.postBuffer(&response_[0], response_.size());
parser.poll();
if (!parser.needData()) {
need_data = false;
if (parser.httpParseOk()) {
receive_done_ = true;
}
}
} catch (const std::exception& ex) {
need_data = false;
ADD_FAILURE() << "error parsing response: " << ex.what();
}
}
if (!need_data) {
io_service_->stop();
} else {
receivePartialResponse();
}
});
}
/// @brief Checks if the TCP connection is still open.
///
/// Tests the TCP connection by trying to read from the socket.
/// Unfortunately expected failure depends on a race between the read
/// and the other side close so to check if the connection is closed
/// please use @c isConnectionClosed instead.
///
/// @return true if the TCP connection is open.
virtual bool isConnectionAlive() {<--- Function in derived class
// Remember the current non blocking setting.
const bool non_blocking_orig = socket_.non_blocking();
// Set the socket to non blocking mode. We're going to test if the socket
// returns would_block status on the attempt to read from it.
socket_.non_blocking(true);
// We need to provide a buffer for a call to read.
char data[2];
boost::system::error_code ec;
boost::asio::read(socket_, boost::asio::buffer(data, sizeof(data)), ec);
// Revert the original non_blocking flag on the socket.
socket_.non_blocking(non_blocking_orig);
// If the connection is alive we'd typically get would_block status code.
// If there are any data that haven't been read we may also get success
// status. We're guessing that try_again may also be returned by some
// implementations in some situations. Any other error code indicates a
// problem with the connection so we assume that the connection has been
// closed.
return (!ec || (ec.value() == boost::asio::error::try_again) ||
(ec.value() == boost::asio::error::would_block));
}
/// @brief Checks if the TCP connection is already closed.
///
/// Tests the TCP connection by trying to read from the socket.
/// The read can block so this must be used to check if a connection
/// is alive so to check if the connection is alive please always
/// use @c isConnectionAlive.
///
/// @return true if the TCP connection is closed.
virtual bool isConnectionClosed() {<--- Function in derived class
// Remember the current non blocking setting.
const bool non_blocking_orig = socket_.non_blocking();
// Set the socket to blocking mode. We're going to test if the socket
// returns eof status on the attempt to read from it.
socket_.non_blocking(false);
// We need to provide a buffer for a call to read.
char data[2];
boost::system::error_code ec;
boost::asio::read(socket_, boost::asio::buffer(data, sizeof(data)), ec);
// Revert the original non_blocking flag on the socket.
socket_.non_blocking(non_blocking_orig);
// If the connection is closed we'd typically get eof status code.
return (ec.value() == boost::asio::error::eof);
}
/// @brief Close connection.
virtual void close() {<--- close is a virtual function<--- Function in derived class
socket_.close();
}
/// @brief Returns the HTTP response string.
///
/// @return string containing the response.
virtual std::string getResponse() const {<--- Function in derived class
return (response_);
}
/// @brief Returns true if the receive completed without error.
///
/// @return True if the receive completed successfully, false
/// otherwise.
virtual bool receiveDone() const {<--- Function in derived class
return (receive_done_);
}
private:
/// @brief Holds pointer to the IO service.
isc::asiolink::IOServicePtr io_service_;
/// @brief A socket used for the connection.
boost::asio::ip::tcp::socket socket_;
/// @brief Buffer into which response is written.
std::array<char, 8192> buf_;
/// @brief Response in the textual format.
std::string response_;
/// @brief IP address of the server.
std::string server_address_;
/// @brief IP port of the server.
uint16_t server_port_;
/// @brief Set to true when the receive has completed successfully.
bool receive_done_;
};
/// @brief Pointer to the TestHttpClient.
typedef boost::shared_ptr<TestHttpClient> TestHttpClientPtr;
/// @brief Entity which can connect to the HTTPS server endpoint.
class TestHttpsClient : public BaseTestHttpClient,
public boost::enable_shared_from_this<TestHttpsClient> {
public:
/// @brief Constructor.
///
/// This constructor creates new socket instance. It doesn't connect. Call
/// connect() to connect to the server.
///
/// @param io_service IO service to be stopped on error.
/// @param tls_context TLS context.
/// @param server_address string containing the IP address of the server.
/// @param port port number of the server.
TestHttpsClient(const IOServicePtr& io_service, TlsContextPtr tls_context,
const std::string& server_address = "127.0.0.1",
uint16_t port = 18123)
: io_service_(io_service), stream_(io_service_->getInternalIOService(),
tls_context->getContext()), buf_(), response_(),
server_address_(server_address), server_port_(port),
receive_done_(false) {
}
/// @brief Destructor.
///
/// Closes the underlying socket if it is open.
virtual ~TestHttpsClient() {<--- Destructor in derived class
close();<--- Calling close
}
/// @brief Send HTTP request specified in textual format.
///
/// @param request HTTP request in the textual format.
virtual void startRequest(const std::string& request) {<--- Function in derived class
tcp::endpoint endpoint(address::from_string(server_address_),
server_port_);
auto ref = shared_from_this();
stream_.lowest_layer().async_connect(endpoint,
[this, ref, request](const boost::system::error_code& ec) {
receive_done_ = false;
if (ec) {
// One would expect that async_connect wouldn't return
// EINPROGRESS error code, but simply wait for the connection
// to get established before the handler is invoked. It turns out,
// however, that on some OSes the connect handler may receive this
// error code which doesn't necessarily indicate a problem.
// Making an attempt to write and read from this socket will
// typically succeed. So, we ignore this error.
if (ec.value() != boost::asio::error::in_progress) {
ADD_FAILURE() << "error occurred while connecting: "
<< ec.message();
io_service_->stop();
return;
}
}
stream_.async_handshake(roleToImpl(TlsRole::CLIENT),
[this, request](const boost::system::error_code& ec) {
if (ec) {
ADD_FAILURE() << "error occurred during handshake: "
<< ec.message();
io_service_->stop();
return;
}
sendRequest(request);
});
});
}
/// @brief Send HTTP request.
///
/// @param request HTTP request in the textual format.
virtual void sendRequest(const std::string& request) {<--- Function in derived class
sendPartialRequest(request);
}
/// @brief Send part of the HTTP request.
///
/// @param request part of the HTTP request to be sent.
virtual void sendPartialRequest(std::string request) {<--- Function in derived class
size_t chuck_size = std::min(TEST_HTTP_CHUCK_SIZE, request.size());
auto ref = shared_from_this();
boost::asio::async_write(stream_,
boost::asio::buffer(request.data(), chuck_size),
[this, ref, request](const boost::system::error_code& ec,
std::size_t bytes_transferred) mutable {
if (ec) {
if (ec.value() == boost::asio::error::operation_aborted) {
return;
} else if ((ec.value() == boost::asio::error::try_again) ||
(ec.value() == boost::asio::error::would_block)) {
// If we should try again make sure there is no garbage in the
// bytes_transferred.
bytes_transferred = 0;
} else {
ADD_FAILURE() << "error occurred while connecting: "
<< ec.message();
io_service_->stop();
return;
}
}
// Remove the part of the request which has been sent.
request.erase(0, bytes_transferred);
// Continue sending request data if there are still some data to be
// sent.
if (!request.empty()) {
sendPartialRequest(request);
} else {
// Request has been sent. Start receiving response.
response_.clear();
receivePartialResponse();
}
});
}
/// @brief Receive response from the server.
virtual void receivePartialResponse() {<--- Function in derived class
auto ref = shared_from_this();
stream_.async_read_some(boost::asio::buffer(ref->buf_.data(), ref->buf_.size()),
[this, ref](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
if (ec) {
// IO service stopped so simply return.
if (ec.value() == boost::asio::error::operation_aborted) {
return;
} else if ((ec.value() == boost::asio::error::try_again) ||
(ec.value() == boost::asio::error::would_block)) {
// If we should try again, make sure that there is no garbage
// in the bytes_transferred.
bytes_transferred = 0;
} else {
// Error occurred, bail...
ADD_FAILURE() << "error occurred while receiving HTTP"
" response from the server: " << ec.message();
io_service_->stop();
}
}
if (bytes_transferred > 0) {
response_.insert(response_.end(), buf_.data(),
buf_.data() + bytes_transferred);
}
// Two consecutive new lines end the part of the response we're
// expecting.
bool need_data(true);
if (response_.find("\r\n\r\n", 0) != std::string::npos) {
// Try to parse the response.
try {
HttpResponse hr;
HttpResponseParser parser(hr);
parser.initModel();
parser.postBuffer(&response_[0], response_.size());
parser.poll();
if (!parser.needData()) {
need_data = false;
if (parser.httpParseOk()) {
receive_done_ = true;
}
}
} catch (const std::exception& ex) {
need_data = false;
ADD_FAILURE() << "error parsing response: " << ex.what();
}
}
if (!need_data) {
io_service_->stop();
} else {
receivePartialResponse();
}
});
}
/// @brief Checks if the TCP connection is still open.
///
/// Tests the TCP connection by trying to read from the socket.
/// Unfortunately expected failure depends on a race between the read
/// and the other side close so to check if the connection is closed
/// please use @c isConnectionClosed instead.
///
/// @return true if the TCP connection is open.
virtual bool isConnectionAlive() {<--- Function in derived class
// Remember the current non blocking setting.
const bool non_blocking_orig = stream_.lowest_layer().non_blocking();
// Set the socket to non blocking mode. We're going to test if the socket
// returns would_block status on the attempt to read from it.
stream_.lowest_layer().non_blocking(true);
// We need to provide a buffer for a call to read.
char data[2];
boost::system::error_code ec;
boost::asio::read(stream_, boost::asio::buffer(data, sizeof(data)), ec);
// Revert the original non_blocking flag on the socket.
stream_.lowest_layer().non_blocking(non_blocking_orig);
// If the connection is alive we'd typically get would_block status code.
// If there are any data that haven't been read we may also get success
// status. We're guessing that try_again may also be returned by some
// implementations in some situations. Any other error code indicates a
// problem with the connection so we assume that the connection has been
// closed.
return (!ec || (ec.value() == boost::asio::error::try_again) ||
(ec.value() == boost::asio::error::would_block));
}
/// @brief Checks if the TCP connection is already closed.
///
/// Tests the TCP connection by trying to read from the socket.
/// The read can block so this must be used to check if a connection
/// is alive so to check if the connection is alive please always
/// use @c isConnectionAlive.
///
/// @return true if the TCP connection is closed.
virtual bool isConnectionClosed() {<--- Function in derived class
// Remember the current non blocking setting.
const bool non_blocking_orig = stream_.lowest_layer().non_blocking();
// Set the socket to blocking mode. We're going to test if the socket
// returns eof status on the attempt to read from it.
stream_.lowest_layer().non_blocking(false);
// We need to provide a buffer for a call to read.
char data[2];
boost::system::error_code ec;
boost::asio::read(stream_, boost::asio::buffer(data, sizeof(data)), ec);
// Revert the original non_blocking flag on the socket.
stream_.lowest_layer().non_blocking(non_blocking_orig);
// If the connection is closed we'd typically get eof or
// stream_truncated status code.
return ((ec.value() == boost::asio::error::eof) ||
(ec.value() == STREAM_TRUNCATED));
}
/// @brief Close connection.
virtual void close() {<--- close is a virtual function<--- Function in derived class
stream_.lowest_layer().close();
}
/// @brief Returns the HTTP response string.
///
/// @return string containing the response.
virtual std::string getResponse() const {<--- Function in derived class
return (response_);
}
/// @brief Returns true if the receive completed without error.
///
/// @return True if the receive completed successfully, false
/// otherwise.
virtual bool receiveDone() const {<--- Function in derived class
return (receive_done_);
}
private:
/// @brief Holds pointer to the IO service.
isc::asiolink::IOServicePtr io_service_;
/// @brief A socket used for the connection.
TlsStreamImpl stream_;
/// @brief Buffer into which response is written.
std::array<char, 8192> buf_;
/// @brief Response in the textual format.
std::string response_;
/// @brief IP address of the server.
std::string server_address_;
/// @brief IP port of the server.
uint16_t server_port_;
/// @brief Set to true when the receive has completed successfully.
bool receive_done_;
};
/// @brief Pointer to the TestHttpsClient.
typedef boost::shared_ptr<TestHttpsClient> TestHttpsClientPtr;
#endif
|