bugfix:重要BUG修正,问题点是,缓冲区只解析了一组值就结束了,如果有多组将出现未解析的情况(非解析失败)。

This commit is contained in:
taynpg 2024-12-15 23:19:56 +08:00
parent 154c670839
commit bdfeb6a02a
3 changed files with 27 additions and 15 deletions

View File

@ -63,12 +63,18 @@ void CTcpClient::async_recv()
}
} else {
buffer_.push(tmp_buf_.data(), length);
auto* frame = CTransProtocal::parse(buffer_);
if (frame) {
if (fun_) {
fun_(frame);
bool done = true;
while (done) {
auto* frame = CTransProtocal::parse(buffer_);
if (frame) {
if (fun_) {
fun_(frame);
}
delete frame;
} else {
done = false;
}
delete frame;
}
async_recv();
}

View File

@ -165,6 +165,7 @@ void CTcpServer::handle_frame()
break;
}
default:
logger_->warn("No Mathched type.");
break;
}
delete buf;

View File

@ -1,5 +1,4 @@
#include "util.h"
#include <cstddef>
#include <cstdint>
std::shared_ptr<spdlog::logger> get_logger(const std::string& mark, const std::string& log_file)
@ -45,27 +44,33 @@ CFrameBuffer* CTransProtocal::parse(CMutBuffer& buffer)
if (find < 0) {
return result;
}
int16_t type = *(reinterpret_cast<const int16_t*>(buffer.get_data() + find + 2));
char mark = *(buffer.get_data() + find + 2 + 2);
int32_t len = *(reinterpret_cast<const int32_t*>(buffer.get_data() + find + 2 + 2 + 1 + 32 + 32));
// reinterpret_cast 的指针转换直接访问内存可能导致未对齐问题(某些架构下)
int16_t type{};
char mark{};
int32_t len{};
std::memcpy(&type, buffer.get_data() + find + 2, sizeof(type));
std::memcpy(&mark, buffer.get_data() + find + 2 + 2, sizeof(mark));
std::memcpy(&len, buffer.get_data() + find + 2 + 2 + 1 + 32 + 32, sizeof(len));
int32_t tail_index = find + 2 + 2 + 1 + 32 + 32 + 4 + len;
if (buffer.get_len() - 2 < tail_index || len < 0) {
return result;
}
unsigned char taila = *((unsigned char*)(buffer.get_data() + tail_index));
unsigned char tailb = *((unsigned char*)(buffer.get_data() + tail_index + 1));
if (taila != tail[0] || tailb != tail[1]) {
if (std::memcmp(buffer.get_data() + tail_index, tail, sizeof(tail)) != 0) {
return result;
}
result = new CFrameBuffer();
result->data_ = new char[len];
std::memset(result->data_, 0x0, len);
if (len > 0) {
result->data_ = new char[len]();
}
result->len_ = len;
result->fid_ = std::string(buffer.get_data() + find + 2 + 2 + 1);
result->tid_ = std::string(buffer.get_data() + find + 2 + 2 + 1 + 32);
result->mark_ = mark;
result->type_ = static_cast<FrameType>(type);
std::memcpy(result->data_, buffer.get_data() + find + 2 + 2 + 1 + 4 + 32 + 32, len);
if (len > 0) {
std::memcpy(result->data_, buffer.get_data() + find + 2 + 2 + 1 + 4 + 32 + 32, len);
}
buffer.remove_of(0, tail_index + 2);
return result;
}