tdlight/td/mtproto/RawConnection.cpp

496 lines
15 KiB
C++
Raw Normal View History

//
2022-12-31 22:28:08 +01:00
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2023
//
// 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/mtproto/RawConnection.h"
#include "td/mtproto/AuthKey.h"
2021-03-27 03:19:22 +01:00
#include "td/mtproto/IStreamTransport.h"
#include "td/mtproto/ProxySecret.h"
#include "td/mtproto/Transport.h"
2021-09-24 12:41:22 +02:00
#if TD_DARWIN_WATCH_OS
2021-03-26 16:52:45 +01:00
#include "td/net/DarwinHttp.h"
#endif
#include "td/utils/FlatHashMap.h"
#include "td/utils/format.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
2021-03-27 03:19:22 +01:00
#include "td/utils/MpscPollableQueue.h"
#include "td/utils/port/EventFd.h"
#include "td/utils/Slice.h"
#include "td/utils/SliceBuilder.h"
#include "td/utils/Status.h"
#include "td/utils/StorerBase.h"
2021-03-27 03:19:22 +01:00
#include <memory>
#include <utility>
namespace td {
namespace mtproto {
RawConnection::~RawConnection() {
LOG(DEBUG) << "Destroy raw connection " << this;
}
class RawConnectionDefault final : public RawConnection {
2021-03-26 16:04:01 +01:00
public:
2021-10-22 18:59:15 +02:00
RawConnectionDefault(BufferedFd<SocketFd> buffered_socket_fd, TransportType transport_type,
unique_ptr<StatsCallback> stats_callback)
: socket_fd_(std::move(buffered_socket_fd))
2021-10-18 18:26:14 +02:00
, transport_(create_transport(std::move(transport_type)))
2021-03-26 16:04:01 +01:00
, stats_callback_(std::move(stats_callback)) {
LOG(DEBUG) << "Create raw connection " << this;
2021-03-26 16:04:01 +01:00
transport_->init(&socket_fd_.input_buffer(), &socket_fd_.output_buffer());
}
2021-09-16 18:09:39 +02:00
void set_connection_token(ConnectionManager::ConnectionToken connection_token) final {
2021-03-26 16:04:01 +01:00
connection_token_ = std::move(connection_token);
}
2021-07-03 22:51:36 +02:00
bool can_send() const final {
2021-03-26 16:04:01 +01:00
return transport_->can_write();
}
2021-07-03 22:51:36 +02:00
TransportType get_transport_type() const final {
2021-03-26 16:04:01 +01:00
return transport_->get_type();
}
2023-05-14 22:00:56 +02:00
size_t send_crypto(const Storer &storer, uint64 session_id, int64 salt, const AuthKey &auth_key,
uint64 quick_ack_token) final {
2023-09-09 23:04:55 +02:00
PacketInfo packet_info;
packet_info.version = 2;
packet_info.no_crypto_flag = false;
packet_info.salt = salt;
packet_info.session_id = session_id;
packet_info.use_random_padding = transport_->use_random_padding();
auto packet =
2023-09-09 23:04:55 +02:00
Transport::write(storer, auth_key, &packet_info, transport_->max_prepend_size(), transport_->max_append_size());
2021-03-26 16:04:01 +01:00
bool use_quick_ack = false;
if (quick_ack_token != 0 && transport_->support_quick_ack()) {
2023-09-09 23:04:55 +02:00
CHECK(packet_info.message_ack & (1u << 31));
auto tmp = quick_ack_to_token_.emplace(packet_info.message_ack, quick_ack_token);
2021-03-26 16:04:01 +01:00
if (tmp.second) {
use_quick_ack = true;
} else {
2023-09-09 23:04:55 +02:00
LOG(ERROR) << "Quick ack " << packet_info.message_ack << " collision";
2021-03-26 16:04:01 +01:00
}
}
2021-03-26 16:04:01 +01:00
auto packet_size = packet.size();
2021-03-26 16:04:01 +01:00
transport_->write(std::move(packet), use_quick_ack);
return packet_size;
}
2021-07-03 22:51:36 +02:00
uint64 send_no_crypto(const Storer &storer) final {
2023-09-09 23:04:55 +02:00
PacketInfo packet_info;
packet_info.no_crypto_flag = true;
auto packet = Transport::write(storer, AuthKey(), &packet_info, transport_->max_prepend_size(),
transport_->max_append_size());
2021-03-26 16:04:01 +01:00
LOG(INFO) << "Send handshake packet: " << format::as_hex_dump<4>(packet.as_slice());
transport_->write(std::move(packet), false);
2023-09-09 23:04:55 +02:00
return packet_info.message_id;
2021-03-26 16:04:01 +01:00
}
2021-07-03 22:51:36 +02:00
PollableFdInfo &get_poll_info() final {
2021-03-26 16:04:01 +01:00
return socket_fd_.get_poll_info();
}
2021-07-03 22:51:36 +02:00
StatsCallback *stats_callback() final {
2021-03-26 16:04:01 +01:00
return stats_callback_.get();
}
// NB: After first returned error, all subsequent calls will return error too.
2021-07-03 22:51:36 +02:00
Status flush(const AuthKey &auth_key, Callback &callback) final {
2021-03-26 16:04:01 +01:00
auto status = do_flush(auth_key, callback);
if (status.is_error()) {
if (stats_callback_ && status.code() != 2) {
stats_callback_->on_error();
}
has_error_ = true;
}
return status;
}
2021-07-03 22:51:36 +02:00
bool has_error() const final {
2021-03-26 16:04:01 +01:00
return has_error_;
}
2021-07-03 22:51:36 +02:00
void close() final {
LOG(DEBUG) << "Close raw connection " << this;
2021-03-26 16:04:01 +01:00
transport_.reset();
socket_fd_.close();
}
2021-07-03 22:51:36 +02:00
PublicFields &extra() final {
2021-03-26 16:04:01 +01:00
return extra_;
}
2021-07-03 22:51:36 +02:00
const PublicFields &extra() const final {
2021-03-26 16:04:01 +01:00
return extra_;
}
private:
PublicFields extra_;
BufferedFd<SocketFd> socket_fd_;
unique_ptr<IStreamTransport> transport_;
FlatHashMap<uint32, uint64> quick_ack_to_token_;
2021-03-26 16:04:01 +01:00
bool has_error_{false};
unique_ptr<StatsCallback> stats_callback_;
2021-09-16 18:09:39 +02:00
ConnectionManager::ConnectionToken connection_token_;
void on_read(size_t size, Callback &callback) {
if (size <= 0) {
return;
}
if (stats_callback_) {
stats_callback_->on_read(size);
}
callback.on_read(size);
}
2021-03-26 16:04:01 +01:00
Status flush_read(const AuthKey &auth_key, Callback &callback) {
auto r = socket_fd_.flush_read();
if (r.is_ok()) {
on_read(r.ok(), callback);
}
2021-03-26 16:04:01 +01:00
while (transport_->can_read()) {
BufferSlice packet;
uint32 quick_ack = 0;
TRY_RESULT(wait_size, transport_->read_next(&packet, &quick_ack));
if (wait_size != 0) {
constexpr size_t MAX_PACKET_SIZE = (1 << 22) + 1024;
if (wait_size > MAX_PACKET_SIZE) {
return Status::Error(PSLICE() << "Expected packet size is too big: " << wait_size);
}
break;
}
if (quick_ack != 0) {
TRY_STATUS(on_quick_ack(quick_ack, callback));
continue;
}
2023-05-26 12:24:55 +02:00
auto old_pointer = packet.as_slice().ubegin();
if (!is_aligned_pointer<4>(old_pointer)) {
BufferSlice new_packet(packet.size());
new_packet.as_mutable_slice().copy_from(packet.as_slice());
packet = std::move(new_packet);
}
LOG_CHECK(is_aligned_pointer<4>(packet.as_slice().ubegin()))
<< old_pointer << ' ' << packet.as_slice().ubegin() << ' ' << BufferSlice(0).as_slice().ubegin() << ' '
<< packet.size() << ' ' << wait_size << ' ' << quick_ack;
2023-09-09 23:04:55 +02:00
PacketInfo packet_info;
packet_info.version = 2;
2021-03-26 16:04:01 +01:00
2023-09-09 23:04:55 +02:00
TRY_RESULT(read_result, Transport::read(packet.as_mutable_slice(), auth_key, &packet_info));
2021-03-26 16:04:01 +01:00
switch (read_result.type()) {
2023-05-26 12:24:55 +02:00
case Transport::ReadResult::Quickack:
2021-03-26 16:04:01 +01:00
TRY_STATUS(on_quick_ack(read_result.quick_ack(), callback));
break;
2023-05-26 12:24:55 +02:00
case Transport::ReadResult::Error:
2021-03-26 16:04:01 +01:00
TRY_STATUS(on_read_mtproto_error(read_result.error()));
break;
2023-05-26 12:24:55 +02:00
case Transport::ReadResult::Packet:
2021-03-26 16:04:01 +01:00
// If a packet was successfully decrypted, then it is ok to assume that the connection is alive
if (!auth_key.empty()) {
if (stats_callback_) {
stats_callback_->on_pong();
}
}
2023-09-09 23:04:55 +02:00
TRY_STATUS(callback.on_raw_packet(packet_info, packet.from_slice(read_result.packet())));
2021-03-26 16:04:01 +01:00
break;
case Transport::ReadResult::Nop:
break;
default:
UNREACHABLE();
}
}
TRY_STATUS(std::move(r));
return Status::OK();
}
Status on_read_mtproto_error(int32 error_code) {
if (error_code == -429) {
if (stats_callback_) {
stats_callback_->on_mtproto_error();
}
return Status::Error(500, PSLICE() << "MTProto error: " << error_code);
}
if (error_code == -404) {
return Status::Error(-404, PSLICE() << "MTProto error: " << error_code);
}
return Status::Error(PSLICE() << "MTProto error: " << error_code);
}
Status on_quick_ack(uint32 quick_ack, Callback &callback) {
if ((quick_ack & (1u << 31)) == 0) {
LOG(ERROR) << "Receive invalid quick_ack " << quick_ack;
return Status::OK();
}
2021-03-26 16:04:01 +01:00
auto it = quick_ack_to_token_.find(quick_ack);
if (it == quick_ack_to_token_.end()) {
LOG(WARNING) << "Receive unknown quick_ack " << quick_ack;
2021-03-26 16:04:01 +01:00
return Status::OK();
}
auto token = it->second;
quick_ack_to_token_.erase(it);
callback.on_quick_ack(token).ignore();
return Status::OK();
}
Status flush_write() {
TRY_RESULT(size, socket_fd_.flush_write());
if (size > 0 && stats_callback_) {
stats_callback_->on_write(size);
}
return Status::OK();
}
2021-03-26 16:04:01 +01:00
Status do_flush(const AuthKey &auth_key, Callback &callback) TD_WARN_UNUSED_RESULT {
if (has_error_) {
return Status::Error("Connection has already failed");
}
2021-03-26 16:04:01 +01:00
sync_with_poll(socket_fd_);
// read/write
2022-09-15 14:03:19 +02:00
// EINVAL can be returned in Linux kernel < 2.6.28. And on some new kernels too.
2021-03-26 16:04:01 +01:00
// just close connection and hope that read or write will not return this error too.
TRY_STATUS(socket_fd_.get_pending_error());
2021-03-26 16:04:01 +01:00
TRY_STATUS(flush_read(auth_key, callback));
TRY_STATUS(callback.before_write());
TRY_STATUS(flush_write());
if (can_close_local(socket_fd_)) {
return Status::Error("Connection closed");
}
return Status::OK();
}
};
2021-09-24 12:41:22 +02:00
#if TD_DARWIN_WATCH_OS
class RawConnectionHttp final : public RawConnection {
2021-03-26 16:04:01 +01:00
public:
RawConnectionHttp(IPAddress ip_address, unique_ptr<StatsCallback> stats_callback)
: ip_address_(std::move(ip_address)), stats_callback_(std::move(stats_callback)) {
LOG(DEBUG) << "Create raw connection " << this;
2021-03-26 16:04:01 +01:00
answers_ = std::make_shared<MpscPollableQueue<Result<BufferSlice>>>();
answers_->init();
}
2021-09-16 18:09:39 +02:00
void set_connection_token(ConnectionManager::ConnectionToken connection_token) final {
2021-03-26 16:04:01 +01:00
connection_token_ = std::move(connection_token);
}
2021-07-03 22:51:36 +02:00
bool can_send() const final {
2021-03-26 16:04:01 +01:00
return mode_ == Send;
}
2021-07-03 22:51:36 +02:00
TransportType get_transport_type() const final {
2021-03-26 16:04:01 +01:00
return mtproto::TransportType{mtproto::TransportType::Http, 0, mtproto::ProxySecret()};
}
2023-05-14 22:00:56 +02:00
size_t send_crypto(const Storer &storer, uint64 session_id, int64 salt, const AuthKey &auth_key,
uint64 quick_ack_token) final {
2023-09-09 23:04:55 +02:00
PacketInfo packet_info;
packet_info.version = 2;
packet_info.no_crypto_flag = false;
packet_info.salt = salt;
packet_info.session_id = session_id;
packet_info.use_random_padding = false;
auto packet = Transport::write(storer, auth_key, &packet_info);
2021-03-26 16:04:01 +01:00
auto packet_size = packet.size();
2021-03-26 16:04:01 +01:00
send_packet(packet.as_buffer_slice());
return packet_size;
2021-03-26 16:04:01 +01:00
}
2021-07-03 22:51:36 +02:00
uint64 send_no_crypto(const Storer &storer) final {
2023-09-09 23:04:55 +02:00
PacketInfo packet_info;
packet_info.no_crypto_flag = true;
auto packet = Transport::write(storer, AuthKey(), &packet_info);
2021-03-26 16:04:01 +01:00
LOG(INFO) << "Send handshake packet: " << format::as_hex_dump<4>(packet.as_slice());
send_packet(packet.as_buffer_slice());
2023-09-09 23:04:55 +02:00
return packet_info.message_id;
2021-03-26 16:04:01 +01:00
}
2021-07-03 22:51:36 +02:00
PollableFdInfo &get_poll_info() final {
2021-03-26 16:04:01 +01:00
return answers_->reader_get_event_fd().get_poll_info();
}
2021-07-03 22:51:36 +02:00
StatsCallback *stats_callback() final {
2021-03-26 16:04:01 +01:00
return stats_callback_.get();
}
// NB: After first returned error, all subsequent calls will return error too.
2021-07-03 22:51:36 +02:00
Status flush(const AuthKey &auth_key, Callback &callback) final {
2021-03-26 16:04:01 +01:00
auto status = do_flush(auth_key, callback);
if (status.is_error()) {
if (stats_callback_ && status.code() != 2) {
stats_callback_->on_error();
}
2021-03-26 16:04:01 +01:00
has_error_ = true;
}
return status;
}
2021-07-03 22:51:36 +02:00
bool has_error() const final {
2021-03-26 16:04:01 +01:00
return has_error_;
}
2021-07-03 22:51:36 +02:00
void close() final {
LOG(DEBUG) << "Close raw connection " << this;
2021-03-26 16:04:01 +01:00
}
2021-07-03 22:51:36 +02:00
PublicFields &extra() final {
2021-03-26 16:04:01 +01:00
return extra_;
}
2021-07-03 22:51:36 +02:00
const PublicFields &extra() const final {
2021-03-26 16:04:01 +01:00
return extra_;
}
private:
PublicFields extra_;
IPAddress ip_address_;
bool has_error_{false};
EventFd event_fd_;
enum Mode { Send, Receive } mode_{Send};
unique_ptr<StatsCallback> stats_callback_;
2021-09-16 18:09:39 +02:00
ConnectionManager::ConnectionToken connection_token_;
2021-03-26 16:04:01 +01:00
std::shared_ptr<MpscPollableQueue<Result<BufferSlice>>> answers_;
std::vector<BufferSlice> to_send_;
2023-03-10 11:22:18 +01:00
void on_read(size_t size, Callback &callback) {
if (size <= 0) {
return;
}
if (stats_callback_) {
stats_callback_->on_read(size);
}
callback.on_read(size);
}
2021-03-26 16:04:01 +01:00
void send_packet(BufferSlice packet) {
CHECK(mode_ == Send);
mode_ = Receive;
to_send_.push_back(std::move(packet));
}
Status flush_read(const AuthKey &auth_key, Callback &callback) {
while (true) {
auto packets_n = answers_->reader_wait_nonblock();
if (packets_n == 0) {
break;
}
2021-03-26 16:04:01 +01:00
for (int i = 0; i < packets_n; i++) {
TRY_RESULT(packet, answers_->reader_get_unsafe());
on_read(packet.size(), callback);
2021-03-26 16:04:01 +01:00
CHECK(mode_ == Receive);
mode_ = Send;
2023-09-09 23:04:55 +02:00
PacketInfo packet_info;
packet_info.version = 2;
2021-03-26 16:04:01 +01:00
2023-09-09 23:04:55 +02:00
TRY_RESULT(read_result, Transport::read(packet.as_mutable_slice(), auth_key, &packet_info));
2021-03-26 16:04:01 +01:00
switch (read_result.type()) {
case Transport::ReadResult::Quickack: {
break;
}
case Transport::ReadResult::Error: {
TRY_STATUS(on_read_mtproto_error(read_result.error()));
break;
}
case Transport::ReadResult::Packet: {
// If a packet was successfully decrypted, then it is ok to assume that the connection is alive
if (!auth_key.empty()) {
if (stats_callback_) {
stats_callback_->on_pong();
}
}
2023-09-09 23:04:55 +02:00
TRY_STATUS(callback.on_raw_packet(packet_info, packet.from_slice(read_result.packet())));
2021-03-26 16:04:01 +01:00
break;
}
case Transport::ReadResult::Nop:
break;
default:
UNREACHABLE();
}
}
}
2021-03-26 16:04:01 +01:00
return Status::OK();
}
2021-03-26 16:04:01 +01:00
Status on_read_mtproto_error(int32 error_code) {
if (error_code == -429) {
if (stats_callback_) {
stats_callback_->on_mtproto_error();
}
return Status::Error(500, PSLICE() << "MTProto error: " << error_code);
}
2021-03-26 16:04:01 +01:00
if (error_code == -404) {
return Status::Error(-404, PSLICE() << "MTProto error: " << error_code);
}
return Status::Error(PSLICE() << "MTProto error: " << error_code);
}
2021-03-26 16:04:01 +01:00
Status flush_write() {
for (auto &packet : to_send_) {
TRY_STATUS(do_send(packet.as_slice()));
if (packet.size() > 0 && stats_callback_) {
stats_callback_->on_write(packet.size());
}
}
to_send_.clear();
return Status::OK();
}
2021-03-26 16:04:01 +01:00
Status do_send(Slice data) {
2023-06-11 12:25:06 +02:00
DarwinHttp::post(PSLICE() << "http://" << ip_address_.get_ip_host() << ":" << ip_address_.get_port() << "/api",
data, [answers = answers_](auto res) { answers->writer_put(std::move(res)); });
return Status::OK();
}
2021-03-26 16:04:01 +01:00
Status do_flush(const AuthKey &auth_key, Callback &callback) TD_WARN_UNUSED_RESULT {
if (has_error_) {
return Status::Error("Connection has already failed");
}
TRY_STATUS(flush_read(auth_key, callback));
TRY_STATUS(callback.before_write());
TRY_STATUS(flush_write());
return Status::OK();
}
2021-03-26 16:04:01 +01:00
};
#endif
2021-10-22 18:59:15 +02:00
unique_ptr<RawConnection> RawConnection::create(IPAddress ip_address, BufferedFd<SocketFd> buffered_socket_fd,
TransportType transport_type,
2021-03-27 03:19:22 +01:00
unique_ptr<StatsCallback> stats_callback) {
2021-09-24 12:41:22 +02:00
#if TD_DARWIN_WATCH_OS
2021-10-21 11:51:16 +02:00
return td::make_unique<RawConnectionHttp>(std::move(ip_address), std::move(stats_callback));
2021-03-26 16:04:01 +01:00
#else
2021-10-22 18:59:15 +02:00
return td::make_unique<RawConnectionDefault>(std::move(buffered_socket_fd), std::move(transport_type),
2021-10-21 11:51:16 +02:00
std::move(stats_callback));
2021-03-26 16:04:01 +01:00
#endif
}
} // namespace mtproto
} // namespace td