checkout ptr

Signed-off-by: faithwang <wangyanteng@huawei.com>
This commit is contained in:
faithwang 2022-03-10 15:35:18 +08:00
parent f06b299519
commit f546bd6085
59 changed files with 1169 additions and 1169 deletions

View File

@ -81,9 +81,9 @@ bool HdcChannelBase::SetChannelTCPString(const string &addrString)
void HdcChannelBase::ClearChannels()
{
for (auto v : mapChannel) {
HChannelPtr hChannelPtr = (HChannelPtr)v.second;
if (!hChannelPtr->isDead) {
FreeChannel(hChannelPtr->channelId);
HChannel hChannel = (HChannel)v.second;
if (!hChannel->isDead) {
FreeChannel(hChannel->channelId);
}
}
}
@ -104,8 +104,8 @@ void HdcChannelBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t
int indexBuf = 0;
int childRet = 0;
bool needExit = false;
HChannelPtr hChannelPtr = (HChannelPtr)tcp->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannelPtr->clsChannel;
HChannel hChannel = (HChannel)tcp->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
if (thisClass == nullptr) {
return;
}
@ -126,30 +126,30 @@ void HdcChannelBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t
needExit = true;
goto Finish;
} else {
hChannelPtr->availTailIndex += nread;
hChannel->availTailIndex += nread;
}
while (hChannelPtr->availTailIndex > DWORD_SERIALIZE_SIZE) {
size = ntohl(*(uint32_t *)(hChannelPtr->ioBuf + indexBuf)); // big endian
while (hChannel->availTailIndex > DWORD_SERIALIZE_SIZE) {
size = ntohl(*(uint32_t *)(hChannel->ioBuf + indexBuf)); // big endian
if (size <= 0 || (uint32_t)size > HDC_BUF_MAX_BYTES) {
needExit = true;
break;
}
if (hChannelPtr->availTailIndex - DWORD_SERIALIZE_SIZE < size) {
if (hChannel->availTailIndex - DWORD_SERIALIZE_SIZE < size) {
break;
}
childRet = thisClass->ReadChannel(hChannelPtr, (uint8_t *)hChannelPtr->ioBuf + DWORD_SERIALIZE_SIZE + indexBuf, size);
childRet = thisClass->ReadChannel(hChannel, (uint8_t *)hChannel->ioBuf + DWORD_SERIALIZE_SIZE + indexBuf, size);
if (childRet < 0) {
if (!hChannelPtr->keepAlive) {
if (!hChannel->keepAlive) {
needExit = true;
break;
}
}
// update io
hChannelPtr->availTailIndex -= (DWORD_SERIALIZE_SIZE + size);
hChannel->availTailIndex -= (DWORD_SERIALIZE_SIZE + size);
indexBuf += DWORD_SERIALIZE_SIZE + size;
}
if (indexBuf > 0 && hChannelPtr->availTailIndex > 0) {
if (memmove_s(hChannelPtr->ioBuf, hChannelPtr->bufSize, hChannelPtr->ioBuf + indexBuf, hChannelPtr->availTailIndex)) {
if (indexBuf > 0 && hChannel->availTailIndex > 0) {
if (memmove_s(hChannel->ioBuf, hChannel->bufSize, hChannel->ioBuf + indexBuf, hChannel->availTailIndex)) {
needExit = true;
goto Finish;
}
@ -157,7 +157,7 @@ void HdcChannelBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t
Finish:
if (needExit) {
thisClass->FreeChannel(hChannelPtr->channelId);
thisClass->FreeChannel(hChannel->channelId);
WRITE_LOG(LOG_DEBUG, "Read Stream needExit, FreeChannel finish");
}
}
@ -167,16 +167,16 @@ void HdcChannelBase::WriteCallback(uv_write_t *req, int status)
if (req == nullptr || req->handle == nullptr || req->handle->data == nullptr) {
return;
}
HChannelPtr hChannelPtr = (HChannelPtr)req->handle->data;
--hChannelPtr->ref;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannelPtr->clsChannel;
HChannel hChannel = (HChannel)req->handle->data;
--hChannel->ref;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
if (thisClass == nullptr) {
return;
}
if (status < 0) {
Base::TryCloseHandle((uv_handle_t *)req->handle);
if (!hChannelPtr->isDead && !hChannelPtr->ref) {
thisClass->FreeChannel(hChannelPtr->channelId);
if (!hChannel->isDead && !hChannel->ref) {
thisClass->FreeChannel(hChannel->channelId);
WRITE_LOG(LOG_DEBUG, "WriteCallback TryCloseHandle");
}
}
@ -269,7 +269,7 @@ void HdcChannelBase::PushAsyncMessage(const uint32_t channelId, const uint8_t me
uv_async_send(&asyncMainLoop);
}
void HdcChannelBase::SendChannel(HChannelPtr hChannelPtr, uint8_t *bufPtr, const int size)
void HdcChannelBase::SendChannel(HChannel hChannel, uint8_t *bufPtr, const int size)
{
uv_stream_t *sendStream = nullptr;
int sizeNewBuf = size + DWORD_SERIALIZE_SIZE;
@ -282,13 +282,13 @@ void HdcChannelBase::SendChannel(HChannelPtr hChannelPtr, uint8_t *bufPtr, const
delete[] data;
return;
}
if (hChannelPtr->hWorkThread == uv_thread_self()) {
sendStream = (uv_stream_t *)&hChannelPtr->hWorkTCP;
if (hChannel->hWorkThread == uv_thread_self()) {
sendStream = (uv_stream_t *)&hChannel->hWorkTCP;
} else {
sendStream = (uv_stream_t *)&hChannelPtr->hChildWorkTCP;
sendStream = (uv_stream_t *)&hChannel->hChildWorkTCP;
}
if (!uv_is_closing((const uv_handle_t *)sendStream) && uv_is_writable(sendStream)) {
++hChannelPtr->ref;
++hChannel->ref;
Base::SendToStreamEx(sendStream, data, sizeNewBuf, nullptr, (void *)WriteCallback, data);
} else {
delete[] data;
@ -298,17 +298,17 @@ void HdcChannelBase::SendChannel(HChannelPtr hChannelPtr, uint8_t *bufPtr, const
// works only in current working thread
void HdcChannelBase::Send(const uint32_t channelId, uint8_t *bufPtr, const int size)
{
HChannelPtr hChannelPtr = (HChannelPtr)AdminChannel(OP_QUERY_REF, channelId, nullptr);
if (!hChannelPtr) {
HChannel hChannel = (HChannel)AdminChannel(OP_QUERY_REF, channelId, nullptr);
if (!hChannel) {
return;
}
do {
if (hChannelPtr->isDead) {
if (hChannel->isDead) {
break;
}
SendChannel(hChannelPtr, bufPtr, size);
SendChannel(hChannel, bufPtr, size);
} while (false);
--hChannelPtr->ref;
--hChannel->ref;
}
void HdcChannelBase::AllocCallback(uv_handle_t *handle, size_t sizeWanted, uv_buf_t *buf)
@ -316,7 +316,7 @@ void HdcChannelBase::AllocCallback(uv_handle_t *handle, size_t sizeWanted, uv_bu
if (handle == nullptr || handle->data == nullptr || buf == nullptr) {
return;
}
HChannelPtr context = (HChannelPtr)handle->data;
HChannel context = (HChannel)handle->data;
Base::ReallocBuf(&context->ioBuf, &context->bufSize, Base::GetMaxBufSize() * 4);
buf->base = (char *)context->ioBuf + context->availTailIndex;
buf->len = context->bufSize - context->availTailIndex;
@ -325,35 +325,35 @@ void HdcChannelBase::AllocCallback(uv_handle_t *handle, size_t sizeWanted, uv_bu
uint32_t HdcChannelBase::GetChannelPseudoUid()
{
uint32_t uid = 0;
HChannelPtr hInput = nullptr;
HChannel hInput = nullptr;
do {
uid = static_cast<uint32_t>(Base::GetRandom());
} while ((hInput = AdminChannel(OP_QUERY, uid, nullptr)) != nullptr);
return uid;
}
uint32_t HdcChannelBase::MallocChannel(HChannelPtr *hOutChannel)
uint32_t HdcChannelBase::MallocChannel(HChannel *hOutChannel)
{
if (hOutChannel == nullptr) {
return 0;
}
auto hChannelPtr = new(std::nothrow) HdcChannel();
if (!hChannelPtr) {
auto hChannel = new(std::nothrow) HdcChannel();
if (!hChannel) {
return 0;
}
uint32_t channelId = GetChannelPseudoUid();
if (isServerOrClient) {
hChannelPtr->serverOrClient = isServerOrClient;
hChannel->serverOrClient = isServerOrClient;
++channelId; // Use different value for serverForClient&client in per process
}
uv_tcp_init(loopMain, &hChannelPtr->hWorkTCP);
++hChannelPtr->uvHandleRef;
hChannelPtr->hWorkThread = uv_thread_self();
hChannelPtr->hWorkTCP.data = hChannelPtr;
hChannelPtr->clsChannel = this;
hChannelPtr->channelId = channelId;
AdminChannel(OP_ADD, channelId, hChannelPtr);
*hOutChannel = hChannelPtr;
uv_tcp_init(loopMain, &hChannel->hWorkTCP);
++hChannel->uvHandleRef;
hChannel->hWorkThread = uv_thread_self();
hChannel->hWorkTCP.data = hChannel;
hChannel->clsChannel = this;
hChannel->channelId = channelId;
AdminChannel(OP_ADD, channelId, hChannel);
*hOutChannel = hChannel;
WRITE_LOG(LOG_DEBUG, "Mallocchannel:%u", channelId);
return channelId;
}
@ -364,46 +364,46 @@ void HdcChannelBase::FreeChannelFinally(uv_idle_t *handle)
if (handle == nullptr || handle->data == nullptr) {
return;
}
HChannelPtr hChannelPtr = (HChannelPtr)handle->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannelPtr->clsChannel;
if (hChannelPtr->uvHandleRef > 0 || thisClass == nullptr) {
HChannel hChannel = (HChannel)handle->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
if (hChannel->uvHandleRef > 0 || thisClass == nullptr) {
return;
}
thisClass->NotifyInstanceChannelFree(hChannelPtr);
thisClass->AdminChannel(OP_REMOVE, hChannelPtr->channelId, nullptr);
WRITE_LOG(LOG_DEBUG, "!!!FreeChannelFinally channelId:%u finish", hChannelPtr->channelId);
if (!hChannelPtr->serverOrClient) {
thisClass->NotifyInstanceChannelFree(hChannel);
thisClass->AdminChannel(OP_REMOVE, hChannel->channelId, nullptr);
WRITE_LOG(LOG_DEBUG, "!!!FreeChannelFinally channelId:%u finish", hChannel->channelId);
if (!hChannel->serverOrClient) {
uv_stop(thisClass->loopMain);
}
delete hChannelPtr;
delete hChannel;
Base::TryCloseHandle((const uv_handle_t *)handle, Base::CloseIdleCallback);
}
void HdcChannelBase::FreeChannelContinue(HChannelPtr hChannelPtr)
void HdcChannelBase::FreeChannelContinue(HChannel hChannel)
{
if (hChannelPtr == nullptr) {
if (hChannel == nullptr) {
return;
}
auto closeChannelHandle = [](uv_handle_t *handle) -> void {
HChannelPtr hChannelPtr = (HChannelPtr)handle->data;
--hChannelPtr->uvHandleRef;
HChannel hChannel = (HChannel)handle->data;
--hChannel->uvHandleRef;
Base::TryCloseHandle((uv_handle_t *)handle);
};
hChannelPtr->availTailIndex = 0;
if (hChannelPtr->ioBuf) {
delete[] hChannelPtr->ioBuf;
hChannelPtr->ioBuf = nullptr;
hChannel->availTailIndex = 0;
if (hChannel->ioBuf) {
delete[] hChannel->ioBuf;
hChannel->ioBuf = nullptr;
}
if (!hChannelPtr->serverOrClient) {
Base::TryCloseHandle((uv_handle_t *)&hChannelPtr->stdinTty, closeChannelHandle);
Base::TryCloseHandle((uv_handle_t *)&hChannelPtr->stdoutTty, closeChannelHandle);
if (!hChannel->serverOrClient) {
Base::TryCloseHandle((uv_handle_t *)&hChannel->stdinTty, closeChannelHandle);
Base::TryCloseHandle((uv_handle_t *)&hChannel->stdoutTty, closeChannelHandle);
}
if (uv_is_closing((const uv_handle_t *)&hChannelPtr->hWorkTCP)) {
--hChannelPtr->uvHandleRef;
if (uv_is_closing((const uv_handle_t *)&hChannel->hWorkTCP)) {
--hChannel->uvHandleRef;
} else {
Base::TryCloseHandle((uv_handle_t *)&hChannelPtr->hWorkTCP, closeChannelHandle);
Base::TryCloseHandle((uv_handle_t *)&hChannel->hWorkTCP, closeChannelHandle);
}
Base::IdleUvTask(loopMain, hChannelPtr, FreeChannelFinally);
Base::IdleUvTask(loopMain, hChannel, FreeChannelFinally);
}
void HdcChannelBase::FreeChannelOpeate(uv_timer_t *handle)
@ -411,26 +411,26 @@ void HdcChannelBase::FreeChannelOpeate(uv_timer_t *handle)
if (handle == nullptr || handle->data == nullptr) {
return;
}
HChannelPtr hChannelPtr = (HChannelPtr)handle->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannelPtr->clsChannel;
if (hChannelPtr->ref > 0 || thisClass == nullptr) {
HChannel hChannel = (HChannel)handle->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
if (hChannel->ref > 0 || thisClass == nullptr) {
return;
}
if (hChannelPtr->hChildWorkTCP.loop) {
auto ctrl = HdcSessionBase::BuildCtrlString(SP_DEATCH_CHANNEL, hChannelPtr->channelId, nullptr, 0);
thisClass->ChannelSendSessionCtrlMsg(ctrl, hChannelPtr->targetSessionId);
if (hChannel->hChildWorkTCP.loop) {
auto ctrl = HdcSessionBase::BuildCtrlString(SP_DEATCH_CHANNEL, hChannel->channelId, nullptr, 0);
thisClass->ChannelSendSessionCtrlMsg(ctrl, hChannel->targetSessionId);
auto callbackCheckFreeChannelContinue = [](uv_timer_t *handle) -> void {
HChannelPtr hChannelPtr = (HChannelPtr)handle->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannelPtr->clsChannel;
if (!hChannelPtr->childCleared) {
HChannel hChannel = (HChannel)handle->data;
HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
if (!hChannel->childCleared) {
return;
}
Base::TryCloseHandle((uv_handle_t *)handle, Base::CloseTimerCallback);
thisClass->FreeChannelContinue(hChannelPtr);
thisClass->FreeChannelContinue(hChannel);
};
Base::TimerUvTask(thisClass->loopMain, hChannelPtr, callbackCheckFreeChannelContinue);
Base::TimerUvTask(thisClass->loopMain, hChannel, callbackCheckFreeChannelContinue);
} else {
thisClass->FreeChannelContinue(hChannelPtr);
thisClass->FreeChannelContinue(hChannel);
}
Base::TryCloseHandle((uv_handle_t *)handle, Base::CloseTimerCallback);
}
@ -441,20 +441,20 @@ void HdcChannelBase::FreeChannel(const uint32_t channelId)
PushAsyncMessage(channelId, ASYNC_FREE_CHANNEL, nullptr, 0);
return;
}
HChannelPtr hChannelPtr = AdminChannel(OP_QUERY, channelId, nullptr);
HChannel hChannel = AdminChannel(OP_QUERY, channelId, nullptr);
do {
if (!hChannelPtr || hChannelPtr->isDead) {
if (!hChannel || hChannel->isDead) {
break;
}
WRITE_LOG(LOG_DEBUG, "Begin to free channel, channelid:%u", channelId);
Base::TimerUvTask(loopMain, hChannelPtr, FreeChannelOpeate, MINOR_TIMEOUT); // do immediately
hChannelPtr->isDead = true;
Base::TimerUvTask(loopMain, hChannel, FreeChannelOpeate, MINOR_TIMEOUT); // do immediately
hChannel->isDead = true;
} while (false);
}
HChannelPtr HdcChannelBase::AdminChannel(const uint8_t op, const uint32_t channelId, HChannelPtr hInput)
HChannel HdcChannelBase::AdminChannel(const uint8_t op, const uint32_t channelId, HChannel hInput)
{
HChannelPtr hRet = nullptr;
HChannel hRet = nullptr;
switch (op) {
case OP_ADD:
uv_rwlock_wrlock(&lockMapChannel);
@ -496,9 +496,9 @@ HChannelPtr HdcChannelBase::AdminChannel(const uint8_t op, const uint32_t channe
return hRet;
}
void HdcChannelBase::EchoToClient(HChannelPtr hChannelPtr, uint8_t *bufPtr, const int size)
void HdcChannelBase::EchoToClient(HChannel hChannel, uint8_t *bufPtr, const int size)
{
if (hChannelPtr == nullptr) {
if (hChannel == nullptr) {
return;
}
@ -513,12 +513,12 @@ void HdcChannelBase::EchoToClient(HChannelPtr hChannelPtr, uint8_t *bufPtr, cons
delete[] data;
return;
}
sendStream = (uv_stream_t *)&hChannelPtr->hChildWorkTCP;
sendStream = (uv_stream_t *)&hChannel->hChildWorkTCP;
if (!uv_is_closing((const uv_handle_t *)sendStream) && uv_is_writable(sendStream)) {
++hChannelPtr->ref;
++hChannel->ref;
Base::SendToStreamEx(sendStream, data, sizeNewBuf, nullptr, (void *)WriteCallback, data);
} else {
WRITE_LOG(LOG_WARN, "EchoToClient, channelId:%u is unwritable.", hChannelPtr->channelId);
WRITE_LOG(LOG_WARN, "EchoToClient, channelId:%u is unwritable.", hChannel->channelId);
delete[] data;
}
}
@ -526,10 +526,10 @@ void HdcChannelBase::EchoToClient(HChannelPtr hChannelPtr, uint8_t *bufPtr, cons
void HdcChannelBase::EchoToAllChannelsViaSessionId(uint32_t targetSessionId, const string &echo)
{
for (auto v : mapChannel) {
HChannelPtr hChannelPtr = (HChannelPtr)v.second;
if (hChannelPtr != nullptr && !hChannelPtr->isDead && hChannelPtr->targetSessionId == targetSessionId) {
HChannel hChannel = (HChannel)v.second;
if (hChannel != nullptr && !hChannel->isDead && hChannel->targetSessionId == targetSessionId) {
WRITE_LOG(LOG_INFO, "%s:%u %s", __FUNCTION__, targetSessionId, echo.c_str());
EchoToClient(hChannelPtr, (uint8_t *)echo.c_str(), echo.size());
EchoToClient(hChannel, (uint8_t *)echo.c_str(), echo.size());
}
}
}

View File

@ -21,7 +21,7 @@ class HdcChannelBase {
public:
HdcChannelBase(const bool serverOrClient, const string &addrString, uv_loop_t *loopMainIn);
virtual ~HdcChannelBase();
HChannelPtr AdminChannel(const uint8_t op, const uint32_t channelId, HChannelPtr hInput);
HChannel AdminChannel(const uint8_t op, const uint32_t channelId, HChannel hInput);
static void AllocCallback(uv_handle_t *handle, size_t sizeWanted, uv_buf_t *buf);
static void ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t *buf);
void PushAsyncMessage(const uint32_t channelId, const uint8_t method, const void *data, const int dataSize);
@ -38,15 +38,15 @@ protected:
char connectKey[MAX_CONNECTKEY_SIZE];
};
} __attribute__((packed));
uint32_t MallocChannel(HChannelPtr *hOutChannel);
virtual int ReadChannel(HChannelPtr hChannel, uint8_t *bufPtr, const int bytesIO)
uint32_t MallocChannel(HChannel *hOutChannel);
virtual int ReadChannel(HChannel hChannel, uint8_t *bufPtr, const int bytesIO)
{
return 0;
}
virtual void NotifyInstanceChannelFree(HChannelPtr hChannel) {};
virtual void NotifyInstanceChannelFree(HChannel hChannel) {};
void Send(const uint32_t channelId, uint8_t *bufPtr, const int size);
void SendChannel(HChannelPtr hChannel, uint8_t *bufPtr, const int size);
void EchoToClient(HChannelPtr hChannel, uint8_t *bufPtr, const int size);
void SendChannel(HChannel hChannel, uint8_t *bufPtr, const int size);
void EchoToClient(HChannel hChannel, uint8_t *bufPtr, const int size);
virtual bool ChannelSendSessionCtrlMsg(vector<uint8_t> &ctrlMsg, uint32_t sessionId)
{
return true; // just server use
@ -68,12 +68,12 @@ private:
static void FreeChannelOpeate(uv_timer_t *handle);
static void FreeChannelFinally(uv_idle_t *handle);
void ClearChannels();
void FreeChannelContinue(HChannelPtr hChannel);
void FreeChannelContinue(HChannel hChannel);
bool SetChannelTCPString(const string &addrString);
uint32_t GetChannelPseudoUid();
uv_rwlock_t lockMapChannel; // protect mapChannel
map<uint32_t, HChannelPtr> mapChannel;
map<uint32_t, HChannel> mapChannel;
uv_thread_t threadChanneMain;
};
} // namespace Hdc

View File

@ -78,7 +78,7 @@ namespace Debug {
}
struct stat statbuf;
stat(filePath.c_str(), &statbuf);
stat(filePath., &statbuf);
int size = statbuf.st_size;
if (size > bufLen) {
fclose(fp);
@ -93,11 +93,11 @@ namespace Debug {
return size;
}
void DetermineThread(HSessionPtr hSessionPtr)
void DetermineThread(HSession hSession)
{
if (uv_thread_self() == hSessionPtr->hWorkThread) {
if (uv_thread_self() == hSession->hWorkThread) {
WRITE_LOG(LOG_WARN, "At main workthread");
} else if (uv_thread_self() == hSessionPtr->hWorkChildThread) {
} else if (uv_thread_self() == hSession->hWorkChildThread) {
WRITE_LOG(LOG_WARN, "At child workthread");
} else {
WRITE_LOG(LOG_WARN, "At unknow workthread");
@ -119,4 +119,4 @@ namespace Debug {
return 0;
}
}
} // namespace Hdc
} // namespace Hdc

View File

@ -21,7 +21,7 @@ namespace Debug {
FILE* OpenValidDebugFilePath(const char *fileName, const std::string& mode, std::string& filePath);
int WriteHexToDebugFile(const char *fileName, const uint8_t *buf, const int bufLen);
int ReadHexFromDebugFile(const char *fileName, uint8_t *buf, const int bufLen);
void DetermineThread(HSessionPtr hSessionPtr);
void DetermineThread(HSession hSession);
int PrintfHexBuf(const uint8_t *buf, int bufLen);
}
} // namespace Hdc

View File

@ -236,7 +236,7 @@ struct TaskInformation {
void *ownerSessionClass;
uint32_t closeRetryCount;
};
using HTaskInfoPtr = TaskInformation *;
using HTaskInfo = TaskInformation *;
#pragma pack(pop)
@ -295,7 +295,7 @@ struct HdcUSB {
mutex lockDeviceHandle;
mutex lockSendUsbBlock;
};
using HUSBPtr = struct HdcUSB *;
using HUSB = struct HdcUSB *;
#ifdef HDC_SUPPORT_UART
struct HdcUART {
@ -322,7 +322,7 @@ struct HdcUART {
HdcUART();
~HdcUART();
};
using HUARTPtr = struct HdcUART *;
using HUART = struct HdcUART *;
#endif
struct HdcSession {
@ -337,7 +337,7 @@ struct HdcSession {
uint8_t uvHandleRef; // libuv handle ref -- just main thread now
uint8_t uvChildRef; // libuv handle ref -- just main thread now
bool childCleared;
map<uint32_t, HTaskInfoPtr> *mapTask;
map<uint32_t, HTaskInfo> *mapTask;
// class ptr
void *classInstance; // HdcSessionBase instance, HdcServer or HdcDaemon
void *classModule; // Communicate module, TCP or USB instance,HdcDaemonUSB HdcDaemonTCP etc...
@ -360,9 +360,9 @@ struct HdcSession {
uv_tcp_t hChildWorkTCP; // work channelseparate thread for server/daemon
uv_os_sock_t fdChildWorkTCP;
// usb handle
HUSBPtr hUSB;
HUSB hUSB;
#ifdef HDC_SUPPORT_UART
HUARTPtr hUART = nullptr;
HUART hUART = nullptr;
#endif
// tcp handle
uv_tcp_t hWorkTCP;
@ -393,7 +393,7 @@ struct HdcSession {
}
}
};
using HSessionPtr = struct HdcSession *;
using HSession = struct HdcSession *;
struct HdcChannel {
void *clsChannel; // ptr Class of serverForClient or client
@ -422,7 +422,7 @@ struct HdcChannel {
uv_tty_t stdoutTty;
char bufStd[128];
};
using HChannelPtr = struct HdcChannel *;
using HChannel = struct HdcChannel *;
struct HdcDaemonInformation {
uint8_t connType;
@ -430,9 +430,9 @@ struct HdcDaemonInformation {
string connectKey;
string usbMountPoint;
string devName;
HSessionPtr hSessionPtr;
HSession hSession;
};
using HDaemonInfoPtr = struct HdcDaemonInformation *;
using HDaemonInfo = struct HdcDaemonInformation *;
struct HdcForwardInformation {
string taskString;
@ -440,6 +440,6 @@ struct HdcForwardInformation {
uint32_t sessionId;
uint32_t channelId;
};
using HForwardInfoPtr = struct HdcForwardInformation *;
using HForwardInfo = struct HdcForwardInformation *;
}
#endif

View File

@ -16,7 +16,7 @@
#include "serial_struct.h"
namespace Hdc {
HdcFile::HdcFile(HTaskInfoPtr hTaskInfo)
HdcFile::HdcFile(HTaskInfo hTaskInfo)
: HdcTransferBase(hTaskInfo)
{
commandBegin = CMD_FILE_BEGIN;

View File

@ -20,7 +20,7 @@
namespace Hdc {
class HdcFile : public HdcTransferBase {
public:
HdcFile(HTaskInfoPtr hTaskInfo);
HdcFile(HTaskInfo hTaskInfo);
virtual ~HdcFile();
void StopTask();
bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize);

View File

@ -16,7 +16,7 @@
#include "base.h"
namespace Hdc {
HdcForwardBase::HdcForwardBase(HTaskInfoPtr hTaskInfo)
HdcForwardBase::HdcForwardBase(HTaskInfo hTaskInfo)
: HdcTaskBase(hTaskInfo)
{
}

View File

@ -19,7 +19,7 @@
namespace Hdc {
class HdcForwardBase : public HdcTaskBase {
public:
HdcForwardBase(HTaskInfoPtr hTaskInfo);
HdcForwardBase(HTaskInfo hTaskInfo);
virtual ~HdcForwardBase();
bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize);
bool BeginForward(const string &command, string &sError);

File diff suppressed because it is too large Load Diff

View File

@ -57,16 +57,16 @@ public:
HdcSessionBase(bool serverOrDaemonIn);
virtual ~HdcSessionBase();
virtual void AttachChannel(HSessionPtr hSessionPtr, const uint32_t channelId)
virtual void AttachChannel(HSession hSession, const uint32_t channelId)
{
}
virtual void DeatchChannel(HSessionPtr hSessionPtr, const uint32_t channelId)
virtual void DeatchChannel(HSession hSession, const uint32_t channelId)
{
}
virtual void NotifyInstanceSessionFree(HSessionPtr hSessionPtr, bool freeOrClear)
virtual void NotifyInstanceSessionFree(HSession hSession, bool freeOrClear)
{
}
virtual bool RedirectToTask(HTaskInfoPtr hTaskInfo, HSessionPtr hSessionPtr, const uint32_t channelId,
virtual bool RedirectToTask(HTaskInfo hTaskInfo, HSession hSession, const uint32_t channelId,
const uint16_t command, uint8_t *payload, const int payloadSize)
{
return true;
@ -82,27 +82,27 @@ public:
static void SessionWorkThread(uv_work_t *arg);
static void ReadCtrlFromMain(uv_stream_t *uvpipe, ssize_t nread, const uv_buf_t *buf);
static void ReadCtrlFromSession(uv_stream_t *uvpipe, ssize_t nread, const uv_buf_t *buf);
HSessionPtr QueryUSBDeviceRegister(void *pDev, uint8_t busIDIn, uint8_t devIDIn);
virtual HSessionPtr MallocSession(bool serverOrDaemon, const ConnType connType, void *classModule, uint32_t sessionId = 0);
HSession QueryUSBDeviceRegister(void *pDev, uint8_t busIDIn, uint8_t devIDIn);
virtual HSession MallocSession(bool serverOrDaemon, const ConnType connType, void *classModule, uint32_t sessionId = 0);
virtual void FreeSession(const uint32_t sessionId);
void WorkerPendding();
int OnRead(HSessionPtr hSessionPtr, uint8_t *bufPtr, const int bufLen);
int OnRead(HSession hSession, uint8_t *bufPtr, const int bufLen);
int Send(const uint32_t sessionId, const uint32_t channelId, const uint16_t commandFlag, const uint8_t *data,
const int dataSize);
int SendByProtocol(HSessionPtr hSessionPtr, uint8_t *bufPtr, const int bufLen);
virtual HSessionPtr AdminSession(const uint8_t op, const uint32_t sessionId, HSessionPtr hInput);
virtual int FetchIOBuf(HSessionPtr hSessionPtr, uint8_t *ioBuf, int read);
int SendByProtocol(HSession hSession, uint8_t *bufPtr, const int bufLen);
virtual HSession AdminSession(const uint8_t op, const uint32_t sessionId, HSession hInput);
virtual int FetchIOBuf(HSession hSession, uint8_t *ioBuf, int read);
virtual void PushAsyncMessage(const uint32_t sessionId, const uint8_t method, const void *data, const int dataSize);
HTaskInfoPtr AdminTask(const uint8_t op, HSessionPtr hSessionPtr, const uint32_t channelId, HTaskInfoPtr hInput);
bool DispatchTaskData(HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command, uint8_t *payload,
HTaskInfo AdminTask(const uint8_t op, HSession hSession, const uint32_t channelId, HTaskInfo hInput);
bool DispatchTaskData(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
int payloadSize);
void EnumUSBDeviceRegister(void (*pCallBack)(HSessionPtr hSessionPtr));
void EnumUSBDeviceRegister(void (*pCallBack)(HSession hSession));
#ifdef HDC_SUPPORT_UART
using UartKickoutZombie = const std::function<void(HSessionPtr hSessionPtr)>;
using UartKickoutZombie = const std::function<void(HSession hSession)>;
virtual void EnumUARTDeviceRegister(UartKickoutZombie);
#endif
void ClearOwnTasks(HSessionPtr hSessionPtr, const uint32_t channelIDInput);
virtual bool FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command, uint8_t *payload,
void ClearOwnTasks(HSession hSession, const uint32_t channelIDInput);
virtual bool FetchCommand(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
int payloadSize)
{
return true;
@ -112,7 +112,7 @@ public:
{
return true;
}
virtual bool RemoveInstanceTask(const uint8_t op, HTaskInfoPtr hTask)
virtual bool RemoveInstanceTask(const uint8_t op, HTaskInfo hTask)
{
return true;
}
@ -142,7 +142,7 @@ protected:
}
// must be define in haderfile, cannot in cpp file
template<class T>
bool TaskCommandDispatch(HTaskInfoPtr hTaskInfo, uint8_t taskType, const uint16_t command, uint8_t *payload,
bool TaskCommandDispatch(HTaskInfo hTaskInfo, uint8_t taskType, const uint16_t command, uint8_t *payload,
const int payloadSize)
{
bool ret = true;
@ -163,7 +163,7 @@ protected:
}
return ret;
}
template<class T> bool DoTaskRemove(HTaskInfoPtr hTaskInfo, const uint8_t op)
template<class T> bool DoTaskRemove(HTaskInfo hTaskInfo, const uint8_t op)
{
T *ptrTask = (T *)hTaskInfo->taskClass;
if (OP_CLEAR == op) {
@ -182,24 +182,24 @@ private:
virtual void ClearInstanceResource()
{
}
int DecryptPayload(HSessionPtr hSessionPtr, PayloadHead *payloadHeadBe, uint8_t *encBuf);
bool DispatchMainThreadCommand(HSessionPtr hSessionPtr, const CtrlStruct *ctrl);
bool DispatchSessionThreadCommand(uv_stream_t *uvpipe, HSessionPtr hSessionPtr, const uint8_t *baseBuf,
int DecryptPayload(HSession hSession, PayloadHead *payloadHeadBe, uint8_t *encBuf);
bool DispatchMainThreadCommand(HSession hSession, const CtrlStruct *ctrl);
bool DispatchSessionThreadCommand(uv_stream_t *uvpipe, HSession hSession, const uint8_t *baseBuf,
const int bytesIO);
bool BeginRemoveTask(HTaskInfoPtr hTask);
bool TryRemoveTask(HTaskInfoPtr hTask);
void ReChildLoopForSessionClear(HSessionPtr hSessionPtr);
void FreeSessionContinue(HSessionPtr hSessionPtr);
bool BeginRemoveTask(HTaskInfo hTask);
bool TryRemoveTask(HTaskInfo hTask);
void ReChildLoopForSessionClear(HSession hSession);
void FreeSessionContinue(HSession hSession);
static void FreeSessionFinally(uv_idle_t *handle);
static void AsyncMainLoopTask(uv_idle_t *handle);
static void FreeSessionOpeate(uv_timer_t *handle);
int MallocSessionByConnectType(HSessionPtr hSessionPtr);
void FreeSessionByConnectType(HSessionPtr hSessionPtr);
bool WorkThreadStartSession(HSessionPtr hSessionPtr);
int MallocSessionByConnectType(HSession hSession);
void FreeSessionByConnectType(HSession hSession);
bool WorkThreadStartSession(HSession hSession);
uint32_t GetSessionPseudoUid();
bool NeedNewTaskInfo(const uint16_t command, bool &masterTask);
map<uint32_t, HSessionPtr> mapSession;
map<uint32_t, HSession> mapSession;
uv_rwlock_t lockMapSession;
std::atomic<uint32_t> sessionRef = 0;
const uint8_t payloadProtectStaticVcode = 0x09;

View File

@ -18,7 +18,7 @@ namespace Hdc {
// -----------------------------------------------------------
// notice!!! The constructor is called at the Child thread, so in addition to initialization, do not excess actions, if
// destructor is required, please clean up in the subclasses.
HdcTaskBase::HdcTaskBase(HTaskInfoPtr hTaskInfo)
HdcTaskBase::HdcTaskBase(HTaskInfo hTaskInfo)
{
taskInfo = hTaskInfo;
if (hTaskInfo != nullptr) {
@ -83,8 +83,8 @@ bool HdcTaskBase::ServerCommand(const uint16_t command, uint8_t *bufPtr, const i
if (taskInfo == nullptr || taskInfo->ownerSessionClass == nullptr) {
return false;
}
HdcSessionBase *hSessionPtr = (HdcSessionBase *)taskInfo->ownerSessionClass;
return hSessionPtr->ServerCommand(taskInfo->sessionId, taskInfo->channelId, command, bufPtr, size);
HdcSessionBase *hSession = (HdcSessionBase *)taskInfo->ownerSessionClass;
return hSession->ServerCommand(taskInfo->sessionId, taskInfo->channelId, command, bufPtr, size);
}
// cross thread
@ -94,15 +94,15 @@ int HdcTaskBase::ThreadCtrlCommunicate(const uint8_t *bufPtr, const int size)
return false;
}
HdcSessionBase *sessionBase = (HdcSessionBase *)taskInfo->ownerSessionClass;
HSessionPtr hSessionPtr = sessionBase->AdminSession(OP_QUERY, taskInfo->sessionId, nullptr);
if (!hSessionPtr) {
HSession hSession = sessionBase->AdminSession(OP_QUERY, taskInfo->sessionId, nullptr);
if (!hSession) {
return -1;
}
uv_stream_t *handleStream = nullptr;
if (uv_thread_self() == hSessionPtr->hWorkThread) {
handleStream = (uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN];
} else if (uv_thread_self() == hSessionPtr->hWorkChildThread) {
handleStream = (uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_WORK];
if (uv_thread_self() == hSession->hWorkThread) {
handleStream = (uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN];
} else if (uv_thread_self() == hSession->hWorkChildThread) {
handleStream = (uv_stream_t *)&hSession->ctrlPipe[STREAM_WORK];
} else {
return ERR_GENERIC;
}

View File

@ -20,7 +20,7 @@ namespace Hdc {
// Only allow inheritance
class HdcTaskBase {
public:
HdcTaskBase(HTaskInfoPtr hTaskInfo);
HdcTaskBase(HTaskInfo hTaskInfo);
virtual ~HdcTaskBase();
virtual bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize)
{
@ -47,7 +47,7 @@ protected:
// step, when the value is false, the Task class will be destructured as soon as possible
bool childReady; // Subcompulents have been prepared
bool singalStop; // Request stop signal
HTaskInfoPtr taskInfo;
HTaskInfo taskInfo;
uint32_t refCount;
private:

View File

@ -79,8 +79,8 @@ void HdcTCPBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t *buf
if (tcp == nullptr || tcp->data == nullptr) {
return;
}
HSessionPtr hSessionPtr = (HSessionPtr)tcp->data;
HdcTCPBase *thisClass = (HdcTCPBase *)hSessionPtr->classModule;
HSession hSession = (HSession)tcp->data;
HdcTCPBase *thisClass = (HdcTCPBase *)hSession->classModule;
if (thisClass == nullptr || thisClass->clsMainBase) {
return;
}
@ -99,7 +99,7 @@ void HdcTCPBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t *buf
WRITE_LOG(LOG_DEBUG, "HdcTCPBase::ReadStream < 0 %s", buffer);
break;
}
if (hSessionBase->FetchIOBuf(hSessionPtr, hSessionPtr->ioBuf, nread) < 0) {
if (hSessionBase->FetchIOBuf(hSession, hSession->ioBuf, nread) < 0) {
break;
}
ret = true;
@ -108,7 +108,7 @@ void HdcTCPBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t *buf
if (!ret) {
// The first time is closed first, prevent the write function from continuing to write
Base::TryCloseHandle(reinterpret_cast<uv_handle_t *>(tcp));
hSessionBase->FreeSession(hSessionPtr->sessionId);
hSessionBase->FreeSession(hSession->sessionId);
}
}
} // namespace Hdc

View File

@ -22,7 +22,7 @@
namespace Hdc {
constexpr uint64_t HDC_TIME_CONVERT_BASE = 1000000000;
HdcTransferBase::HdcTransferBase(HTaskInfoPtr hTaskInfo)
HdcTransferBase::HdcTransferBase(HTaskInfo hTaskInfo)
: HdcTaskBase(hTaskInfo)
{
ResetCtx(&ctxNow, true);

View File

@ -43,7 +43,7 @@ public:
uint32_t compressSize;
uint32_t uncompressSize;
};
HdcTransferBase(HTaskInfoPtr hTaskInfo);
HdcTransferBase(HTaskInfo hTaskInfo);
virtual ~HdcTransferBase();
virtual void StopTask()
{

View File

@ -333,8 +333,8 @@ int HdcUARTBase::UartToHdcProtocol(uv_stream_t *stream, uint8_t *data, int dataS
if (stream == nullptr || stream->data == nullptr) {
return ERR_IO_FAIL;
}
HSessionPtr hSessionPtr = (HSessionPtr)stream->data;
unsigned int fd = hSessionPtr->dataFd[STREAM_MAIN];
HSession hSession = (HSession)stream->data;
unsigned int fd = hSession->dataFd[STREAM_MAIN];
fd_set fdSet;
struct timeval timeout = {3, 0};
FD_ZERO(&fdSet);
@ -377,18 +377,18 @@ int HdcUARTBase::UartToHdcProtocol(uv_stream_t *stream, uint8_t *data, int dataS
return index;
}
RetErrCode HdcUARTBase::DispatchToWorkThread(HSessionPtr hSessionPtr, uint8_t *readBuf, int readBytes)
RetErrCode HdcUARTBase::DispatchToWorkThread(HSession hSession, uint8_t *readBuf, int readBytes)
{
if (hSessionPtr == nullptr) {
if (hSession == nullptr) {
return ERR_SESSION_NOFOUND;
}
if (!UartSendToHdcStream(hSessionPtr, readBuf, readBytes)) {
if (!UartSendToHdcStream(hSession, readBuf, readBytes)) {
return ERR_IO_FAIL;
}
return RET_SUCCESS;
}
size_t HdcUARTBase::PackageProcess(vector<uint8_t> &data, HSessionPtr hSessionPtr)
size_t HdcUARTBase::PackageProcess(vector<uint8_t> &data, HSession hSession)
{
while (data.size() >= sizeof(UartHead)) {
// is size more than one head
@ -409,25 +409,25 @@ size_t HdcUARTBase::PackageProcess(vector<uint8_t> &data, HSessionPtr hSessionPt
// if the size of packge have all received ?
if (data.size() >= packetSize) {
// send the data to logic level (link to logic)
if (hSessionPtr == nullptr) {
if (hSession == nullptr) {
#ifdef HDC_HOST
hSessionPtr = GetSession(sessionId);
hSession = GetSession(sessionId);
#else
// for daemon side we can make a new session for it
hSessionPtr = GetSession(sessionId, true);
hSession = GetSession(sessionId, true);
#endif
}
if (hSessionPtr == nullptr) {
if (hSession == nullptr) {
WRITE_LOG(LOG_WARN, "%s have not found seesion (%u). skip it", sessionId);
} else {
if (hSessionPtr->hUART->dispatchedPackageIndex == packageIndex) {
if (hSession->hUART->dispatchedPackageIndex == packageIndex) {
// we need check if the duplication pacakge we have already send
WRITE_LOG(LOG_WARN, "%s dup package %u, skip send to session logic",
__FUNCTION__, packageIndex);
} else {
// update the last package we will send to hdc
hSessionPtr->hUART->dispatchedPackageIndex = packageIndex;
RetErrCode ret = DispatchToWorkThread(hSessionPtr, data.data(), packetSize);
hSession->hUART->dispatchedPackageIndex = packageIndex;
RetErrCode ret = DispatchToWorkThread(hSession, data.data(), packetSize);
if (ret == RET_SUCCESS) {
WRITE_LOG(LOG_DEBUG, "%s DispatchToWorkThread successful",
__FUNCTION__);
@ -438,7 +438,7 @@ size_t HdcUARTBase::PackageProcess(vector<uint8_t> &data, HSessionPtr hSessionPt
"%s DispatchToWorkThread fail %d. requeset free session in "
"other side",
__FUNCTION__, ret);
ResponseUartTrans(hSessionPtr->sessionId, ++hSessionPtr->hUART->packageIndex,
ResponseUartTrans(hSession->sessionId, ++hSession->hUART->packageIndex,
PKG_OPTION_FREE);
}
}
@ -461,7 +461,7 @@ size_t HdcUARTBase::PackageProcess(vector<uint8_t> &data, HSessionPtr hSessionPt
return data.size() > 1 ? sizeof(UartHead) : 0;
}
bool HdcUARTBase::SendUARTRaw(HSessionPtr hSessionPtr, uint8_t *data, const size_t length)
bool HdcUARTBase::SendUARTRaw(HSession hSession, uint8_t *data, const size_t length)
{
struct UartHead *uartHeader = (struct UartHead *)data;
if (uartHeader == nullptr) {
@ -480,36 +480,36 @@ bool HdcUARTBase::SendUARTRaw(HSessionPtr hSessionPtr, uint8_t *data, const size
#endif
// for normal package
if (hSessionPtr == nullptr) {
hSessionPtr = GetSession(uartHeader->sessionId);
if (hSessionPtr == nullptr) {
if (hSession == nullptr) {
hSession = GetSession(uartHeader->sessionId);
if (hSession == nullptr) {
// session is not found
WRITE_LOG(LOG_WARN, "%s hSessionPtr not found:%zu", __FUNCTION__, uartHeader->sessionId);
WRITE_LOG(LOG_WARN, "%s hSession not found:%zu", __FUNCTION__, uartHeader->sessionId);
return false;
}
}
hSessionPtr->ref++;
hSession->ref++;
WRITE_LOG(LOG_DEBUG, "%s length:%d", __FUNCTION__, length);
#ifdef HDC_HOST
ssize_t sendBytes = WriteUartDev(data, length, *hSessionPtr->hUART);
ssize_t sendBytes = WriteUartDev(data, length, *hSession->hUART);
#else
ssize_t sendBytes = WriteUartDev(data, length, deamonUart);
#endif
WRITE_LOG(LOG_DEBUG, "%s sendBytes %zu", __FUNCTION__, sendBytes);
if (sendBytes < 0) {
WRITE_LOG(LOG_DEBUG, "%s send fail. try to freesession", __FUNCTION__);
OnTransferError(hSessionPtr);
OnTransferError(hSession);
}
hSessionPtr->ref--;
hSession->ref--;
return sendBytes > 0;
}
// this function will not check the data correct again
// just send the data to hdc session side
bool HdcUARTBase::UartSendToHdcStream(HSessionPtr hSessionPtr, uint8_t *data, size_t size)
bool HdcUARTBase::UartSendToHdcStream(HSession hSession, uint8_t *data, size_t size)
{
WRITE_LOG(LOG_DEBUG, "%s send to session %s package size %zu", __FUNCTION__,
hSessionPtr->ToDebugString().c_str(), size);
hSession->ToDebugString().c_str(), size);
int ret = RET_SUCCESS;
@ -527,21 +527,21 @@ bool HdcUARTBase::UartSendToHdcStream(HSessionPtr hSessionPtr, uint8_t *data, si
*(data + sizeof(UartHead) + 1));
// review need check logic again here or err process
if (head->sessionId != hSessionPtr->sessionId) {
if (hSessionPtr->serverOrDaemon && !hSessionPtr->hUART->resetIO) {
if (head->sessionId != hSession->sessionId) {
if (hSession->serverOrDaemon && !hSession->hUART->resetIO) {
WRITE_LOG(LOG_FATAL, "%s sessionId not matched, reset sessionId:%d.", __FUNCTION__,
head->sessionId);
SendUartSoftReset(hSessionPtr, head->sessionId);
hSessionPtr->hUART->resetIO = true;
SendUartSoftReset(hSession, head->sessionId);
hSession->hUART->resetIO = true;
ret = ERR_IO_SOFT_RESET;
// dont break ,we need rease these data in recv buffer
}
} else {
// data to session
hSessionPtr->hUART->streamSize += head->dataSize; // this is only for debug,
hSession->hUART->streamSize += head->dataSize; // this is only for debug,
WRITE_LOG(LOG_ALL, "%s stream wait session read size: %zu", __FUNCTION__,
hSessionPtr->hUART->streamSize.load());
if (UartToHdcProtocol(reinterpret_cast<uv_stream_t *>(&hSessionPtr->dataPipe[STREAM_MAIN]),
hSession->hUART->streamSize.load());
if (UartToHdcProtocol(reinterpret_cast<uv_stream_t *>(&hSession->dataPipe[STREAM_MAIN]),
data + sizeof(UartHead), head->dataSize) < 0) {
ret = ERR_IO_FAIL;
WRITE_LOG(LOG_FATAL, "%s Error uart send to stream", __FUNCTION__);
@ -837,13 +837,13 @@ void HdcUARTBase::ResponseUartTrans(uint32_t sessionId, uint32_t packageIndex,
RequestSendPackage(reinterpret_cast<uint8_t *>(&uartHeader), sizeof(UartHead), false);
}
int HdcUARTBase::SendUARTData(HSessionPtr hSessionPtr, uint8_t *data, const size_t length)
int HdcUARTBase::SendUARTData(HSession hSession, uint8_t *data, const size_t length)
{
if (hSessionPtr == nullptr) {
if (hSession == nullptr) {
return ERR_GENERIC;
}
constexpr int maxIOSize = MAX_UART_SIZE_IOBUF;
WRITE_LOG(LOG_DEBUG, "SendUARTData hSessionPtr:%u, total length:%d", hSessionPtr->sessionId, length);
WRITE_LOG(LOG_DEBUG, "SendUARTData hSession:%u, total length:%d", hSession->sessionId, length);
const int packageDataMaxSize = maxIOSize - sizeof(UartHead);
size_t offset = 0;
uint8_t sendDataBuf[MAX_UART_SIZE_IOBUF];
@ -859,8 +859,8 @@ int HdcUARTBase::SendUARTData(HSessionPtr hSessionPtr, uint8_t *data, const size
EOK) {
return ERR_BUF_COPY;
}
head->sessionId = hSessionPtr->sessionId;
head->packageIndex = ++hSessionPtr->hUART->packageIndex;
head->sessionId = hSession->sessionId;
head->packageIndex = ++hSession->hUART->packageIndex;
int RemainingDataSize = length - offset;
if (RemainingDataSize > packageDataMaxSize) {
@ -896,9 +896,9 @@ void HdcUARTBase::ReadDataFromUARTStream(uv_stream_t *stream, ssize_t nread, con
if (stream == nullptr || stream->data == nullptr) {
return;
}
HSessionPtr hSessionPtr = (HSessionPtr)stream->data;
HdcUARTBase *hUARTBase = (HdcUARTBase *)hSessionPtr->classModule;
if (hUARTBase == nullptr || hSessionPtr->hUART == nullptr) {
HSession hSession = (HSession)stream->data;
HdcUARTBase *hUARTBase = (HdcUARTBase *)hSession->classModule;
if (hUARTBase == nullptr || hSession->hUART == nullptr) {
return;
}
std::lock_guard<std::mutex> lock(hUARTBase->workThreadProcessingData);
@ -909,47 +909,47 @@ void HdcUARTBase::ReadDataFromUARTStream(uv_stream_t *stream, ssize_t nread, con
uv_err_name_r(nread, buffer, bufSize);
}
WRITE_LOG(LOG_DEBUG, "%s sessionId:%u, nread:%zd %s streamSize %zu", __FUNCTION__,
hSessionPtr->sessionId, nread, buffer,
hSessionPtr->hUART->streamSize.load());
HdcSessionBase *hSessionBase = (HdcSessionBase *)hSessionPtr->classInstance;
hSession->sessionId, nread, buffer,
hSession->hUART->streamSize.load());
HdcSessionBase *hSessionBase = (HdcSessionBase *)hSession->classInstance;
if (hSessionBase == nullptr) {
return;
}
if (nread <= 0 or nread > signed(hSessionPtr->hUART->streamSize)) {
if (nread <= 0 or nread > signed(hSession->hUART->streamSize)) {
WRITE_LOG(LOG_FATAL, "%s nothing need to do ! because no data here", __FUNCTION__);
return;
}
if (hSessionBase->FetchIOBuf(hSessionPtr, hSessionPtr->ioBuf, nread) < 0) {
if (hSessionBase->FetchIOBuf(hSession, hSession->ioBuf, nread) < 0) {
WRITE_LOG(LOG_FATAL, "%s FetchIOBuf failed , free the other side session", __FUNCTION__);
// seesion side said the dont understand this seesion data
// so we also need tell other side to free it session.
hUARTBase->ResponseUartTrans(hSessionPtr->sessionId, ++hSessionPtr->hUART->packageIndex,
hUARTBase->ResponseUartTrans(hSession->sessionId, ++hSession->hUART->packageIndex,
PKG_OPTION_FREE);
WRITE_LOG(LOG_FATAL, "%s FetchIOBuf failed , free the session", __FUNCTION__);
hSessionBase->FreeSession(hSessionPtr->sessionId);
hSessionBase->FreeSession(hSession->sessionId);
}
hSessionPtr->hUART->streamSize -= nread;
WRITE_LOG(LOG_DEBUG, "%s sessionId:%u, nread:%d", __FUNCTION__, hSessionPtr->sessionId, nread);
hSession->hUART->streamSize -= nread;
WRITE_LOG(LOG_DEBUG, "%s sessionId:%u, nread:%d", __FUNCTION__, hSession->sessionId, nread);
}
bool HdcUARTBase::ReadyForWorkThread(HSessionPtr hSessionPtr)
bool HdcUARTBase::ReadyForWorkThread(HSession hSession)
{
if (hSessionPtr == nullptr) {
if (hSession == nullptr) {
return false;
}
if (externInterface.UvTcpInit(&hSessionPtr->childLoop, &hSessionPtr->dataPipe[STREAM_WORK],
hSessionPtr->dataFd[STREAM_WORK])) {
if (externInterface.UvTcpInit(&hSession->childLoop, &hSession->dataPipe[STREAM_WORK],
hSession->dataFd[STREAM_WORK])) {
WRITE_LOG(LOG_FATAL, "%s init child TCP failed", __FUNCTION__);
return false;
}
hSessionPtr->dataPipe[STREAM_WORK].data = hSessionPtr;
HdcSessionBase *pSession = (HdcSessionBase *)hSessionPtr->classInstance;
hSession->dataPipe[STREAM_WORK].data = hSession;
HdcSessionBase *pSession = (HdcSessionBase *)hSession->classInstance;
if (pSession == nullptr) {
return false;
}
externInterface.SetTcpOptions(&hSessionPtr->dataPipe[STREAM_WORK]);
if (externInterface.UvRead((uv_stream_t *)&hSessionPtr->dataPipe[STREAM_WORK],
externInterface.SetTcpOptions(&hSession->dataPipe[STREAM_WORK]);
if (externInterface.UvRead((uv_stream_t *)&hSession->dataPipe[STREAM_WORK],
pSession->AllocCallback, &HdcUARTBase::ReadDataFromUARTStream)) {
WRITE_LOG(LOG_FATAL, "%s child TCP read failed", __FUNCTION__);
return false;
@ -958,7 +958,7 @@ bool HdcUARTBase::ReadyForWorkThread(HSessionPtr hSessionPtr)
return true;
}
void HdcUARTBase::Restartession(const HSessionPtr session)
void HdcUARTBase::Restartession(const HSession session)
{
if (session != nullptr) {
WRITE_LOG(LOG_FATAL, "%s:%s", __FUNCTION__, session->ToDebugString().c_str());
@ -967,11 +967,11 @@ void HdcUARTBase::Restartession(const HSessionPtr session)
}
}
void HdcUARTBase::StopSession(HSessionPtr hSessionPtr)
void HdcUARTBase::StopSession(HSession hSession)
{
if (hSessionPtr != nullptr) {
WRITE_LOG(LOG_WARN, "%s:%s", __FUNCTION__, hSessionPtr->ToDebugString().c_str());
ClearUARTOutMap(hSessionPtr->sessionId);
if (hSession != nullptr) {
WRITE_LOG(LOG_WARN, "%s:%s", __FUNCTION__, hSession->ToDebugString().c_str());
ClearUARTOutMap(hSession->sessionId);
} else {
WRITE_LOG(LOG_FATAL, "%s: clean null session", __FUNCTION__);
}

View File

@ -160,11 +160,11 @@ public:
static ExternInterface defaultInterface;
HdcUARTBase(HdcSessionBase &, ExternInterface & = defaultInterface);
virtual ~HdcUARTBase();
bool ReadyForWorkThread(HSessionPtr hSessionPtr);
int SendUARTData(HSessionPtr hSessionPtr, uint8_t *data, const size_t length);
bool ReadyForWorkThread(HSession hSession);
int SendUARTData(HSession hSession, uint8_t *data, const size_t length);
// call from session side
// we need know when we need clear the pending send data
virtual void StopSession(HSessionPtr hSessionPtr);
virtual void StopSession(HSession hSession);
protected:
static constexpr uint32_t DEFAULT_BAUD_RATE_VALUE = 921600;
@ -175,10 +175,10 @@ protected:
// Mainly used to reply a data back before stop.
std::mutex workThreadProcessingData;
// review how about make a HUARTPtr in daemon side and put the devhandle in it ?
// review how about make a HUART in daemon side and put the devhandle in it ?
int uartHandle = -1;
virtual bool SendUARTRaw(HSessionPtr hSessionPtr, uint8_t *data, const size_t length);
virtual void SendUartSoftReset(HSessionPtr hUART, uint32_t sessionId) {};
virtual bool SendUARTRaw(HSession hSession, uint8_t *data, const size_t length);
virtual void SendUartSoftReset(HSession hUART, uint32_t sessionId) {};
virtual RetErrCode ValidateUartPacket(vector<uint8_t> &data, uint32_t &sessionId,
uint32_t &packageIndex, size_t &fullPackageLength);
virtual void NotifyTransfer();
@ -186,12 +186,12 @@ protected:
{
return;
}
virtual void Restartession(const HSessionPtr session);
virtual void Restartession(const HSession session);
#ifndef _WIN32
int SetSerial(int fd, int nSpeed, int nBits, char nEvent, int nStop);
#endif // _WIN32
virtual bool UartSendToHdcStream(HSessionPtr hSessionPtr, uint8_t *data, size_t size);
virtual bool UartSendToHdcStream(HSession hSession, uint8_t *data, size_t size);
static void ReadDataFromUARTStream(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf);
bool uartOpened;
@ -203,11 +203,11 @@ protected:
virtual void ResponseUartTrans(uint32_t sessionId, uint32_t packageIndex,
UartProtocolOption option);
virtual size_t PackageProcess(vector<uint8_t> &data, HSessionPtr hSessionPtr = nullptr);
virtual RetErrCode DispatchToWorkThread(HSessionPtr hSessionPtr, uint8_t *readBuf, int readBytes);
virtual size_t PackageProcess(vector<uint8_t> &data, HSession hSession = nullptr);
virtual RetErrCode DispatchToWorkThread(HSession hSession, uint8_t *readBuf, int readBytes);
virtual void OnTransferError(const HSessionPtr session) = 0;
virtual HSessionPtr GetSession(const uint32_t sessionId, bool create = false) = 0;
virtual void OnTransferError(const HSession session) = 0;
virtual HSession GetSession(const uint32_t sessionId, bool create = false) = 0;
/*
read data from uart devices

View File

@ -31,32 +31,32 @@ void HdcUSBBase::ReadUSB(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf
if (stream == nullptr || stream->data == nullptr) {
return;
}
HSessionPtr hSessionPtr = (HSessionPtr)stream->data;
HdcSessionBase *hSessionBase = (HdcSessionBase *)hSessionPtr->classInstance;
HSession hSession = (HSession)stream->data;
HdcSessionBase *hSessionBase = (HdcSessionBase *)hSession->classInstance;
if (hSessionBase == nullptr) {
return;
}
if (hSessionBase->FetchIOBuf(hSessionPtr, hSessionPtr->ioBuf, nread) < 0) {
hSessionBase->FreeSession(hSessionPtr->sessionId);
if (hSessionBase->FetchIOBuf(hSession, hSession->ioBuf, nread) < 0) {
hSessionBase->FreeSession(hSession->sessionId);
}
}
bool HdcUSBBase::ReadyForWorkThread(HSessionPtr hSessionPtr)
bool HdcUSBBase::ReadyForWorkThread(HSession hSession)
{
// Server-end USB IO is handed over to each sub-thread, only the daemon is still read by the main IO to distribute
// to each sub-thread by DataPipe.
if (hSessionPtr == nullptr || hSessionPtr->classInstance == nullptr) {
if (hSession == nullptr || hSession->classInstance == nullptr) {
return false;
}
if (uv_tcp_init(&hSessionPtr->childLoop, &hSessionPtr->dataPipe[STREAM_WORK])
|| uv_tcp_open(&hSessionPtr->dataPipe[STREAM_WORK], hSessionPtr->dataFd[STREAM_WORK])) {
if (uv_tcp_init(&hSession->childLoop, &hSession->dataPipe[STREAM_WORK])
|| uv_tcp_open(&hSession->dataPipe[STREAM_WORK], hSession->dataFd[STREAM_WORK])) {
WRITE_LOG(LOG_FATAL, "USBBase ReadyForWorkThread init child TCP failed");
return false;
}
hSessionPtr->dataPipe[STREAM_WORK].data = hSessionPtr;
HdcSessionBase *pSession = (HdcSessionBase *)hSessionPtr->classInstance;
Base::SetTcpOptions(&hSessionPtr->dataPipe[STREAM_WORK]);
if (uv_read_start((uv_stream_t *)&hSessionPtr->dataPipe[STREAM_WORK], pSession->AllocCallback, ReadUSB)) {
hSession->dataPipe[STREAM_WORK].data = hSession;
HdcSessionBase *pSession = (HdcSessionBase *)hSession->classInstance;
Base::SetTcpOptions(&hSession->dataPipe[STREAM_WORK]);
if (uv_read_start((uv_stream_t *)&hSession->dataPipe[STREAM_WORK], pSession->AllocCallback, ReadUSB)) {
WRITE_LOG(LOG_FATAL, "USBBase ReadyForWorkThread child TCP read failed");
return false;
}
@ -80,36 +80,36 @@ vector<uint8_t> HdcUSBBase::BuildPacketHeader(uint32_t sessionId, uint8_t option
// USB big data stream, block transmission, mainly to prevent accidental data packets from writing through EP port,
// inserting the send queue causes the program to crash
int HdcUSBBase::SendUSBBlock(HSessionPtr hSessionPtr, uint8_t *data, const int length)
int HdcUSBBase::SendUSBBlock(HSession hSession, uint8_t *data, const int length)
{
if (hSessionPtr == nullptr) {
if (hSession == nullptr) {
return ERR_IO_FAIL;
}
int childRet = 0;
int ret = ERR_IO_FAIL;
auto header = BuildPacketHeader(hSessionPtr->sessionId, USB_OPTION_HEADER, length);
hSessionPtr->hUSB->lockSendUsbBlock.lock();
auto header = BuildPacketHeader(hSession->sessionId, USB_OPTION_HEADER, length);
hSession->hUSB->lockSendUsbBlock.lock();
do {
if ((childRet = SendUSBRaw(hSessionPtr, header.data(), header.size())) <= 0) {
if ((childRet = SendUSBRaw(hSession, header.data(), header.size())) <= 0) {
WRITE_LOG(LOG_FATAL, "SendUSBRaw index failed");
break;
}
if ((childRet = SendUSBRaw(hSessionPtr, data, length)) <= 0) {
if ((childRet = SendUSBRaw(hSession, data, length)) <= 0) {
WRITE_LOG(LOG_FATAL, "SendUSBRaw body failed");
break;
}
if (childRet > 0 && (childRet % hSessionPtr->hUSB->wMaxPacketSizeSend == 0)) {
if (childRet > 0 && (childRet % hSession->hUSB->wMaxPacketSizeSend == 0)) {
// win32 send ZLP will block winusb driver and LIBUSB_TRANSFER_ADD_ZERO_PACKET not effect
// so, we send dummy packet to prevent zero packet generate
auto dummy = BuildPacketHeader(hSessionPtr->sessionId, 0, 0);
if ((childRet = SendUSBRaw(hSessionPtr, dummy.data(), dummy.size())) <= 0) {
auto dummy = BuildPacketHeader(hSession->sessionId, 0, 0);
if ((childRet = SendUSBRaw(hSession, dummy.data(), dummy.size())) <= 0) {
WRITE_LOG(LOG_FATAL, "SendUSBRaw dummy failed");
break;
}
}
ret = length;
} while (false);
hSessionPtr->hUSB->lockSendUsbBlock.unlock();
hSession->hUSB->lockSendUsbBlock.unlock();
return ret;
}
@ -141,18 +141,18 @@ bool HdcUSBBase::IsUsbPacketHeader(uint8_t *ioBuf, int ioBytes)
return isHeader;
}
void HdcUSBBase::PreSendUsbSoftReset(HSessionPtr hSessionPtr, uint32_t sessionIdOld)
void HdcUSBBase::PreSendUsbSoftReset(HSession hSession, uint32_t sessionIdOld)
{
if (hSessionPtr == nullptr || hSessionPtr->hUSB == nullptr) {
if (hSession == nullptr || hSession->hUSB == nullptr) {
return;
}
HUSBPtr hUSB = hSessionPtr->hUSB;
HUSB hUSB = hSession->hUSB;
int childRet = 0;
if (hSessionPtr->serverOrDaemon && !hUSB->resetIO) {
if (hSession->serverOrDaemon && !hUSB->resetIO) {
hUSB->lockSendUsbBlock.lock();
WRITE_LOG(LOG_WARN, "SendToHdcStream check, sessionId not matched");
auto header = BuildPacketHeader(sessionIdOld, USB_OPTION_RESET, 0);
if ((childRet = SendUSBRaw(hSessionPtr, header.data(), header.size())) <= 0) {
if ((childRet = SendUSBRaw(hSession, header.data(), header.size())) <= 0) {
WRITE_LOG(LOG_FATAL, "PreSendUsbSoftReset send failed");
}
hUSB->lockSendUsbBlock.unlock();
@ -160,23 +160,23 @@ void HdcUSBBase::PreSendUsbSoftReset(HSessionPtr hSessionPtr, uint32_t sessionId
}
}
int HdcUSBBase::CheckPacketOption(HSessionPtr hSessionPtr, uint8_t *appendData, int dataSize)
int HdcUSBBase::CheckPacketOption(HSession hSession, uint8_t *appendData, int dataSize)
{
if (hSessionPtr == nullptr || hSessionPtr->hUSB == nullptr || appendData == nullptr) {
if (hSession == nullptr || hSession->hUSB == nullptr || appendData == nullptr) {
return ERR_GENERIC;
}
HUSBPtr hUSB = hSessionPtr->hUSB;
HUSB hUSB = hSession->hUSB;
// special short packet
USBHead *header = (USBHead *)appendData;
header->sessionId = ntohl(header->sessionId);
header->dataSize = ntohl(header->dataSize);
if (header->sessionId != hSessionPtr->sessionId) {
if (header->sessionId != hSession->sessionId) {
// Only server do it here, daemon 'SendUsbSoftReset' no use
// hilog + ctrl^C to reproduction scene
//
// Because the USB-reset API does not work on all platforms, the last session IO data may be
// recveived, we need to ignore it.
PreSendUsbSoftReset(hSessionPtr, header->sessionId);
PreSendUsbSoftReset(hSession, header->sessionId);
return 0;
}
if (header->option & USB_OPTION_HEADER) {
@ -188,19 +188,19 @@ int HdcUSBBase::CheckPacketOption(HSessionPtr hSessionPtr, uint8_t *appendData,
}
// return value: <0 error; = 0 all finish; >0 need size
int HdcUSBBase::SendToHdcStream(HSessionPtr hSessionPtr, uv_stream_t *stream, uint8_t *appendData, int dataSize)
int HdcUSBBase::SendToHdcStream(HSession hSession, uv_stream_t *stream, uint8_t *appendData, int dataSize)
{
if (hSessionPtr == nullptr || hSessionPtr->hUSB == nullptr) {
return ERR_GENERIC;
if (hSession == nullptr || hSession->hUSB == nullptr) {
return ;
}
int childRet = 0;
HUSBPtr hUSB = hSessionPtr->hUSB;
HUSB hUSB = hSession->hUSB;
if (IsUsbPacketHeader(appendData, dataSize)) {
return CheckPacketOption(hSessionPtr, appendData, dataSize);
return CheckPacketOption(hSession, appendData, dataSize);
}
if (hUSB->payloadSize <= (uint32_t)childRet) {
// last session data
PreSendUsbSoftReset(hSessionPtr, 0); // 0 == reset current
PreSendUsbSoftReset(hSession, 0); // 0 == reset current
return 0;
}
if ((childRet = UsbToHdcProtocol(stream, appendData, dataSize)) < 0) {

View File

@ -21,12 +21,12 @@ class HdcUSBBase {
public:
HdcUSBBase(const bool serverOrDaemonIn, void *ptrMainBase);
virtual ~HdcUSBBase();
virtual bool ReadyForWorkThread(HSessionPtr hSessionPtr);
virtual void CancelUsbIo(HSessionPtr hSessionPtr) {};
int SendUSBBlock(HSessionPtr hSessionPtr, uint8_t *data, const int length);
virtual bool ReadyForWorkThread(HSession hSession);
virtual void CancelUsbIo(HSession hSession) {};
int SendUSBBlock(HSession hSession, uint8_t *data, const int length);
protected:
virtual int SendUSBRaw(HSessionPtr hSessionPtr, uint8_t *data, const int length)
virtual int SendUSBRaw(HSession hSession, uint8_t *data, const int length)
{
return 0;
}
@ -34,7 +34,7 @@ protected:
{
return 0;
};
int SendToHdcStream(HSessionPtr hSessionPtr, uv_stream_t *stream, uint8_t *appendData, int dataSize);
int SendToHdcStream(HSession hSession, uv_stream_t *stream, uint8_t *appendData, int dataSize);
int GetSafeUsbBlockSize(uint16_t wMaxPacketSizeSend);
bool IsUsbPacketHeader(uint8_t *ioBuf, int ioBytes);
@ -46,8 +46,8 @@ protected:
private:
static void ReadUSB(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf);
vector<uint8_t> BuildPacketHeader(uint32_t sessionId, uint8_t option, uint32_t dataSize);
int CheckPacketOption(HSessionPtr hSessionPtr, uint8_t *appendData, int dataSize);
void PreSendUsbSoftReset(HSessionPtr hSessionPtr, uint32_t sessionIdOld);
int CheckPacketOption(HSession hSession, uint8_t *appendData, int dataSize);
void PreSendUsbSoftReset(HSession hSession, uint32_t sessionIdOld);
};
} // namespace Hdc

View File

@ -135,7 +135,7 @@ void HdcDaemon::InitMod(bool bEnableTCP, bool bEnableUSB)
}
// clang-format off
bool HdcDaemon::RedirectToTask(HTaskInfoPtr hTaskInfo, HSessionPtr hSessionPtr, const uint32_t channelId,
bool HdcDaemon::RedirectToTask(HTaskInfo hTaskInfo, HSession hSession, const uint32_t channelId,
const uint16_t command, uint8_t *payload, const int payloadSize)
{
bool ret = true;
@ -187,16 +187,16 @@ bool HdcDaemon::RedirectToTask(HTaskInfoPtr hTaskInfo, HSessionPtr hSessionPtr,
}
// clang-format on
bool HdcDaemon::HandDaemonAuth(HSessionPtr hSessionPtr, const uint32_t channelId, SessionHandShake &handshake)
bool HdcDaemon::HandDaemonAuth(HSession hSession, const uint32_t channelId, SessionHandShake &handshake)
{
bool ret = false;
switch (handshake.authType) {
case AUTH_NONE: { // AUTH_NONE -> AUTH
hSessionPtr->tokenRSA = Base::GetRandomString(SHA_DIGEST_LENGTH);
hSession->tokenRSA = Base::GetRandomString(SHA_DIGEST_LENGTH);
handshake.authType = AUTH_TOKEN;
handshake.buf = hSessionPtr->tokenRSA;
handshake.buf = hSession->tokenRSA;
string bufString = SerialStruct::SerializeToString(handshake);
Send(hSessionPtr->sessionId, channelId, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
Send(hSession->sessionId, channelId, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
ret = true;
break;
}
@ -208,13 +208,13 @@ bool HdcDaemon::HandDaemonAuth(HSessionPtr hSessionPtr, const uint32_t channelId
// jump out dialog, and click the system, the system will store the Host public key certificate in the
// device locally, and the signature authentication will be correct when the subsequent connection is
// connected.
if (!HdcAuth::AuthVerify((uint8_t *)hSessionPtr->tokenRSA.c_str(), (uint8_t *)handshake.buf.c_str(),
if (!HdcAuth::AuthVerify((uint8_t *)hSession->tokenRSA.c_str(), (uint8_t *)handshake.buf.c_str(),
handshake.buf.size())) {
// Next auth
handshake.authType = AUTH_TOKEN;
handshake.buf = hSessionPtr->tokenRSA;
handshake.buf = hSession->tokenRSA;
string bufString = SerialStruct::SerializeToString(handshake);
Send(hSessionPtr->sessionId, channelId, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(),
Send(hSession->sessionId, channelId, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(),
bufString.size());
break;
}
@ -232,7 +232,7 @@ bool HdcDaemon::HandDaemonAuth(HSessionPtr hSessionPtr, const uint32_t channelId
return ret;
}
bool HdcDaemon::DaemonSessionHandshake(HSessionPtr hSessionPtr, const uint32_t channelId, uint8_t *payload, int payloadSize)
bool HdcDaemon::DaemonSessionHandshake(HSession hSession, const uint32_t channelId, uint8_t *payload, int payloadSize)
{
// session handshake step2
string s = string((char *)payload, payloadSize);
@ -240,42 +240,42 @@ bool HdcDaemon::DaemonSessionHandshake(HSessionPtr hSessionPtr, const uint32_t c
string err;
SerialStruct::ParseFromString(handshake, s);
#ifdef HDC_DEBUG
WRITE_LOG(LOG_DEBUG, "session %s try to handshake", hSessionPtr->ToDebugString().c_str());
WRITE_LOG(LOG_DEBUG, "session %s try to handshake", hSession->ToDebugString().c_str());
#endif
// banner to check is parse ok...
if (handshake.banner != HANDSHAKE_MESSAGE) {
hSessionPtr->availTailIndex = 0;
hSession->availTailIndex = 0;
WRITE_LOG(LOG_FATAL, "Recv server-hello failed");
return false;
}
if (handshake.authType == AUTH_NONE) {
// daemon handshake 1st packet
uint32_t unOld = hSessionPtr->sessionId;
hSessionPtr->sessionId = handshake.sessionId;
hSessionPtr->connectKey = handshake.connectKey;
AdminSession(OP_UPDATE, unOld, hSessionPtr);
uint32_t unOld = hSession->sessionId;
hSession->sessionId = handshake.sessionId;
hSession->connectKey = handshake.connectKey;
AdminSession(OP_UPDATE, unOld, hSession);
#ifdef HDC_SUPPORT_UART
if (hSessionPtr->connType == CONN_SERIAL and clsUARTServ!= nullptr) {
if (hSession->connType == CONN_SERIAL and clsUARTServ!= nullptr) {
WRITE_LOG(LOG_DEBUG, " HdcDaemon::DaemonSessionHandshake %s",
handshake.ToDebugString().c_str());
if (clsUARTServ != nullptr) {
(static_cast<HdcDaemonUART *>(clsUARTServ))->OnNewHandshakeOK(hSessionPtr->sessionId);
(static_cast<HdcDaemonUART *>(clsUARTServ))->OnNewHandshakeOK(hSession->sessionId);
}
} else
#endif // HDC_SUPPORT_UART
if (clsUSBServ != nullptr) {
(reinterpret_cast<HdcDaemonUSB *>(clsUSBServ))->OnNewHandshakeOK(hSessionPtr->sessionId);
(reinterpret_cast<HdcDaemonUSB *>(clsUSBServ))->OnNewHandshakeOK(hSession->sessionId);
}
handshake.sessionId = 0;
handshake.connectKey = "";
}
if (enableSecure && !HandDaemonAuth(hSessionPtr, channelId, handshake)) {
if (enableSecure && !HandDaemonAuth(hSession, channelId, handshake)) {
return false;
}
// handshake auth OK.Can append the sending device information to HOST
#ifdef HDC_DEBUG
WRITE_LOG(LOG_INFO, "session %u handshakeOK send back CMD_KERNEL_HANDSHAKE", hSessionPtr->sessionId);
WRITE_LOG(LOG_INFO, "session %u handshakeOK send back CMD_KERNEL_HANDSHAKE", hSession->sessionId);
#endif
char hostName[BUF_SIZE_MEDIUM] = "";
size_t len = sizeof(hostName);
@ -283,18 +283,18 @@ bool HdcDaemon::DaemonSessionHandshake(HSessionPtr hSessionPtr, const uint32_t c
handshake.authType = AUTH_OK;
handshake.buf = hostName;
string bufString = SerialStruct::SerializeToString(handshake);
Send(hSessionPtr->sessionId, channelId, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
hSessionPtr->handshakeOK = true;
Send(hSession->sessionId, channelId, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
hSession->handshakeOK = true;
return true;
}
bool HdcDaemon::FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command, uint8_t *payload,
bool HdcDaemon::FetchCommand(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
const int payloadSize)
{
bool ret = true;
if (!hSessionPtr->handshakeOK and command != CMD_KERNEL_HANDSHAKE) {
if (!hSession->handshakeOK and command != CMD_KERNEL_HANDSHAKE) {
WRITE_LOG(LOG_WARN, "session %u wait CMD_KERNEL_HANDSHAKE , but got command %u",
hSessionPtr->sessionId, command);
hSession->sessionId, command);
ret = false;
return ret;
}
@ -302,26 +302,26 @@ bool HdcDaemon::FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId,
switch (command) {
case CMD_KERNEL_HANDSHAKE: {
// session handshake step2
ret = DaemonSessionHandshake(hSessionPtr, channelId, payload, payloadSize);
ret = DaemonSessionHandshake(hSession, channelId, payload, payloadSize);
break;
}
case CMD_KERNEL_CHANNEL_CLOSE: { // Daemon is only cleaning up the Channel task
ClearOwnTasks(hSessionPtr, channelId);
ClearOwnTasks(hSession, channelId);
if (*payload != 0) {
--(*payload);
Send(hSessionPtr->sessionId, channelId, CMD_KERNEL_CHANNEL_CLOSE, payload, 1);
Send(hSession->sessionId, channelId, CMD_KERNEL_CHANNEL_CLOSE, payload, 1);
}
ret = true;
break;
}
default:
ret = DispatchTaskData(hSessionPtr, channelId, command, payload, payloadSize);
ret = DispatchTaskData(hSession, channelId, command, payload, payloadSize);
break;
}
return ret;
}
bool HdcDaemon::RemoveInstanceTask(const uint8_t op, HTaskInfoPtr hTask)
bool HdcDaemon::RemoveInstanceTask(const uint8_t op, HTaskInfo hTask)
{
bool ret = true;
switch (hTask->taskType) {
@ -360,14 +360,14 @@ void HdcDaemon::JdwpNewFileDescriptor(const uint8_t *buf, const int bytesIO)
((HdcJdwp *)clsJdwp)->SendJdwpNewFD(pid, fd);
}
void HdcDaemon::NotifyInstanceSessionFree(HSessionPtr hSessionPtr, bool freeOrClear)
void HdcDaemon::NotifyInstanceSessionFree(HSession hSession, bool freeOrClear)
{
if (!freeOrClear) {
return; // ignore step 1
}
if (clsUSBServ != nullptr) {
auto clsUsbModule = reinterpret_cast<HdcDaemonUSB *>(clsUSBServ);
clsUsbModule->OnSessionFreeFinally(hSessionPtr);
clsUsbModule->OnSessionFreeFinally(hSession);
}
}
} // namespace Hdc

View File

@ -26,7 +26,7 @@ public:
#else
void InitMod(bool bEnableTCP, bool bEnableUSB);
#endif
bool FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command, uint8_t *payload,
bool FetchCommand(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
const int payloadSize);
bool ServerCommand(const uint32_t sessionId, const uint32_t channelId, const uint16_t command, uint8_t *bufPtr,
const int size);
@ -38,19 +38,19 @@ public:
void *clsJdwp;
private:
bool RemoveInstanceTask(const uint8_t op, HTaskInfoPtr hTask);
bool RedirectToTask(HTaskInfoPtr hTaskInfo, HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command,
bool RemoveInstanceTask(const uint8_t op, HTaskInfo hTask);
bool RedirectToTask(HTaskInfo hTaskInfo, HSession hSession, const uint32_t channelId, const uint16_t command,
uint8_t *payload, const int payloadSize);
void JdwpNewFileDescriptor(const uint8_t *buf, const int bytesIO);
bool HandDaemonAuth(HSessionPtr hSessionPtr, const uint32_t channelId, SessionHandShake &handshake);
bool HandDaemonAuth(HSession hSession, const uint32_t channelId, SessionHandShake &handshake);
void ClearInstanceResource();
bool DaemonSessionHandshake(HSessionPtr hSessionPtr, const uint32_t channelId, uint8_t *payload, int payloadSize);
bool DaemonSessionHandshake(HSession hSession, const uint32_t channelId, uint8_t *payload, int payloadSize);
void TryStopInstance();
// deprecated, remove later
#ifdef HDC_SUPPORT_FLASHD
// null
#else
void NotifyInstanceSessionFree(HSessionPtr hSessionPtr, bool freeOrClear);
void NotifyInstanceSessionFree(HSession hSession, bool freeOrClear);
#endif
bool enableSecure;

View File

@ -15,7 +15,7 @@
#include "daemon_app.h"
namespace Hdc {
HdcDaemonApp::HdcDaemonApp(HTaskInfoPtr hTaskInfo)
HdcDaemonApp::HdcDaemonApp(HTaskInfo hTaskInfo)
: HdcTransferBase(hTaskInfo)
{
commandBegin = CMD_APP_BEGIN;

View File

@ -19,7 +19,7 @@
namespace Hdc {
class HdcDaemonApp : public HdcTransferBase {
public:
HdcDaemonApp(HTaskInfoPtr hTaskInfo);
HdcDaemonApp(HTaskInfo hTaskInfo);
virtual ~HdcDaemonApp();
bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize);
bool ReadyForRelease();

View File

@ -15,7 +15,7 @@
#include "daemon_forward.h"
namespace Hdc {
HdcDaemonForward::HdcDaemonForward(HTaskInfoPtr hTaskInfo)
HdcDaemonForward::HdcDaemonForward(HTaskInfo hTaskInfo)
: HdcForwardBase(hTaskInfo)
{
}

View File

@ -19,7 +19,7 @@
namespace Hdc {
class HdcDaemonForward : public HdcForwardBase {
public:
HdcDaemonForward(HTaskInfoPtr hTaskInfo);
HdcDaemonForward(HTaskInfo hTaskInfo);
virtual ~HdcDaemonForward();
private:

View File

@ -66,26 +66,26 @@ void HdcDaemonTCP::AcceptClient(uv_stream_t *server, int status)
HdcSessionBase *daemon = reinterpret_cast<HdcSessionBase *>(thisClass->clsMainBase);
const uint16_t maxWaitTime = UV_DEFAULT_INTERVAL;
auto ctrl = daemon->BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
HSessionPtr hSessionPtr = ptrConnect->MallocSession(false, CONN_TCP, thisClass);
if (!hSessionPtr) {
HSession hSession = ptrConnect->MallocSession(false, CONN_TCP, thisClass);
if (!hSession) {
return;
}
if (uv_accept(server, (uv_stream_t *)&hSessionPtr->hWorkTCP) < 0) {
if (uv_accept(server, (uv_stream_t *)&hSession->hWorkTCP) < 0) {
goto Finish;
}
if ((hSessionPtr->fdChildWorkTCP = Base::DuplicateUvSocket(&hSessionPtr->hWorkTCP)) < 0) {
if ((hSession->fdChildWorkTCP = Base::DuplicateUvSocket(&hSession->hWorkTCP)) < 0) {
goto Finish;
};
Base::TryCloseHandle((uv_handle_t *)&hSessionPtr->hWorkTCP);
Base::StartWorkThread(ptrLoop, ptrConnect->SessionWorkThread, Base::FinishWorkThread, hSessionPtr);
Base::TryCloseHandle((uv_handle_t *)&hSession->hWorkTCP);
Base::StartWorkThread(ptrLoop, ptrConnect->SessionWorkThread, Base::FinishWorkThread, hSession);
// wait for thread up
while (hSessionPtr->childLoop.active_handles == 0) {
while (hSession->childLoop.active_handles == 0) {
usleep(maxWaitTime);
}
Base::SendToStream((uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
Base::SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
return;
Finish:
ptrConnect->FreeSession(hSessionPtr->sessionId);
ptrConnect->FreeSession(hSession->sessionId);
}
void HdcDaemonTCP::RecvUDPEntry(const sockaddr *addrSrc, uv_udp_t *handle, const uv_buf_t *rcvbuf)

View File

@ -166,28 +166,28 @@ void HdcDaemonUART::ResetOldSession(uint32_t sessionId)
if (sessionId == 0) {
sessionId = currentSessionId;
}
HSessionPtr hSessionPtr = daemon.AdminSession(OP_QUERY, sessionId, nullptr);
if (hSessionPtr == nullptr) {
HSession hSession = daemon.AdminSession(OP_QUERY, sessionId, nullptr);
if (hSession == nullptr) {
return;
}
if (hSessionPtr->hUART != nullptr) {
hSessionPtr->hUART->resetIO = true;
if (hSession->hUART != nullptr) {
hSession->hUART->resetIO = true;
}
// The Host side is restarted, but the USB cable is still connected
WRITE_LOG(LOG_WARN, "Hostside softreset to restart daemon, old sessionId:%u", sessionId);
OnTransferError(hSessionPtr);
OnTransferError(hSession);
}
HSessionPtr HdcDaemonUART::GetSession(const uint32_t sessionId, bool create = false)
HSession HdcDaemonUART::GetSession(const uint32_t sessionId, bool create = false)
{
HSessionPtr hSessionPtr = daemon.AdminSession(OP_QUERY, sessionId, nullptr);
if (hSessionPtr == nullptr and create) {
hSessionPtr = PrepareNewSession(sessionId);
HSession hSession = daemon.AdminSession(OP_QUERY, sessionId, nullptr);
if (hSession == nullptr and create) {
hSession = PrepareNewSession(sessionId);
}
return hSessionPtr;
return hSession;
}
void HdcDaemonUART::OnTransferError(const HSessionPtr session)
void HdcDaemonUART::OnTransferError(const HSession session)
{
// review maybe we can do something more ?
if (session != nullptr) {
@ -202,11 +202,11 @@ void HdcDaemonUART::OnNewHandshakeOK(const uint32_t sessionId)
currentSessionId = sessionId;
}
HSessionPtr HdcDaemonUART::PrepareNewSession(uint32_t sessionId)
HSession HdcDaemonUART::PrepareNewSession(uint32_t sessionId)
{
WRITE_LOG(LOG_FATAL, "%s sessionId:%u", __FUNCTION__, sessionId);
HSessionPtr hSessionPtr = daemon.MallocSession(false, CONN_SERIAL, this, sessionId);
if (!hSessionPtr) {
HSession hSession = daemon.MallocSession(false, CONN_SERIAL, this, sessionId);
if (!hSession) {
WRITE_LOG(LOG_FATAL, "new session malloc failed for sessionId:%u", sessionId);
return nullptr;
}
@ -217,24 +217,24 @@ HSessionPtr HdcDaemonUART::PrepareNewSession(uint32_t sessionId)
daemon.PushAsyncMessage(currentSessionId, ASYNC_FREE_SESSION, nullptr, 0);
}
externInterface.StartWorkThread(&daemon.loopMain, daemon.SessionWorkThread,
Base::FinishWorkThread, hSessionPtr);
Base::FinishWorkThread, hSession);
auto funcNewSessionUp = [](uv_timer_t *handle) -> void {
HSessionPtr hSessionPtr = reinterpret_cast<HSessionPtr>(handle->data);
HdcDaemon &daemonSession = *reinterpret_cast<HdcDaemon *>(hSessionPtr->classInstance);
if (hSessionPtr->childLoop.active_handles == 0) {
HSession hSession = reinterpret_cast<HSession>(handle->data);
HdcDaemon &daemonSession = *reinterpret_cast<HdcDaemon *>(hSession->classInstance);
if (hSession->childLoop.active_handles == 0) {
WRITE_LOG(LOG_DEBUG, "No active_handles.");
return;
}
if (!hSessionPtr->isDead) {
if (!hSession->isDead) {
auto ctrl = daemonSession.BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
Base::SendToStream((uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN], ctrl.data(),
Base::SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrl.data(),
ctrl.size());
WRITE_LOG(LOG_DEBUG, "Main thread uartio mirgate finish");
}
Base::TryCloseHandle(reinterpret_cast<uv_handle_t *>(handle), Base::CloseTimerCallback);
};
externInterface.TimerUvTask(&daemon.loopMain, hSessionPtr, funcNewSessionUp);
return hSessionPtr;
externInterface.TimerUvTask(&daemon.loopMain, hSession, funcNewSessionUp);
return hSession;
}
// review Merge this with Host side
@ -314,18 +314,18 @@ int HdcDaemonUART::LoopUARTWrite()
return -1;
}
bool HdcDaemonUART::IsSendReady(HSessionPtr hSessionPtr)
bool HdcDaemonUART::IsSendReady(HSession hSession)
{
if (isAlive and !hSessionPtr->isDead and uartHandle >= 0 and !hSessionPtr->hUART->resetIO) {
if (isAlive and !hSession->isDead and uartHandle >= 0 and !hSession->hUART->resetIO) {
return true;
} else {
if (!isAlive) {
WRITE_LOG(LOG_WARN, "!isAlive");
} else if (hSessionPtr->isDead) {
} else if (hSession->isDead) {
WRITE_LOG(LOG_WARN, "session isDead");
} else if (uartHandle < 0) {
WRITE_LOG(LOG_WARN, "uartHandle is not valid");
} else if (hSessionPtr->hUART->resetIO) {
} else if (hSession->hUART->resetIO) {
WRITE_LOG(LOG_WARN, "session have resetIO");
}
return false;

View File

@ -29,8 +29,8 @@ public:
void OnNewHandshakeOK(const uint32_t sessionId);
void Stop();
protected:
virtual HSessionPtr GetSession(const uint32_t sessionId, bool create) override;
virtual void OnTransferError(const HSessionPtr session) override;
virtual HSession GetSession(const uint32_t sessionId, bool create) override;
virtual void OnTransferError(const HSession session) override;
private:
static inline void UvWatchTimer(uv_timer_t *handle)
@ -49,9 +49,9 @@ private:
virtual int OpenUartDevice();
virtual int LoopUARTRead();
virtual int LoopUARTWrite();
virtual bool IsSendReady(HSessionPtr hSessionPtr);
virtual bool IsSendReady(HSession hSession);
virtual int PrepareBufForRead();
virtual HSessionPtr PrepareNewSession(uint32_t sessionId);
virtual HSession PrepareNewSession(uint32_t sessionId);
virtual void DeamonReadThread();
virtual void DeamonWriteThread();
std::vector<uint8_t> dataReadBuf; // from uart dev

View File

@ -16,7 +16,7 @@
#include <sys/mount.h>
namespace Hdc {
HdcDaemonUnity::HdcDaemonUnity(HTaskInfoPtr hTaskInfo)
HdcDaemonUnity::HdcDaemonUnity(HTaskInfo hTaskInfo)
: HdcTaskBase(hTaskInfo)
{
currentDataCommand = CMD_KERNEL_ECHO_RAW; // Default output to shelldata

View File

@ -19,7 +19,7 @@
namespace Hdc {
class HdcDaemonUnity : public HdcTaskBase {
public:
HdcDaemonUnity(HTaskInfoPtr hTaskInfo);
HdcDaemonUnity(HTaskInfo hTaskInfo);
virtual ~HdcDaemonUnity();
bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize);
void StopTask();

View File

@ -139,7 +139,7 @@ void HdcDaemonUSB::FillUsbV2Head(usb_functionfs_desc_v2 &descUsbFfs)
}
// DAEMON end USB module USB-FFS EP port connection
int HdcDaemonUSB::ConnectEPPoint(HUSBPtr hUSB)
int HdcDaemonUSB::ConnectEPPoint(HUSB hUSB)
{
int ret = ERR_GENERIC;
struct usb_functionfs_desc_v2 descUsbFfs = {};
@ -193,7 +193,7 @@ int HdcDaemonUSB::ConnectEPPoint(HUSBPtr hUSB)
return ret;
}
void HdcDaemonUSB::CloseEndpoint(HUSBPtr hUSB, bool closeCtrlEp)
void HdcDaemonUSB::CloseEndpoint(HUSB hUSB, bool closeCtrlEp)
{
if (hUSB->bulkIn > 0) {
close(hUSB->bulkIn);
@ -217,8 +217,8 @@ void HdcDaemonUSB::ResetOldSession(uint32_t sessionId)
if (sessionId == 0) {
sessionId = currentSessionId;
}
HSessionPtr hSessionPtr = daemon->AdminSession(OP_QUERY, sessionId, nullptr);
if (hSessionPtr == nullptr) {
HSession hSession = daemon->AdminSession(OP_QUERY, sessionId, nullptr);
if (hSession == nullptr) {
return;
}
// The Host side is restarted, but the USB cable is still connected
@ -249,9 +249,9 @@ int HdcDaemonUSB::AvailablePacket(uint8_t *ioBuf, int ioBytes, uint32_t *session
}
// Work in subcreteWork thread is ready
bool HdcDaemonUSB::ReadyForWorkThread(HSessionPtr hSessionPtr)
bool HdcDaemonUSB::ReadyForWorkThread(HSession hSession)
{
HdcUSBBase::ReadyForWorkThread(hSessionPtr);
HdcUSBBase::ReadyForWorkThread(hSession);
return true;
};
@ -286,13 +286,13 @@ int HdcDaemonUSB::CloseBulkEp(bool bulkInOut, int bulkFd, uv_loop_t *loop)
return 0;
}
int HdcDaemonUSB::SendUSBIOSync(HSessionPtr hSessionPtr, HUSBPtr hMainUSB, const uint8_t *data, const int length)
int HdcDaemonUSB::SendUSBIOSync(HSession hSession, HUSB hMainUSB, const uint8_t *data, const int length)
{
int bulkIn = hMainUSB->bulkIn;
int childRet = 0;
int ret = ERR_IO_FAIL;
int offset = 0;
while (modRunning && isAlive && !hSessionPtr->isDead) {
while (modRunning && isAlive && !hSession->isDead) {
childRet = write(bulkIn, (uint8_t *)data + offset, length - offset);
if (childRet <= 0) {
int err = errno;
@ -314,20 +314,20 @@ int HdcDaemonUSB::SendUSBIOSync(HSessionPtr hSessionPtr, HUSBPtr hMainUSB, const
ret = length;
} else {
WRITE_LOG(LOG_FATAL, "BulkinWrite write failed, nsize:%d really:%d modRunning:%d isAlive:%d SessionDead:%d",
length, offset, modRunning, isAlive, hSessionPtr->isDead);
length, offset, modRunning, isAlive, hSession->isDead);
}
return ret;
}
int HdcDaemonUSB::SendUSBRaw(HSessionPtr hSessionPtr, uint8_t *data, const int length)
int HdcDaemonUSB::SendUSBRaw(HSession hSession, uint8_t *data, const int length)
{
HdcDaemon *daemon = (HdcDaemon *)hSessionPtr->classInstance;
HdcDaemon *daemon = (HdcDaemon *)hSession->classInstance;
std::unique_lock<std::mutex> lock(mutexUsbFfs);
++hSessionPtr->ref;
int ret = SendUSBIOSync(hSessionPtr, &usbHandle, data, length);
--hSessionPtr->ref;
++hSession->ref;
int ret = SendUSBIOSync(hSession, &usbHandle, data, length);
--hSession->ref;
if (ret < 0) {
daemon->FreeSession(hSessionPtr->sessionId);
daemon->FreeSession(hSession->sessionId);
WRITE_LOG(LOG_DEBUG, "SendUSBRaw try to freesession");
}
return ret;
@ -340,25 +340,25 @@ void HdcDaemonUSB::OnNewHandshakeOK(const uint32_t sessionId)
}
// MainThreadCall, when seession was freeed
void HdcDaemonUSB::OnSessionFreeFinally(const HSessionPtr hSessionPtr)
void HdcDaemonUSB::OnSessionFreeFinally(const HSession hSession)
{
if (currentSessionId == hSessionPtr->sessionId) {
if (currentSessionId == hSession->sessionId) {
isAlive = false;
// uv_cancel ctxRecv.req == UV_EBUSY, not effect immediately. It must be close by logic
}
}
HSessionPtr HdcDaemonUSB::PrepareNewSession(uint32_t sessionId, uint8_t *pRecvBuf, int recvBytesIO)
HSession HdcDaemonUSB::PrepareNewSession(uint32_t sessionId, uint8_t *pRecvBuf, int recvBytesIO)
{
HdcDaemon *daemon = reinterpret_cast<HdcDaemon *>(clsMainBase);
HSessionPtr hChildSession = daemon->MallocSession(false, CONN_USB, this, sessionId);
HSession hChildSession = daemon->MallocSession(false, CONN_USB, this, sessionId);
if (!hChildSession) {
return nullptr;
}
currentSessionId = sessionId;
Base::StartWorkThread(&daemon->loopMain, daemon->SessionWorkThread, Base::FinishWorkThread, hChildSession);
auto funcNewSessionUp = [](uv_timer_t *handle) -> void {
HSessionPtr hChildSession = reinterpret_cast<HSessionPtr>(handle->data);
HSession hChildSession = reinterpret_cast<HSession>(handle->data);
HdcDaemon *daemon = reinterpret_cast<HdcDaemon *>(hChildSession->classInstance);
if (hChildSession->childLoop.active_handles == 0) {
return;
@ -381,7 +381,7 @@ int HdcDaemonUSB::UsbToHdcProtocol(uv_stream_t *stream, uint8_t *appendData, int
int HdcDaemonUSB::DispatchToWorkThread(uint32_t sessionId, uint8_t *readBuf, int readBytes)
{
HSessionPtr hChildSession = nullptr;
HSession hChildSession = nullptr;
HdcDaemon *daemon = reinterpret_cast<HdcDaemon *>(clsMainBase);
int childRet = RET_SUCCESS;
if (sessionId == 0) {
@ -430,7 +430,7 @@ bool HdcDaemonUSB::JumpAntiquePacket(const uint8_t &buf, ssize_t bytes) const
void HdcDaemonUSB::OnUSBRead(uv_fs_t *req)
{ // Only read at the main thread
auto ctxIo = reinterpret_cast<CtxUvFileCommonIo *>(req->data);
auto hUSB = reinterpret_cast<HUSBPtr>(ctxIo->data);
auto hUSB = reinterpret_cast<HUSB>(ctxIo->data);
auto thisClass = reinterpret_cast<HdcDaemonUSB *>(ctxIo->thisClass);
uint8_t *bufPtr = ctxIo->buf;
ssize_t bytesIOBytes = req->result;
@ -498,7 +498,7 @@ void HdcDaemonUSB::OnUSBRead(uv_fs_t *req)
}
}
int HdcDaemonUSB::LoopUSBRead(HUSBPtr hUSB, int readMaxWanted)
int HdcDaemonUSB::LoopUSBRead(HUSB hUSB, int readMaxWanted)
{
int ret = ERR_GENERIC;
HdcDaemon *daemon = reinterpret_cast<HdcDaemon *>(clsMainBase);
@ -522,7 +522,7 @@ int HdcDaemonUSB::LoopUSBRead(HUSBPtr hUSB, int readMaxWanted)
void HdcDaemonUSB::WatchEPTimer(uv_timer_t *handle)
{
HdcDaemonUSB *thisClass = (HdcDaemonUSB *)handle->data;
HUSBPtr hUSB = &thisClass->usbHandle;
HUSB hUSB = &thisClass->usbHandle;
HdcDaemon *daemon = reinterpret_cast<HdcDaemon *>(thisClass->clsMainBase);
if (thisClass->isAlive || thisClass->ctxRecv.atPollQueue) {
return;

View File

@ -23,9 +23,9 @@ public:
virtual ~HdcDaemonUSB();
int Initial();
void Stop();
int SendUSBRaw(HSessionPtr hSessionPtr, uint8_t *data, const int length);
int SendUSBRaw(HSession hSession, uint8_t *data, const int length);
void OnNewHandshakeOK(const uint32_t sessionId);
void OnSessionFreeFinally(const HSessionPtr hSessionPtr);
void OnSessionFreeFinally(const HSession hSession);
private:
struct CtxUvFileCommonIo {
@ -39,16 +39,16 @@ private:
};
static void OnUSBRead(uv_fs_t *req);
static void WatchEPTimer(uv_timer_t *handle);
int ConnectEPPoint(HUSBPtr hUSB);
int ConnectEPPoint(HUSB hUSB);
int DispatchToWorkThread(uint32_t sessionId, uint8_t *readBuf, int readBytes);
int AvailablePacket(uint8_t *ioBuf, int ioBytes, uint32_t *sessionId);
void CloseEndpoint(HUSBPtr hUSB, bool closeCtrlEp = false);
void CloseEndpoint(HUSB hUSB, bool closeCtrlEp = false);
string GetDevPath(const std::string &path);
bool ReadyForWorkThread(HSessionPtr hSessionPtr);
int LoopUSBRead(HUSBPtr hUSB, int readMaxWanted);
HSessionPtr PrepareNewSession(uint32_t sessionId, uint8_t *pRecvBuf, int recvBytesIO);
bool ReadyForWorkThread(HSession hSession);
int LoopUSBRead(HUSB hUSB, int readMaxWanted);
HSession PrepareNewSession(uint32_t sessionId, uint8_t *pRecvBuf, int recvBytesIO);
bool JumpAntiquePacket(const uint8_t &buf, ssize_t bytes) const;
int SendUSBIOSync(HSessionPtr hSessionPtr, HUSBPtr hMainUSB, const uint8_t *data, const int length);
int SendUSBIOSync(HSession hSession, HUSB hMainUSB, const uint8_t *data, const int length);
int CloseBulkEp(bool bulkInOut, int bulkFd, uv_loop_t *loop);
void ResetOldSession(uint32_t sessionId);
int GetMaxPacketSize(int fdFfs);

View File

@ -377,7 +377,7 @@ size_t HdcJdwp::JdwpProcessListMsg(char *buffer, size_t bufferlen)
return len + headerLen;
}
void HdcJdwp::SendProcessList(HTaskInfoPtr t, string data)
void HdcJdwp::SendProcessList(HTaskInfo t, string data)
{
if (t == nullptr || data.size() == 0) {
WRITE_LOG(LOG_WARN, " SendProcessList, Nothing needs to be sent.");
@ -388,7 +388,7 @@ void HdcJdwp::SendProcessList(HTaskInfoPtr t, string data)
sessionBase->LogMsg(t->sessionId, t->channelId, MSG_OK, data.c_str());
}
void HdcJdwp::ProcessListUpdated(HTaskInfoPtr task)
void HdcJdwp::ProcessListUpdated(HTaskInfo task)
{
if (jdwpTrackers.size() <= 0) {
WRITE_LOG(LOG_DEBUG, "None jdwpTrackers.");
@ -425,7 +425,7 @@ void HdcJdwp::ProcessListUpdated(HTaskInfoPtr task)
}
}
bool HdcJdwp::CreateJdwpTracker(HTaskInfoPtr taskInfo)
bool HdcJdwp::CreateJdwpTracker(HTaskInfo taskInfo)
{
if (taskInfo == nullptr) {
return false;
@ -440,7 +440,7 @@ bool HdcJdwp::CreateJdwpTracker(HTaskInfoPtr taskInfo)
return true;
}
void HdcJdwp::RemoveJdwpTracker(HTaskInfoPtr taskInfo)
void HdcJdwp::RemoveJdwpTracker(HTaskInfo taskInfo)
{
if (taskInfo == nullptr) {
return;

View File

@ -24,8 +24,8 @@ public:
virtual ~HdcJdwp();
int Initial();
void Stop();
bool CreateJdwpTracker(HTaskInfoPtr taskInfo);
void RemoveJdwpTracker(HTaskInfoPtr taskInfo);
bool CreateJdwpTracker(HTaskInfo taskInfo);
void RemoveJdwpTracker(HTaskInfo taskInfo);
bool ReadyForRelease();
string GetProcessList();
bool SendJdwpNewFD(uint32_t targetPID, int fd);
@ -85,8 +85,8 @@ private:
void FreeContext(HCtxJdwp ctx);
void *AdminContext(const uint8_t op, const uint32_t pid, HCtxJdwp ctxJdwp);
int CreateFdEventPoll();
void ProcessListUpdated(HTaskInfoPtr task = nullptr);
void SendProcessList(HTaskInfoPtr t, string data);
void ProcessListUpdated(HTaskInfo task = nullptr);
void SendProcessList(HTaskInfo t, string data);
void DrainAwakenPollThread() const;
void WakePollThread();
uv_loop_t *loop;
@ -97,7 +97,7 @@ private:
uv_rwlock_t lockMapContext;
uv_rwlock_t lockJdwpTrack;
std::unordered_map<int, PollNode> pollNodeMap; // fd, PollNode
std::vector<HTaskInfoPtr> jdwpTrackers;
std::vector<HTaskInfo> jdwpTrackers;
bool stop;
};
} // namespace Hdc

View File

@ -18,7 +18,7 @@
namespace Hdc {
std::mutex HdcShell::mutexPty;
HdcShell::HdcShell(HTaskInfoPtr hTaskInfo)
HdcShell::HdcShell(HTaskInfo hTaskInfo)
: HdcTaskBase(hTaskInfo)
{
childShell = nullptr;

View File

@ -20,7 +20,7 @@
namespace Hdc {
class HdcShell : public HdcTaskBase {
public:
HdcShell(HTaskInfoPtr hTaskInfo);
HdcShell(HTaskInfo hTaskInfo);
virtual ~HdcShell();
bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize);
void StopTask();

View File

@ -31,7 +31,7 @@ HdcClient::~HdcClient()
Base::TryCloseLoop(loopMain, "ExecuteCommand finish");
}
void HdcClient::NotifyInstanceChannelFree(HChannelPtr hChannel)
void HdcClient::NotifyInstanceChannelFree(HChannel hChannel)
{
if (bShellInteractive) {
WRITE_LOG(LOG_DEBUG, "Restore tty");
@ -220,7 +220,7 @@ void HdcClient::AllocStdbuf(uv_handle_t *handle, size_t sizeWanted, uv_buf_t *bu
if (sizeWanted <= 0) {
return;
}
HChannelPtr context = (HChannelPtr)handle->data;
HChannel context = (HChannel)handle->data;
int availSize = strlen(context->bufStd);
buf->base = (char *)context->bufStd + availSize;
buf->len = sizeof(context->bufStd) - availSize - 2; // reserve 2bytes
@ -228,7 +228,7 @@ void HdcClient::AllocStdbuf(uv_handle_t *handle, size_t sizeWanted, uv_buf_t *bu
void HdcClient::ReadStd(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
{
HChannelPtr hChannel = (HChannelPtr)stream->data;
HChannel hChannel = (HChannel)stream->data;
HdcClient *thisClass = (HdcClient *)hChannel->clsChannel;
char *command = hChannel->bufStd;
if (nread <= 0) {
@ -261,7 +261,7 @@ void HdcClient::ModifyTty(bool setOrRestore, uv_tty_t *tty)
}
}
void HdcClient::BindLocalStd(HChannelPtr hChannel)
void HdcClient::BindLocalStd(HChannel hChannel)
{
if (command == CMDSTR_SHELL) {
bShellInteractive = true;
@ -292,7 +292,7 @@ void HdcClient::Connect(uv_connect_t *connection, int status)
{
HdcClient *thisClass = (HdcClient *)connection->data;
delete connection;
HChannelPtr hChannel = (HChannelPtr)thisClass->channel;
HChannel hChannel = (HChannel)thisClass->channel;
if (status < 0 || uv_is_closing((const uv_handle_t *)&hChannel->hWorkTCP)) {
WRITE_LOG(LOG_FATAL, "connect failed");
thisClass->FreeChannel(hChannel->channelId);
@ -303,7 +303,7 @@ void HdcClient::Connect(uv_connect_t *connection, int status)
uv_read_start((uv_stream_t *)&hChannel->hWorkTCP, AllocCallback, ReadStream);
}
int HdcClient::PreHandshake(HChannelPtr hChannel, const uint8_t *buf)
int HdcClient::PreHandshake(HChannel hChannel, const uint8_t *buf)
{
ChannelHandShake *hShake = (ChannelHandShake *)buf;
if (strncmp(hShake->banner, HANDSHAKE_MESSAGE.c_str(), HANDSHAKE_MESSAGE.size())) {
@ -335,7 +335,7 @@ int HdcClient::PreHandshake(HChannelPtr hChannel, const uint8_t *buf)
}
// read serverForClient(server)TCP data
int HdcClient::ReadChannel(HChannelPtr hChannel, uint8_t *buf, const int bytesIO)
int HdcClient::ReadChannel(HChannel hChannel, uint8_t *buf, const int bytesIO)
{
if (!hChannel->handshakeOK) {
return PreHandshake(hChannel, buf);

View File

@ -33,15 +33,15 @@ private:
static void ReadStd(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf);
static void CommandWorker(uv_timer_t *handle);
int ConnectServerForClient(const char *ip, uint16_t port);
int ReadChannel(HChannelPtr hChannel, uint8_t *buf, const int bytesIO);
int PreHandshake(HChannelPtr hChannel, const uint8_t *buf);
int ReadChannel(HChannel hChannel, uint8_t *buf, const int bytesIO);
int PreHandshake(HChannel hChannel, const uint8_t *buf);
string AutoConnectKey(string &doCommand, const string &preConnectKey) const;
uint32_t GetLastPID();
bool StartKillServer(const char *cmd, bool startOrKill);
void BindLocalStd();
void BindLocalStd(HChannelPtr hChannel);
void BindLocalStd(HChannel hChannel);
void ModifyTty(bool setOrRestore, uv_tty_t *tty);
void NotifyInstanceChannelFree(HChannelPtr hChannel);
void NotifyInstanceChannelFree(HChannel hChannel);
#ifndef _WIN32
termios terminalState;
@ -52,7 +52,7 @@ private:
bool bShellInteractive = false;
uv_timer_t waitTimeDoCmd;
uv_check_t ctrlServerWork;
HChannelPtr channel;
HChannel channel;
};
} // namespace Hdc
#endif

View File

@ -15,7 +15,7 @@
#include "host_app.h"
namespace Hdc {
HdcHostApp::HdcHostApp(HTaskInfoPtr hTaskInfo)
HdcHostApp::HdcHostApp(HTaskInfo hTaskInfo)
: HdcTransferBase(hTaskInfo)
{
commandBegin = CMD_APP_BEGIN;

View File

@ -19,7 +19,7 @@
namespace Hdc {
class HdcHostApp : public HdcTransferBase {
public:
HdcHostApp(HTaskInfoPtr hTaskInfo);
HdcHostApp(HTaskInfo hTaskInfo);
virtual ~HdcHostApp();
bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize);

View File

@ -15,7 +15,7 @@
#include "host_forward.h"
namespace Hdc {
HdcHostForward::HdcHostForward(HTaskInfoPtr hTaskInfo)
HdcHostForward::HdcHostForward(HTaskInfo hTaskInfo)
: HdcForwardBase(hTaskInfo)
{
}

View File

@ -19,7 +19,7 @@
namespace Hdc {
class HdcHostForward : public HdcForwardBase {
public:
HdcHostForward(HTaskInfoPtr hTaskInfo);
HdcHostForward(HTaskInfo hTaskInfo);
virtual ~HdcHostForward();
private:

View File

@ -95,32 +95,32 @@ void HdcHostTCP::BroadcatFindDaemon(const char *broadcastLanIP)
void HdcHostTCP::Connect(uv_connect_t *connection, int status)
{
HSessionPtr hSessionPtr = (HSessionPtr)connection->data;
HSession hSession = (HSession)connection->data;
delete connection;
HdcSessionBase *ptrConnect = (HdcSessionBase *)hSessionPtr->classInstance;
HdcSessionBase *ptrConnect = (HdcSessionBase *)hSession->classInstance;
auto ctrl = ptrConnect->BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
if (status < 0) {
goto Finish;
}
if ((hSessionPtr->fdChildWorkTCP = Base::DuplicateUvSocket(&hSessionPtr->hWorkTCP)) < 0) {
if ((hSession->fdChildWorkTCP = Base::DuplicateUvSocket(&hSession->hWorkTCP)) < 0) {
goto Finish;
}
uv_read_stop((uv_stream_t *)&hSessionPtr->hWorkTCP);
Base::SetTcpOptions((uv_tcp_t *)&hSessionPtr->hWorkTCP);
uv_read_stop((uv_stream_t *)&hSession->hWorkTCP);
Base::SetTcpOptions((uv_tcp_t *)&hSession->hWorkTCP);
WRITE_LOG(LOG_DEBUG, "HdcHostTCP::Connect");
Base::StartWorkThread(&ptrConnect->loopMain, ptrConnect->SessionWorkThread, Base::FinishWorkThread, hSessionPtr);
Base::StartWorkThread(&ptrConnect->loopMain, ptrConnect->SessionWorkThread, Base::FinishWorkThread, hSession);
// wait for thread up
while (hSessionPtr->childLoop.active_handles == 0) {
while (hSession->childLoop.active_handles == 0) {
uv_sleep(MINOR_TIMEOUT);
}
Base::SendToStream((uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
Base::SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
return;
Finish:
WRITE_LOG(LOG_FATAL, "Connect failed");
ptrConnect->FreeSession(hSessionPtr->sessionId);
ptrConnect->FreeSession(hSession->sessionId);
}
HSessionPtr HdcHostTCP::ConnectDaemon(const string &connectKey)
HSession HdcHostTCP::ConnectDaemon(const string &connectKey)
{
char ip[BUF_SIZE_TINY] = "";
uint16_t port = 0;
@ -129,23 +129,23 @@ HSessionPtr HdcHostTCP::ConnectDaemon(const string &connectKey)
}
HdcSessionBase *ptrConnect = (HdcSessionBase *)clsMainBase;
HSessionPtr hSessionPtr = ptrConnect->MallocSession(true, CONN_TCP, this);
if (!hSessionPtr) {
HSession hSession = ptrConnect->MallocSession(true, CONN_TCP, this);
if (!hSession) {
return nullptr;
}
hSessionPtr->connectKey = connectKey;
hSession->connectKey = connectKey;
struct sockaddr_in6 dest;
uv_ip6_addr(ip, port, &dest);
uv_connect_t *conn = new(std::nothrow) uv_connect_t();
if (conn == nullptr) {
WRITE_LOG(LOG_FATAL, "ConnectDaemon new conn failed");
delete hSessionPtr;
hSessionPtr = nullptr;
delete hSession;
hSession = nullptr;
return nullptr;
}
conn->data = hSessionPtr;
uv_tcp_connect(conn, (uv_tcp_t *)&hSessionPtr->hWorkTCP, (const struct sockaddr *)&dest, Connect);
return hSessionPtr;
conn->data = hSession;
uv_tcp_connect(conn, (uv_tcp_t *)&hSession->hWorkTCP, (const struct sockaddr *)&dest, Connect);
return hSession;
}
void HdcHostTCP::FindLanDaemon()

View File

@ -22,7 +22,7 @@ public:
HdcHostTCP(const bool serverOrDaemonIn, void *ptrMainBase);
virtual ~HdcHostTCP();
void FindLanDaemon();
HSessionPtr ConnectDaemon(const string &connectKey);
HSession ConnectDaemon(const string &connectKey);
void Stop();
list<string> lstDaemonResult;

View File

@ -38,9 +38,9 @@ int HdcHostUART::Initial()
return StartupUARTWork();
}
bool HdcHostUART::NeedStop(const HSessionPtr hSessionPtr)
bool HdcHostUART::NeedStop(const HSession hSession)
{
return (!uartOpened or (hSessionPtr->isDead and hSessionPtr->ref == 0));
return (!uartOpened or (hSession->isDead and hSession->ref == 0));
}
bool HdcHostUART::IsDeviceOpened(const HdcUART &uart)
@ -69,22 +69,22 @@ void HdcHostUART::UartWriteThread()
return;
}
void HdcHostUART::UartReadThread(HSessionPtr hSessionPtr)
void HdcHostUART::UartReadThread(HSession hSession)
{
HUARTPtr hUART = hSessionPtr->hUART;
HUART hUART = hSession->hUART;
vector<uint8_t> dataReadBuf; // each thread/session have it own data buff
// If something unexpected happens , max buffer size we allow
WRITE_LOG(LOG_DEBUG, "%s devUartHandle:%d", __FUNCTION__, hUART->devUartHandle);
size_t expectedSize = 0;
while (dataReadBuf.size() < MAX_READ_BUFFER) {
if (NeedStop(hSessionPtr)) {
if (NeedStop(hSession)) {
WRITE_LOG(LOG_FATAL, "%s stop ", __FUNCTION__);
break;
}
ssize_t bytesRead = ReadUartDev(dataReadBuf, expectedSize, *hUART);
if (bytesRead < 0) {
WRITE_LOG(LOG_INFO, "%s read got fail , free the session", __FUNCTION__);
OnTransferError(hSessionPtr);
OnTransferError(hSession);
} else if (bytesRead == 0) {
WRITE_LOG(LOG_DEBUG, "%s read %zd, clean the data try read again.", __FUNCTION__,
bytesRead);
@ -102,7 +102,7 @@ void HdcHostUART::UartReadThread(HSessionPtr hSessionPtr)
}
WRITE_LOG(LOG_DEBUG, "%s PackageProcess dataReadBuf.size():%d.", __FUNCTION__,
dataReadBuf.size());
expectedSize = PackageProcess(dataReadBuf, hSessionPtr);
expectedSize = PackageProcess(dataReadBuf, hSession);
}
WRITE_LOG(LOG_INFO, "Leave %s", __FUNCTION__);
return;
@ -233,7 +233,7 @@ std::string WstringToString(const std::wstring &wstr)
}
// review reanme for same func from linux
int HdcHostUART::WinSetSerial(HUARTPtr hUART, string serialPort, int byteSize, int eqBaudRate)
int HdcHostUART::WinSetSerial(HUART hUART, string serialPort, int byteSize, int eqBaudRate)
{
int winRet = RET_SUCCESS;
COMMTIMEOUTS timeouts;
@ -399,31 +399,31 @@ int HdcHostUART::OpenSerialPort(const std::string &connectKey)
return ret;
}
void HdcHostUART::UpdateUARTDaemonInfo(const std::string &connectKey, HSessionPtr hSessionPtr,
void HdcHostUART::UpdateUARTDaemonInfo(const std::string &connectKey, HSession hSession,
ConnStatus connStatus)
{
// add to list
HdcDaemonInformation diNew;
HDaemonInfoPtr diNewPtr = &diNew;
HDaemonInfo diNewPtr = &diNew;
diNew.connectKey = connectKey;
diNew.connType = CONN_SERIAL;
diNew.connStatus = connStatus;
diNew.hSessionPtr = hSessionPtr;
diNew.hSession = hSession;
WRITE_LOG(LOG_DEBUG, "%s uart connectKey :%s session %s change to %d", __FUNCTION__,
connectKey.c_str(),
hSessionPtr == nullptr ? "<null>" : hSessionPtr->ToDebugString().c_str(), connStatus);
hSession == nullptr ? "<null>" : hSession->ToDebugString().c_str(), connStatus);
if (connStatus == STATUS_UNKNOW) {
server.AdminDaemonMap(OP_REMOVE, connectKey, diNewPtr);
if (hSessionPtr != nullptr and hSessionPtr->hUART != nullptr) {
connectedPorts.erase(hSessionPtr->hUART->serialPort);
if (hSession != nullptr and hSession->hUART != nullptr) {
connectedPorts.erase(hSession->hUART->serialPort);
}
} else {
if (connStatus == STATUS_CONNECTED) {
if (hSessionPtr != nullptr and hSessionPtr->hUART != nullptr) {
connectedPorts.emplace(hSessionPtr->hUART->serialPort);
if (hSession != nullptr and hSession->hUART != nullptr) {
connectedPorts.emplace(hSession->hUART->serialPort);
}
}
HDaemonInfoPtr diOldPtr = nullptr;
HDaemonInfo diOldPtr = nullptr;
server.AdminDaemonMap(OP_QUERY, connectKey, diOldPtr);
if (diOldPtr == nullptr) {
WRITE_LOG(LOG_DEBUG, "%s add new di", __FUNCTION__);
@ -434,14 +434,14 @@ void HdcHostUART::UpdateUARTDaemonInfo(const std::string &connectKey, HSessionPt
}
}
bool HdcHostUART::StartUartReadThread(HSessionPtr hSessionPtr)
bool HdcHostUART::StartUartReadThread(HSession hSession)
{
try {
HUARTPtr hUART = hSessionPtr->hUART;
hUART->readThread = std::thread(&HdcHostUART::UartReadThread, this, hSessionPtr);
HUART hUART = hSession->hUART;
hUART->readThread = std::thread(&HdcHostUART::UartReadThread, this, hSession);
} catch (...) {
server.FreeSession(hSessionPtr->sessionId);
UpdateUARTDaemonInfo(hSessionPtr->connectKey, hSessionPtr, STATUS_UNKNOW);
server.FreeSession(hSession->sessionId);
UpdateUARTDaemonInfo(hSession->connectKey, hSession, STATUS_UNKNOW);
WRITE_LOG(LOG_WARN, "%s failed err", __FUNCTION__);
return false;
}
@ -465,30 +465,30 @@ bool HdcHostUART::StartUartSendThread()
}
// Determines that daemonInfo must have the device
HSessionPtr HdcHostUART::ConnectDaemonByUart(const HSessionPtr hSessionPtr, const HDaemonInfoPtr)
HSession HdcHostUART::ConnectDaemonByUart(const HSession hSession, const HDaemonInfo)
{
if (!uartOpened) {
WRITE_LOG(LOG_DEBUG, "%s non uart opened.", __FUNCTION__);
return nullptr;
}
HUARTPtr hUART = hSessionPtr->hUART;
UpdateUARTDaemonInfo(hSessionPtr->connectKey, hSessionPtr, STATUS_READY);
HUART hUART = hSession->hUART;
UpdateUARTDaemonInfo(hSession->connectKey, hSession, STATUS_READY);
WRITE_LOG(LOG_DEBUG, "%s :%s", __FUNCTION__, hUART->serialPort.c_str());
if (!StartUartReadThread(hSessionPtr)) {
if (!StartUartReadThread(hSession)) {
WRITE_LOG(LOG_DEBUG, "%s StartUartReadThread fail.", __FUNCTION__);
return nullptr;
}
externInterface.StartWorkThread(&server.loopMain, server.SessionWorkThread,
Base::FinishWorkThread, hSessionPtr);
Base::FinishWorkThread, hSession);
// wait for thread up
while (hSessionPtr->childLoop.active_handles == 0) {
while (hSession->childLoop.active_handles == 0) {
uv_sleep(1);
}
auto ctrl = server.BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
externInterface.SendToStream((uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN], ctrl.data(),
externInterface.SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrl.data(),
ctrl.size());
return hSessionPtr;
return hSession;
}
RetErrCode HdcHostUART::StartupUARTWork()
@ -508,7 +508,7 @@ RetErrCode HdcHostUART::StartupUARTWork()
return RET_SUCCESS;
}
HSessionPtr HdcHostUART::ConnectDaemon(const std::string &connectKey)
HSession HdcHostUART::ConnectDaemon(const std::string &connectKey)
{
WRITE_LOG(LOG_DEBUG, "%s", __FUNCTION__);
OpenSerialPort(connectKey);
@ -532,7 +532,7 @@ void HdcHostUART::WatchUartDevPlugin()
for (const auto &port : serialPortInfo) {
WRITE_LOG(LOG_INFO, "%s found uart port :%s", __FUNCTION__, port.c_str());
// check port have session
HDaemonInfoPtr hdi = nullptr;
HDaemonInfo hdi = nullptr;
server.AdminDaemonMap(OP_QUERY, port, hdi);
if (hdi == nullptr and connectedPorts.find(port) == connectedPorts.end()) {
UpdateUARTDaemonInfo(port, nullptr, STATUS_READY);
@ -541,9 +541,9 @@ void HdcHostUART::WatchUartDevPlugin()
for (const auto &port : serialPortRemoved) {
WRITE_LOG(LOG_INFO, "%s remove uart port :%s", __FUNCTION__, port.c_str());
// check port have session
HDaemonInfoPtr hdi = nullptr;
HDaemonInfo hdi = nullptr;
server.AdminDaemonMap(OP_QUERY, port, hdi);
if (hdi != nullptr and hdi->hSessionPtr == nullptr) {
if (hdi != nullptr and hdi->hSession == nullptr) {
// we only remove the empty port
UpdateUARTDaemonInfo(port, nullptr, STATUS_UNKNOW);
}
@ -551,7 +551,7 @@ void HdcHostUART::WatchUartDevPlugin()
}
}
bool HdcHostUART::ConnectMyNeed(HUARTPtr hUART, std::string connectKey)
bool HdcHostUART::ConnectMyNeed(HUART hUART, std::string connectKey)
{
// we never use port to connect, we use connect key
if (connectKey.empty()) {
@ -562,16 +562,16 @@ bool HdcHostUART::ConnectMyNeed(HUARTPtr hUART, std::string connectKey)
}
UpdateUARTDaemonInfo(connectKey, nullptr, STATUS_READY);
HSessionPtr hSessionPtr = server.MallocSession(true, CONN_SERIAL, this);
hSessionPtr->connectKey = connectKey;
HSession hSession = server.MallocSession(true, CONN_SERIAL, this);
hSession->connectKey = connectKey;
#if defined(HOST_LINUX)
hSessionPtr->hUART->devUartHandle = hUART->devUartHandle;
hSession->hUART->devUartHandle = hUART->devUartHandle;
#elif defined(HOST_MINGW)
hSessionPtr->hUART->devUartHandle = hUART->devUartHandle;
hSession->hUART->devUartHandle = hUART->devUartHandle;
#endif
hSessionPtr->hUART->serialPort = hUART->serialPort;
WRITE_LOG(LOG_DEBUG, "%s connectkey:%s,port:%s", __FUNCTION__, hSessionPtr->connectKey.c_str(),
hSession->hUART->serialPort = hUART->serialPort;
WRITE_LOG(LOG_DEBUG, "%s connectkey:%s,port:%s", __FUNCTION__, hSession->connectKey.c_str(),
hUART->serialPort.c_str());
uv_timer_t *waitTimeDoCmd = new(std::nothrow) uv_timer_t;
if (waitTimeDoCmd == nullptr) {
@ -579,10 +579,10 @@ bool HdcHostUART::ConnectMyNeed(HUARTPtr hUART, std::string connectKey)
return false;
}
uv_timer_init(&server.loopMain, waitTimeDoCmd);
waitTimeDoCmd->data = hSessionPtr;
waitTimeDoCmd->data = hSession;
if (externInterface.UvTimerStart(waitTimeDoCmd, server.UartPreConnect, UV_TIMEOUT, UV_REPEAT) !=
RET_SUCCESS) {
WRITE_LOG(LOG_DEBUG, "%s for %s:%s fail.", __FUNCTION__, hSessionPtr->connectKey.c_str(),
WRITE_LOG(LOG_DEBUG, "%s for %s:%s fail.", __FUNCTION__, hSession->connectKey.c_str(),
hUART->serialPort.c_str());
return false;
}
@ -591,29 +591,29 @@ bool HdcHostUART::ConnectMyNeed(HUARTPtr hUART, std::string connectKey)
return true;
}
void HdcHostUART::KickoutZombie(HSessionPtr hSessionPtr)
void HdcHostUART::KickoutZombie(HSession hSession)
{
if (hSessionPtr == nullptr or hSessionPtr->hUART == nullptr or hSessionPtr->isDead) {
if (hSession == nullptr or hSession->hUART == nullptr or hSession->isDead) {
return;
}
#ifdef _WIN32
if (hSessionPtr->hUART->devUartHandle == INVALID_HANDLE_VALUE) {
if (hSession->hUART->devUartHandle == INVALID_HANDLE_VALUE) {
return;
}
#else
if (hSessionPtr->hUART->devUartHandle < 0) {
if (hSession->hUART->devUartHandle < 0) {
return;
}
#endif
WRITE_LOG(LOG_DEBUG, "%s FreeSession %s", __FUNCTION__, hSessionPtr->ToDebugString().c_str());
server.FreeSession(hSessionPtr->sessionId);
WRITE_LOG(LOG_DEBUG, "%s FreeSession %s", __FUNCTION__, hSession->ToDebugString().c_str());
server.FreeSession(hSession->sessionId);
}
HSessionPtr HdcHostUART::GetSession(const uint32_t sessionId, bool)
HSession HdcHostUART::GetSession(const uint32_t sessionId, bool)
{
return server.AdminSession(OP_QUERY, sessionId, nullptr);
}
void HdcHostUART::CloseSerialPort(const HUARTPtr hUART)
void HdcHostUART::CloseSerialPort(const HUART hUART)
{
WRITE_LOG(LOG_DEBUG, "try to close dev handle %d", __FUNCTION__, hUART->devUartHandle);
@ -630,7 +630,7 @@ void HdcHostUART::CloseSerialPort(const HUARTPtr hUART)
#endif
}
void HdcHostUART::OnTransferError(const HSessionPtr session)
void HdcHostUART::OnTransferError(const HSession session)
{
if (session != nullptr) {
WRITE_LOG(LOG_FATAL, "%s:%s", __FUNCTION__, session->ToDebugString().c_str());
@ -655,7 +655,7 @@ void HdcHostUART::OnTransferError(const HSessionPtr session)
}
// review what about merge Restartession with OnTransferError ?
void HdcHostUART::Restartession(const HSessionPtr session)
void HdcHostUART::Restartession(const HSession session)
{
HdcUARTBase::Restartession(session);
// allow timer watcher make a new session.
@ -668,15 +668,15 @@ void HdcHostUART::Restartession(const HSessionPtr session)
}
}
void HdcHostUART::StopSession(HSessionPtr hSessionPtr)
void HdcHostUART::StopSession(HSession hSession)
{
if (hSessionPtr == nullptr) {
WRITE_LOG(LOG_FATAL, "%s hSessionPtr is null", __FUNCTION__);
if (hSession == nullptr) {
WRITE_LOG(LOG_FATAL, "%s hSession is null", __FUNCTION__);
return;
}
WRITE_LOG(LOG_DEBUG, "%s hSessionPtr %s will be stop and free", __FUNCTION__,
hSessionPtr->ToDebugString().c_str());
HUARTPtr hUART = hSessionPtr->hUART;
WRITE_LOG(LOG_DEBUG, "%s hSession %s will be stop and free", __FUNCTION__,
hSession->ToDebugString().c_str());
HUART hUART = hSession->hUART;
if (hUART == nullptr) {
WRITE_LOG(LOG_FATAL, "%s hUART is null", __FUNCTION__);
} else {
@ -697,7 +697,7 @@ void HdcHostUART::StopSession(HSessionPtr hSessionPtr)
}
// call the base side
HdcUARTBase::StopSession(hSessionPtr);
HdcUARTBase::StopSession(hSession);
}
std::vector<std::string> HdcHostUART::StringSplit(std::string source, std::string split)
@ -747,7 +747,7 @@ bool HdcHostUART::GetPortFromKey(const std::string &connectKey, std::string &por
}
}
void HdcHostUART::SendUartSoftReset(HSessionPtr hSessionPtr, uint32_t sessionId)
void HdcHostUART::SendUartSoftReset(HSession hSession, uint32_t sessionId)
{
UartHead resetPackage(sessionId, PKG_OPTION_RESET);
resetPackage.dataSize = sizeof(UartHead);

View File

@ -37,18 +37,18 @@ public:
~HdcHostUART();
int Initial();
virtual void Stop();
HSessionPtr ConnectDaemonByUart(const HSessionPtr hSessionPtr,
[[maybe_unused]] const HDaemonInfoPtr = nullptr);
HSession ConnectDaemonByUart(const HSession hSession,
[[maybe_unused]] const HDaemonInfo = nullptr);
// logic layer will free the session
// all the thread maybe need exit if needed.
void StopSession(HSessionPtr hSessionPtr) override;
HSessionPtr ConnectDaemon(const std::string &connectKey);
void StopSession(HSession hSession) override;
HSession ConnectDaemon(const std::string &connectKey);
protected:
virtual void OnTransferError(const HSessionPtr session) override;
virtual HSessionPtr GetSession(const uint32_t sessionId, bool create) override;
virtual void Restartession(const HSessionPtr session) override;
virtual void OnTransferError(const HSession session) override;
virtual HSession GetSession(const uint32_t sessionId, bool create) override;
virtual void Restartession(const HSession session) override;
private:
enum UartCheckStatus {
@ -59,9 +59,9 @@ private:
};
// review maybe merge to base ?
virtual bool StartUartSendThread();
virtual bool StartUartReadThread(HSessionPtr hSessionPtr);
virtual bool StartUartReadThread(HSession hSession);
size_t SendUARTDev(HSessionPtr hSessionPtr, uint8_t *data, const size_t length);
size_t SendUARTDev(HSession hSession, uint8_t *data, const size_t length);
static inline void UvWatchUartDevPlugin(uv_timer_t *handle)
{
if (handle != nullptr) {
@ -74,11 +74,11 @@ private:
WRITE_LOG(LOG_FATAL, "%s have not got correct class parameter", __FUNCTION__);
};
virtual void WatchUartDevPlugin();
void KickoutZombie(HSessionPtr hSessionPtr);
virtual void UpdateUARTDaemonInfo(const std::string &connectKey, HSessionPtr hSessionPtr, ConnStatus connStatus);
bool ConnectMyNeed(HUARTPtr hUART, std::string connectKey = "");
void KickoutZombie(HSession hSession);
virtual void UpdateUARTDaemonInfo(const std::string &connectKey, HSession hSession, ConnStatus connStatus);
bool ConnectMyNeed(HUART hUART, std::string connectKey = "");
virtual int OpenSerialPort(const std::string &portName = "");
virtual void CloseSerialPort(const HUARTPtr hUART);
virtual void CloseSerialPort(const HUART hUART);
virtual RetErrCode StartupUARTWork();
// we use this function check if the uart read nothing in a timeout
@ -86,14 +86,14 @@ private:
// More importantly, the bootloader will output data. We use this to detect whether it is the
// bootloader stage.
virtual bool WaitUartIdle(HdcUART &uart, bool retry = true);
virtual void SendUartSoftReset(HSessionPtr hSessionPtr, uint32_t sessionId) override;
virtual void SendUartSoftReset(HSession hSession, uint32_t sessionId) override;
virtual bool EnumSerialPort(bool &portChange);
virtual bool IsDeviceOpened(const HdcUART &uart);
virtual bool NeedStop(const HSessionPtr hSessionPtr);
virtual void UartReadThread(HSessionPtr hSessionPtr);
virtual bool NeedStop(const HSession hSession);
virtual void UartReadThread(HSession hSession);
#ifdef HOST_MINGW
int WinSetSerial(HUARTPtr hUART, string serialPort, int byteSize, int eqBaudRate);
int WinSetSerial(HUART hUART, string serialPort, int byteSize, int eqBaudRate);
bool enumDetailsSerialPorts(bool *portChange);
static constexpr uint8_t PORT_NAME_LEN = 10;
static constexpr uint8_t PORT_NUM = 100;

View File

@ -15,7 +15,7 @@
#include "host_unity.h"
namespace Hdc {
HdcHostUnity::HdcHostUnity(HTaskInfoPtr hTaskInfo)
HdcHostUnity::HdcHostUnity(HTaskInfo hTaskInfo)
: HdcTaskBase(hTaskInfo)
{
opContext.thisClass = this;

View File

@ -19,7 +19,7 @@
namespace Hdc {
class HdcHostUnity : public HdcTaskBase {
public:
HdcHostUnity(HTaskInfoPtr hTaskInfo);
HdcHostUnity(HTaskInfo hTaskInfo);
virtual ~HdcHostUnity();
bool CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize);
void StopTask();

View File

@ -56,7 +56,7 @@ int HdcHostUSB::Initial()
bool HdcHostUSB::DetectMyNeed(libusb_device *device, string &sn)
{
HUSBPtr hUSB = new(std::nothrow) HdcUSB();
HUSB hUSB = new(std::nothrow) HdcUSB();
if (hUSB == nullptr) {
WRITE_LOG(LOG_FATAL, "DetectMyNeed new hUSB failed");
return false;
@ -78,8 +78,8 @@ bool HdcHostUSB::DetectMyNeed(libusb_device *device, string &sn)
// USB device is automatically connected after recognition, auto connect USB
UpdateUSBDaemonInfo(hUSB, nullptr, STATUS_READY);
HdcServer *hdcServer = (HdcServer *)clsMainBase;
HSessionPtr hSessionPtr = hdcServer->MallocSession(true, CONN_USB, this);
hSessionPtr->connectKey = hUSB->serialNumber;
HSession hSession = hdcServer->MallocSession(true, CONN_USB, this);
hSession->connectKey = hUSB->serialNumber;
uv_timer_t *waitTimeDoCmd = new(std::nothrow) uv_timer_t;
if (waitTimeDoCmd == nullptr) {
WRITE_LOG(LOG_FATAL, "DetectMyNeed new waitTimeDoCmd failed");
@ -87,26 +87,26 @@ bool HdcHostUSB::DetectMyNeed(libusb_device *device, string &sn)
return false;
}
uv_timer_init(&hdcServer->loopMain, waitTimeDoCmd);
waitTimeDoCmd->data = hSessionPtr;
waitTimeDoCmd->data = hSession;
uv_timer_start(waitTimeDoCmd, hdcServer->UsbPreConnect, 0, DEVICE_CHECK_INTERVAL);
mapIgnoreDevice[sn] = HOST_USB_REGISTER;
delete hUSB;
return true;
}
void HdcHostUSB::KickoutZombie(HSessionPtr hSessionPtr)
void HdcHostUSB::KickoutZombie(HSession hSession)
{
HdcServer *ptrConnect = (HdcServer *)hSessionPtr->classInstance;
HUSBPtr hUSB = hSessionPtr->hUSB;
HdcServer *ptrConnect = (HdcServer *)hSession->classInstance;
HUSB hUSB = hSession->hUSB;
if (!hUSB->devHandle) {
WRITE_LOG(LOG_WARN, "KickoutZombie devHandle:%p isDead:%d", hUSB->devHandle, hSessionPtr->isDead);
WRITE_LOG(LOG_WARN, "KickoutZombie devHandle:%p isDead:%d", hUSB->devHandle, hSession->isDead);
return;
}
if (LIBUSB_ERROR_NO_DEVICE != libusb_kernel_driver_active(hUSB->devHandle, hUSB->interfaceNumber)) {
return;
}
WRITE_LOG(LOG_WARN, "KickoutZombie LIBUSB_ERROR_NO_DEVICE serialNumber:%s", hUSB->serialNumber.c_str());
ptrConnect->FreeSession(hSessionPtr->sessionId);
ptrConnect->FreeSession(hSession->sessionId);
}
void HdcHostUSB::RemoveIgnoreDevice(string &mountInfo)
@ -184,7 +184,7 @@ int HdcHostUSB::StartupUSBWork()
return 0;
}
int HdcHostUSB::CheckDescriptor(HUSBPtr hUSB)
int HdcHostUSB::CheckDescriptor(HUSB hUSB)
{
char serialNum[BUF_SIZE_MEDIUM] = "";
int childRet = 0;
@ -211,8 +211,8 @@ int HdcHostUSB::CheckDescriptor(HUSBPtr hUSB)
return 0;
}
// hSessionPtr can be null
void HdcHostUSB::UpdateUSBDaemonInfo(HUSBPtr hUSB, HSessionPtr hSessionPtr, uint8_t connStatus)
// hSession can be null
void HdcHostUSB::UpdateUSBDaemonInfo(HUSB hUSB, HSession hSession, uint8_t connStatus)
{
// add to list
HdcServer *pServer = (HdcServer *)clsMainBase;
@ -220,12 +220,12 @@ void HdcHostUSB::UpdateUSBDaemonInfo(HUSBPtr hUSB, HSessionPtr hSessionPtr, uint
di.connectKey = hUSB->serialNumber;
di.connType = CONN_USB;
di.connStatus = connStatus;
di.hSessionPtr = hSessionPtr;
di.hSession = hSession;
di.usbMountPoint = "";
di.usbMountPoint = Base::StringFormat("%d-%d", hUSB->busId, hUSB->devId);
HDaemonInfoPtr pDi = nullptr;
HDaemonInfoPtr hdiNew = &di;
HDaemonInfo pDi = nullptr;
HDaemonInfo hdiNew = &di;
pServer->AdminDaemonMap(OP_QUERY, hUSB->serialNumber, pDi);
if (!pDi) {
pServer->AdminDaemonMap(OP_ADD, hUSB->serialNumber, hdiNew);
@ -254,7 +254,7 @@ bool HdcHostUSB::IsDebuggableDev(const struct libusb_interface_descriptor *ifDes
return true;
}
int HdcHostUSB::CheckActiveConfig(libusb_device *device, HUSBPtr hUSB)
int HdcHostUSB::CheckActiveConfig(libusb_device *device, HUSB hUSB)
{
unsigned int j = 0;
int ret = -1;
@ -299,10 +299,10 @@ int HdcHostUSB::CheckActiveConfig(libusb_device *device, HUSBPtr hUSB)
}
// multi-thread calll
void HdcHostUSB::CancelUsbIo(HSessionPtr hSessionPtr)
void HdcHostUSB::CancelUsbIo(HSession hSession)
{
WRITE_LOG(LOG_DEBUG, "HostUSB CancelUsbIo, ref:%u", uint32_t(hSessionPtr->ref));
HUSBPtr hUSB = hSessionPtr->hUSB;
WRITE_LOG(LOG_DEBUG, "HostUSB CancelUsbIo, ref:%u", uint32_t(hSession->ref));
HUSB hUSB = hSession->hUSB;
std::unique_lock<std::mutex> lock(hUSB->lockDeviceHandle);
if (!hUSB->hostBulkIn.isShutdown) {
if (!hUSB->hostBulkIn.isComplete) {
@ -326,8 +326,8 @@ void HdcHostUSB::CancelUsbIo(HSessionPtr hSessionPtr)
// no use uvwrite, raw write to socketpair's fd
int HdcHostUSB::UsbToHdcProtocol(uv_stream_t *stream, uint8_t *appendData, int dataSize)
{
HSessionPtr hSessionPtr = (HSessionPtr)stream->data;
unsigned int fd = hSessionPtr->dataFd[STREAM_MAIN];
HSession hSession = (HSession)stream->data;
unsigned int fd = hSession->dataFd[STREAM_MAIN];
fd_set fdSet;
struct timeval timeout = { 3, 0 };
FD_ZERO(&fdSet);
@ -399,9 +399,9 @@ void LIBUSB_CALL HdcHostUSB::USBBulkCallback(struct libusb_transfer *transfer)
ep->cv.notify_one();
}
int HdcHostUSB::SubmitUsbBio(HSessionPtr hSessionPtr, bool sendOrRecv, uint8_t *buf, int bufSize)
int HdcHostUSB::SubmitUsbBio(HSession hSession, bool sendOrRecv, uint8_t *buf, int bufSize)
{
HUSBPtr hUSB = hSessionPtr->hUSB;
HUSB hUSB = hSession->hUSB;
int timeout = 0;
int childRet = 0;
int ret = ERR_IO_FAIL;
@ -436,42 +436,42 @@ int HdcHostUSB::SubmitUsbBio(HSessionPtr hSessionPtr, bool sendOrRecv, uint8_t *
return ret;
}
void HdcHostUSB::BeginUsbRead(HSessionPtr hSessionPtr)
void HdcHostUSB::BeginUsbRead(HSession hSession)
{
HUSBPtr hUSB = hSessionPtr->hUSB;
HUSB hUSB = hSession->hUSB;
hUSB->hostBulkIn.isShutdown = false;
hUSB->hostBulkOut.isShutdown = false;
++hSessionPtr->ref;
++hSession->ref;
// loop read
std::thread([this, hSessionPtr, hUSB]() {
std::thread([this, hSession, hUSB]() {
int childRet = 0;
int nextReadSize = 0;
while (!hSessionPtr->isDead) {
while (!hSession->isDead) {
// if readIO < wMaxPacketSizeSend, libusb report overflow
nextReadSize = (childRet < hUSB->wMaxPacketSizeSend ? hUSB->wMaxPacketSizeSend
: std::min(childRet, Base::GetUsbffsBulkSize()));
childRet = SubmitUsbBio(hSessionPtr, false, hUSB->hostBulkIn.buf, nextReadSize);
childRet = SubmitUsbBio(hSession, false, hUSB->hostBulkIn.buf, nextReadSize);
if (childRet < 0) {
WRITE_LOG(LOG_FATAL, "Read usb failed, ret:%d", childRet);
break;
}
childRet = SendToHdcStream(hSessionPtr, reinterpret_cast<uv_stream_t *>(&hSessionPtr->dataPipe[STREAM_MAIN]),
childRet = SendToHdcStream(hSession, reinterpret_cast<uv_stream_t *>(&hSession->dataPipe[STREAM_MAIN]),
hUSB->hostBulkIn.buf, childRet);
if (childRet < 0) {
WRITE_LOG(LOG_FATAL, "SendToHdcStream failed, ret:%d", childRet);
break;
}
}
--hSessionPtr->ref;
--hSession->ref;
auto server = reinterpret_cast<HdcServer *>(clsMainBase);
hUSB->hostBulkIn.isShutdown = true;
server->FreeSession(hSessionPtr->sessionId);
server->FreeSession(hSession->sessionId);
WRITE_LOG(LOG_DEBUG, "Usb loop read finish");
}).detach();
}
// ==0 Represents new equipment and is what we need,<0 my need
int HdcHostUSB::OpenDeviceMyNeed(HUSBPtr hUSB)
int HdcHostUSB::OpenDeviceMyNeed(HUSB hUSB)
{
libusb_device *device = hUSB->device;
int ret = -1;
@ -502,23 +502,23 @@ int HdcHostUSB::OpenDeviceMyNeed(HUSBPtr hUSB)
return ret;
}
int HdcHostUSB::SendUSBRaw(HSessionPtr hSessionPtr, uint8_t *data, const int length)
int HdcHostUSB::SendUSBRaw(HSession hSession, uint8_t *data, const int length)
{
int ret = ERR_GENERIC;
HdcSessionBase *server = reinterpret_cast<HdcSessionBase *>(hSessionPtr->classInstance);
++hSessionPtr->ref;
ret = SubmitUsbBio(hSessionPtr, true, data, length);
HdcSessionBase *server = reinterpret_cast<HdcSessionBase *>(hSession->classInstance);
++hSession->ref;
ret = SubmitUsbBio(hSession, true, data, length);
if (ret < 0) {
WRITE_LOG(LOG_FATAL, "Send usb failed, ret:%d", ret);
CancelUsbIo(hSessionPtr);
hSessionPtr->hUSB->hostBulkOut.isShutdown = true;
server->FreeSession(hSessionPtr->sessionId);
CancelUsbIo(hSession);
hSession->hUSB->hostBulkOut.isShutdown = true;
server->FreeSession(hSession->sessionId);
}
--hSessionPtr->ref;
--hSession->ref;
return ret;
}
bool HdcHostUSB::FindDeviceByID(HUSBPtr hUSB, const char *usbMountPoint, libusb_context *ctxUSB)
bool HdcHostUSB::FindDeviceByID(HUSB hUSB, const char *usbMountPoint, libusb_context *ctxUSB)
{
libusb_device **listDevices = nullptr;
bool ret = false;
@ -561,35 +561,35 @@ bool HdcHostUSB::FindDeviceByID(HUSBPtr hUSB, const char *usbMountPoint, libusb_
return ret;
}
bool HdcHostUSB::ReadyForWorkThread(HSessionPtr hSessionPtr)
bool HdcHostUSB::ReadyForWorkThread(HSession hSession)
{
HdcUSBBase::ReadyForWorkThread(hSessionPtr);
HdcUSBBase::ReadyForWorkThread(hSession);
return true;
};
// Determines that daemonInfo must have the device
HSessionPtr HdcHostUSB::ConnectDetectDaemon(const HSessionPtr hSessionPtr, const HDaemonInfoPtr pdi)
HSession HdcHostUSB::ConnectDetectDaemon(const HSession hSession, const HDaemonInfo pdi)
{
HdcServer *pServer = (HdcServer *)clsMainBase;
HUSBPtr hUSB = hSessionPtr->hUSB;
HUSB hUSB = hSession->hUSB;
hUSB->usbMountPoint = pdi->usbMountPoint;
hUSB->ctxUSB = ctxUSB;
if (!FindDeviceByID(hUSB, hUSB->usbMountPoint.c_str(), hUSB->ctxUSB)) {
pServer->FreeSession(hSessionPtr->sessionId);
pServer->FreeSession(hSession->sessionId);
return nullptr;
}
UpdateUSBDaemonInfo(hUSB, hSessionPtr, STATUS_CONNECTED);
BeginUsbRead(hSessionPtr);
UpdateUSBDaemonInfo(hUSB, hSession, STATUS_CONNECTED);
BeginUsbRead(hSession);
hUSB->usbMountPoint = pdi->usbMountPoint;
WRITE_LOG(LOG_DEBUG, "HSessionPtr HdcHostUSB::ConnectDaemon");
WRITE_LOG(LOG_DEBUG, "HSession HdcHostUSB::ConnectDaemon");
Base::StartWorkThread(&pServer->loopMain, pServer->SessionWorkThread, Base::FinishWorkThread, hSessionPtr);
Base::StartWorkThread(&pServer->loopMain, pServer->SessionWorkThread, Base::FinishWorkThread, hSession);
// wait for thread up
while (hSessionPtr->childLoop.active_handles == 0) {
while (hSession->childLoop.active_handles == 0) {
uv_sleep(1);
}
auto ctrl = pServer->BuildCtrlString(SP_START_SESSION, 0, nullptr, 0);
Base::SendToStream((uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
return hSessionPtr;
Base::SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
return hSession;
}
} // namespace Hdc

View File

@ -22,8 +22,8 @@ public:
HdcHostUSB(const bool serverOrDaemonIn, void *ptrMainBase, void *ctxUSBin);
virtual ~HdcHostUSB();
int Initial();
int SendUSBRaw(HSessionPtr hSessionPtr, uint8_t *data, const int length);
HSessionPtr ConnectDetectDaemon(const HSessionPtr hSessionPtr, const HDaemonInfoPtr pdi);
int SendUSBRaw(HSession hSession, uint8_t *data, const int length);
HSession ConnectDetectDaemon(const HSession hSession, const HDaemonInfo pdi);
void Stop();
void RemoveIgnoreDevice(string &mountInfo);
@ -37,23 +37,23 @@ private:
libusb_hotplug_event event, void *userData);
static void UsbWorkThread(void *arg); // 3rd thread
static void WatchUsbNodeChange(uv_timer_t *handle);
static void KickoutZombie(HSessionPtr hSessionPtr);
static void KickoutZombie(HSession hSession);
static void LIBUSB_CALL USBBulkCallback(struct libusb_transfer *transfer);
int StartupUSBWork();
int CheckActiveConfig(libusb_device *device, HUSBPtr hUSB);
int OpenDeviceMyNeed(HUSBPtr hUSB);
int CheckDescriptor(HUSBPtr hUSB);
int CheckActiveConfig(libusb_device *device, HUSB hUSB);
int OpenDeviceMyNeed(HUSB hUSB);
int CheckDescriptor(HUSB hUSB);
bool IsDebuggableDev(const struct libusb_interface_descriptor *ifDescriptor);
bool ReadyForWorkThread(HSessionPtr hSessionPtr);
bool FindDeviceByID(HUSBPtr hUSB, const char *usbMountPoint, libusb_context *ctxUSB);
bool ReadyForWorkThread(HSession hSession);
bool FindDeviceByID(HUSB hUSB, const char *usbMountPoint, libusb_context *ctxUSB);
bool DetectMyNeed(libusb_device *device, string &sn);
void RestoreHdcProtocol(HUSBPtr hUsb, const uint8_t *buf, int bufSize);
void UpdateUSBDaemonInfo(HUSBPtr hUSB, HSessionPtr hSessionPtr, uint8_t connStatus);
void BeginUsbRead(HSessionPtr hSessionPtr);
void RestoreHdcProtocol(HUSB hUsb, const uint8_t *buf, int bufSize);
void UpdateUSBDaemonInfo(HUSB hUSB, HSession hSession, uint8_t connStatus);
void BeginUsbRead(HSession hSession);
void ReviewUsbNodeLater(string &nodeKey);
void CancelUsbIo(HSessionPtr hSessionPtr);
void CancelUsbIo(HSession hSession);
int UsbToHdcProtocol(uv_stream_t *stream, uint8_t *appendData, int dataSize);
int SubmitUsbBio(HSessionPtr hSessionPtr, bool sendOrRecv, uint8_t *buf, int bufSize);
int SubmitUsbBio(HSession hSession, bool sendOrRecv, uint8_t *buf, int bufSize);
libusb_context *ctxUSB;
uv_timer_t devListWatcher;

View File

@ -193,11 +193,11 @@ bool HdcServer::PullupServer(const char *listenString)
void HdcServer::ClearMapDaemonInfo()
{
map<string, HDaemonInfoPtr>::iterator iter;
map<string, HDaemonInfo>::iterator iter;
uv_rwlock_rdlock(&daemonAdmin);
for (iter = mapDaemon.begin(); iter != mapDaemon.end();) {
string sKey = iter->first;
HDaemonInfoPtr hDi = iter->second;
HDaemonInfo hDi = iter->second;
delete hDi;
++iter;
}
@ -207,7 +207,7 @@ void HdcServer::ClearMapDaemonInfo()
uv_rwlock_wrunlock(&daemonAdmin);
}
void HdcServer::BuildDaemonVisableLine(HDaemonInfoPtr hdi, bool fullDisplay, string &out)
void HdcServer::BuildDaemonVisableLine(HDaemonInfo hdi, bool fullDisplay, string &out)
{
if (fullDisplay) {
string sConn;
@ -262,10 +262,10 @@ string HdcServer::GetDaemonMapList(uint8_t opType)
fullDisplay = true;
}
uv_rwlock_rdlock(&daemonAdmin);
map<string, HDaemonInfoPtr>::iterator iter;
map<string, HDaemonInfo>::iterator iter;
string echoLine;
for (iter = mapDaemon.begin(); iter != mapDaemon.end(); ++iter) {
HDaemonInfoPtr di = iter->second;
HDaemonInfo di = iter->second;
if (!di) {
continue;
}
@ -277,7 +277,7 @@ string HdcServer::GetDaemonMapList(uint8_t opType)
return ret;
}
void HdcServer::GetDaemonMapOnlyOne(HDaemonInfoPtr &hDaemonInfoInOut)
void HdcServer::GetDaemonMapOnlyOne(HDaemonInfo &hDaemonInfoInOut)
{
uv_rwlock_rdlock(&daemonAdmin);
string key;
@ -297,12 +297,12 @@ void HdcServer::GetDaemonMapOnlyOne(HDaemonInfoPtr &hDaemonInfoInOut)
uv_rwlock_rdunlock(&daemonAdmin);
}
string HdcServer::AdminDaemonMap(uint8_t opType, const string &connectKey, HDaemonInfoPtr &hDaemonInfoInOut)
string HdcServer::AdminDaemonMap(uint8_t opType, const string &connectKey, HDaemonInfo &hDaemonInfoInOut)
{
string sRet;
switch (opType) {
case OP_ADD: {
HDaemonInfoPtr pdiNew = new(std::nothrow) HdcDaemonInformation();
HDaemonInfo pdiNew = new(std::nothrow) HdcDaemonInformation();
if (pdiNew == nullptr) {
WRITE_LOG(LOG_FATAL, "AdminDaemonMap new pdiNew failed");
break;
@ -338,9 +338,9 @@ string HdcServer::AdminDaemonMap(uint8_t opType, const string &connectKey, HDaem
}
case OP_GET_ANY: {
uv_rwlock_rdlock(&daemonAdmin);
map<string, HDaemonInfoPtr>::iterator iter;
map<string, HDaemonInfo>::iterator iter;
for (iter = mapDaemon.begin(); iter != mapDaemon.end(); ++iter) {
HDaemonInfoPtr di = iter->second;
HDaemonInfo di = iter->second;
// usb will be auto connected
if (di->connStatus == STATUS_READY || di->connStatus == STATUS_CONNECTED) {
hDaemonInfoInOut = di;
@ -356,7 +356,7 @@ string HdcServer::AdminDaemonMap(uint8_t opType, const string &connectKey, HDaem
}
case OP_UPDATE: { // Cannot update the Object HDi lower key value by direct value
uv_rwlock_wrlock(&daemonAdmin);
HDaemonInfoPtr hdi = mapDaemon[hDaemonInfoInOut->connectKey];
HDaemonInfo hdi = mapDaemon[hDaemonInfoInOut->connectKey];
if (hdi) {
*mapDaemon[hDaemonInfoInOut->connectKey] = *hDaemonInfoInOut;
}
@ -369,10 +369,10 @@ string HdcServer::AdminDaemonMap(uint8_t opType, const string &connectKey, HDaem
return sRet;
}
void HdcServer::NotifyInstanceSessionFree(HSessionPtr hSessionPtr, bool freeOrClear)
void HdcServer::NotifyInstanceSessionFree(HSession hSession, bool freeOrClear)
{
HDaemonInfoPtr hdiOld = nullptr;
AdminDaemonMap(OP_QUERY, hSessionPtr->connectKey, hdiOld);
HDaemonInfo hdiOld = nullptr;
AdminDaemonMap(OP_QUERY, hSession->connectKey, hdiOld);
if (hdiOld == nullptr) {
return;
}
@ -380,8 +380,8 @@ void HdcServer::NotifyInstanceSessionFree(HSessionPtr hSessionPtr, bool freeOrCl
// update
HdcDaemonInformation diNew = *hdiOld;
diNew.connStatus = STATUS_OFFLINE;
HDaemonInfoPtr hdiNew = &diNew;
AdminDaemonMap(OP_UPDATE, hSessionPtr->connectKey, hdiNew);
HDaemonInfo hdiNew = &diNew;
AdminDaemonMap(OP_UPDATE, hSession->connectKey, hdiNew);
} else { // step2
string usbMountPoint = hdiOld->usbMountPoint;
// The waiting time must be longer than DEVICE_CHECK_INTERVAL. Wait the method WatchUsbNodeChange
@ -399,7 +399,7 @@ void HdcServer::NotifyInstanceSessionFree(HSessionPtr hSessionPtr, bool freeOrCl
}
}
bool HdcServer::HandServerAuth(HSessionPtr hSessionPtr, SessionHandShake &handshake)
bool HdcServer::HandServerAuth(HSession hSession, SessionHandShake &handshake)
{
bool ret = false;
int retChild = 0;
@ -407,12 +407,12 @@ bool HdcServer::HandServerAuth(HSessionPtr hSessionPtr, SessionHandShake &handsh
switch (handshake.authType) {
case AUTH_TOKEN: {
void *ptr = nullptr;
bool retChild = HdcAuth::KeylistIncrement(hSessionPtr->listKey, hSessionPtr->authKeyIndex, &ptr);
bool retChild = HdcAuth::KeylistIncrement(hSession->listKey, hSession->authKeyIndex, &ptr);
// HdcAuth::FreeKey will be effect at funciton 'FreeSession'
if (!retChild) {
// Iteration call certificate authentication
handshake.authType = AUTH_PUBLICKEY;
ret = HandServerAuth(hSessionPtr, handshake);
ret = HandServerAuth(hSession, handshake);
break;
}
char sign[BUF_SIZE_DEFAULT2] = { 0 };
@ -423,7 +423,7 @@ bool HdcServer::HandServerAuth(HSessionPtr hSessionPtr, SessionHandShake &handsh
handshake.buf = string(sign, retChild);
handshake.authType = AUTH_SIGNATURE;
bufString = SerialStruct::SerializeToString(handshake);
Send(hSessionPtr->sessionId, 0, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
Send(hSession->sessionId, 0, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
ret = true;
break;
}
@ -436,7 +436,7 @@ bool HdcServer::HandServerAuth(HSessionPtr hSessionPtr, SessionHandShake &handsh
handshake.buf = string(bufPrivateKey, retChild);
handshake.authType = AUTH_PUBLICKEY;
bufString = SerialStruct::SerializeToString(handshake);
Send(hSessionPtr->sessionId, 0, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
Send(hSession->sessionId, 0, CMD_KERNEL_HANDSHAKE, (uint8_t *)bufString.c_str(), bufString.size());
ret = true;
break;
}
@ -446,7 +446,7 @@ bool HdcServer::HandServerAuth(HSessionPtr hSessionPtr, SessionHandShake &handsh
return ret;
}
bool HdcServer::ServerSessionHandshake(HSessionPtr hSessionPtr, uint8_t *payload, int payloadSize)
bool HdcServer::ServerSessionHandshake(HSession hSession, uint8_t *payload, int payloadSize)
{
// session handshake step3
string s = string((char *)payload, payloadSize);
@ -460,20 +460,20 @@ bool HdcServer::ServerSessionHandshake(HSessionPtr hSessionPtr, uint8_t *payload
return false;
}
if (handshake.authType != AUTH_OK) {
if (!HandServerAuth(hSessionPtr, handshake)) {
if (!HandServerAuth(hSession, handshake)) {
WRITE_LOG(LOG_DEBUG, "Auth failed");
return false;
}
return true;
}
// handshake auth OK
HDaemonInfoPtr hdiOld = nullptr;
AdminDaemonMap(OP_QUERY, hSessionPtr->connectKey, hdiOld);
HDaemonInfo hdiOld = nullptr;
AdminDaemonMap(OP_QUERY, hSession->connectKey, hdiOld);
if (!hdiOld) {
return false;
}
HdcDaemonInformation diNew = *hdiOld;
HDaemonInfoPtr hdiNew = &diNew;
HDaemonInfo hdiNew = &diNew;
// update
hdiNew->connStatus = STATUS_CONNECTED;
if (handshake.buf.size() > sizeof(hdiNew->devName) || !handshake.buf.size()) {
@ -481,25 +481,25 @@ bool HdcServer::ServerSessionHandshake(HSessionPtr hSessionPtr, uint8_t *payload
} else {
hdiNew->devName = handshake.buf;
}
AdminDaemonMap(OP_UPDATE, hSessionPtr->connectKey, hdiNew);
hSessionPtr->handshakeOK = true;
AdminDaemonMap(OP_UPDATE, hSession->connectKey, hdiNew);
hSession->handshakeOK = true;
return true;
}
// call in child thread
bool HdcServer::FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command, uint8_t *payload,
bool HdcServer::FetchCommand(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
const int payloadSize)
{
bool ret = true;
HdcServerForClient *sfc = static_cast<HdcServerForClient *>(clsServerForClient);
if (CMD_KERNEL_HANDSHAKE == command) {
ret = ServerSessionHandshake(hSessionPtr, payload, payloadSize);
ret = ServerSessionHandshake(hSession, payload, payloadSize);
WRITE_LOG(LOG_DEBUG, "Session handshake %s connType:%d", ret ? "successful" : "failed",
hSessionPtr->connType);
hSession->connType);
return ret;
}
// When you first initialize, ChannelID may be 0
HChannelPtr hChannel = sfc->AdminChannel(OP_QUERY_REF, channelId, nullptr);
HChannel hChannel = sfc->AdminChannel(OP_QUERY_REF, channelId, nullptr);
if (!hChannel) {
if (command == CMD_KERNEL_CHANNEL_CLOSE) {
// Daemon close channel and want to notify server close channel also, but it may has been
@ -510,7 +510,7 @@ bool HdcServer::FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId,
WRITE_LOG(LOG_DEBUG, "channelId :%lu die", channelId);
}
uint8_t flag = 0;
Send(hSessionPtr->sessionId, channelId, CMD_KERNEL_CHANNEL_CLOSE, &flag, 1);
Send(hSession->sessionId, channelId, CMD_KERNEL_CHANNEL_CLOSE, &flag, 1);
return ret;
}
if (hChannel->isDead) {
@ -532,21 +532,21 @@ bool HdcServer::FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId,
case CMD_KERNEL_CHANNEL_CLOSE: {
WRITE_LOG(LOG_DEBUG, "CMD_KERNEL_CHANNEL_CLOSE channelid:%u", channelId);
// Forcibly closing the tcp handle here may result in incomplete data reception on the client side
ClearOwnTasks(hSessionPtr, channelId);
ClearOwnTasks(hSession, channelId);
// crossthread free
sfc->PushAsyncMessage(channelId, ASYNC_FREE_CHANNEL, nullptr, 0);
if (*payload != 0) {
--(*payload);
Send(hSessionPtr->sessionId, channelId, CMD_KERNEL_CHANNEL_CLOSE, payload, 1);
Send(hSession->sessionId, channelId, CMD_KERNEL_CHANNEL_CLOSE, payload, 1);
}
break;
}
case CMD_FORWARD_SUCCESS: {
// add to local
HdcForwardInformation di;
HForwardInfoPtr pdiNew = &di;
HForwardInfo pdiNew = &di;
pdiNew->channelId = channelId;
pdiNew->sessionId = hSessionPtr->sessionId;
pdiNew->sessionId = hSession->sessionId;
pdiNew->forwardDirection = ((char *)payload)[0] == '1';
pdiNew->taskString = (char *)payload + 2;
AdminForwardMap(OP_ADD, STRING_EMPTY, pdiNew);
@ -554,12 +554,12 @@ bool HdcServer::FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId,
break;
}
default: {
HSessionPtr hSessionPtr = AdminSession(OP_QUERY, hChannel->targetSessionId, nullptr);
if (!hSessionPtr) {
HSession hSession = AdminSession(OP_QUERY, hChannel->targetSessionId, nullptr);
if (!hSession) {
ret = false;
break;
}
ret = DispatchTaskData(hSessionPtr, channelId, command, payload, payloadSize);
ret = DispatchTaskData(hSession, channelId, command, payload, payloadSize);
break;
}
}
@ -567,7 +567,7 @@ bool HdcServer::FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId,
return ret;
}
void HdcServer::BuildForwardVisableLine(bool fullOrSimble, HForwardInfoPtr hfi, string &echo)
void HdcServer::BuildForwardVisableLine(bool fullOrSimble, HForwardInfo hfi, string &echo)
{
string buf;
if (fullOrSimble) {
@ -579,12 +579,12 @@ void HdcServer::BuildForwardVisableLine(bool fullOrSimble, HForwardInfoPtr hfi,
echo += buf;
}
string HdcServer::AdminForwardMap(uint8_t opType, const string &taskString, HForwardInfoPtr &hForwardInfoInOut)
string HdcServer::AdminForwardMap(uint8_t opType, const string &taskString, HForwardInfo &hForwardInfoInOut)
{
string sRet;
switch (opType) {
case OP_ADD: {
HForwardInfoPtr pfiNew = new(std::nothrow) HdcForwardInformation();
HForwardInfo pfiNew = new(std::nothrow) HdcForwardInformation();
if (pfiNew == nullptr) {
WRITE_LOG(LOG_FATAL, "AdminForwardMap new pfiNew failed");
break;
@ -600,9 +600,9 @@ string HdcServer::AdminForwardMap(uint8_t opType, const string &taskString, HFor
case OP_GET_STRLIST:
case OP_GET_STRLIST_FULL: {
uv_rwlock_rdlock(&forwardAdmin);
map<string, HForwardInfoPtr>::iterator iter;
map<string, HForwardInfo>::iterator iter;
for (iter = mapForward.begin(); iter != mapForward.end(); ++iter) {
HForwardInfoPtr di = iter->second;
HForwardInfo di = iter->second;
if (!di) {
continue;
}
@ -635,28 +635,28 @@ string HdcServer::AdminForwardMap(uint8_t opType, const string &taskString, HFor
void HdcServer::UsbPreConnect(uv_timer_t *handle)
{
HSessionPtr hSessionPtr = (HSessionPtr)handle->data;
HSession hSession = (HSession)handle->data;
bool stopLoop = false;
HdcServer *hdcServer = (HdcServer *)hSessionPtr->classInstance;
HdcServer *hdcServer = (HdcServer *)hSession->classInstance;
const int usbConnectRetryMax = 5;
while (true) {
WRITE_LOG(LOG_DEBUG, "HdcServer::UsbPreConnect");
if (++hSessionPtr->hUSB->retryCount > usbConnectRetryMax) { // max 15s
hdcServer->FreeSession(hSessionPtr->sessionId);
if (++hSession->hUSB->retryCount > usbConnectRetryMax) { // max 15s
hdcServer->FreeSession(hSession->sessionId);
stopLoop = true;
break;
}
HDaemonInfoPtr pDi = nullptr;
if (hSessionPtr->connectKey == "any") {
hdcServer->AdminDaemonMap(OP_GET_ANY, hSessionPtr->connectKey, pDi);
HDaemonInfo pDi = nullptr;
if (hSession->connectKey == "any") {
hdcServer->AdminDaemonMap(OP_GET_ANY, hSession->connectKey, pDi);
} else {
hdcServer->AdminDaemonMap(OP_QUERY, hSessionPtr->connectKey, pDi);
hdcServer->AdminDaemonMap(OP_QUERY, hSession->connectKey, pDi);
}
if (!pDi || !pDi->usbMountPoint.size()) {
break;
}
HdcHostUSB *hdcHostUSB = (HdcHostUSB *)hSessionPtr->classModule;
hdcHostUSB->ConnectDetectDaemon(hSessionPtr, pDi);
HdcHostUSB *hdcHostUSB = (HdcHostUSB *)hSession->classModule;
hdcHostUSB->ConnectDetectDaemon(hSession, pDi);
stopLoop = true;
break;
}
@ -668,29 +668,29 @@ void HdcServer::UsbPreConnect(uv_timer_t *handle)
void HdcServer::UartPreConnect(uv_timer_t *handle)
{
WRITE_LOG(LOG_DEBUG, "%s", __FUNCTION__);
HSessionPtr hSessionPtr = (HSessionPtr)handle->data;
HSession hSession = (HSession)handle->data;
bool stopLoop = false;
HdcServer *hdcServer = (HdcServer *)hSessionPtr->classInstance;
HdcServer *hdcServer = (HdcServer *)hSession->classInstance;
const int uartConnectRetryMax = 100; // max 6s
while (true) {
if (hSessionPtr->hUART->retryCount > uartConnectRetryMax) {
if (hSession->hUART->retryCount > uartConnectRetryMax) {
WRITE_LOG(LOG_DEBUG, "%s failed because max retry limit %d", __FUNCTION__,
hSessionPtr->hUART->retryCount);
hdcServer->FreeSession(hSessionPtr->sessionId);
hSession->hUART->retryCount);
hdcServer->FreeSession(hSession->sessionId);
stopLoop = true;
break;
}
hSessionPtr->hUART->retryCount++;
HDaemonInfoPtr pDi = nullptr;
hSession->hUART->retryCount++;
HDaemonInfo pDi = nullptr;
WRITE_LOG(LOG_DEBUG, "%s query %s", __FUNCTION__, hSessionPtr->ToDebugString().c_str());
hdcServer->AdminDaemonMap(OP_QUERY, hSessionPtr->connectKey, pDi);
WRITE_LOG(LOG_DEBUG, "%s query %s", __FUNCTION__, hSession->ToDebugString().c_str());
hdcServer->AdminDaemonMap(OP_QUERY, hSession->connectKey, pDi);
if (!pDi) {
WRITE_LOG(LOG_DEBUG, "%s not found", __FUNCTION__);
break;
}
HdcHostUART *hdcHostUART = (HdcHostUART *)hSessionPtr->classModule;
hdcHostUART->ConnectDaemonByUart(hSessionPtr, pDi);
HdcHostUART *hdcHostUART = (HdcHostUART *)hSession->classModule;
hdcHostUART->ConnectDaemonByUart(hSession, pDi);
WRITE_LOG(LOG_DEBUG, "%s ConnectDaemonByUart done", __FUNCTION__);
stopLoop = true;
@ -701,7 +701,7 @@ void HdcServer::UartPreConnect(uv_timer_t *handle)
}
}
void HdcServer::CreatConnectUart(HSessionPtr hSessionPtr)
void HdcServer::CreatConnectUart(HSession hSession)
{
uv_timer_t *waitTimeDoCmd = new(std::nothrow) uv_timer_t;
if (waitTimeDoCmd == nullptr) {
@ -709,7 +709,7 @@ void HdcServer::CreatConnectUart(HSessionPtr hSessionPtr)
return;
}
uv_timer_init(&loopMain, waitTimeDoCmd);
waitTimeDoCmd->data = hSessionPtr;
waitTimeDoCmd->data = hSession;
uv_timer_start(waitTimeDoCmd, UartPreConnect, UV_TIMEOUT, UV_REPEAT);
}
#endif
@ -728,7 +728,7 @@ int HdcServer::CreateConnect(const string &connectKey)
else { // USB
connType = CONN_USB;
}
HDaemonInfoPtr hdi = nullptr;
HDaemonInfo hdi = nullptr;
if (connectKey == "any") {
return RET_SUCCESS;
}
@ -738,57 +738,57 @@ int HdcServer::CreateConnect(const string &connectKey)
di.connectKey = connectKey;
di.connType = connType;
di.connStatus = STATUS_UNKNOW;
HDaemonInfoPtr pDi = (HDaemonInfoPtr)&di;
HDaemonInfo pDi = (HDaemonInfo)&di;
AdminDaemonMap(OP_ADD, "", pDi);
AdminDaemonMap(OP_QUERY, connectKey, hdi);
}
if (!hdi || hdi->connStatus == STATUS_CONNECTED) {
return ERR_GENERIC;
}
HSessionPtr hSessionPtr = nullptr;
HSession hSession = nullptr;
if (CONN_TCP == connType) {
hSessionPtr = clsTCPClt->ConnectDaemon(connectKey);
hSession = clsTCPClt->ConnectDaemon(connectKey);
} else if (CONN_SERIAL == connType) {
#ifdef HDC_SUPPORT_UART
hSessionPtr = clsUARTClt->ConnectDaemon(connectKey);
hSession = clsUARTClt->ConnectDaemon(connectKey);
#endif
} else {
hSessionPtr = MallocSession(true, CONN_USB, clsUSBClt);
hSessionPtr->connectKey = connectKey;
hSession = MallocSession(true, CONN_USB, clsUSBClt);
hSession->connectKey = connectKey;
uv_timer_t *waitTimeDoCmd = new(std::nothrow) uv_timer_t;
if (waitTimeDoCmd == nullptr) {
WRITE_LOG(LOG_FATAL, "CreateConnect new waitTimeDoCmd failed");
return ERR_GENERIC;
}
uv_timer_init(&loopMain, waitTimeDoCmd);
waitTimeDoCmd->data = hSessionPtr;
waitTimeDoCmd->data = hSession;
uv_timer_start(waitTimeDoCmd, UsbPreConnect, 10, 100);
}
if (!hSessionPtr) {
if (!hSession) {
return ERR_BUF_ALLOC;
}
HDaemonInfoPtr hdiQuery = nullptr;
HDaemonInfo hdiQuery = nullptr;
AdminDaemonMap(OP_QUERY, connectKey, hdiQuery);
if (hdiQuery) {
HdcDaemonInformation diNew = *hdiQuery;
diNew.hSessionPtr = hSessionPtr;
HDaemonInfoPtr hdiNew = &diNew;
diNew.hSession = hSession;
HDaemonInfo hdiNew = &diNew;
AdminDaemonMap(OP_UPDATE, hdiQuery->connectKey, hdiNew);
}
return RET_SUCCESS;
}
void HdcServer::AttachChannel(HSessionPtr hSessionPtr, const uint32_t channelId)
void HdcServer::AttachChannel(HSession hSession, const uint32_t channelId)
{
int ret = 0;
HdcServerForClient *hSfc = static_cast<HdcServerForClient *>(clsServerForClient);
HChannelPtr hChannel = hSfc->AdminChannel(OP_QUERY_REF, channelId, nullptr);
HChannel hChannel = hSfc->AdminChannel(OP_QUERY_REF, channelId, nullptr);
if (!hChannel) {
return;
}
uv_tcp_init(&hSessionPtr->childLoop, &hChannel->hChildWorkTCP);
uv_tcp_init(&hSession->childLoop, &hChannel->hChildWorkTCP);
hChannel->hChildWorkTCP.data = hChannel;
hChannel->targetSessionId = hSessionPtr->sessionId;
hChannel->targetSessionId = hSession->sessionId;
if ((ret = uv_tcp_open((uv_tcp_t *)&hChannel->hChildWorkTCP, hChannel->fdChildWorkTCP)) < 0) {
constexpr int bufSize = 1024;
char buf[bufSize] = { 0 };
@ -804,11 +804,11 @@ void HdcServer::AttachChannel(HSessionPtr hSessionPtr, const uint32_t channelId)
--hChannel->ref;
};
void HdcServer::DeatchChannel(HSessionPtr hSessionPtr, const uint32_t channelId)
void HdcServer::DeatchChannel(HSession hSession, const uint32_t channelId)
{
HdcServerForClient *hSfc = static_cast<HdcServerForClient *>(clsServerForClient);
// childCleared has not set, no need OP_QUERY_REF
HChannelPtr hChannel = hSfc->AdminChannel(OP_QUERY, channelId, nullptr);
HChannel hChannel = hSfc->AdminChannel(OP_QUERY, channelId, nullptr);
if (!hChannel) {
return;
}
@ -817,18 +817,18 @@ void HdcServer::DeatchChannel(HSessionPtr hSessionPtr, const uint32_t channelId)
return;
}
// The own task for this channel must be clear before free channel
ClearOwnTasks(hSessionPtr, channelId);
ClearOwnTasks(hSession, channelId);
uint8_t count = 0;
Send(hSessionPtr->sessionId, hChannel->channelId, CMD_KERNEL_CHANNEL_CLOSE, &count, 1);
Send(hSession->sessionId, hChannel->channelId, CMD_KERNEL_CHANNEL_CLOSE, &count, 1);
if (uv_is_closing((const uv_handle_t *)&hChannel->hChildWorkTCP)) {
Base::DoNextLoop(&hSessionPtr->childLoop, hChannel, [](const uint8_t flag, string &msg, const void *data) {
HChannelPtr hChannel = (HChannelPtr)data;
Base::DoNextLoop(&hSession->childLoop, hChannel, [](const uint8_t flag, string &msg, const void *data) {
HChannel hChannel = (HChannel)data;
hChannel->childCleared = true;
WRITE_LOG(LOG_DEBUG, "Childchannel free direct, cid:%u", hChannel->channelId);
});
} else {
Base::TryCloseHandle((uv_handle_t *)&hChannel->hChildWorkTCP, [](uv_handle_t *handle) -> void {
HChannelPtr hChannel = (HChannelPtr)handle->data;
HChannel hChannel = (HChannel)handle->data;
hChannel->childCleared = true;
WRITE_LOG(LOG_DEBUG, "Childchannel free callback, cid:%u", hChannel->channelId);
});
@ -839,16 +839,16 @@ bool HdcServer::ServerCommand(const uint32_t sessionId, const uint32_t channelId
uint8_t *bufPtr, const int size)
{
HdcServerForClient *hSfc = static_cast<HdcServerForClient *>(clsServerForClient);
HChannelPtr hChannel = hSfc->AdminChannel(OP_QUERY, channelId, nullptr);
HSessionPtr hSessionPtr = AdminSession(OP_QUERY, sessionId, nullptr);
if (!hChannel || !hSessionPtr) {
HChannel hChannel = hSfc->AdminChannel(OP_QUERY, channelId, nullptr);
HSession hSession = AdminSession(OP_QUERY, sessionId, nullptr);
if (!hChannel || !hSession) {
return false;
}
return FetchCommand(hSessionPtr, channelId, command, bufPtr, size);
return FetchCommand(hSession, channelId, command, bufPtr, size);
}
// clang-format off
bool HdcServer::RedirectToTask(HTaskInfoPtr hTaskInfo, HSessionPtr hSessionPtr, const uint32_t channelId,
bool HdcServer::RedirectToTask(HTaskInfo hTaskInfo, HSession hSession, const uint32_t channelId,
const uint16_t command, uint8_t *payload, const int payloadSize)
// clang-format on
{
@ -889,7 +889,7 @@ bool HdcServer::RedirectToTask(HTaskInfoPtr hTaskInfo, HSessionPtr hSessionPtr,
return ret;
}
bool HdcServer::RemoveInstanceTask(const uint8_t op, HTaskInfoPtr hTask)
bool HdcServer::RemoveInstanceTask(const uint8_t op, HTaskInfo hTask)
{
bool ret = true;
switch (hTask->taskType) {

View File

@ -21,23 +21,23 @@ class HdcServer : public HdcSessionBase {
public:
HdcServer(bool serverOrDaemonIn);
virtual ~HdcServer();
bool FetchCommand(HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command, uint8_t *payload,
bool FetchCommand(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
const int payloadSize);
virtual string AdminDaemonMap(uint8_t opType, const string &connectKey, HDaemonInfoPtr &hDaemonInfoInOut);
string AdminForwardMap(uint8_t opType, const string &taskString, HForwardInfoPtr &hForwardInfoInOut);
virtual string AdminDaemonMap(uint8_t opType, const string &connectKey, HDaemonInfo &hDaemonInfoInOut);
string AdminForwardMap(uint8_t opType, const string &taskString, HForwardInfo &hForwardInfoInOut);
int CreateConnect(const string &connectKey);
bool Initial(const char *listenString);
void AttachChannel(HSessionPtr hSessionPtr, const uint32_t channelId);
void DeatchChannel(HSessionPtr hSessionPtr, const uint32_t channelId);
void AttachChannel(HSession hSession, const uint32_t channelId);
void DeatchChannel(HSession hSession, const uint32_t channelId);
virtual void EchoToClientsForSession(uint32_t targetSessionId, const string &echo);
static bool PullupServer(const char *listenString);
static void UsbPreConnect(uv_timer_t *handle);
void NotifyInstanceSessionFree(HSessionPtr hSessionPtr, bool freeOrClear);
void NotifyInstanceSessionFree(HSession hSession, bool freeOrClear);
HdcHostTCP *clsTCPClt;
HdcHostUSB *clsUSBClt;
#ifdef HDC_SUPPORT_UART
void CreatConnectUart(HSessionPtr hSessionPtr);
void CreatConnectUart(HSession hSession);
static void UartPreConnect(uv_timer_t *handle);
HdcHostUART *clsUARTClt = nullptr;
#endif
@ -45,26 +45,26 @@ public:
private:
void ClearInstanceResource();
void BuildDaemonVisableLine(HDaemonInfoPtr hdi, bool fullDisplay, string &out);
void BuildForwardVisableLine(bool fullOrSimble, HForwardInfoPtr hfi, string &echo);
void BuildDaemonVisableLine(HDaemonInfo hdi, bool fullDisplay, string &out);
void BuildForwardVisableLine(bool fullOrSimble, HForwardInfo hfi, string &echo);
void ClearMapDaemonInfo();
bool ServerCommand(const uint32_t sessionId, const uint32_t channelId, const uint16_t command, uint8_t *bufPtr,
const int size);
bool RedirectToTask(HTaskInfoPtr hTaskInfo, HSessionPtr hSessionPtr, const uint32_t channelId, const uint16_t command,
bool RedirectToTask(HTaskInfo hTaskInfo, HSession hSession, const uint32_t channelId, const uint16_t command,
uint8_t *payload, const int payloadSize);
bool RemoveInstanceTask(const uint8_t op, HTaskInfoPtr hTask);
void BuildForwardVisableLine(HDaemonInfoPtr hdi, char *out, int sizeOutBuf);
bool HandServerAuth(HSessionPtr hSessionPtr, SessionHandShake &handshake);
bool RemoveInstanceTask(const uint8_t op, HTaskInfo hTask);
void BuildForwardVisableLine(HDaemonInfo hdi, char *out, int sizeOutBuf);
bool HandServerAuth(HSession hSession, SessionHandShake &handshake);
string GetDaemonMapList(uint8_t opType);
bool ServerSessionHandshake(HSessionPtr hSessionPtr, uint8_t *payload, int payloadSize);
void GetDaemonMapOnlyOne(HDaemonInfoPtr &hDaemonInfoInOut);
bool ServerSessionHandshake(HSession hSession, uint8_t *payload, int payloadSize);
void GetDaemonMapOnlyOne(HDaemonInfo &hDaemonInfoInOut);
void TryStopInstance();
static bool PullupServerWin32(const char *path, const char *listenString);
uv_rwlock_t daemonAdmin;
map<string, HDaemonInfoPtr> mapDaemon;
map<string, HDaemonInfo> mapDaemon;
uv_rwlock_t forwardAdmin;
map<string, HForwardInfoPtr> mapForward;
map<string, HForwardInfo> mapForward;
};
} // namespace Hdc
#endif

View File

@ -42,32 +42,32 @@ void HdcServerForClient::AcceptClient(uv_stream_t *server, int status)
{
uv_tcp_t *pServTCP = (uv_tcp_t *)server;
HdcServerForClient *thisClass = (HdcServerForClient *)pServTCP->data;
HChannelPtr hChannelPtr = nullptr;
uint32_t uid = thisClass->MallocChannel(&hChannelPtr);
if (!hChannelPtr) {
HChannel hChannel = nullptr;
uint32_t uid = thisClass->MallocChannel(&hChannel);
if (!hChannel) {
return;
}
if (uv_accept(server, (uv_stream_t *)&hChannelPtr->hWorkTCP) < 0) {
if (uv_accept(server, (uv_stream_t *)&hChannel->hWorkTCP) < 0) {
thisClass->FreeChannel(uid);
return;
}
WRITE_LOG(LOG_DEBUG, "HdcServerForClient acceptClient");
// limit first recv
int bufMaxSize = 0;
uv_recv_buffer_size((uv_handle_t *)&hChannelPtr->hWorkTCP, &bufMaxSize);
uv_recv_buffer_size((uv_handle_t *)&hChannel->hWorkTCP, &bufMaxSize);
auto funcChannelHeaderAlloc = [](uv_handle_t *handle, size_t sizeWanted, uv_buf_t *buf) -> void {
HChannelPtr context = (HChannelPtr)handle->data;
HChannel context = (HChannel)handle->data;
Base::ReallocBuf(&context->ioBuf, &context->bufSize, sizeWanted); // sizeWanted default 6k
buf->base = (char *)context->ioBuf + context->availTailIndex;
buf->len = sizeof(struct ChannelHandShake) + DWORD_SERIALIZE_SIZE; // only recv static size
};
// first packet static size, after this packet will be dup for normal recv
uv_read_start((uv_stream_t *)&hChannelPtr->hWorkTCP, funcChannelHeaderAlloc, ReadStream);
uv_read_start((uv_stream_t *)&hChannel->hWorkTCP, funcChannelHeaderAlloc, ReadStream);
// channel handshake step1
struct ChannelHandShake handShake = {};
if (EOK == strcpy_s(handShake.banner, sizeof(handShake.banner), HANDSHAKE_MESSAGE.c_str())) {
handShake.channelId = htonl(hChannelPtr->channelId);
thisClass->Send(hChannelPtr->channelId, (uint8_t *)&handShake, sizeof(struct ChannelHandShake));
handShake.channelId = htonl(hChannel->channelId);
thisClass->Send(hChannel->channelId, (uint8_t *)&handShake, sizeof(struct ChannelHandShake));
}
}
@ -95,7 +95,7 @@ int HdcServerForClient::Initial()
return 0;
}
void HdcServerForClient::EchoClient(HChannelPtr hChannelPtr, MessageLevel level, const char *msg, ...)
void HdcServerForClient::EchoClient(HChannel hChannel, MessageLevel level, const char *msg, ...)
{
string logInfo = "";
switch (level) {
@ -115,31 +115,31 @@ void HdcServerForClient::EchoClient(HChannelPtr hChannelPtr, MessageLevel level,
if (log.back() != '\n') {
log += "\r\n";
}
SendChannel(hChannelPtr, (uint8_t *)log.c_str(), log.size());
SendChannel(hChannel, (uint8_t *)log.c_str(), log.size());
}
void HdcServerForClient::EchoClientRaw(const HChannelPtr hChannelPtr, uint8_t *payload, const int payloadSize)
void HdcServerForClient::EchoClientRaw(const HChannel hChannel, uint8_t *payload, const int payloadSize)
{
SendChannel(hChannelPtr, payload, payloadSize);
SendChannel(hChannel, payload, payloadSize);
}
bool HdcServerForClient::SendToDaemon(HChannelPtr hChannelPtr, const uint16_t commandFlag, uint8_t *bufPtr, const int bufSize)
bool HdcServerForClient::SendToDaemon(HChannel hChannel, const uint16_t commandFlag, uint8_t *bufPtr, const int bufSize)
{
HDaemonInfoPtr hdi = nullptr;
HDaemonInfo hdi = nullptr;
bool ret = false;
HdcServer *ptrServer = (HdcServer *)clsServer;
while (true) {
ptrServer->AdminDaemonMap(OP_QUERY, hChannelPtr->connectKey, hdi);
ptrServer->AdminDaemonMap(OP_QUERY, hChannel->connectKey, hdi);
if (hdi == nullptr) {
break;
}
if (hdi->connStatus != STATUS_CONNECTED) {
break;
}
if (!hdi->hSessionPtr) {
if (!hdi->hSession) {
break;
}
if (ptrServer->Send(hdi->hSessionPtr->sessionId, hChannelPtr->channelId, commandFlag, bufPtr, bufSize) < 0) {
if (ptrServer->Send(hdi->hSession->sessionId, hChannel->channelId, commandFlag, bufPtr, bufSize) < 0) {
break;
}
ret = true;
@ -148,10 +148,10 @@ bool HdcServerForClient::SendToDaemon(HChannelPtr hChannelPtr, const uint16_t co
return ret;
}
void HdcServerForClient::OrderFindTargets(HChannelPtr hChannelPtr)
void HdcServerForClient::OrderFindTargets(HChannel hChannel)
{
int count = 0;
EchoClient(hChannelPtr, MSG_INFO, "Please add HDC server's firewall ruler to allow udp incoming, udpport:%d",
EchoClient(hChannel, MSG_INFO, "Please add HDC server's firewall ruler to allow udp incoming, udpport:%d",
DEFAULT_PORT);
HdcServer *ptrServer = (HdcServer *)clsServer;
ptrServer->clsTCPClt->FindLanDaemon();
@ -164,11 +164,11 @@ void HdcServerForClient::OrderFindTargets(HChannelPtr hChannelPtr)
di.connectKey = lst.front();
di.connType = CONN_TCP;
di.connStatus = STATUS_READY;
HDaemonInfoPtr pDi = (HDaemonInfoPtr)&di;
HDaemonInfo pDi = (HDaemonInfo)&di;
ptrServer->AdminDaemonMap(OP_ADD, STRING_EMPTY, pDi);
lst.pop_front();
}
EchoClient(hChannelPtr, MSG_INFO, "Broadcast find daemon, total:%d", count);
EchoClient(hChannel, MSG_INFO, "Broadcast find daemon, total:%d", count);
#ifdef UNIT_TEST
string bufString = std::to_string(count);
Base::WriteBinFile((UT_TMP_PATH + "/base-discover.result").c_str(), (uint8_t *)bufString.c_str(), bufString.size(),
@ -178,14 +178,14 @@ void HdcServerForClient::OrderFindTargets(HChannelPtr hChannelPtr)
void HdcServerForClient::OrderConnecTargetResult(uv_timer_t *req)
{
HChannelPtr hChannelPtr = (HChannelPtr)req->data;
HdcServerForClient *thisClass = (HdcServerForClient *)hChannelPtr->clsChannel;
HChannel hChannel = (HChannel)req->data;
HdcServerForClient *thisClass = (HdcServerForClient *)hChannel->clsChannel;
HdcServer *ptrServer = (HdcServer *)thisClass->clsServer;
bool bConnectOK = false;
bool bExitRepet = false;
HDaemonInfoPtr hdi = nullptr;
HDaemonInfo hdi = nullptr;
string sRet;
string target = std::string(hChannelPtr->bufStd + 2);
string target = std::string(hChannel->bufStd + 2);
if (target == "any") {
ptrServer->AdminDaemonMap(OP_GET_ANY, target, hdi);
} else {
@ -198,28 +198,28 @@ void HdcServerForClient::OrderConnecTargetResult(uv_timer_t *req)
if (bConnectOK) {
bExitRepet = true;
sRet = "Connect OK";
thisClass->EchoClient(hChannelPtr, MSG_OK, (char *)sRet.c_str());
thisClass->EchoClient(hChannel, MSG_OK, (char *)sRet.c_str());
break;
} else {
uint16_t *bRetryCount = (uint16_t *)hChannelPtr->bufStd;
uint16_t *bRetryCount = (uint16_t *)hChannel->bufStd;
++(*bRetryCount);
if (*bRetryCount > 500) {
// 5s
bExitRepet = true;
sRet = "Connect failed";
thisClass->EchoClient(hChannelPtr, MSG_FAIL, (char *)sRet.c_str());
thisClass->EchoClient(hChannel, MSG_FAIL, (char *)sRet.c_str());
break;
}
}
break;
}
if (bExitRepet) {
thisClass->FreeChannel(hChannelPtr->channelId);
thisClass->FreeChannel(hChannel->channelId);
Base::TryCloseHandle((const uv_handle_t *)req, Base::CloseTimerCallback);
}
}
bool HdcServerForClient::NewConnectTry(void *ptrServer, HChannelPtr hChannelPtr, const string &connectKey)
bool HdcServerForClient::NewConnectTry(void *ptrServer, HChannel hChannel, const string &connectKey)
{
#ifdef HDC_DEBUG
WRITE_LOG(LOG_ALL, "%s %s", __FUNCTION__, connectKey.c_str());
@ -227,55 +227,55 @@ bool HdcServerForClient::NewConnectTry(void *ptrServer, HChannelPtr hChannelPtr,
int childRet = ((HdcServer *)ptrServer)->CreateConnect(connectKey);
bool ret = false;
if (-1 == childRet) {
EchoClient(hChannelPtr, MSG_INFO, "Target is connected, repeat operation");
EchoClient(hChannel, MSG_INFO, "Target is connected, repeat operation");
} else if (-2 == childRet) {
EchoClient(hChannelPtr, MSG_FAIL, "CreateConnect failed");
EchoClient(hChannel, MSG_FAIL, "CreateConnect failed");
WRITE_LOG(LOG_FATAL, "CreateConnect failed");
} else {
Base::ZeroBuf(hChannelPtr->bufStd, 2);
childRet = snprintf_s(hChannelPtr->bufStd + 2, sizeof(hChannelPtr->bufStd) - 2, sizeof(hChannelPtr->bufStd) - 3, "%s",
Base::ZeroBuf(hChannel->bufStd, 2);
childRet = snprintf_s(hChannel->bufStd + 2, sizeof(hChannel->bufStd) - 2, sizeof(hChannel->bufStd) - 3, "%s",
(char *)connectKey.c_str());
if (childRet > 0) {
Base::TimerUvTask(loopMain, hChannelPtr, OrderConnecTargetResult, 10);
Base::TimerUvTask(loopMain, hChannel, OrderConnecTargetResult, 10);
ret = true;
}
}
return ret;
}
bool HdcServerForClient::CommandRemoveSession(HChannelPtr hChannelPtr, const char *connectKey)
bool HdcServerForClient::CommandRemoveSession(HChannel hChannel, const char *connectKey)
{
HdcServer *ptrServer = (HdcServer *)clsServer;
HDaemonInfoPtr hdiOld = nullptr;
HDaemonInfo hdiOld = nullptr;
((HdcServer *)ptrServer)->AdminDaemonMap(OP_QUERY, connectKey, hdiOld);
if (!hdiOld) {
EchoClient(hChannelPtr, MSG_FAIL, "No target available");
EchoClient(hChannel, MSG_FAIL, "No target available");
return false;
}
((HdcServer *)ptrServer)->FreeSession(hdiOld->hSessionPtr->sessionId);
((HdcServer *)ptrServer)->FreeSession(hdiOld->hSession->sessionId);
return true;
}
bool HdcServerForClient::CommandRemoveForward(const string &forwardKey)
{
HdcServer *ptrServer = (HdcServer *)clsServer;
HForwardInfoPtr hfi = nullptr;
HForwardInfo hfi = nullptr;
ptrServer->AdminForwardMap(OP_QUERY, forwardKey, hfi);
if (!hfi) {
return false;
}
HSessionPtr hSessionPtr = ptrServer->AdminSession(OP_QUERY, hfi->sessionId, nullptr);
if (!hSessionPtr) {
HSession hSession = ptrServer->AdminSession(OP_QUERY, hfi->sessionId, nullptr);
if (!hSession) {
return false;
}
ptrServer->ClearOwnTasks(hSessionPtr, hfi->channelId);
ptrServer->ClearOwnTasks(hSession, hfi->channelId);
FreeChannel(hfi->channelId);
hfi = nullptr;
ptrServer->AdminForwardMap(OP_REMOVE, forwardKey, hfi);
return true;
}
void HdcServerForClient::GetTargetList(HChannelPtr hChannelPtr, void *formatCommandInput)
void HdcServerForClient::GetTargetList(HChannel hChannel, void *formatCommandInput)
{
TranslateCommand::FormatCommand *formatCommand = (TranslateCommand::FormatCommand *)formatCommandInput;
HdcServer *ptrServer = (HdcServer *)clsServer;
@ -283,30 +283,30 @@ void HdcServerForClient::GetTargetList(HChannelPtr hChannelPtr, void *formatComm
if (formatCommand->parameters == "v") {
cmd = OP_GET_STRLIST_FULL;
}
HDaemonInfoPtr hdi = nullptr;
HDaemonInfo hdi = nullptr;
string sRet = ptrServer->AdminDaemonMap(cmd, STRING_EMPTY, hdi);
if (!sRet.length()) {
sRet = EMPTY_ECHO;
}
EchoClient(hChannelPtr, MSG_OK, (char *)sRet.c_str());
EchoClient(hChannel, MSG_OK, (char *)sRet.c_str());
#ifdef UNIT_TEST
Base::WriteBinFile((UT_TMP_PATH + "/base-list.result").c_str(), (uint8_t *)MESSAGE_SUCCESS.c_str(),
MESSAGE_SUCCESS.size(), true);
#endif
}
bool HdcServerForClient::GetAnyTarget(HChannelPtr hChannelPtr)
bool HdcServerForClient::GetAnyTarget(HChannel hChannel)
{
HdcServer *ptrServer = (HdcServer *)clsServer;
HDaemonInfoPtr hdi = nullptr;
HDaemonInfo hdi = nullptr;
ptrServer->AdminDaemonMap(OP_GET_ANY, STRING_EMPTY, hdi);
if (!hdi) {
EchoClient(hChannelPtr, MSG_FAIL, "No target available");
EchoClient(hChannel, MSG_FAIL, "No target available");
return false;
}
// can not use hdi->connectKey.This memory may be released to re-Malloc
string connectKey = hdi->connectKey;
bool ret = NewConnectTry(ptrServer, hChannelPtr, connectKey);
bool ret = NewConnectTry(ptrServer, hChannel, connectKey);
#ifdef UNIT_TEST
Base::WriteBinFile((UT_TMP_PATH + "/base-any.result").c_str(), (uint8_t *)MESSAGE_SUCCESS.c_str(),
MESSAGE_SUCCESS.size(), true);
@ -314,11 +314,11 @@ bool HdcServerForClient::GetAnyTarget(HChannelPtr hChannelPtr)
return ret;
}
bool HdcServerForClient::RemoveForward(HChannelPtr hChannelPtr, const char *parameterString)
bool HdcServerForClient::RemoveForward(HChannel hChannel, const char *parameterString)
{
HdcServer *ptrServer = (HdcServer *)clsServer;
if (parameterString == nullptr) { // remove all
HForwardInfoPtr hfi = nullptr; // dummy
HForwardInfo hfi = nullptr; // dummy
string echo = ptrServer->AdminForwardMap(OP_GET_STRLIST, "", hfi);
if (!echo.length()) {
return false;
@ -327,18 +327,18 @@ bool HdcServerForClient::RemoveForward(HChannelPtr hChannelPtr, const char *para
Base::SplitString(echo, string("\n"), filterStrings);
for (auto &&s : filterStrings) {
if (!CommandRemoveForward(s.c_str())) {
EchoClient(hChannelPtr, MSG_FAIL, "Remove forward ruler failed,ruler:%s", s.c_str());
EchoClient(hChannel, MSG_FAIL, "Remove forward ruler failed,ruler:%s", s.c_str());
}
}
} else { // remove single
if (!CommandRemoveForward(parameterString)) {
EchoClient(hChannelPtr, MSG_FAIL, "Remove forward ruler failed,ruler:%s", parameterString);
EchoClient(hChannel, MSG_FAIL, "Remove forward ruler failed,ruler:%s", parameterString);
}
}
return true;
}
bool HdcServerForClient::DoCommandLocal(HChannelPtr hChannelPtr, void *formatCommandInput)
bool HdcServerForClient::DoCommandLocal(HChannel hChannel, void *formatCommandInput)
{
TranslateCommand::FormatCommand *formatCommand = (TranslateCommand::FormatCommand *)formatCommandInput;
HdcServer *ptrServer = (HdcServer *)clsServer;
@ -347,12 +347,12 @@ bool HdcServerForClient::DoCommandLocal(HChannelPtr hChannelPtr, void *formatCom
// Main thread command, direct Listen main thread
switch (formatCommand->cmdFlag) {
case CMD_KERNEL_TARGET_DISCOVER: {
OrderFindTargets(hChannelPtr);
OrderFindTargets(hChannel);
ret = false;
break;
}
case CMD_KERNEL_TARGET_LIST: {
GetTargetList(hChannelPtr, formatCommandInput);
GetTargetList(hChannel, formatCommandInput);
ret = false;
break;
}
@ -360,18 +360,18 @@ bool HdcServerForClient::DoCommandLocal(HChannelPtr hChannelPtr, void *formatCom
#ifdef HDC_DEBUG
WRITE_LOG(LOG_DEBUG, "%s CMD_KERNEL_TARGET_ANY %s", __FUNCTION__, parameterString);
#endif
ret = GetAnyTarget(hChannelPtr);
ret = GetAnyTarget(hChannel);
break;
}
case CMD_KERNEL_TARGET_CONNECT: {
#ifdef HDC_DEBUG
WRITE_LOG(LOG_DEBUG, "%s CMD_KERNEL_TARGET_CONNECT %s", __FUNCTION__, parameterString);
#endif
ret = NewConnectTry(ptrServer, hChannelPtr, parameterString);
ret = NewConnectTry(ptrServer, hChannel, parameterString);
break;
}
case CMD_KERNEL_TARGET_DISCONNECT: {
CommandRemoveSession(hChannelPtr, parameterString);
CommandRemoveSession(hChannel, parameterString);
break;
}
case CMD_KERNEL_SERVER_KILL: {
@ -382,33 +382,33 @@ bool HdcServerForClient::DoCommandLocal(HChannelPtr hChannelPtr, void *formatCom
}
// task will be global taskTherefore, it can only be controlled in the global session.
case CMD_FORWARD_LIST: {
HForwardInfoPtr hfi = nullptr; // dummy
HForwardInfo hfi = nullptr; // dummy
string echo = ptrServer->AdminForwardMap(OP_GET_STRLIST_FULL, "", hfi);
if (!echo.length()) {
echo = EMPTY_ECHO;
}
EchoClient(hChannelPtr, MSG_OK, (char *)echo.c_str());
EchoClient(hChannel, MSG_OK, (char *)echo.c_str());
break;
}
case CMD_FORWARD_REMOVE: {
RemoveForward(hChannelPtr, parameterString);
RemoveForward(hChannel, parameterString);
break;
}
case CMD_KERNEL_ENABLE_KEEPALIVE: {
// just use for 'list targets' now
hChannelPtr->keepAlive = true;
hChannel->keepAlive = true;
ret = true;
break;
}
default: {
EchoClient(hChannelPtr, MSG_FAIL, "ExecuteCommand need connect-key?");
EchoClient(hChannel, MSG_FAIL, "ExecuteCommand need connect-key?");
break;
}
}
return ret;
}
bool HdcServerForClient::TaskCommand(HChannelPtr hChannelPtr, void *formatCommandInput)
bool HdcServerForClient::TaskCommand(HChannel hChannel, void *formatCommandInput)
{
TranslateCommand::FormatCommand *formatCommand = (TranslateCommand::FormatCommand *)formatCommandInput;
HdcServer *ptrServer = (HdcServer *)clsServer;
@ -436,19 +436,19 @@ bool HdcServerForClient::TaskCommand(HChannelPtr hChannelPtr, void *formatComman
}
uint8_t *payload = reinterpret_cast<uint8_t *>(const_cast<char *>(formatCommand->parameters.c_str())) + sizeCmdFlag;
if (!strncmp(formatCommand->parameters.c_str(), cmdFlag.c_str(), sizeCmdFlag)) { // local do
HSessionPtr hSessionPtr = FindAliveSession(hChannelPtr->targetSessionId);
if (!hSessionPtr) {
HSession hSession = FindAliveSession(hChannel->targetSessionId);
if (!hSession) {
return false;
}
ptrServer->DispatchTaskData(hSessionPtr, hChannelPtr->channelId, formatCommand->cmdFlag, payload,
ptrServer->DispatchTaskData(hSession, hChannel->channelId, formatCommand->cmdFlag, payload,
sizeSend - sizeCmdFlag);
} else { // Send to Daemon-side to do
SendToDaemon(hChannelPtr, formatCommand->cmdFlag, payload, sizeSend - sizeCmdFlag);
SendToDaemon(hChannel, formatCommand->cmdFlag, payload, sizeSend - sizeCmdFlag);
}
return true;
}
bool HdcServerForClient::DoCommandRemote(HChannelPtr hChannelPtr, void *formatCommandInput)
bool HdcServerForClient::DoCommandRemote(HChannel hChannel, void *formatCommandInput)
{
TranslateCommand::FormatCommand *formatCommand = (TranslateCommand::FormatCommand *)formatCommandInput;
bool ret = false;
@ -467,14 +467,14 @@ bool HdcServerForClient::DoCommandRemote(HChannelPtr hChannelPtr, void *formatCo
case CMD_UNITY_ROOTRUN:
case CMD_JDWP_TRACK:
case CMD_JDWP_LIST: {
if (!SendToDaemon(hChannelPtr, formatCommand->cmdFlag,
if (!SendToDaemon(hChannel, formatCommand->cmdFlag,
reinterpret_cast<uint8_t *>(const_cast<char *>(formatCommand->parameters.c_str())),
sizeSend)) {
break;
}
ret = true;
if (CMD_SHELL_INIT == formatCommand->cmdFlag) {
hChannelPtr->interactiveShellMode = true;
hChannel->interactiveShellMode = true;
}
break;
}
@ -484,7 +484,7 @@ bool HdcServerForClient::DoCommandRemote(HChannelPtr hChannelPtr, void *formatCo
case CMD_APP_UNINSTALL:
case CMD_UNITY_BUGREPORT_INIT:
case CMD_APP_SIDELOAD: {
TaskCommand(hChannelPtr, formatCommandInput);
TaskCommand(hChannel, formatCommandInput);
ret = true;
break;
}
@ -492,124 +492,124 @@ bool HdcServerForClient::DoCommandRemote(HChannelPtr hChannelPtr, void *formatCo
break;
}
if (!ret) {
EchoClient(hChannelPtr, MSG_FAIL, "Failed to communicate with daemon");
EchoClient(hChannel, MSG_FAIL, "Failed to communicate with daemon");
}
return ret;
}
// Do not specify Target's operations no longer need to put it in the thread.
bool HdcServerForClient::DoCommand(HChannelPtr hChannelPtr, void *formatCommandInput)
bool HdcServerForClient::DoCommand(HChannel hChannel, void *formatCommandInput)
{
bool ret = false;
if (!hChannelPtr->hChildWorkTCP.loop) {
if (!hChannel->hChildWorkTCP.loop) {
// Main thread command, direct Listen main thread
ret = DoCommandLocal(hChannelPtr, formatCommandInput);
ret = DoCommandLocal(hChannel, formatCommandInput);
} else { // CONNECT DAEMON's work thread command, non-primary thread
ret = DoCommandRemote(hChannelPtr, formatCommandInput);
ret = DoCommandRemote(hChannel, formatCommandInput);
}
return ret;
}
// just call from BindChannelToSession
HSessionPtr HdcServerForClient::FindAliveSessionFromDaemonMap(const HChannelPtr hChannelPtr)
HSession HdcServerForClient::FindAliveSessionFromDaemonMap(const HChannel hChannel)
{
HSessionPtr hSessionPtr = nullptr;
HDaemonInfoPtr hdi = nullptr;
HSession hSession = nullptr;
HDaemonInfo hdi = nullptr;
HdcServer *ptrServer = (HdcServer *)clsServer;
ptrServer->AdminDaemonMap(OP_QUERY, hChannelPtr->connectKey, hdi);
ptrServer->AdminDaemonMap(OP_QUERY, hChannel->connectKey, hdi);
if (!hdi) {
EchoClient(hChannelPtr, MSG_FAIL, "Not match target founded, check connect-key please");
EchoClient(hChannel, MSG_FAIL, "Not match target founded, check connect-key please");
return nullptr;
}
if (hdi->connStatus != STATUS_CONNECTED) {
EchoClient(hChannelPtr, MSG_FAIL, "Device not founded or connected");
EchoClient(hChannel, MSG_FAIL, "Device not founded or connected");
return nullptr;
}
if (hdi->hSessionPtr->isDead) {
EchoClient(hChannelPtr, MSG_FAIL, "Bind tartget session is dead");
if (hdi->hSession->isDead) {
EchoClient(hChannel, MSG_FAIL, "Bind tartget session is dead");
return nullptr;
}
hSessionPtr = (HSessionPtr)hdi->hSessionPtr;
return hSessionPtr;
hSession = (HSession)hdi->hSession;
return hSession;
}
int HdcServerForClient::BindChannelToSession(HChannelPtr hChannelPtr, uint8_t *bufPtr, const int bytesIO)
int HdcServerForClient::BindChannelToSession(HChannel hChannel, uint8_t *bufPtr, const int bytesIO)
{
HSessionPtr hSessionPtr = nullptr;
if ((hSessionPtr = FindAliveSessionFromDaemonMap(hChannelPtr)) == nullptr) {
HSession hSession = nullptr;
if ((hSession = FindAliveSessionFromDaemonMap(hChannel)) == nullptr) {
return ERR_SESSION_NOFOUND;
}
bool isClosing = uv_is_closing((const uv_handle_t *)&hChannelPtr->hWorkTCP);
if (!isClosing && (hChannelPtr->fdChildWorkTCP = Base::DuplicateUvSocket(&hChannelPtr->hWorkTCP)) < 0) {
WRITE_LOG(LOG_FATAL, "Duplicate socket failed, cid:%d", hChannelPtr->channelId);
bool isClosing = uv_is_closing((const uv_handle_t *)&hChannel->hWorkTCP);
if (!isClosing && (hChannel->fdChildWorkTCP = Base::DuplicateUvSocket(&hChannel->hWorkTCP)) < 0) {
WRITE_LOG(LOG_FATAL, "Duplicate socket failed, cid:%d", hChannel->channelId);
return ERR_SOCKET_DUPLICATE;
}
uv_close_cb funcWorkTcpClose = [](uv_handle_t *handle) -> void {
HChannelPtr hChannelPtr = (HChannelPtr)handle->data;
--hChannelPtr->ref;
HChannel hChannel = (HChannel)handle->data;
--hChannel->ref;
};
++hChannelPtr->ref;
++hChannel->ref;
if (!isClosing) {
uv_close((uv_handle_t *)&hChannelPtr->hWorkTCP, funcWorkTcpClose);
uv_close((uv_handle_t *)&hChannel->hWorkTCP, funcWorkTcpClose);
}
Base::DoNextLoop(loopMain, hChannelPtr, [](const uint8_t flag, string &msg, const void *data) {
Base::DoNextLoop(loopMain, hChannel, [](const uint8_t flag, string &msg, const void *data) {
// Thread message can avoid using thread lock and improve program efficiency
// If not next loop call, ReadStream will thread conflict
HChannelPtr hChannelPtr = (HChannelPtr)data;
auto thisClass = (HdcServerForClient *)hChannelPtr->clsChannel;
HSessionPtr hSessionPtr = nullptr;
if ((hSessionPtr = thisClass->FindAliveSessionFromDaemonMap(hChannelPtr)) == nullptr) {
HChannel hChannel = (HChannel)data;
auto thisClass = (HdcServerForClient *)hChannel->clsChannel;
HSession hSession = nullptr;
if ((hSession = thisClass->FindAliveSessionFromDaemonMap(hChannel)) == nullptr) {
return;
}
auto ctrl = HdcSessionBase::BuildCtrlString(SP_ATTACH_CHANNEL, hChannelPtr->channelId, nullptr, 0);
Base::SendToStream((uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
auto ctrl = HdcSessionBase::BuildCtrlString(SP_ATTACH_CHANNEL, hChannel->channelId, nullptr, 0);
Base::SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrl.data(), ctrl.size());
});
return RET_SUCCESS;
}
bool HdcServerForClient::CheckAutoFillTarget(HChannelPtr hChannelPtr)
bool HdcServerForClient::CheckAutoFillTarget(HChannel hChannel)
{
HdcServer *ptrServer = (HdcServer *)clsServer;
if (!hChannelPtr->connectKey.size()) {
if (!hChannel->connectKey.size()) {
return false; // Operation of non-bound destination of scanning
}
if (hChannelPtr->connectKey == CMDSTR_CONNECT_ANY) {
HDaemonInfoPtr hdiOld = nullptr;
if (hChannel->connectKey == CMDSTR_CONNECT_ANY) {
HDaemonInfo hdiOld = nullptr;
ptrServer->AdminDaemonMap(OP_GET_ONLY, "", hdiOld);
if (!hdiOld) {
return false;
}
hChannelPtr->connectKey = hdiOld->connectKey;
hChannel->connectKey = hdiOld->connectKey;
return true;
}
return true;
}
int HdcServerForClient::ChannelHandShake(HChannelPtr hChannelPtr, uint8_t *bufPtr, const int bytesIO)
int HdcServerForClient::ChannelHandShake(HChannel hChannel, uint8_t *bufPtr, const int bytesIO)
{
vector<uint8_t> rebuildHandshake;
rebuildHandshake.insert(rebuildHandshake.end(), bufPtr, bufPtr + bytesIO);
rebuildHandshake.push_back(0x00);
struct ChannelHandShake *handShake = reinterpret_cast<struct ChannelHandShake *>(rebuildHandshake.data());
if (strncmp(handShake->banner, HANDSHAKE_MESSAGE.c_str(), HANDSHAKE_MESSAGE.size())) {
hChannelPtr->availTailIndex = 0;
hChannel->availTailIndex = 0;
WRITE_LOG(LOG_DEBUG, "Channel Hello failed");
return ERR_HANDSHAKE_NOTMATCH;
}
if (strlen(handShake->connectKey) > sizeof(handShake->connectKey)) {
hChannelPtr->availTailIndex = 0;
hChannel->availTailIndex = 0;
WRITE_LOG(LOG_DEBUG, "Connectkey's size incorrect");
return ERR_HANDSHAKE_CONNECTKEY_FAILED;
}
// channel handshake step3
WRITE_LOG(LOG_DEBUG, "ServerForClient channel handshake finished");
hChannelPtr->connectKey = handShake->connectKey;
hChannelPtr->handshakeOK = true;
if (!CheckAutoFillTarget(hChannelPtr)) {
hChannel->connectKey = handShake->connectKey;
hChannel->handshakeOK = true;
if (!CheckAutoFillTarget(hChannel)) {
return 0;
}
// channel handshake stBindChannelToSession
if (BindChannelToSession(hChannelPtr, nullptr, 0)) {
hChannelPtr->availTailIndex = 0;
if (BindChannelToSession(hChannel, nullptr, 0)) {
hChannel->availTailIndex = 0;
WRITE_LOG(LOG_FATAL, "BindChannelToSession failed");
return ERR_GENERIC;
}
@ -617,21 +617,21 @@ int HdcServerForClient::ChannelHandShake(HChannelPtr hChannelPtr, uint8_t *bufPt
}
// Here is Server to get data, the source is the SERVER's ChildWork to send data
int HdcServerForClient::ReadChannel(HChannelPtr hChannelPtr, uint8_t *bufPtr, const int bytesIO)
int HdcServerForClient::ReadChannel(HChannel hChannel, uint8_t *bufPtr, const int bytesIO)
{
int ret = 0;
if (!hChannelPtr->handshakeOK) {
return ChannelHandShake(hChannelPtr, bufPtr, bytesIO);
if (!hChannel->handshakeOK) {
return ChannelHandShake(hChannel, bufPtr, bytesIO);
}
struct TranslateCommand::FormatCommand formatCommand = { 0 };
if (!hChannelPtr->interactiveShellMode) {
if (!hChannel->interactiveShellMode) {
string retEcho = String2FormatCommand((char *)bufPtr, bytesIO, &formatCommand);
if (retEcho.length()) {
if (!strcmp((char *)bufPtr, CMDSTR_SOFTWARE_HELP.c_str())
|| !strcmp((char *)bufPtr, CMDSTR_SOFTWARE_VERSION.c_str())) {
EchoClient(hChannelPtr, MSG_OK, retEcho.c_str());
EchoClient(hChannel, MSG_OK, retEcho.c_str());
} else {
EchoClient(hChannelPtr, MSG_FAIL, retEcho.c_str());
EchoClient(hChannel, MSG_FAIL, retEcho.c_str());
}
}
WRITE_LOG(LOG_DEBUG, "ReadChannel command: %s", bufPtr);
@ -644,7 +644,7 @@ int HdcServerForClient::ReadChannel(HChannelPtr hChannelPtr, uint8_t *bufPtr, co
formatCommand.cmdFlag = CMD_SHELL_DATA;
}
if (!DoCommand(hChannelPtr, &formatCommand)) {
if (!DoCommand(hChannel, &formatCommand)) {
return -3; // -3: error or want close
}
ret = bytesIO;
@ -652,23 +652,23 @@ int HdcServerForClient::ReadChannel(HChannelPtr hChannelPtr, uint8_t *bufPtr, co
};
// avoid session dead
HSessionPtr HdcServerForClient::FindAliveSession(uint32_t sessionId)
HSession HdcServerForClient::FindAliveSession(uint32_t sessionId)
{
HdcServer *ptrServer = (HdcServer *)clsServer;
HSessionPtr hSessionPtr = ptrServer->AdminSession(OP_QUERY, sessionId, nullptr);
if (!hSessionPtr || hSessionPtr->isDead) {
HSession hSession = ptrServer->AdminSession(OP_QUERY, sessionId, nullptr);
if (!hSession || hSession->isDead) {
return nullptr;
} else {
return hSessionPtr;
return hSession;
}
}
bool HdcServerForClient::ChannelSendSessionCtrlMsg(vector<uint8_t> &ctrlMsg, uint32_t sessionId)
{
HSessionPtr hSessionPtr = FindAliveSession(sessionId);
if (!hSessionPtr) {
HSession hSession = FindAliveSession(sessionId);
if (!hSession) {
return false;
}
return Base::SendToStream((uv_stream_t *)&hSessionPtr->ctrlPipe[STREAM_MAIN], ctrlMsg.data(), ctrlMsg.size()) > 0;
return Base::SendToStream((uv_stream_t *)&hSession->ctrlPipe[STREAM_MAIN], ctrlMsg.data(), ctrlMsg.size()) > 0;
}
} // namespace Hdc

View File

@ -23,8 +23,8 @@ public:
HdcServerForClient(const bool serverOrClient, const string &addrString, void *pClsServer, uv_loop_t *loopMainIn);
virtual ~HdcServerForClient();
int Initial();
void EchoClient(HChannelPtr hChannel, MessageLevel level, const char *msg, ...);
void EchoClientRaw(const HChannelPtr hChannel, uint8_t *payload, const int payloadSize);
void EchoClient(HChannel hChannel, MessageLevel level, const char *msg, ...);
void EchoClientRaw(const HChannel hChannel, uint8_t *payload, const int payloadSize);
uint16_t GetTCPListenPort();
void Stop();
@ -32,26 +32,26 @@ protected:
private:
static void AcceptClient(uv_stream_t *server, int status);
void SetTCPListen();
int ReadChannel(HChannelPtr hChannel, uint8_t *bufPtr, const int bytesIO);
bool DoCommand(HChannelPtr hChannel, void *formatCommandInput);
void OrderFindTargets(HChannelPtr hChannel);
bool NewConnectTry(void *ptrServer, HChannelPtr hChannel, const string &connectKey);
int ReadChannel(HChannel hChannel, uint8_t *bufPtr, const int bytesIO);
bool DoCommand(HChannel hChannel, void *formatCommandInput);
void OrderFindTargets(HChannel hChannel);
bool NewConnectTry(void *ptrServer, HChannel hChannel, const string &connectKey);
static void OrderConnecTargetResult(uv_timer_t *req);
bool SendToDaemon(HChannelPtr hChannel, const uint16_t commandFlag, uint8_t *bufPtr, const int bufSize);
int BindChannelToSession(HChannelPtr hChannel, uint8_t *bufPtr, const int bytesIO);
bool CheckAutoFillTarget(HChannelPtr hChannel);
bool CommandRemoveSession(HChannelPtr hChannel, const char *connectKey);
bool SendToDaemon(HChannel hChannel, const uint16_t commandFlag, uint8_t *bufPtr, const int bufSize);
int BindChannelToSession(HChannel hChannel, uint8_t *bufPtr, const int bytesIO);
bool CheckAutoFillTarget(HChannel hChannel);
bool CommandRemoveSession(HChannel hChannel, const char *connectKey);
bool CommandRemoveForward(const string &forwardKey);
bool DoCommandLocal(HChannelPtr hChannel, void *formatCommandInput);
bool DoCommandRemote(HChannelPtr hChannel, void *formatCommandInput);
void GetTargetList(HChannelPtr hChannel, void *formatCommandInput);
bool GetAnyTarget(HChannelPtr hChannel);
bool RemoveForward(HChannelPtr hChannel, const char *parameterString);
bool TaskCommand(HChannelPtr hChannel, void *formatCommandInput);
int ChannelHandShake(HChannelPtr hChannel, uint8_t *bufPtr, const int bytesIO);
bool DoCommandLocal(HChannel hChannel, void *formatCommandInput);
bool DoCommandRemote(HChannel hChannel, void *formatCommandInput);
void GetTargetList(HChannel hChannel, void *formatCommandInput);
bool GetAnyTarget(HChannel hChannel);
bool RemoveForward(HChannel hChannel, const char *parameterString);
bool TaskCommand(HChannel hChannel, void *formatCommandInput);
int ChannelHandShake(HChannel hChannel, uint8_t *bufPtr, const int bytesIO);
bool ChannelSendSessionCtrlMsg(vector<uint8_t> &ctrlMsg, uint32_t sessionId);
HSessionPtr FindAliveSession(uint32_t sessionId);
HSessionPtr FindAliveSessionFromDaemonMap(const HChannelPtr hChannel);
HSession FindAliveSession(uint32_t sessionId);
HSession FindAliveSessionFromDaemonMap(const HChannel hChannel);
uv_tcp_t tcpListen;
void *clsServer;

View File

@ -58,7 +58,7 @@ HWTEST_F(HdcJdwpTest, TestCreateJdwpTracker, TestSize.Level1)
ASSERT_NE(mJdwpTest, nullptr) << "Instanse HdcJdwp fail.";
ASSERT_EQ(mJdwpTest->Initial(), 0) << "Instanse HdcJdwp fail.";
ASSERT_EQ(mJdwpTest->CreateJdwpTracker(nullptr), 0) << "CreateJdwpTracker nullptr fail.";
HTaskInfoPtr hTaskInfo = new TaskInformation();
HTaskInfo hTaskInfo = new TaskInformation();
HdcSessionBase HdcSessionTest(false);
hTaskInfo->ownerSessionClass = &HdcSessionTest;
ASSERT_EQ(mJdwpTest->CreateJdwpTracker(hTaskInfo), 1) << "CreateJdwpTracker valid param fail.";

View File

@ -39,11 +39,11 @@ public:
std::default_random_engine rnd;
class MockHdcDaemon : public HdcDaemon {
MockHdcDaemon() : HdcDaemon(false) {};
MOCK_METHOD4(MallocSession, HSessionPtr(bool, const ConnType, void *, uint32_t));
MOCK_METHOD4(MallocSession, HSession(bool, const ConnType, void *, uint32_t));
MOCK_METHOD4(PushAsyncMessage,
void(const uint32_t, const uint8_t, const void *, const int));
MOCK_METHOD1(FreeSession, void(const uint32_t));
MOCK_METHOD3(AdminSession, HSessionPtr(const uint8_t, const uint32_t, HSessionPtr));
MOCK_METHOD3(AdminSession, HSession(const uint8_t, const uint32_t, HSession));
} mockDaemon;
const std::string nullDevPath = "/dev/null";
@ -68,11 +68,11 @@ public:
MOCK_METHOD0(WatcherTimerCallBack, void(void));
MOCK_METHOD0(DeamonReadThread, void(void));
MOCK_METHOD0(DeamonWriteThread, void(void));
MOCK_METHOD1(IsSendReady, bool(HSessionPtr));
MOCK_METHOD1(PrepareNewSession, HSessionPtr(uint32_t));
MOCK_METHOD2(PackageProcess, size_t(vector<uint8_t> &data, HSessionPtr hSessionPtr));
MOCK_METHOD3(SendUARTDev, size_t(HSessionPtr, uint8_t *, const size_t));
MOCK_METHOD3(UartSendToHdcStream, bool(HSessionPtr, uint8_t *, size_t));
MOCK_METHOD1(IsSendReady, bool(HSession));
MOCK_METHOD1(PrepareNewSession, HSession(uint32_t));
MOCK_METHOD2(PackageProcess, size_t(vector<uint8_t> &data, HSession hSession));
MOCK_METHOD3(SendUARTDev, size_t(HSession, uint8_t *, const size_t));
MOCK_METHOD3(UartSendToHdcStream, bool(HSession, uint8_t *, size_t));
MOCK_METHOD4(ValidateUartPacket,
RetErrCode(vector<uint8_t> &, uint32_t &, uint32_t &, size_t &));
} mockDaemonUART;
@ -351,8 +351,8 @@ HWTEST_F(HdcDaemonUARTTest, LoopUARTWrite, TestSize.Level1)
*/
HWTEST_F(HdcDaemonUARTTest, IsSendReady, TestSize.Level1)
{
ON_CALL(mockDaemonUART, IsSendReady).WillByDefault([&](HSessionPtr hSessionPtr) {
return mockDaemonUART.HdcDaemonUART::IsSendReady(hSessionPtr);
ON_CALL(mockDaemonUART, IsSendReady).WillByDefault([&](HSession hSession) {
return mockDaemonUART.HdcDaemonUART::IsSendReady(hSession);
});
EXPECT_CALL(mockDaemonUART, IsSendReady).Times(AtLeast(1));

View File

@ -42,11 +42,11 @@ public:
const std::string nullDevPath = "/dev/null";
class MockHdcServer : public HdcServer {
MockHdcServer() : HdcServer(true) {};
MOCK_METHOD3(AdminDaemonMap, string(uint8_t, const string &, HDaemonInfoPtr &));
MOCK_METHOD3(AdminDaemonMap, string(uint8_t, const string &, HDaemonInfo &));
MOCK_METHOD1(EnumUARTDeviceRegister, void(UartKickoutZombie));
MOCK_METHOD4(MallocSession, HSessionPtr(bool, const ConnType, void *, uint32_t));
MOCK_METHOD4(MallocSession, HSession(bool, const ConnType, void *, uint32_t));
MOCK_METHOD1(FreeSession, void(const uint32_t));
MOCK_METHOD3(AdminSession, HSessionPtr(const uint8_t, const uint32_t, HSessionPtr));
MOCK_METHOD3(AdminSession, HSession(const uint8_t, const uint32_t, HSession));
MOCK_METHOD2(EchoToClientsForSession, void(uint32_t, const string &));
} mockServer;
@ -69,24 +69,24 @@ public:
}
MOCK_METHOD0(StartupUARTWork, RetErrCode());
MOCK_METHOD0(UartWriteThread, void());
MOCK_METHOD1(CloseSerialPort, void(const HUARTPtr));
MOCK_METHOD1(CloseSerialPort, void(const HUART));
MOCK_METHOD1(EnumSerialPort, bool(bool &));
MOCK_METHOD0(Stop, void());
MOCK_METHOD3(UpdateUARTDaemonInfo, void(const std::string &, HSessionPtr, ConnStatus));
MOCK_METHOD1(StartUartReadThread, bool(HSessionPtr));
MOCK_METHOD3(UpdateUARTDaemonInfo, void(const std::string &, HSession, ConnStatus));
MOCK_METHOD1(StartUartReadThread, bool(HSession));
MOCK_METHOD0(StartUartSendThread, bool());
MOCK_METHOD0(WatchUartDevPlugin, void());
MOCK_METHOD1(OpenSerialPort, int(const std::string &));
MOCK_METHOD1(UartReadThread, void(HSessionPtr));
MOCK_METHOD3(SendUARTRaw, bool(HSessionPtr, uint8_t *, const size_t));
MOCK_METHOD1(UartReadThread, void(HSession));
MOCK_METHOD3(SendUARTRaw, bool(HSession, uint8_t *, const size_t));
MOCK_METHOD3(RequestSendPackage, void(uint8_t *, const size_t, bool));
MOCK_METHOD1(UartSendThread, void(HSessionPtr));
MOCK_METHOD1(UartSendThread, void(HSession));
MOCK_METHOD0(SendPkgInUARTOutMap, void());
MOCK_METHOD1(IsDeviceOpened, bool(const HdcUART &));
MOCK_METHOD3(ReadUartDev, ssize_t(std::vector<uint8_t> &, size_t, HdcUART &));
MOCK_METHOD1(NeedStop, bool(const HSessionPtr));
MOCK_METHOD2(PackageProcess, size_t(vector<uint8_t> &, HSessionPtr hSessionPtr));
MOCK_METHOD1(OnTransferError, void(const HSessionPtr));
MOCK_METHOD1(NeedStop, bool(const HSession));
MOCK_METHOD2(PackageProcess, size_t(vector<uint8_t> &, HSession hSession));
MOCK_METHOD1(OnTransferError, void(const HSession));
MOCK_METHOD1(ClearUARTOutMap, void(uint32_t));
} mockHostUART;
@ -372,8 +372,8 @@ HWTEST_F(HdcHostUARTTest, UpdateUARTDaemonInfo, TestSize.Level1)
{
EXPECT_CALL(mockHostUART, UpdateUARTDaemonInfo)
.WillRepeatedly(
[&](const std::string &connectKey, HSessionPtr hSessionPtr, ConnStatus connStatus) {
mockHostUART.HdcHostUART::UpdateUARTDaemonInfo(connectKey, hSessionPtr, connStatus);
[&](const std::string &connectKey, HSession hSession, ConnStatus connStatus) {
mockHostUART.HdcHostUART::UpdateUARTDaemonInfo(connectKey, hSession, connStatus);
});
// case 1 STATUS_UNKNOW
@ -408,8 +408,8 @@ HWTEST_F(HdcHostUARTTest, UpdateUARTDaemonInfo, TestSize.Level1)
*/
HWTEST_F(HdcHostUARTTest, StartUartReadThread, TestSize.Level1)
{
EXPECT_CALL(mockHostUART, StartUartReadThread).WillOnce(Invoke([&](HSessionPtr hSessionPtr) {
return mockHostUART.HdcHostUART::StartUartReadThread(hSessionPtr);
EXPECT_CALL(mockHostUART, StartUartReadThread).WillOnce(Invoke([&](HSession hSession) {
return mockHostUART.HdcHostUART::StartUartReadThread(hSession);
}));
EXPECT_CALL(mockHostUART, UartReadThread(&mySession)).Times(1);
@ -563,8 +563,8 @@ HWTEST_F(HdcHostUARTTest, StartUartSendThread, TestSize.Level1)
*/
HWTEST_F(HdcHostUARTTest, NeedStop, TestSize.Level1)
{
EXPECT_CALL(mockHostUART, NeedStop).WillRepeatedly([&](const HSessionPtr hSessionPtr) {
return mockHostUART.HdcHostUART::NeedStop(hSessionPtr);
EXPECT_CALL(mockHostUART, NeedStop).WillRepeatedly([&](const HSession hSession) {
return mockHostUART.HdcHostUART::NeedStop(hSession);
});
mockHostUART.uartOpened = true;
mySession.isDead = false;
@ -644,8 +644,8 @@ HWTEST_F(HdcHostUARTTest, UartWriteThread, TestSize.Level1)
*/
HWTEST_F(HdcHostUARTTest, UartReadThread, TestSize.Level1)
{
EXPECT_CALL(mockHostUART, UartReadThread).WillRepeatedly(Invoke([&](HSessionPtr hSessionPtr) {
return mockHostUART.HdcHostUART::UartReadThread(hSessionPtr);
EXPECT_CALL(mockHostUART, UartReadThread).WillRepeatedly(Invoke([&](HSession hSession) {
return mockHostUART.HdcHostUART::UartReadThread(hSession);
}));
// case 1 need stop
@ -815,7 +815,7 @@ HWTEST_F(HdcHostUARTTest, StopSession, TestSize.Level1)
*/
HWTEST_F(HdcHostUARTTest, OnTransferError, TestSize.Level1)
{
EXPECT_CALL(mockHostUART, OnTransferError).WillRepeatedly(Invoke([&](const HSessionPtr session) {
EXPECT_CALL(mockHostUART, OnTransferError).WillRepeatedly(Invoke([&](const HSession session) {
return mockHostUART.HdcHostUART::OnTransferError(session);
}));
mockHostUART.OnTransferError(nullptr);

View File

@ -64,14 +64,14 @@ public:
class MockHdcUARTBase : public HdcUARTBase {
public:
std::vector<uint8_t> expectRawData;
MOCK_METHOD2(SendUartSoftReset, void(HSessionPtr, uint32_t));
MOCK_METHOD2(SendUartSoftReset, void(HSession, uint32_t));
MOCK_METHOD1(ResetOldSession, void(uint32_t));
MOCK_METHOD3(RequestSendPackage, void(uint8_t *, const size_t, bool));
MOCK_METHOD1(ProcessResponsePackage, void(const UartHead &));
MOCK_METHOD3(ResponseUartTrans, void(uint32_t, uint32_t, UartProtocolOption));
MOCK_METHOD3(UartToHdcProtocol, int(uv_stream_t *, uint8_t *, int));
MOCK_METHOD1(OnTransferError, void(const HSessionPtr));
MOCK_METHOD2(GetSession, HSessionPtr(uint32_t, bool));
MOCK_METHOD1(OnTransferError, void(const HSession));
MOCK_METHOD2(GetSession, HSession(uint32_t, bool));
MOCK_METHOD1(ClearUARTOutMap, void(uint32_t));
MockHdcUARTBase(HdcSessionBase &mockSessionBaseIn, MockBaseInterface &interfaceIn)
@ -183,12 +183,12 @@ bool HdcUARTBaseTest::MakeData(std::vector<uint8_t> &data, UartHead &head)
*/
HWTEST_F(HdcUARTBaseTest, SendUARTRaw, TestSize.Level1)
{
HSessionPtr hSessionPtr = nullptr;
HSession hSession = nullptr;
unsigned char dummyData[] = "1234567980";
uint8_t *dummyPtr = static_cast<unsigned char *>(&dummyData[0]);
int dummySize = sizeof(dummyData);
EXPECT_CALL(mockUARTBase, GetSession).Times(1);
EXPECT_EQ(mockUARTBase.SendUARTRaw(hSessionPtr, dummyPtr, dummySize), 0);
EXPECT_EQ(mockUARTBase.SendUARTRaw(hSession, dummyPtr, dummySize), 0);
}
/*
@ -214,13 +214,13 @@ HWTEST_F(HdcUARTBaseTest, ResetOldSession, TestSize.Level1)
HWTEST_F(HdcUARTBaseTest, SendUartSoftReset, TestSize.Level1)
{
EXPECT_CALL(mockUARTBase, SendUartSoftReset)
.WillRepeatedly([&](HSessionPtr hUART, uint32_t sessionId) {
.WillRepeatedly([&](HSession hUART, uint32_t sessionId) {
mockUARTBase.HdcUARTBase::SendUartSoftReset(hUART, sessionId);
});
HSessionPtr hSessionPtr = nullptr;
HSession hSession = nullptr;
uint32_t sessionId = 1234567980;
EXPECT_CALL(mockUARTBase, SendUartSoftReset(hSessionPtr, sessionId)).Times(1);
mockUARTBase.SendUartSoftReset(hSessionPtr, sessionId);
EXPECT_CALL(mockUARTBase, SendUartSoftReset(hSession, sessionId)).Times(1);
mockUARTBase.SendUartSoftReset(hSession, sessionId);
}
/*
@ -454,7 +454,7 @@ HWTEST_F(HdcUARTBaseTest, ReadDataFromUARTStream, TestSize.Level1)
ssize_t dummySize = sizeof(dummyArray);
class MockHdcSessionBase : public HdcSessionBase {
public:
MOCK_METHOD3(FetchIOBuf, int(HSessionPtr, uint8_t *, int));
MOCK_METHOD3(FetchIOBuf, int(HSession, uint8_t *, int));
explicit MockHdcSessionBase(bool server) : HdcSessionBase(server) {}
} mockSession(true);
hdcSession.classInstance = static_cast<void *>(&mockSession);