• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "channel.h"
16 namespace Hdc {
HdcChannelBase(const bool serverOrClient,const string & addrString,uv_loop_t * loopMainIn)17 HdcChannelBase::HdcChannelBase(const bool serverOrClient, const string &addrString, uv_loop_t *loopMainIn)
18 {
19     SetChannelTCPString(addrString);
20     isServerOrClient = serverOrClient;
21     loopMain = loopMainIn;
22     threadChanneMain = uv_thread_self();
23     uv_rwlock_init(&mainAsync);
24     uv_async_init(loopMain, &asyncMainLoop, MainAsyncCallback);
25     uv_rwlock_init(&lockMapChannel);
26 }
27 
~HdcChannelBase()28 HdcChannelBase::~HdcChannelBase()
29 {
30     ClearChannels();
31     // clear
32     if (!uv_is_closing((uv_handle_t *)&asyncMainLoop)) {
33         uv_close((uv_handle_t *)&asyncMainLoop, nullptr);
34     }
35 
36     uv_rwlock_destroy(&mainAsync);
37     uv_rwlock_destroy(&lockMapChannel);
38 }
39 
GetChannelHandshake(string & connectKey) const40 vector<uint8_t> HdcChannelBase::GetChannelHandshake(string &connectKey) const
41 {
42     vector<uint8_t> ret;
43     struct ChannelHandShake handshake = {};
44     if (strcpy_s(handshake.banner, sizeof(handshake.banner), HANDSHAKE_MESSAGE.c_str()) != EOK) {
45         return ret;
46     }
47     if (strcpy_s(handshake.connectKey, sizeof(handshake.connectKey), connectKey.c_str()) != EOK) {
48         return ret;
49     }
50     ret.insert(ret.begin(), (uint8_t *)&handshake, (uint8_t *)&handshake + sizeof(ChannelHandShake));
51     return ret;
52 }
53 
SetChannelTCPString(const string & addrString)54 bool HdcChannelBase::SetChannelTCPString(const string &addrString)
55 {
56     bool ret = false;
57     while (true) {
58         if (addrString.find(":") == string::npos) {
59             break;
60         }
61         std::size_t found = addrString.find_last_of(":");
62         if (found == string::npos) {
63             break;
64         }
65 
66         string host = addrString.substr(0, found);
67         string port = addrString.substr(found + 1);
68 
69         channelPort = std::atoi(port.c_str());
70         sockaddr_in addrv4;
71         sockaddr_in6 addrv6;
72         if (!channelPort) {
73             break;
74         }
75 
76         if (uv_ip6_addr(host.c_str(), channelPort, &addrv6) != 0 &&
77             uv_ip4_addr(host.c_str(), channelPort, &addrv4) != 0) {
78             break;
79         }
80         channelHost = host;
81         channelHostPort = addrString;
82         ret = true;
83         break;
84     }
85     if (!ret) {
86         channelPort = 0;
87         channelHost = STRING_EMPTY;
88         channelHostPort = STRING_EMPTY;
89     }
90     return ret;
91 }
92 
ClearChannels()93 void HdcChannelBase::ClearChannels()
94 {
95     for (auto v : mapChannel) {
96         HChannel hChannel = (HChannel)v.second;
97         if (!hChannel->isDead) {
98             FreeChannel(hChannel->channelId);
99         }
100     }
101 }
102 
WorkerPendding()103 void HdcChannelBase::WorkerPendding()
104 {
105     WRITE_LOG(LOG_DEBUG, "Begin host channel pendding");
106     uv_run(loopMain, UV_RUN_DEFAULT);
107     uv_loop_close(loopMain);
108 }
109 
ReadStream(uv_stream_t * tcp,ssize_t nread,const uv_buf_t * buf)110 void HdcChannelBase::ReadStream(uv_stream_t *tcp, ssize_t nread, const uv_buf_t *buf)
111 {
112     StartTraceScope("HdcChannelBase::ReadStream");
113     int size = 0;
114     int indexBuf = 0;
115     int childRet = 0;
116     bool needExit = false;
117     HChannel hChannel = (HChannel)tcp->data;
118     HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
119     uint32_t channelId = hChannel->channelId;
120 
121     if (nread == UV_ENOBUFS) {
122         WRITE_LOG(LOG_FATAL, "ReadStream nobufs channelId:%u", channelId);
123         return;
124     } else if (nread == 0) {
125         // maybe just after accept, second client req
126         WRITE_LOG(LOG_FATAL, "ReadStream idle read channelId:%u", channelId);
127         return;
128     } else if (nread < 0) {
129         Base::TryCloseHandle((uv_handle_t *)tcp);
130         constexpr int bufSize = 1024;
131         char buffer[bufSize] = { 0 };
132         uv_err_name_r(nread, buffer, bufSize);
133         WRITE_LOG(LOG_DEBUG, "ReadStream channelId:%u failed:%s", channelId, buffer);
134         needExit = true;
135         goto Finish;
136     } else {
137         hChannel->availTailIndex += nread;
138     }
139     while (hChannel->availTailIndex > DWORD_SERIALIZE_SIZE) {
140         size = ntohl(*reinterpret_cast<uint32_t *>(hChannel->ioBuf + indexBuf));  // big endian
141         if (size <= 0 || static_cast<uint32_t>(size) > HDC_BUF_MAX_BYTES) {
142             WRITE_LOG(LOG_FATAL, "ReadStream size:%d channelId:%u", size, channelId);
143             needExit = true;
144             break;
145         }
146         if (hChannel->availTailIndex - DWORD_SERIALIZE_SIZE < size) {
147             break;
148         }
149         childRet = thisClass->ReadChannel(hChannel, reinterpret_cast<uint8_t *>(hChannel->ioBuf) +
150                                           DWORD_SERIALIZE_SIZE + indexBuf, size);
151         if (childRet < 0) {
152             WRITE_LOG(LOG_WARN, "ReadStream childRet:%d channelId:%u keepAlive:%d",
153                 childRet, channelId, hChannel->keepAlive);
154             if (!hChannel->keepAlive) {
155                 needExit = true;
156                 break;
157             }
158         }
159         // update io
160         hChannel->availTailIndex -= (DWORD_SERIALIZE_SIZE + size);
161         indexBuf += DWORD_SERIALIZE_SIZE + size;
162     }
163     if (indexBuf > 0 && hChannel->availTailIndex > 0) {
164         if (memmove_s(hChannel->ioBuf, hChannel->bufSize, hChannel->ioBuf + indexBuf, hChannel->availTailIndex)) {
165             needExit = true;
166             goto Finish;
167         }
168     }
169 
170 Finish:
171     if (needExit) {
172         thisClass->FreeChannel(hChannel->channelId);
173         WRITE_LOG(LOG_DEBUG, "Read Stream needExit, FreeChannel finish channelId:%u", channelId);
174     }
175 }
176 
WriteCallback(uv_write_t * req,int status)177 void HdcChannelBase::WriteCallback(uv_write_t *req, int status)
178 {
179     HChannel hChannel = (HChannel)req->handle->data;
180     --hChannel->ref;
181     HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
182     if (status < 0) {
183         WRITE_LOG(LOG_WARN, "WriteCallback TryCloseHandle channelId:%u isDead:%d ref:%d",
184             hChannel->channelId, hChannel->isDead, int32_t(hChannel->ref));
185         Base::TryCloseHandle((uv_handle_t *)req->handle);
186         if (!hChannel->isDead && !hChannel->ref) {
187             thisClass->FreeChannel(hChannel->channelId);
188         }
189     }
190     delete[]((uint8_t *)req->data);
191     delete req;
192 }
193 
AsyncMainLoopTask(uv_idle_t * handle)194 void HdcChannelBase::AsyncMainLoopTask(uv_idle_t *handle)
195 {
196     AsyncParam *param = (AsyncParam *)handle->data;
197     HdcChannelBase *thisClass = (HdcChannelBase *)param->thisClass;
198 
199     switch (param->method) {
200         case ASYNC_FREE_CHANNEL: {
201             // alloc/release should pair in main thread.
202             thisClass->FreeChannel(param->sid);
203             break;
204         }
205         default:
206             break;
207     }
208     if (param->data) {
209         delete[]((uint8_t *)param->data);
210     }
211     delete param;
212     uv_close((uv_handle_t *)handle, Base::CloseIdleCallback);
213 }
214 
215 // multiple uv_async_send() calls may be merged by libuv,so not each call will yield callback as expected.
216 // eg: if uv_async_send() 5 times before callback calling,it will be called only once.
217 // if uv_async_send() is called again after callback calling, it will be called again.
MainAsyncCallback(uv_async_t * handle)218 void HdcChannelBase::MainAsyncCallback(uv_async_t *handle)
219 {
220     HdcChannelBase *thisClass = (HdcChannelBase *)handle->data;
221     if (uv_is_closing((uv_handle_t *)thisClass->loopMain)) {
222         WRITE_LOG(LOG_WARN, "MainAsyncCallback uv_is_closing loopMain");
223         return;
224     }
225     list<void *>::iterator i;
226     list<void *> &lst = thisClass->lstMainThreadOP;
227     uv_rwlock_wrlock(&thisClass->mainAsync);
228     for (i = lst.begin(); i != lst.end();) {
229         AsyncParam *param = (AsyncParam *)*i;
230         Base::IdleUvTask(thisClass->loopMain, param, AsyncMainLoopTask);
231         i = lst.erase(i);
232     }
233     uv_rwlock_wrunlock(&thisClass->mainAsync);
234 }
235 
PushAsyncMessage(const uint32_t channelId,const uint8_t method,const void * data,const int dataSize)236 void HdcChannelBase::PushAsyncMessage(const uint32_t channelId, const uint8_t method, const void *data,
237                                       const int dataSize)
238 {
239     if (uv_is_closing((uv_handle_t *)&asyncMainLoop)) {
240         WRITE_LOG(LOG_WARN, "PushAsyncMessage uv_is_closing asyncMainLoop");
241         return;
242     }
243     auto param = new AsyncParam();
244     if (!param) {
245         return;
246     }
247     param->sid = channelId;  // Borrow SID storage
248     param->thisClass = this;
249     param->method = method;
250     if (dataSize > 0) {
251         param->dataSize = dataSize;
252         param->data = new uint8_t[param->dataSize]();
253         if (!param->data) {
254             delete param;
255             return;
256         }
257         if (memcpy_s((uint8_t *)param->data, param->dataSize, data, dataSize)) {
258             delete[]((uint8_t *)param->data);
259             delete param;
260             return;
261         }
262     }
263     asyncMainLoop.data = this;
264     uv_rwlock_wrlock(&mainAsync);
265     lstMainThreadOP.push_back(param);
266     uv_rwlock_wrunlock(&mainAsync);
267     uv_async_send(&asyncMainLoop);
268 }
269 
270 // add commandflag ahead real buf data
SendChannelWithCmd(HChannel hChannel,const uint16_t commandFlag,uint8_t * bufPtr,const int size)271 void HdcChannelBase::SendChannelWithCmd(HChannel hChannel, const uint16_t commandFlag, uint8_t *bufPtr, const int size)
272 {
273     StartTraceScope("HdcChannelBase::SendChannelWithCmd");
274     auto data = new uint8_t[size + sizeof(commandFlag)]();
275     if (!data) {
276         return;
277     }
278 
279     if (memcpy_s(data, size + sizeof(commandFlag), &commandFlag, sizeof(commandFlag))) {
280         delete[] data;
281         return;
282     }
283 
284     if (size > 0 && memcpy_s(data + sizeof(commandFlag), size, bufPtr, size)) {
285         delete[] data;
286         return;
287     }
288 
289     SendChannel(hChannel, data, size + sizeof(commandFlag));
290     delete[] data;
291 }
292 
SendWithCmd(const uint32_t channelId,const uint16_t commandFlag,uint8_t * bufPtr,const int size)293 void HdcChannelBase::SendWithCmd(const uint32_t channelId, const uint16_t commandFlag, uint8_t *bufPtr, const int size)
294 {
295     StartTraceScope("HdcChannelBase::SendWithCmd");
296     HChannel hChannel = reinterpret_cast<HChannel>(AdminChannel(OP_QUERY_REF, channelId, nullptr));
297     if (!hChannel) {
298         WRITE_LOG(LOG_FATAL, "SendWithCmd hChannel nullptr channelId:%u", channelId);
299         return;
300     }
301     do {
302         if (hChannel->isDead) {
303             WRITE_LOG(LOG_FATAL, "SendWithCmd isDead channelId:%u", channelId);
304             break;
305         }
306         SendChannelWithCmd(hChannel, commandFlag, bufPtr, size);
307     } while (false);
308     --hChannel->ref;
309 }
310 
SendChannel(HChannel hChannel,uint8_t * bufPtr,const int size)311 void HdcChannelBase::SendChannel(HChannel hChannel, uint8_t *bufPtr, const int size)
312 {
313     StartTraceScope("HdcChannelBase::SendChannel");
314     uv_stream_t *sendStream = nullptr;
315     int sizeNewBuf = size + DWORD_SERIALIZE_SIZE;
316     auto data = new uint8_t[sizeNewBuf]();
317     if (!data) {
318         return;
319     }
320     *reinterpret_cast<uint32_t *>(data) = htonl(size);  // big endian
321     if (memcpy_s(data + DWORD_SERIALIZE_SIZE, sizeNewBuf - DWORD_SERIALIZE_SIZE, bufPtr, size)) {
322         delete[] data;
323         return;
324     }
325     if (hChannel->hWorkThread == uv_thread_self()) {
326         sendStream = (uv_stream_t *)&hChannel->hWorkTCP;
327     } else {
328         sendStream = (uv_stream_t *)&hChannel->hChildWorkTCP;
329     }
330     if (!uv_is_closing((const uv_handle_t *)sendStream) && uv_is_writable(sendStream)) {
331         ++hChannel->ref;
332         Base::SendToStreamEx(sendStream, data, sizeNewBuf, nullptr, (void *)WriteCallback, data);
333     } else {
334         delete[] data;
335     }
336 }
337 
338 // works only in current working thread
Send(const uint32_t channelId,uint8_t * bufPtr,const int size)339 void HdcChannelBase::Send(const uint32_t channelId, uint8_t *bufPtr, const int size)
340 {
341     StartTraceScope("HdcChannelBase::Send");
342     HChannel hChannel = reinterpret_cast<HChannel>(AdminChannel(OP_QUERY_REF, channelId, nullptr));
343     if (!hChannel) {
344         WRITE_LOG(LOG_FATAL, "Send hChannel nullptr channelId:%u", channelId);
345         return;
346     }
347     do {
348         if (hChannel->isDead) {
349             WRITE_LOG(LOG_FATAL, "Send isDead channelId:%u", channelId);
350             break;
351         }
352         SendChannel(hChannel, bufPtr, size);
353     } while (false);
354     --hChannel->ref;
355 }
356 
AllocCallback(uv_handle_t * handle,size_t sizeWanted,uv_buf_t * buf)357 void HdcChannelBase::AllocCallback(uv_handle_t *handle, size_t sizeWanted, uv_buf_t *buf)
358 {
359     HChannel context = (HChannel)handle->data;
360     Base::ReallocBuf(&context->ioBuf, &context->bufSize, Base::GetMaxBufSize() * BUF_EXTEND_SIZE);
361     buf->base = (char *)context->ioBuf + context->availTailIndex;
362     int size = context->bufSize - context->availTailIndex;
363     buf->len = std::min(size, static_cast<int>(sizeWanted));
364 }
365 
GetChannelPseudoUid()366 uint32_t HdcChannelBase::GetChannelPseudoUid()
367 {
368     uint32_t uid = 0;
369     do {
370         uid = Base::GetSecureRandom();
371     } while (AdminChannel(OP_QUERY, uid, nullptr) != nullptr);
372     return uid;
373 }
374 
MallocChannel(HChannel * hOutChannel)375 uint32_t HdcChannelBase::MallocChannel(HChannel *hOutChannel)
376 {
377 #ifdef CONFIG_USE_JEMALLOC_DFX_INIF
378     mallopt(M_DELAYED_FREE, M_DELAYED_FREE_DISABLE);
379     mallopt(M_SET_THREAD_CACHE, M_THREAD_CACHE_DISABLE);
380 #endif
381     auto hChannel = new HdcChannel();
382     if (!hChannel) {
383         WRITE_LOG(LOG_FATAL, "malloc channel failed");
384         return 0;
385     }
386     hChannel->stdinTty.data = nullptr;
387     hChannel->stdoutTty.data = nullptr;
388     uint32_t channelId = GetChannelPseudoUid();
389     if (isServerOrClient) {
390         hChannel->serverOrClient = isServerOrClient;
391         ++channelId;  // Use different value for serverForClient&client in per process
392     }
393     uv_tcp_init(loopMain, &hChannel->hWorkTCP);
394     ++hChannel->uvHandleRef;
395     hChannel->hWorkThread = uv_thread_self();
396     hChannel->hWorkTCP.data = hChannel;
397     hChannel->clsChannel = this;
398     hChannel->channelId = channelId;
399     (void)memset_s(&hChannel->hChildWorkTCP, sizeof(hChannel->hChildWorkTCP), 0, sizeof(uv_tcp_t));
400     AdminChannel(OP_ADD, channelId, hChannel);
401     *hOutChannel = hChannel;
402     if (isServerOrClient) {
403         WRITE_LOG(LOG_INFO, "Mallocchannel:%u", channelId);
404     } else {
405         WRITE_LOG(LOG_DEBUG, "Mallocchannel:%u", channelId);
406     }
407     return channelId;
408 }
409 
410 // work when libuv-handle at struct of HdcSession has all callback finished
FreeChannelFinally(uv_idle_t * handle)411 void HdcChannelBase::FreeChannelFinally(uv_idle_t *handle)
412 {
413     HChannel hChannel = (HChannel)handle->data;
414     HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
415     if (hChannel->uvHandleRef > 0) {
416         if (hChannel->serverOrClient) {
417             WRITE_LOG(LOG_INFO, "FreeChannelFinally uvHandleRef:%d channelId:%u sid:%u",
418                 hChannel->uvHandleRef, hChannel->channelId, hChannel->targetSessionId);
419         } else {
420             WRITE_LOG(LOG_DEBUG, "FreeChannelFinally uvHandleRef:%d channelId:%u sid:%u",
421                 hChannel->uvHandleRef, hChannel->channelId, hChannel->targetSessionId);
422         }
423         return;
424     }
425     thisClass->NotifyInstanceChannelFree(hChannel);
426     thisClass->AdminChannel(OP_REMOVE, hChannel->channelId, nullptr);
427 
428     if (!hChannel->serverOrClient) {
429         WRITE_LOG(LOG_DEBUG, "!!!FreeChannelFinally channelId:%u sid:%u finish",
430             hChannel->channelId, hChannel->targetSessionId);
431         uv_stop(thisClass->loopMain);
432     } else {
433         WRITE_LOG(LOG_INFO, "!!!FreeChannelFinally channelId:%u sid:%u finish",
434             hChannel->channelId, hChannel->targetSessionId);
435     }
436 #ifdef HDC_HOST
437     Base::TryCloseHandle((const uv_handle_t *)&hChannel->hChildWorkTCP);
438 #endif
439     delete hChannel;
440     Base::TryCloseHandle((const uv_handle_t *)handle, Base::CloseIdleCallback);
441 }
442 
FreeChannelContinue(HChannel hChannel)443 void HdcChannelBase::FreeChannelContinue(HChannel hChannel)
444 {
445     auto closeChannelHandle = [](uv_handle_t *handle) -> void {
446         if (handle->data == nullptr) {
447             WRITE_LOG(LOG_DEBUG, "FreeChannelContinue handle->data is nullptr");
448             return;
449         }
450         HChannel channel = reinterpret_cast<HChannel>(handle->data);
451         --channel->uvHandleRef;
452         Base::TryCloseHandle((uv_handle_t *)handle);
453     };
454     hChannel->availTailIndex = 0;
455     if (hChannel->ioBuf) {
456         delete[] hChannel->ioBuf;
457         hChannel->ioBuf = nullptr;
458     }
459     if (!hChannel->serverOrClient) {
460         Base::TryCloseHandle((uv_handle_t *)&hChannel->stdinTty, closeChannelHandle);
461         Base::TryCloseHandle((uv_handle_t *)&hChannel->stdoutTty, closeChannelHandle);
462     }
463     if (uv_is_closing((const uv_handle_t *)&hChannel->hWorkTCP)) {
464         --hChannel->uvHandleRef;
465     } else {
466         Base::TryCloseHandle((uv_handle_t *)&hChannel->hWorkTCP, closeChannelHandle);
467     }
468     Base::IdleUvTask(loopMain, hChannel, FreeChannelFinally);
469 }
470 
FreeChannelOpeate(uv_timer_t * handle)471 void HdcChannelBase::FreeChannelOpeate(uv_timer_t *handle)
472 {
473     HChannel hChannel = (HChannel)handle->data;
474     HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
475     if (hChannel->ref > 0) {
476         return;
477     }
478     if (hChannel->hChildWorkTCP.loop) {
479         auto ctrl = HdcSessionBase::BuildCtrlString(SP_DEATCH_CHANNEL, hChannel->channelId, nullptr, 0);
480         bool ret = thisClass->ChannelSendSessionCtrlMsg(ctrl, hChannel->targetSessionId);
481         if (!ret) {
482             WRITE_LOG(LOG_WARN, "FreeChannelOpeate deatch failed channelId:%u sid:%u",
483                 hChannel->channelId, hChannel->targetSessionId);
484         }
485         auto callbackCheckFreeChannelContinue = [](uv_timer_t *handle) -> void {
486             HChannel hChannel = (HChannel)handle->data;
487             HdcChannelBase *thisClass = (HdcChannelBase *)hChannel->clsChannel;
488             if (!hChannel->childCleared) {
489                 WRITE_LOG(LOG_WARN, "FreeChannelOpeate childCleared:%d channelId:%u sid:%u",
490                     hChannel->childCleared, hChannel->channelId, hChannel->targetSessionId);
491                 return;
492             }
493             Base::TryCloseHandle((uv_handle_t *)handle, Base::CloseTimerCallback);
494             thisClass->FreeChannelContinue(hChannel);
495         };
496         Base::TimerUvTask(thisClass->loopMain, hChannel, callbackCheckFreeChannelContinue);
497     } else {
498         thisClass->FreeChannelContinue(hChannel);
499     }
500     Base::TryCloseHandle((uv_handle_t *)handle, Base::CloseTimerCallback);
501 }
502 
FreeChannel(const uint32_t channelId)503 void HdcChannelBase::FreeChannel(const uint32_t channelId)
504 {
505     if (threadChanneMain != uv_thread_self()) {
506         PushAsyncMessage(channelId, ASYNC_FREE_CHANNEL, nullptr, 0);
507         WRITE_LOG(LOG_INFO, "FreeChannel not uv_thread_self channelid:%u", channelId);
508         return;
509     }
510     HChannel hChannel = AdminChannel(OP_QUERY, channelId, nullptr);
511     do {
512         if (!hChannel || hChannel->isDead) {
513             WRITE_LOG(LOG_WARN, "FreeChannel hChannel nullptr or isDead channelid:%u", channelId);
514             break;
515         }
516         WRITE_LOG(LOG_DEBUG, "Begin to free channel, channelid:%u", channelId);
517         Base::TimerUvTask(loopMain, hChannel, FreeChannelOpeate, MINOR_TIMEOUT);  // do immediately
518         hChannel->isDead = true;
519     } while (false);
520 }
521 
AdminChannel(const uint8_t op,const uint32_t channelId,HChannel hInput)522 HChannel HdcChannelBase::AdminChannel(const uint8_t op, const uint32_t channelId, HChannel hInput)
523 {
524     HChannel hRet = nullptr;
525     switch (op) {
526         case OP_ADD:
527             uv_rwlock_wrlock(&lockMapChannel);
528             mapChannel[channelId] = hInput;
529             uv_rwlock_wrunlock(&lockMapChannel);
530             break;
531         case OP_REMOVE:
532             uv_rwlock_wrlock(&lockMapChannel);
533             mapChannel.erase(channelId);
534             uv_rwlock_wrunlock(&lockMapChannel);
535             break;
536         case OP_QUERY:
537             uv_rwlock_rdlock(&lockMapChannel);
538             if (mapChannel.count(channelId)) {
539                 hRet = mapChannel[channelId];
540             }
541             uv_rwlock_rdunlock(&lockMapChannel);
542             break;
543         case OP_QUERY_REF:
544             uv_rwlock_wrlock(&lockMapChannel);
545             if (mapChannel.count(channelId)) {
546                 hRet = mapChannel[channelId];
547                 ++hRet->ref;
548             }
549             uv_rwlock_wrunlock(&lockMapChannel);
550             break;
551         case OP_UPDATE:
552             uv_rwlock_wrlock(&lockMapChannel);
553             // remove old
554             mapChannel.erase(channelId);
555             mapChannel[hInput->channelId] = hInput;
556             uv_rwlock_wrunlock(&lockMapChannel);
557             break;
558         default:
559             break;
560     }
561     return hRet;
562 }
563 
EchoToClient(HChannel hChannel,uint8_t * bufPtr,const int size)564 void HdcChannelBase::EchoToClient(HChannel hChannel, uint8_t *bufPtr, const int size)
565 {
566     StartTraceScope("HdcChannelBase::EchoToClient");
567     uv_stream_t *sendStream = nullptr;
568     int sizeNewBuf = size + DWORD_SERIALIZE_SIZE;
569     auto data = new uint8_t[sizeNewBuf]();
570     if (!data) {
571         return;
572     }
573     *reinterpret_cast<uint32_t *>(data) = htonl(size);
574     if (memcpy_s(data + DWORD_SERIALIZE_SIZE, sizeNewBuf - DWORD_SERIALIZE_SIZE, bufPtr, size)) {
575         delete[] data;
576         return;
577     }
578     sendStream = (uv_stream_t *)&hChannel->hChildWorkTCP;
579     if (!uv_is_closing((const uv_handle_t *)sendStream) && uv_is_writable(sendStream)) {
580         ++hChannel->ref;
581         Base::SendToStreamEx(sendStream, data, sizeNewBuf, nullptr, (void *)WriteCallback, data);
582     } else {
583         WRITE_LOG(LOG_WARN, "EchoToClient, channelId:%u is unwritable.", hChannel->channelId);
584         delete[] data;
585     }
586 }
587 
EchoToAllChannelsViaSessionId(uint32_t targetSessionId,const string & echo)588 void HdcChannelBase::EchoToAllChannelsViaSessionId(uint32_t targetSessionId, const string &echo)
589 {
590     for (auto v : mapChannel) {
591         HChannel hChannel = (HChannel)v.second;
592         if (!hChannel->isDead && hChannel->targetSessionId == targetSessionId) {
593             WRITE_LOG(LOG_INFO, "%s:%u %s", __FUNCTION__, targetSessionId, echo.c_str());
594             EchoToClient(hChannel, (uint8_t *)echo.c_str(), echo.size());
595         }
596     }
597 }
598 }
599