1 parent
38e86d4a07
commit
6dddf513b3
6 files changed
+600
-3
No files matched your search
@@ -13,8 +13,12 @@
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
@@ -122,6 +126,10 @@ namespace Echoion::Protocol
|
||||
|
||||
void TsClient::connect(const TsClientOptions& opts)
|
||||
{
|
||||
if (thread_.joinable()) {
|
||||
forceClose();
|
||||
thread_.join();
|
||||
}
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (!opts.identity) {
|
||||
throw std::runtime_error("TsClient: identity is required");
|
||||
@@ -352,6 +360,172 @@ namespace Echoion::Protocol
|
||||
}
|
||||
}
|
||||
|
||||
CommandResult TsClient::requestCommand(
|
||||
const std::string& cmd, std::chrono::milliseconds timeout)
|
||||
{
|
||||
if (std::this_thread::get_id() == thread_.get_id()) {
|
||||
return {{}, -1, "requestCommand cannot block the receive thread"};
|
||||
}
|
||||
// TeamSpeak returns data records without a request identifier; keep one
|
||||
// response-bearing command in flight so those records remain unambiguous.
|
||||
std::unique_lock<std::mutex> serialLock(requestSerialMutex_);
|
||||
auto pending = std::make_shared<PendingRequest>();
|
||||
pending->returnCode = "echoion-" + std::to_string(++requestId_);
|
||||
{
|
||||
// Keep queue insertion and wire send in the same order when callers
|
||||
// issue requests concurrently.
|
||||
std::lock_guard<std::recursive_mutex> sendLock(mu_);
|
||||
if (state_.load() != ClientState::Connected) {
|
||||
return {{}, -1, "client is not connected"};
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> pendingLock(pendingMutex_);
|
||||
pendingRequests_.push_back(pending);
|
||||
}
|
||||
sendCommand(cmd + " return_code=" + pending->returnCode);
|
||||
}
|
||||
|
||||
std::unique_lock<std::mutex> lock(pendingMutex_);
|
||||
if (!pending->cv.wait_for(lock, timeout,
|
||||
[&pending] { return pending->completed; })) {
|
||||
const auto entry =
|
||||
std::find(pendingRequests_.begin(), pendingRequests_.end(), pending);
|
||||
if (entry != pendingRequests_.end()) {
|
||||
pendingRequests_.erase(entry);
|
||||
}
|
||||
return {{}, -1, "command timed out"};
|
||||
}
|
||||
return pending->result;
|
||||
}
|
||||
|
||||
CommandResult TsClient::downloadFile(
|
||||
const std::string& remotePath, const std::string& destination,
|
||||
uint64_t channelId, const std::string& channelPassword,
|
||||
std::chrono::milliseconds timeout)
|
||||
{
|
||||
CommandParams parameters;
|
||||
parameters["cid"] = std::to_string(channelId);
|
||||
parameters["cpw"] = channelPassword;
|
||||
parameters["name"] = remotePath;
|
||||
parameters["clientftfid"] = std::to_string(++transferId_);
|
||||
parameters["seekpos"] = "0";
|
||||
auto result = requestCommand(buildCommand("ftinitdownload", parameters),
|
||||
timeout);
|
||||
if (!result.ok() || result.records.empty()) {
|
||||
if (result.ok()) {
|
||||
result.errorId = -1;
|
||||
result.errorMessage = "file transfer returned no connection data";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const auto& record = result.records.front();
|
||||
auto value = [&record](const char* name) -> std::string {
|
||||
const auto entry = record.find(name);
|
||||
return entry == record.end() ? std::string{} : entry->second;
|
||||
};
|
||||
const auto transferKey = value("ftkey");
|
||||
const auto portText = value("port");
|
||||
const auto sizeText = value("size");
|
||||
if (transferKey.empty() || portText.empty() || sizeText.empty()) {
|
||||
return {{}, -1, "file transfer response is incomplete"};
|
||||
}
|
||||
|
||||
addrinfo hints{};
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
addrinfo* addresses = nullptr;
|
||||
if (getaddrinfo(opts_.host.c_str(), portText.c_str(), &hints,
|
||||
&addresses) != 0 || !addresses) {
|
||||
return {{}, -1, "cannot resolve file-transfer endpoint"};
|
||||
}
|
||||
int transferSocket = -1;
|
||||
for (auto* address = addresses; address; address = address->ai_next) {
|
||||
transferSocket =
|
||||
::socket(address->ai_family, address->ai_socktype,
|
||||
address->ai_protocol);
|
||||
if (transferSocket >= 0 &&
|
||||
::connect(transferSocket, address->ai_addr, address->ai_addrlen) ==
|
||||
0) {
|
||||
break;
|
||||
}
|
||||
if (transferSocket >= 0) {
|
||||
::close(transferSocket);
|
||||
transferSocket = -1;
|
||||
}
|
||||
}
|
||||
freeaddrinfo(addresses);
|
||||
if (transferSocket < 0) {
|
||||
return {{}, -1, "cannot connect to file-transfer endpoint"};
|
||||
}
|
||||
|
||||
const auto temporary = destination + ".part";
|
||||
if (const auto parent = std::filesystem::path(destination).parent_path();
|
||||
!parent.empty()) {
|
||||
std::error_code directoryError;
|
||||
std::filesystem::create_directories(parent, directoryError);
|
||||
if (directoryError) {
|
||||
::close(transferSocket);
|
||||
return {{}, -1, "cannot create file-transfer destination"};
|
||||
}
|
||||
}
|
||||
std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
|
||||
timeval socketTimeout{};
|
||||
socketTimeout.tv_sec = static_cast<long>(
|
||||
std::max<int64_t>(1, timeout.count() / 1000));
|
||||
setsockopt(transferSocket, SOL_SOCKET, SO_RCVTIMEO, &socketTimeout,
|
||||
sizeof(socketTimeout));
|
||||
size_t keySent = 0;
|
||||
while (keySent < transferKey.size()) {
|
||||
const auto count = ::send(transferSocket, transferKey.data() + keySent,
|
||||
transferKey.size() - keySent, 0);
|
||||
if (count <= 0) {
|
||||
break;
|
||||
}
|
||||
keySent += static_cast<size_t>(count);
|
||||
}
|
||||
if (!output || keySent != transferKey.size()) {
|
||||
::close(transferSocket);
|
||||
std::filesystem::remove(temporary);
|
||||
return {{}, -1, "cannot start file transfer"};
|
||||
}
|
||||
std::array<char, 81920> buffer{};
|
||||
uint64_t received = 0;
|
||||
while (true) {
|
||||
const auto count = ::recv(transferSocket, buffer.data(), buffer.size(), 0);
|
||||
if (count == 0) {
|
||||
break;
|
||||
}
|
||||
if (count < 0) {
|
||||
output.close();
|
||||
::close(transferSocket);
|
||||
std::filesystem::remove(temporary);
|
||||
return {{}, -1, "file transfer was interrupted"};
|
||||
}
|
||||
output.write(buffer.data(), count);
|
||||
received += static_cast<uint64_t>(count);
|
||||
}
|
||||
::close(transferSocket);
|
||||
output.close();
|
||||
uint64_t expected = 0;
|
||||
try {
|
||||
expected = std::stoull(sizeText);
|
||||
} catch (const std::exception&) {
|
||||
std::filesystem::remove(temporary);
|
||||
return {{}, -1, "invalid file-transfer size"};
|
||||
}
|
||||
if (!output || received != expected) {
|
||||
std::filesystem::remove(temporary);
|
||||
return {{}, -1, "file transfer size mismatch"};
|
||||
}
|
||||
std::error_code renameError;
|
||||
std::filesystem::rename(temporary, destination, renameError);
|
||||
if (renameError) {
|
||||
std::filesystem::remove(temporary);
|
||||
return {{}, -1, "cannot install downloaded file"};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void TsClient::sendVoice(std::span<const uint8_t> opus)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
@@ -660,6 +834,47 @@ namespace Echoion::Protocol
|
||||
}
|
||||
|
||||
const std::string& name = parsed.name;
|
||||
if (name == "error") {
|
||||
std::shared_ptr<PendingRequest> pending;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingMutex_);
|
||||
const auto returnCode = parsed.params.find("return_code");
|
||||
if (!pendingRequests_.empty() &&
|
||||
returnCode != parsed.params.end() &&
|
||||
returnCode->second == pendingRequests_.front()->returnCode) {
|
||||
pending = pendingRequests_.front();
|
||||
pendingRequests_.pop_front();
|
||||
if (const auto id = parsed.params.find("id");
|
||||
id != parsed.params.end()) {
|
||||
try {
|
||||
pending->result.errorId = std::stoi(id->second);
|
||||
} catch (const std::exception&) {
|
||||
pending->result.errorId = -1;
|
||||
}
|
||||
}
|
||||
if (const auto message = parsed.params.find("msg");
|
||||
message != parsed.params.end()) {
|
||||
pending->result.errorMessage = message->second;
|
||||
}
|
||||
pending->completed = true;
|
||||
}
|
||||
}
|
||||
if (pending) {
|
||||
pending->cv.notify_all();
|
||||
}
|
||||
} else if (!name.starts_with("notify") && name != "initivexpand" &&
|
||||
name != "initivexpand2" && name != "initserver") {
|
||||
std::lock_guard<std::mutex> lock(pendingMutex_);
|
||||
if (!pendingRequests_.empty()) {
|
||||
auto& records = pendingRequests_.front()->result.records;
|
||||
if (parsed.groups.empty()) {
|
||||
records.push_back(parsed.params);
|
||||
} else {
|
||||
records.insert(records.end(), parsed.groups.begin(),
|
||||
parsed.groups.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (name == "initivexpand") {
|
||||
handleInitIvExpand(parsed.params);
|
||||
} else if (name == "initivexpand2") {
|
||||
@@ -963,6 +1178,7 @@ namespace Echoion::Protocol
|
||||
if (sock_ >= 0) {
|
||||
::shutdown(sock_, SHUT_RDWR);
|
||||
}
|
||||
cancelPendingRequests("connection closed");
|
||||
}
|
||||
|
||||
void TsClient::cleanup()
|
||||
@@ -972,9 +1188,27 @@ namespace Echoion::Protocol
|
||||
}
|
||||
state_ = ClientState::Disconnected;
|
||||
running_ = false;
|
||||
cancelPendingRequests("connection closed");
|
||||
if (cb_.onDisconnected) {
|
||||
cb_.onDisconnected();
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::cancelPendingRequests(const std::string& reason)
|
||||
{
|
||||
std::deque<std::shared_ptr<PendingRequest>> pending;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingMutex_);
|
||||
pending.swap(pendingRequests_);
|
||||
for (const auto& request : pending) {
|
||||
request->result.errorId = -1;
|
||||
request->result.errorMessage = reason;
|
||||
request->completed = true;
|
||||
}
|
||||
}
|
||||
for (const auto& request : pending) {
|
||||
request->cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
Reference in new issue
Block a user