Kea 2.7.0
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#if BOOST_VERSION < 106600
77 return (socket_.native());
78#else
79 return (socket_.native_handle());
80#endif
81 }
82
84 virtual int getProtocol() const {
85 return (IPPROTO_TCP);
86 }
87
91 virtual bool isOpenSynchronous() const {
92 return (false);
93 }
94
101 bool isUsable() const {
102 // If the socket is open it doesn't mean that it is still usable. The connection
103 // could have been closed on the other end. We have to check if we can still
104 // use this socket.
105 if (socket_.is_open()) {
106 // Remember the current non blocking setting.
107 const bool non_blocking_orig = socket_.non_blocking();
108 // Set the socket to non blocking mode. We're going to test if the socket
109 // returns would_block status on the attempt to read from it.
110 socket_.non_blocking(true);
111
112 boost::system::error_code ec;
113 char data[2];
114
115 // Use receive with message peek flag to avoid removing the data awaiting
116 // to be read.
117 socket_.receive(boost::asio::buffer(data, sizeof(data)),
118 boost::asio::socket_base::message_peek,
119 ec);
120
121 // Revert the original non_blocking flag on the socket.
122 socket_.non_blocking(non_blocking_orig);
123
124 // If the connection is alive we'd typically get would_block status code.
125 // If there are any data that haven't been read we may also get success
126 // status. We're guessing that try_again may also be returned by some
127 // implementations in some situations. Any other error code indicates a
128 // problem with the connection so we assume that the connection has been
129 // closed.
130 return (!ec || (ec.value() == boost::asio::error::try_again) ||
131 (ec.value() == boost::asio::error::would_block));
132 }
133
134 return (false);
135 }
136
144 virtual void open(const IOEndpoint* endpoint, C& callback);
145
158 virtual void asyncSend(const void* data, size_t length,
159 const IOEndpoint* endpoint, C& callback);
160
173 void asyncSend(const void* data, size_t length, C& callback);
174
186 virtual void asyncReceive(void* data, size_t length, size_t offset,
187 IOEndpoint* endpoint, C& callback);
188
204 virtual bool processReceivedData(const void* staging, size_t length,
205 size_t& cumulative, size_t& offset,
206 size_t& expected,
208
210 virtual void cancel();
211
213 virtual void close();
214
218 virtual boost::asio::ip::tcp::socket& getASIOSocket() const {
219 return (socket_);
220 }
221
222private:
223
225 IOServicePtr io_service_;
226
230
232 std::unique_ptr<boost::asio::ip::tcp::socket> socket_ptr_;
233
235 boost::asio::ip::tcp::socket& socket_;
236
250
252 isc::util::OutputBufferPtr send_buffer_;
253};
254
255// Constructor - caller manages socket
256
257template <typename C>
258TCPSocket<C>::TCPSocket(boost::asio::ip::tcp::socket& socket) :
259 socket_ptr_(), socket_(socket), send_buffer_() {
260}
261
262// Constructor - create socket on the fly
263
264template <typename C>
265TCPSocket<C>::TCPSocket(const IOServicePtr& io_service) : io_service_(io_service),
266 socket_ptr_(new boost::asio::ip::tcp::socket(io_service_->getInternalIOService())),
267 socket_(*socket_ptr_) {
268}
269
270// Destructor.
271
272template <typename C>
274 close();
275}
276
277// Open the socket.
278
279template <typename C> void
280TCPSocket<C>::open(const IOEndpoint* endpoint, C& callback) {
281 // If socket is open on this end but has been closed by the peer,
282 // we need to reconnect.
283 if (socket_.is_open() && !isUsable()) {
284 close();
285 }
286 // Ignore opens on already-open socket. Don't throw a failure because
287 // of uncertainties as to what precedes when using asynchronous I/O.
288 // Also allows us a treat a passed-in socket as a self-managed socket.
289 if (!socket_.is_open()) {
290 if (endpoint->getFamily() == AF_INET) {
291 socket_.open(boost::asio::ip::tcp::v4());
292 } else {
293 socket_.open(boost::asio::ip::tcp::v6());
294 }
295
296 // Set options on the socket:
297
298 // Reuse address - allow the socket to bind to a port even if the port
299 // is in the TIMED_WAIT state.
300 socket_.set_option(boost::asio::socket_base::reuse_address(true));
301 }
302
303 // Upconvert to a TCPEndpoint. We need to do this because although
304 // IOEndpoint is the base class of UDPEndpoint and TCPEndpoint, it does not
305 // contain a method for getting at the underlying endpoint type - that is in
307 isc_throw_assert(endpoint->getProtocol() == IPPROTO_TCP);
308 const TCPEndpoint* tcp_endpoint =
309 static_cast<const TCPEndpoint*>(endpoint);
310
311 // Connect to the remote endpoint. On success, the handler will be
312 // called (with one argument - the length argument will default to
313 // zero).
314 socket_.async_connect(tcp_endpoint->getASIOEndpoint(), callback);
315}
316
317// Send a message. Should never do this if the socket is not open, so throw
318// an exception if this is the case.
319
320template <typename C> void
321TCPSocket<C>::asyncSend(const void* data, size_t length, C& callback) {
322 if (socket_.is_open()) {
323
324 try {
325 send_buffer_.reset(new isc::util::OutputBuffer(length));
326 send_buffer_->writeData(data, length);
327
328 // Send the data.
329 socket_.async_send(boost::asio::buffer(send_buffer_->getData(),
330 send_buffer_->getLength()),
331 callback);
332 } catch (const boost::numeric::bad_numeric_cast&) {
334 "attempt to send buffer larger than 64kB");
335 }
336
337 } else {
339 "attempt to send on a TCP socket that is not open");
340 }
341}
342
343template <typename C> void
344TCPSocket<C>::asyncSend(const void* data, size_t length,
345 const IOEndpoint*, C& callback) {
346 if (socket_.is_open()) {
347
351 try {
353 uint16_t count = boost::numeric_cast<uint16_t>(length);
354
356 send_buffer_.reset(new isc::util::OutputBuffer(length + 2));
357 send_buffer_->writeUint16(count);
358 send_buffer_->writeData(data, length);
359
361 socket_.async_send(boost::asio::buffer(send_buffer_->getData(),
362 send_buffer_->getLength()), callback);
363 } catch (const boost::numeric::bad_numeric_cast&) {
365 "attempt to send buffer larger than 64kB");
366 }
367
368 } else {
370 "attempt to send on a TCP socket that is not open");
371 }
372}
373
374// Receive a message. Note that the "offset" argument is used as an index
375// into the buffer in order to decide where to put the data. It is up to the
376// caller to initialize the data to zero
377template <typename C> void
378TCPSocket<C>::asyncReceive(void* data, size_t length, size_t offset,
379 IOEndpoint* endpoint, C& callback) {
380 if (socket_.is_open()) {
381 // Upconvert to a TCPEndpoint. We need to do this because although
382 // IOEndpoint is the base class of UDPEndpoint and TCPEndpoint, it
383 // does not contain a method for getting at the underlying endpoint
384 // type - that is in the derived class and the two classes differ on
385 // return type.
386 isc_throw_assert(endpoint->getProtocol() == IPPROTO_TCP);
387 TCPEndpoint* tcp_endpoint = static_cast<TCPEndpoint*>(endpoint);
388
389 // Write the endpoint details from the communications link. Ideally
390 // we should make IOEndpoint assignable, but this runs in to all sorts
391 // of problems concerning the management of the underlying Boost
392 // endpoint (e.g. if it is not self-managed, is the copied one
393 // self-managed?) The most pragmatic solution is to let Boost take care
394 // of everything and copy details of the underlying endpoint.
395 tcp_endpoint->getASIOEndpoint() = socket_.remote_endpoint();
396
397 // Ensure we can write into the buffer and if so, set the pointer to
398 // where the data will be written.
399 if (offset >= length) {
400 isc_throw(BufferOverflow, "attempt to read into area beyond end of "
401 "TCP receive buffer");
402 }
403 void* buffer_start = static_cast<void*>(static_cast<uint8_t*>(data) + offset);
404
405 // ... and kick off the read.
406 socket_.async_receive(boost::asio::buffer(buffer_start, length - offset), callback);
407
408 } else {
410 "attempt to receive from a TCP socket that is not open");
411 }
412}
413
414// Is the receive complete?
415
416template <typename C> bool
417TCPSocket<C>::processReceivedData(const void* staging, size_t length,
418 size_t& cumulative, size_t& offset,
419 size_t& expected,
421 // Point to the data in the staging buffer and note how much there is.
422 const uint8_t* data = static_cast<const uint8_t*>(staging);
423 size_t data_length = length;
424
425 // Is the number is "expected" valid? It won't be unless we have received
426 // at least two bytes of data in total for this set of receives.
427 if (cumulative < 2) {
428
429 // "expected" is not valid. Did this read give us enough data to
430 // work it out?
431 cumulative += length;
432 if (cumulative < 2) {
433
434 // Nope, still not valid. This must have been the first packet and
435 // was only one byte long. Tell the fetch code to read the next
436 // packet into the staging buffer beyond the data that is already
437 // there so that the next time we are called we have a complete
438 // TCP count.
439 offset = cumulative;
440 return (false);
441 }
442
443 // Have enough data to interpret the packet count, so do so now.
444 expected = isc::util::readUint16(data, cumulative);
445
446 // We have two bytes less of data to process. Point to the start of the
447 // data and adjust the packet size. Note that at this point,
448 // "cumulative" is the true amount of data in the staging buffer, not
449 // "length".
450 data += 2;
451 data_length = cumulative - 2;
452 } else {
453
454 // Update total amount of data received.
455 cumulative += length;
456 }
457
458 // Regardless of anything else, the next read goes into the start of the
459 // staging buffer.
460 offset = 0;
461
462 // Work out how much data we still have to put in the output buffer. (This
463 // could be zero if we have just interpreted the TCP count and that was
464 // set to zero.)
465 if (expected >= outbuff->getLength()) {
466
467 // Still need data in the output packet. Copy what we can from the
468 // staging buffer to the output buffer.
469 size_t copy_amount = std::min(expected - outbuff->getLength(), data_length);
470 outbuff->writeData(data, copy_amount);
471 }
472
473 // We can now say if we have all the data.
474 return (expected == outbuff->getLength());
475}
476
477// Cancel I/O on the socket. No-op if the socket is not open.
478
479template <typename C> void
481 if (socket_.is_open()) {
482 socket_.cancel();
483 }
484}
485
486// Close the socket down. Can only do this if the socket is open and we are
487// managing it ourself.
488
489template <typename C> void
491 if (socket_.is_open() && socket_ptr_) {
492 socket_.close();
493 }
494}
495
496} // namespace asiolink
497} // namespace isc
498
499#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.