Kea 2.7.6
tcp_socket.h
Go to the documentation of this file.
1// Copyright (C) 2011-2024 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#ifndef TCP_SOCKET_H
8#define TCP_SOCKET_H
9
10#ifndef BOOST_ASIO_HPP
11#error "asio.hpp must be included before including this, see asiolink.h as to why"
12#endif
13
16#include <asiolink/io_service.h>
19#include <util/buffer.h>
20#include <util/io.h>
21
22#include <algorithm>
23#include <cstddef>
24
25#include <boost/numeric/conversion/cast.hpp>
26
27#include <netinet/in.h>
28#include <sys/socket.h>
29#include <unistd.h> // for some IPC/network system calls
30
31namespace isc {
32namespace asiolink {
33
37class BufferTooLarge : public IOError {
38public:
39 BufferTooLarge(const char* file, size_t line, const char* what) :
40 IOError(file, line, what) {}
41};
42
47template <typename C>
48class TCPSocket : public IOAsioSocket<C> {
49private:
51 TCPSocket(const TCPSocket&);
52 TCPSocket& operator=(const TCPSocket&);
53
54public:
55
61 TCPSocket(boost::asio::ip::tcp::socket& socket);
62
69 TCPSocket(const IOServicePtr& service);
70
72 virtual ~TCPSocket();
73
75 virtual int getNative() const {
76 return (socket_.native_handle());
77 }
78
80 virtual int getProtocol() const {
81 return (IPPROTO_TCP);
82 }
83
87 virtual bool isOpenSynchronous() const {
88 return (false);
89 }
90
97 bool isUsable() const {
98 // If the socket is open it doesn't mean that it is still usable. The connection
99 // could have been closed on the other end. We have to check if we can still
100 // use this socket.
101 if (socket_.is_open()) {
102 // Remember the current non blocking setting.
103 const bool non_blocking_orig = socket_.non_blocking();
104 // Set the socket to non blocking mode. We're going to test if the socket
105 // returns would_block status on the attempt to read from it.
106 socket_.non_blocking(true);
107
108 boost::system::error_code ec;
109 char data[2];
110
111 // Use receive with message peek flag to avoid removing the data awaiting
112 // to be read.
113 socket_.receive(boost::asio::buffer(data, sizeof(data)),
114 boost::asio::socket_base::message_peek,
115 ec);
116
117 // Revert the original non_blocking flag on the socket.
118 socket_.non_blocking(non_blocking_orig);
119
120 // If the connection is alive we'd typically get would_block status code.
121 // If there are any data that haven't been read we may also get success
122 // status. We're guessing that try_again may also be returned by some
123 // implementations in some situations. Any other error code indicates a
124 // problem with the connection so we assume that the connection has been
125 // closed.
126 return (!ec || (ec.value() == boost::asio::error::try_again) ||
127 (ec.value() == boost::asio::error::would_block));
128 }
129
130 return (false);
131 }
132
140 virtual void open(const IOEndpoint* endpoint, C& callback);
141
154 virtual void asyncSend(const void* data, size_t length,
155 const IOEndpoint* endpoint, C& callback);
156
169 void asyncSend(const void* data, size_t length, C& callback);
170
182 virtual void asyncReceive(void* data, size_t length, size_t offset,
183 IOEndpoint* endpoint, C& callback);
184
200 virtual bool processReceivedData(const void* staging, size_t length,
201 size_t& cumulative, size_t& offset,
202 size_t& expected,
204
206 virtual void cancel();
207
209 virtual void close();
210
214 virtual boost::asio::ip::tcp::socket& getASIOSocket() const {
215 return (socket_);
216 }
217
218private:
219
221 IOServicePtr io_service_;
222
226
228 std::unique_ptr<boost::asio::ip::tcp::socket> socket_ptr_;
229
231 boost::asio::ip::tcp::socket& socket_;
232
246
248 isc::util::OutputBufferPtr send_buffer_;
249};
250
251// Constructor - caller manages socket
252
253template <typename C>
254TCPSocket<C>::TCPSocket(boost::asio::ip::tcp::socket& socket) :
255 socket_ptr_(), socket_(socket), send_buffer_() {
256}
257
258// Constructor - create socket on the fly
259
260template <typename C>
261TCPSocket<C>::TCPSocket(const IOServicePtr& io_service) : io_service_(io_service),
262 socket_ptr_(new boost::asio::ip::tcp::socket(io_service_->getInternalIOService())),
263 socket_(*socket_ptr_) {
264}
265
266// Destructor.
267
268template <typename C>
270 close();
271}
272
273// Open the socket.
274
275template <typename C> void
276TCPSocket<C>::open(const IOEndpoint* endpoint, C& callback) {
277 // If socket is open on this end but has been closed by the peer,
278 // we need to reconnect.
279 if (socket_.is_open() && !isUsable()) {
280 close();
281 }
282 // Ignore opens on already-open socket. Don't throw a failure because
283 // of uncertainties as to what precedes when using asynchronous I/O.
284 // Also allows us a treat a passed-in socket as a self-managed socket.
285 if (!socket_.is_open()) {
286 if (endpoint->getFamily() == AF_INET) {
287 socket_.open(boost::asio::ip::tcp::v4());
288 } else {
289 socket_.open(boost::asio::ip::tcp::v6());
290 }
291
292 // Set options on the socket:
293
294 // Reuse address - allow the socket to bind to a port even if the port
295 // is in the TIMED_WAIT state.
296 socket_.set_option(boost::asio::socket_base::reuse_address(true));
297 }
298
299 // Upconvert to a TCPEndpoint. We need to do this because although
300 // IOEndpoint is the base class of UDPEndpoint and TCPEndpoint, it does not
301 // contain a method for getting at the underlying endpoint type - that is in
303 isc_throw_assert(endpoint->getProtocol() == IPPROTO_TCP);
304 const TCPEndpoint* tcp_endpoint =
305 static_cast<const TCPEndpoint*>(endpoint);
306
307 // Connect to the remote endpoint. On success, the handler will be
308 // called (with one argument - the length argument will default to
309 // zero).
310 socket_.async_connect(tcp_endpoint->getASIOEndpoint(), callback);
311}
312
313// Send a message. Should never do this if the socket is not open, so throw
314// an exception if this is the case.
315
316template <typename C> void
317TCPSocket<C>::asyncSend(const void* data, size_t length, C& callback) {
318 if (socket_.is_open()) {
319
320 try {
321 send_buffer_.reset(new isc::util::OutputBuffer(length));
322 send_buffer_->writeData(data, length);
323
324 // Send the data.
325 socket_.async_send(boost::asio::buffer(send_buffer_->getData(),
326 send_buffer_->getLength()),
327 callback);
328 } catch (const boost::numeric::bad_numeric_cast&) {
330 "attempt to send buffer larger than 64kB");
331 }
332
333 } else {
335 "attempt to send on a TCP socket that is not open");
336 }
337}
338
339template <typename C> void
340TCPSocket<C>::asyncSend(const void* data, size_t length,
341 const IOEndpoint*, C& callback) {
342 if (socket_.is_open()) {
343
347 try {
349 uint16_t count = boost::numeric_cast<uint16_t>(length);
350
352 send_buffer_.reset(new isc::util::OutputBuffer(length + 2));
353 send_buffer_->writeUint16(count);
354 send_buffer_->writeData(data, length);
355
357 socket_.async_send(boost::asio::buffer(send_buffer_->getData(),
358 send_buffer_->getLength()), callback);
359 } catch (const boost::numeric::bad_numeric_cast&) {
361 "attempt to send buffer larger than 64kB");
362 }
363
364 } else {
366 "attempt to send on a TCP socket that is not open");
367 }
368}
369
370// Receive a message. Note that the "offset" argument is used as an index
371// into the buffer in order to decide where to put the data. It is up to the
372// caller to initialize the data to zero
373template <typename C> void
374TCPSocket<C>::asyncReceive(void* data, size_t length, size_t offset,
375 IOEndpoint* endpoint, C& callback) {
376 if (socket_.is_open()) {
377 // Upconvert to a TCPEndpoint. We need to do this because although
378 // IOEndpoint is the base class of UDPEndpoint and TCPEndpoint, it
379 // does not contain a method for getting at the underlying endpoint
380 // type - that is in the derived class and the two classes differ on
381 // return type.
382 isc_throw_assert(endpoint->getProtocol() == IPPROTO_TCP);
383 TCPEndpoint* tcp_endpoint = static_cast<TCPEndpoint*>(endpoint);
384
385 // Write the endpoint details from the communications link. Ideally
386 // we should make IOEndpoint assignable, but this runs in to all sorts
387 // of problems concerning the management of the underlying Boost
388 // endpoint (e.g. if it is not self-managed, is the copied one
389 // self-managed?) The most pragmatic solution is to let Boost take care
390 // of everything and copy details of the underlying endpoint.
391 tcp_endpoint->getASIOEndpoint() = socket_.remote_endpoint();
392
393 // Ensure we can write into the buffer and if so, set the pointer to
394 // where the data will be written.
395 if (offset >= length) {
396 isc_throw(BufferOverflow, "attempt to read into area beyond end of "
397 "TCP receive buffer");
398 }
399 void* buffer_start = static_cast<void*>(static_cast<uint8_t*>(data) + offset);
400
401 // ... and kick off the read.
402 socket_.async_receive(boost::asio::buffer(buffer_start, length - offset), callback);
403
404 } else {
406 "attempt to receive from a TCP socket that is not open");
407 }
408}
409
410// Is the receive complete?
411
412template <typename C> bool
413TCPSocket<C>::processReceivedData(const void* staging, size_t length,
414 size_t& cumulative, size_t& offset,
415 size_t& expected,
417 // Point to the data in the staging buffer and note how much there is.
418 const uint8_t* data = static_cast<const uint8_t*>(staging);
419 size_t data_length = length;
420
421 // Is the number is "expected" valid? It won't be unless we have received
422 // at least two bytes of data in total for this set of receives.
423 if (cumulative < 2) {
424
425 // "expected" is not valid. Did this read give us enough data to
426 // work it out?
427 cumulative += length;
428 if (cumulative < 2) {
429
430 // Nope, still not valid. This must have been the first packet and
431 // was only one byte long. Tell the fetch code to read the next
432 // packet into the staging buffer beyond the data that is already
433 // there so that the next time we are called we have a complete
434 // TCP count.
435 offset = cumulative;
436 return (false);
437 }
438
439 // Have enough data to interpret the packet count, so do so now.
440 expected = isc::util::readUint16(data, cumulative);
441
442 // We have two bytes less of data to process. Point to the start of the
443 // data and adjust the packet size. Note that at this point,
444 // "cumulative" is the true amount of data in the staging buffer, not
445 // "length".
446 data += 2;
447 data_length = cumulative - 2;
448 } else {
449
450 // Update total amount of data received.
451 cumulative += length;
452 }
453
454 // Regardless of anything else, the next read goes into the start of the
455 // staging buffer.
456 offset = 0;
457
458 // Work out how much data we still have to put in the output buffer. (This
459 // could be zero if we have just interpreted the TCP count and that was
460 // set to zero.)
461 if (expected >= outbuff->getLength()) {
462
463 // Still need data in the output packet. Copy what we can from the
464 // staging buffer to the output buffer.
465 size_t copy_amount = std::min(expected - outbuff->getLength(), data_length);
466 outbuff->writeData(data, copy_amount);
467 }
468
469 // We can now say if we have all the data.
470 return (expected == outbuff->getLength());
471}
472
473// Cancel I/O on the socket. No-op if the socket is not open.
474
475template <typename C> void
477 if (socket_.is_open()) {
478 socket_.cancel();
479 }
480}
481
482// Close the socket down. Can only do this if the socket is open and we are
483// managing it ourself.
484
485template <typename C> void
487 if (socket_.is_open() && socket_ptr_) {
488 socket_.close();
489 }
490}
491
492} // namespace asiolink
493} // namespace isc
494
495#endif // TCP_SOCKET_H
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
The OutputBuffer class is a buffer abstraction for manipulating mutable data.
Definition buffer.h:343
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
#define isc_throw_assert(expr)
Replacement for assert() that throws if the expression is false.
Definition isc_assert.h:18
uint16_t readUint16(void const *const buffer, size_t const length)
uint16_t wrapper over readUint.
Definition io.h:76
boost::shared_ptr< OutputBuffer > OutputBufferPtr
Type of pointers to output buffers.
Definition buffer.h:571
Defines the logger used by the top-level component of kea-lfc.