11 #include <boost/asio.hpp>
12 #include <boost/asio/detail/socket_option.hpp>
13 #include <boost/bind/bind.hpp>
14 #include <boost/scoped_array.hpp>
15 #include <boost/asio/detail/recycling_allocator.hpp>
26 using boost::asio::async_write;
27 using boost::asio::buffer;
28 using boost::asio::buffer_cast;
29 using boost::asio::detail::socket_option::integer;
30 using boost::asio::const_buffer;
31 using boost::asio::mutable_buffer;
32 using boost::asio::mutable_buffers_1;
33 using boost::asio::null_buffers;
34 using boost::asio::socket_base;
36 using boost::function;
37 using boost::scoped_array;
38 using boost::system::error_code;
40 using std::ostringstream;
42 using namespace boost::placeholders;
44 using boost::asio::error::try_again;
45 using boost::asio::error::would_block;
46 using boost::asio::error::in_progress;
47 using boost::asio::error::interrupted;
48 using boost::asio::error::network_down;
49 using boost::asio::error::network_reset;
50 using boost::asio::error::network_unreachable;
51 using boost::asio::error::no_buffer_space;
52 using boost::asio::placeholders::error;
53 using boost::asio::placeholders::bytes_transferred;
54 using boost::asio::ip::tcp;
63 :
Task(session->reader_task_id(), session->GetSessionInstance()),
64 session_(session), read_fn_(read_fn), buffer_(buffer) {
67 if (session_->IsEstablished()) {
69 if (session_->IsReaderDeferred()) {
72 session_->stats_.read_blocked++;
73 session_->server_->stats_.read_blocked++;
75 session_->AsyncReadStart();
90 size_t buffer_send_size)
93 read_on_connect_(async_read_ready),
122 uint8_t *data =
new uint8_t[buffer_size];
123 mutable_buffer buffer = mutable_buffer(data, buffer_size);
129 uint8_t *data = buffer_cast<uint8_t *>(buffer);
133 static int BufferCmp(
const mutable_buffer &lhs,
const const_buffer &rhs) {
134 const uint8_t *lp = buffer_cast<uint8_t *>(lhs);
135 const uint8_t *rp = buffer_cast<const uint8_t *>(rhs);
146 std::scoped_lock lock(
mutex_);
169 server_->stats_.read_blocked_duration_usecs += blocked_usecs;
172 std::scoped_lock lock(
mutex_);
178 boost::asio::detail::recycling_allocator<void> allocator;
196 socket()->async_read_some(null_buffers(),
202 async_write(*
socket(), buffer(data, size),
204 error, bytes_transferred));
208 std::scoped_lock lock(
mutex_);
230 local =
socket()->local_endpoint(error);
231 out << local.address().to_string() <<
":" << local.port() <<
"::";
237 std::string hostname =
"";
238 if (local.address().is_v4()) {
243 out << hostname <<
":" <<
remote_.address().to_string();
258 "Passive session Accept complete");
275 std::scoped_lock lock(
mutex_);
284 "Active session connection complete");
308 bool call_observer,
bool notify_server) {
309 std::unique_lock<std::mutex> lock(
mutex_);
313 socket()->shutdown(tcp::socket::shutdown_both, error);
316 "Shutdown failed due to error: " << error.message());
350 boost::asio::detail::recycling_allocator<void> allocator;
357 std::unique_lock<std::mutex> lock(
mutex_);
381 const error_code &error,
383 std::unique_lock<std::mutex> lock(session->mutex_);
384 if (session->IsSocketErrorHard(error)) {
387 "Write failed due to error: " << error.message());
388 session->CloseInternal(error,
true);
395 if (session->IsClosedLocked())
return;
398 session->stats_.write_bytes += wrote;
399 session->server_->stats_.write_bytes += wrote;
401 bool send_ready =
false;
402 bool more_write = session->writer_->UpdateBufferQueue(wrote, &send_ready);
406 session->writer_->TriggerAsyncWrite();
407 }
else if (session->tcp_close_in_progress_) {
409 session->CloseInternal(error,
true);
415 session->WriteReady(error);
421 std::scoped_lock lock(session->mutex_);
426 if (session->IsClosedLocked())
return;
427 session->writer_->TriggerAsyncWrite();
432 std::unique_lock<std::mutex> lock(
mutex_);
443 if (
socket()->non_blocking()) {
445 int len =
writer_->AsyncSend(data, size, &error);
449 "Write failed due to error: "
450 << error.category().name() <<
" "
455 if ((
size_t) len != size)
457 if (sent) *sent = (len > 0) ? len : 0;
463 size_t bytes_transferred) {
464 Buffer rdbuf(buffer_cast<const uint8_t *>(buffer), bytes_transferred);
471 return socket()->read_some(mutable_buffers_1(buffer), *error);
479 size_t size =
socket_->available(error);
486 std::unique_lock<std::mutex> lock(session->mutex_);
487 if (session->closed_) {
491 mutable_buffer buffer =
492 session->AllocateBuffer(session->GetReadBufferSize());
495 size_t bytes_transferred = session->ReadSome(buffer, &error);
496 if (session->IsSocketErrorHard(error)) {
497 session->ReleaseBufferLocked(buffer);
499 if (error != boost::asio::error::eof) {
500 if (strcmp(error.category().name(),
"asio.ssl") == 0 &&
503 "Read failed due to error "
504 << error.category().name() <<
" "
506 <<
" : " << error.message());
509 "Read failed due to error "
510 << error.category().name() <<
" "
512 <<
" : " << error.message());
516 session->CloseInternal(error,
true);
521 session->stats_.read_calls++;
522 session->stats_.read_bytes += bytes_transferred;
523 session->server_->stats_.read_calls++;
524 session->server_->stats_.read_bytes += bytes_transferred;
526 Task *
task = session->CreateReaderTask(buffer, bytes_transferred);
558 return remote.port();
562 const string &md5_password) {
581 : session_(session), callback_(callback), offset_(0), remain_(-1) {
591 return kMaxMessageSize;
593 int bufsize = 1 << 8;
594 for (; bufsize < kMaxMessageSize && bufsize < length; bufsize <<= 1) {
607 assert((dst - data) + bytes < msglength);
608 memcpy(dst, cp, bytes);
616 int count = msglength - (dst - data);
617 assert((dst - data) + count <= msglength);
626 for (BufferQueue::const_iterator iter =
queue_.begin();
627 iter !=
queue_.end(); ++iter) {
638 uint8_t *data,
Buffer buffer,
size_t size)
const {
641 for (BufferQueue::const_iterator iter =
queue_.begin();
642 iter !=
queue_.end(); ++iter) {
652 int remain = size - offset;
653 avail = min(avail, remain);
654 assert(offset + avail <= size);
655 memcpy(data + offset, cp, avail);
660 int remain = size - offset;
661 avail = min(avail, remain);
662 assert(offset + avail <= size);
669 return Buffer(data, size);
682 if (queuelen +
static_cast<int>(size) < kHeaderLenSize) {
686 scoped_array<uint8_t> data(
new uint8_t[kHeaderLenSize]);
687 Buffer header =
PullUp(data.get(), buffer, kHeaderLenSize);
691 remain_ = msglength - queuelen;
706 bool success =
callback_(data.get(), msglength);
717 if (msglength > avail) {
749 if (ec == would_block)
751 if (ec == in_progress)
753 if (ec == interrupted)
755 if (ec == network_down)
757 if (ec == network_reset)
759 if (ec == network_unreachable)
761 if (ec == no_buffer_space)
769 boost::asio::ip::tcp::no_delay no_delay_option(
true);
770 socket()->set_option(no_delay_option, ec);
773 "tcp_no_delay set error: " << ec);
780 socket_base::send_buffer_size send_buffer_size_option(size);
781 socket()->set_option(send_buffer_size_option, ec);
784 "send_buffer_size set error: " << ec);
793 socket_base::receive_buffer_size receive_buffer_size_option(size);
794 socket()->set_option(receive_buffer_size_option, ec);
797 "receive_buffer_size set error: " << ec);
805 int keepalive_intvl,
int keepalive_probes,
int tcp_user_timeout_val) {
807 socket_base::keep_alive keep_alive_option(
true);
808 socket()->set_option(keep_alive_option, ec);
811 "keep_alive set error: " << ec);
815 typedef integer< IPPROTO_TCP, TCP_KEEPIDLE > keepalive_idle_time;
816 keepalive_idle_time keepalive_idle_time_option(keepalive_time);
817 socket()->set_option(keepalive_idle_time_option, ec);
820 "keepalive_idle_time: " << keepalive_time <<
" set error: " << ec);
824 typedef integer< IPPROTO_TCP, TCP_KEEPALIVE > keepalive_idle_time;
825 keepalive_idle_time keepalive_idle_time_option(keepalive_time);
826 socket()->set_option(keepalive_idle_time_option, ec);
829 "keepalive_idle_time: " << keepalive_time <<
" set error: " << ec);
833 #error No TCP keepalive option defined.
836 typedef integer< IPPROTO_TCP, TCP_KEEPINTVL > keepalive_interval;
837 keepalive_interval keepalive_interval_option(keepalive_intvl);
838 socket()->set_option(keepalive_interval_option, ec);
841 "keepalive_interval: " << keepalive_intvl <<
" set error: " << ec);
846 typedef integer< IPPROTO_TCP, TCP_KEEPCNT > keepalive_count;
847 keepalive_count keepalive_count_option(keepalive_probes);
848 socket()->set_option(keepalive_count_option, ec);
851 "keepalive_probes: " << keepalive_probes <<
" set error: " << ec);
855 #ifdef TCP_USER_TIMEOUT
856 typedef integer< IPPROTO_TCP, TCP_USER_TIMEOUT > tcp_user_timeout;
857 tcp_user_timeout tcp_user_timeout_option(tcp_user_timeout_val);
858 socket()->set_option(tcp_user_timeout_option, ec);
861 "tcp_user_timeout: " << tcp_user_timeout_val <<
" set error: "
876 socket()->non_blocking(
true, ec);
879 "Cannot set socket non blocking: " << ec);
883 char *buffer_size_str = getenv(
"TCP_SESSION_SOCKET_BUFFER_SIZE");
884 if (!buffer_size_str)
return ec;
886 uint32_t sz =
static_cast<uint32_t
>(strtoul(buffer_size_str, NULL, 0));
894 socket_base::send_buffer_size send_buffer_size_option(sz);
895 socket()->set_option(send_buffer_size_option, ec);
898 "send_buffer_size set error: " << ec);
902 socket_base::receive_buffer_size receive_buffer_size_option(sz);
903 socket()->set_option(receive_buffer_size_option, ec);
906 "receive_buffer_size set error: " << ec);
std::string ResolveCanonicalNameIPv6(const std::string &ipv6)
std::string ResolveCanonicalName()
boost::asio::io_context * io_service()
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
int GetTaskId(const std::string &name)
void Enqueue(Task *task)
Enqueues a task for running. Starts task if all policy rules are met else puts task in waitq....
static TaskScheduler * GetInstance()
Task is a class to describe a computational task within OpenSDN control plane applications....
static const int kTaskInstanceAny
Specifies value for wildcard (any or *) task data ID.
TcpMessageReader(TcpSession *session, ReceiveCallback callback)
Buffer PullUp(uint8_t *data, Buffer buffer, size_t size) const
int QueueByteLength() const
int AllocBufferSize(int length)
virtual void OnRead(Buffer buffer)
ReceiveCallback callback_
virtual ~TcpMessageReader()
boost::function< bool(const uint8_t *, size_t)> ReceiveCallback
virtual const int GetMaxMessageSize()=0
virtual int MsgLength(Buffer buffer, int offset)=0
uint8_t * BufferConcat(uint8_t *data, Buffer buffer, int msglength)
boost::asio::const_buffer Buffer
virtual const int GetHeaderLenSize()=0
EventManager * event_manager()
int SetDscpSocketOption(NativeSocketType fd, uint8_t value)
int SetMd5SocketOption(NativeSocketType fd, uint32_t peer_ip, const std::string &md5_password)
string Description() const
Gives a description of the task.
virtual bool Run()
Code to execute in a task. Returns true if task is completed. Return false to reschedule the task.
Reader(TcpSessionPtr session, ReadHandler read_fn, Buffer buffer)
function< void(Buffer)> ReadHandler
virtual size_t GetReadBufferSize() const
static void AsyncReadHandler(TcpSessionPtr session)
virtual int GetSessionInstance() const
int ClearMd5SocketOption(uint32_t peer_ip)
virtual void AsyncWrite(const uint8_t *data, std::size_t size)
static bool IsSocketErrorHard(const boost::system::error_code &ec)
void TriggerAsyncReadHandler()
boost::scoped_ptr< Strand > io_strand_
virtual void WriteReady(const boost::system::error_code &error)
std::atomic< bool > defer_reader_
int32_t remote_port() const
void AsyncReadStartInternal(TcpSessionPtr session)
boost::scoped_ptr< Socket > socket_
virtual Task * CreateReaderTask(boost::asio::mutable_buffer, size_t)
std::atomic< bool > tcp_close_in_progress_
boost::system::error_code SetTcpSendBufSize(uint32_t size)
virtual void AsyncReadSome()
uint8_t GetDscpValue() const
boost::asio::strand< boost::asio::io_context::executor_type > Strand
void AsyncWriteInternal(TcpSessionPtr session)
void ReleaseBufferLocked(Buffer buffer)
virtual void OnRead(Buffer buffer)=0
static int reader_task_id_
virtual Socket * socket() const
std::atomic< bool > write_blocked_
static const uint8_t * BufferData(const Buffer &buffer)
boost::system::error_code SetTcpRecvBufSize(uint32_t size)
int SetMd5SocketOption(uint32_t peer_ip, const std::string &md5_password)
BufferQueue buffer_queue_
boost::system::error_code SetTcpNoDelay()
static void AsyncWriteHandler(TcpSessionPtr session, const boost::system::error_code &error, std::size_t bytes_transferred)
static size_t BufferSize(const Buffer &buffer)
void GetRxSocketStats(SocketIOStats *socket_stats) const
void DeleteBuffer(boost::asio::mutable_buffer buffer)
void SessionEstablished(Endpoint remote, Direction direction)
virtual void ReleaseBuffer(Buffer buffer)
boost::asio::mutable_buffer AllocateBuffer(size_t buffer_size)
void set_observer(EventObserver observer)
boost::function< void(TcpSession *, Event)> EventObserver
std::atomic< int > refcount_
virtual void SetDeferReader(bool defer_reader)
boost::asio::ip::tcp::endpoint Endpoint
boost::asio::const_buffer Buffer
boost::system::error_code close_reason_
boost::scoped_ptr< TcpMessageWriter > writer_
void CloseInternal(const boost::system::error_code &ec, bool call_observer, bool notify_server=true)
TcpSession(TcpServer *server, Socket *socket, bool async_read_ready=true, size_t buffer_send_size=TcpSession::kDefaultWriteBufferSize)
boost::intrusive_ptr< TcpSession > TcpSessionPtr
bool IsEstablishedLocked() const
virtual boost::system::error_code SetSocketOptions()
Endpoint local_endpoint() const
boost::system::error_code SetSocketKeepaliveOptions(int keepalive_time, int keepalive_intvl, int keepalive_probes, int tcp_user_timeout_val=0)
void GetTxSocketStats(SocketIOStats *socket_stats) const
static const int kDefaultBufferSize
std::string remote_addr_str_
virtual bool Connected(Endpoint remote)
boost::asio::ip::tcp::socket Socket
virtual void AsyncReadStart()
int32_t local_port() const
virtual bool Send(const uint8_t *data, size_t size, size_t *sent)
virtual size_t ReadSome(boost::asio::mutable_buffer buffer, boost::system::error_code *error)
int SetDscpSocketOption(uint8_t value)
#define TCP_SESSION_LOG_DEBUG(session, dir, arg)
#define TCP_SESSION_LOG_ERROR(session, dir, arg)
#define TCP_SESSION_LOG_UT_DEBUG(session, dir, arg)
std::atomic< uint64_t > read_block_start_time
void GetRxStats(SocketIOStats *socket_stats) const
std::atomic< uint64_t > read_blocked_duration_usecs
void GetTxStats(SocketIOStats *socket_stats) const
static int BufferCmp(const mutable_buffer &lhs, const const_buffer &rhs)
#define SSL_SHORT_READ_ERROR
static uint64_t UTCTimestampUsec()