2018-12-31 20:04:05 +01:00
|
|
|
//
|
2024-01-01 01:07:21 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2024
|
2018-12-31 20:04:05 +01:00
|
|
|
//
|
|
|
|
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
//
|
|
|
|
#include "td/net/TcpListener.h"
|
|
|
|
|
|
|
|
#include "td/utils/logging.h"
|
2018-09-07 02:41:21 +02:00
|
|
|
#include "td/utils/port/detail/PollableFd.h"
|
2018-12-31 20:04:05 +01:00
|
|
|
|
|
|
|
namespace td {
|
2018-09-11 00:20:41 +02:00
|
|
|
|
2020-11-09 21:48:43 +01:00
|
|
|
TcpListener::TcpListener(int port, ActorShared<Callback> callback, Slice server_address)
|
|
|
|
: port_(port), callback_(std::move(callback)), server_address_(server_address.str()) {
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void TcpListener::hangup() {
|
|
|
|
stop();
|
|
|
|
}
|
|
|
|
|
|
|
|
void TcpListener::start_up() {
|
2020-11-09 21:46:07 +01:00
|
|
|
auto r_socket = ServerSocketFd::open(port_, server_address_);
|
2018-12-31 20:04:05 +01:00
|
|
|
if (r_socket.is_error()) {
|
|
|
|
LOG(ERROR) << "Can't open server socket: " << r_socket.error();
|
|
|
|
set_timeout_in(5);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
server_fd_ = r_socket.move_as_ok();
|
2018-09-11 00:20:41 +02:00
|
|
|
Scheduler::subscribe(server_fd_.get_poll_info().extract_pollable_fd(this));
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void TcpListener::tear_down() {
|
|
|
|
if (!server_fd_.empty()) {
|
2018-09-11 00:20:41 +02:00
|
|
|
Scheduler::unsubscribe_before_close(server_fd_.get_poll_info().get_pollable_fd_ref());
|
2018-12-31 20:04:05 +01:00
|
|
|
server_fd_.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void TcpListener::loop() {
|
|
|
|
if (server_fd_.empty()) {
|
|
|
|
start_up();
|
2020-11-10 00:02:36 +01:00
|
|
|
if (server_fd_.empty()) {
|
|
|
|
return;
|
|
|
|
}
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
2020-07-21 17:29:39 +02:00
|
|
|
sync_with_poll(server_fd_);
|
|
|
|
while (can_read_local(server_fd_)) {
|
2018-12-31 20:04:05 +01:00
|
|
|
auto r_socket_fd = server_fd_.accept();
|
|
|
|
if (r_socket_fd.is_error()) {
|
|
|
|
if (r_socket_fd.error().code() != -1) {
|
|
|
|
LOG(ERROR) << r_socket_fd.error();
|
|
|
|
}
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
send_closure(callback_, &Callback::accept, r_socket_fd.move_as_ok());
|
|
|
|
}
|
|
|
|
|
2020-07-21 17:29:39 +02:00
|
|
|
if (can_close_local(server_fd_)) {
|
2018-12-31 20:04:05 +01:00
|
|
|
stop();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace td
|