• 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 "forward.h"
16 #include "base.h"
17 
18 namespace Hdc {
HdcForwardBase(HTaskInfo hTaskInfo)19 HdcForwardBase::HdcForwardBase(HTaskInfo hTaskInfo)
20     : HdcTaskBase(hTaskInfo)
21 {
22     fds[0] = -1;
23     fds[1] = -1;
24 }
25 
~HdcForwardBase()26 HdcForwardBase::~HdcForwardBase()
27 {
28     WRITE_LOG(LOG_DEBUG, "~HdcForwardBase channelId:%u", taskInfo->channelId);
29 };
30 
ReadyForRelease()31 bool HdcForwardBase::ReadyForRelease()
32 {
33     if (!HdcTaskBase::ReadyForRelease()) {
34         WRITE_LOG(LOG_WARN, "not ready for release channelId:%u", taskInfo->channelId);
35         return false;
36     }
37     return true;
38 }
39 
StopTask()40 void HdcForwardBase::StopTask()
41 {
42     ctxPointMutex.lock();
43     vector<HCtxForward> ctxs;
44     map<uint32_t, HCtxForward>::iterator iter;
45     for (iter = mapCtxPoint.begin(); iter != mapCtxPoint.end(); ++iter) {
46         HCtxForward ctx = iter->second;
47         ctxs.push_back(ctx);
48     }
49     // FREECONTEXT in the STOP is triggered by the other party sector, no longer notifying each other.
50     mapCtxPoint.clear();
51     ctxPointMutex.unlock();
52     for (auto ctx: ctxs) {
53         FreeContext(ctx, 0, false);
54     }
55 }
56 
OnAccept(uv_stream_t * server,HCtxForward ctxClient,uv_stream_t * client)57 void HdcForwardBase::OnAccept(uv_stream_t *server, HCtxForward ctxClient, uv_stream_t *client)
58 {
59     HCtxForward ctxListen = (HCtxForward)server->data;
60     char buf[BUF_SIZE_DEFAULT] = { 0 };
61     bool ret = false;
62     while (true) {
63         if (uv_accept(server, client)) {
64             WRITE_LOG(LOG_FATAL, "uv_accept id:%u type:%d remoteParamenters:%s",
65                 ctxListen->id, ctxListen->type, ctxListen->remoteParamenters.c_str());
66             break;
67         }
68         ctxClient->type = ctxListen->type;
69         ctxClient->remoteParamenters = ctxListen->remoteParamenters;
70         int maxSize = sizeof(buf) - forwardParameterBufSize;
71         // clang-format off
72         if (snprintf_s(buf + forwardParameterBufSize, maxSize, maxSize - 1, "%s",
73                        ctxClient->remoteParamenters.c_str()) < 0) {
74             break;
75         }
76         WRITE_LOG(LOG_DEBUG, "OnAccept id:%u type:%d remoteParamenters:%s",
77             ctxClient->id, ctxClient->type, ctxClient->remoteParamenters.c_str());
78         SendToTask(ctxClient->id, CMD_FORWARD_ACTIVE_SLAVE, reinterpret_cast<uint8_t *>(buf),
79                    strlen(buf + forwardParameterBufSize) + 9); // 9: pre 8bytes preserve for param bits
80         ret = true;
81         break;
82     }
83     if (!ret) {
84         FreeContext(ctxClient, 0, false);
85     }
86 }
87 
ListenCallback(uv_stream_t * server,const int status)88 void HdcForwardBase::ListenCallback(uv_stream_t *server, const int status)
89 {
90     HCtxForward ctxListen = (HCtxForward)server->data;
91     HdcForwardBase *thisClass = ctxListen->thisClass;
92     uv_stream_t *client = nullptr;
93 
94     if (status == -1 || !ctxListen->ready) {
95         WRITE_LOG(LOG_FATAL, "ListenCallback status:%d id:%u ready:%d",
96             status, ctxListen->id, ctxListen->ready);
97         thisClass->FreeContext(ctxListen, 0, false);
98         thisClass->TaskFinish();
99         return;
100     }
101     HCtxForward ctxClient = (HCtxForward)thisClass->MallocContext(true);
102     if (!ctxClient) {
103         return;
104     }
105     if (ctxListen->type == FORWARD_TCP) {
106         uv_tcp_init(ctxClient->thisClass->loopTask, &ctxClient->tcp);
107         client = (uv_stream_t *)&ctxClient->tcp;
108     } else {
109         // FORWARD_ABSTRACT, FORWARD_RESERVED, FORWARD_FILESYSTEM,
110         uv_pipe_init(ctxClient->thisClass->loopTask, &ctxClient->pipe, 0);
111         client = (uv_stream_t *)&ctxClient->pipe;
112     }
113     thisClass->OnAccept(server, ctxClient, client);
114 }
115 
MallocContext(bool masterSlave)116 void *HdcForwardBase::MallocContext(bool masterSlave)
117 {
118     HCtxForward ctx = nullptr;
119     if ((ctx = new ContextForward()) == nullptr) {
120         return nullptr;
121     }
122     ctx->id = Base::GetRuntimeMSec();
123     ctx->masterSlave = masterSlave;
124     ctx->thisClass = this;
125     ctx->fdClass = nullptr;
126     ctx->tcp.data = ctx;
127     ctx->pipe.data = ctx;
128     AdminContext(OP_ADD, ctx->id, ctx);
129     refCount++;
130     return ctx;
131 }
132 
FreeContextCallBack(HCtxForward ctx)133 void HdcForwardBase::FreeContextCallBack(HCtxForward ctx)
134 {
135     Base::DoNextLoop(loopTask, ctx, [this](const uint8_t flag, string &msg, const void *data) {
136         HCtxForward ctx = (HCtxForward)data;
137         AdminContext(OP_REMOVE, ctx->id, nullptr);
138         if (ctx != nullptr) {
139             WRITE_LOG(LOG_DEBUG, "Finally to delete id:%u", ctx->id);
140             delete ctx;
141             ctx = nullptr;
142         }
143         if (refCount > 0) {
144             --refCount;
145         }
146     });
147 }
148 
FreeJDWP(HCtxForward ctx)149 void HdcForwardBase::FreeJDWP(HCtxForward ctx)
150 {
151     Base::CloseFd(ctx->fd);
152     if (ctx->fdClass) {
153         ctx->fdClass->StopWorkOnThread(false, nullptr);
154 
155         auto funcReqClose = [](uv_idle_t *handle) -> void {
156             uv_close_cb funcIdleHandleClose = [](uv_handle_t *handle) -> void {
157                 HCtxForward ctx = (HCtxForward)handle->data;
158                 ctx->thisClass->FreeContextCallBack(ctx);
159                 delete (uv_idle_t *)handle;
160             };
161             HCtxForward context = (HCtxForward)handle->data;
162             if (context->fdClass->ReadyForRelease()) {
163                 delete context->fdClass;
164                 context->fdClass = nullptr;
165                 Base::TryCloseHandle((uv_handle_t *)handle, funcIdleHandleClose);
166             }
167         };
168         Base::IdleUvTask(loopTask, ctx, funcReqClose);
169     }
170 }
171 
FreeContext(HCtxForward ctxIn,const uint32_t id,bool bNotifyRemote)172 void HdcForwardBase::FreeContext(HCtxForward ctxIn, const uint32_t id, bool bNotifyRemote)
173 {
174     WRITE_LOG(LOG_DEBUG, "FreeContext id:%u, bNotifyRemote:%d", id, bNotifyRemote);
175     std::lock_guard<std::mutex> lock(ctxFreeMutex);
176     HCtxForward ctx = nullptr;
177     if (!ctxIn) {
178         if (!(ctx = (HCtxForward)AdminContext(OP_QUERY, id, nullptr))) {
179             WRITE_LOG(LOG_DEBUG, "Query id:%u failed", id);
180             return;
181         }
182     } else {
183         ctx = ctxIn;
184     }
185     if (ctx->finish) {
186         return;
187     }
188     if (bNotifyRemote) {
189         SendToTask(ctx->id, CMD_FORWARD_FREE_CONTEXT, nullptr, 0);
190     }
191     uv_close_cb funcHandleClose = [](uv_handle_t *handle) -> void {
192         HCtxForward ctx = (HCtxForward)handle->data;
193         ctx->thisClass->FreeContextCallBack(ctx);
194     };
195     switch (ctx->type) {
196         case FORWARD_TCP:
197         case FORWARD_JDWP:
198         case FORWARD_ARK:
199             Base::TryCloseHandle((uv_handle_t *)&ctx->tcp, true, funcHandleClose);
200             break;
201         case FORWARD_ABSTRACT:
202         case FORWARD_RESERVED:
203         case FORWARD_FILESYSTEM:
204             Base::TryCloseHandle((uv_handle_t *)&ctx->pipe, true, funcHandleClose);
205             break;
206         case FORWARD_DEVICE: {
207             FreeJDWP(ctx);
208             break;
209         }
210         default:
211             break;
212     }
213     ctx->finish = true;
214 }
215 
SendToTask(const uint32_t cid,const uint16_t command,uint8_t * bufPtr,const int bufSize)216 bool HdcForwardBase::SendToTask(const uint32_t cid, const uint16_t command, uint8_t *bufPtr, const int bufSize)
217 {
218     StartTraceScope("HdcForwardBase::SendToTask");
219     bool ret = false;
220     // usually MAX_SIZE_IOBUF*2 from HdcFileDescriptor maxIO
221     if (bufSize > Base::GetMaxBufSize() * 2) {
222         WRITE_LOG(LOG_FATAL, "SendToTask bufSize:%d", bufSize);
223         return false;
224     }
225     auto newBuf = new uint8_t[bufSize + 4];
226     if (!newBuf) {
227         return false;
228     }
229     *reinterpret_cast<uint32_t *>(newBuf) = htonl(cid);
230     if (bufSize > 0 && bufPtr != nullptr && memcpy_s(newBuf + 4, bufSize, bufPtr, bufSize) != EOK) {
231         delete[] newBuf;
232         return false;
233     }
234     ret = SendToAnother(command, newBuf, bufSize + 4);
235     delete[] newBuf;
236     return ret;
237 }
238 
239 // Forward flow is small and frequency is fast
AllocForwardBuf(uv_handle_t * handle,size_t sizeSuggested,uv_buf_t * buf)240 void HdcForwardBase::AllocForwardBuf(uv_handle_t *handle, size_t sizeSuggested, uv_buf_t *buf)
241 {
242     size_t size = sizeSuggested;
243     if (size > MAX_USBFFS_BULK) {
244         size = MAX_USBFFS_BULK;
245     }
246     buf->base = (char *)new char[size];
247     if (buf->base) {
248         buf->len = size - 1;
249     } else {
250         WRITE_LOG(LOG_WARN, "AllocForwardBuf == null");
251     }
252 }
253 
ReadForwardBuf(uv_stream_t * stream,ssize_t nread,const uv_buf_t * buf)254 void HdcForwardBase::ReadForwardBuf(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
255 {
256     HCtxForward ctx = (HCtxForward)stream->data;
257     if (nread < 0) {
258         WRITE_LOG(LOG_INFO, "ReadForwardBuf nread:%zd id:%u", nread, ctx->id);
259         ctx->thisClass->FreeContext(ctx, 0, true);
260         delete[] buf->base;
261         return;
262     }
263     if (nread == 0) {
264         WRITE_LOG(LOG_INFO, "ReadForwardBuf nread:0 id:%u", ctx->id);
265         delete[] buf->base;
266         return;
267     }
268     ctx->thisClass->SendToTask(ctx->id, CMD_FORWARD_DATA, (uint8_t *)buf->base, nread);
269     // clear
270     delete[] buf->base;
271 }
272 
ConnectTarget(uv_connect_t * connection,int status)273 void HdcForwardBase::ConnectTarget(uv_connect_t *connection, int status)
274 {
275     HCtxForward ctx = (HCtxForward)connection->data;
276     HdcForwardBase *thisClass = ctx->thisClass;
277     delete connection;
278     if (status < 0) {
279         constexpr int bufSize = 1024;
280         char buf[bufSize] = { 0 };
281         uv_err_name_r(status, buf, bufSize);
282         WRITE_LOG(LOG_WARN, "Forward connect result:%d error:%s", status, buf);
283     }
284     thisClass->SetupPointContinue(ctx, status);
285 }
286 
CheckNodeInfo(const char * nodeInfo,string as[2])287 bool HdcForwardBase::CheckNodeInfo(const char *nodeInfo, string as[2])
288 {
289     string str = nodeInfo;
290     size_t strLen = str.size();
291     size_t pos = str.find(':');
292     if (pos != string::npos) {
293         if (pos == 0 || pos == strLen - 1) {
294             return false;
295         }
296         as[0] = str.substr(0, pos);
297         as[1] = str.substr(pos + 1);
298     } else {
299         return false;
300     }
301     if (as[0] == "tcp") {
302         if (as[1].size() > std::to_string(MAX_IP_PORT).size()) {
303             return false;
304         }
305         int port = atoi(as[1].c_str());
306         if (port <= 0 || port > MAX_IP_PORT) {
307             return false;
308         }
309     }
310     return true;
311 }
312 
SetupPointContinue(HCtxForward ctx,int status)313 bool HdcForwardBase::SetupPointContinue(HCtxForward ctx, int status)
314 {
315     if (ctx->checkPoint) {
316         // send to active
317         uint8_t flag = status > 0;
318         SendToTask(ctx->id, CMD_FORWARD_CHECK_RESULT, &flag, 1);
319         FreeContext(ctx, 0, false);
320         return true;
321     }
322     if (status < 0) {
323         FreeContext(ctx, 0, true);
324         return false;
325     }
326     // send to active
327     if (!SendToTask(ctx->id, CMD_FORWARD_ACTIVE_MASTER, nullptr, 0)) {
328         WRITE_LOG(LOG_FATAL, "SetupPointContinue SendToTask failed id:%u", ctx->id);
329         FreeContext(ctx, 0, true);
330         return false;
331     }
332     return DoForwardBegin(ctx);
333 }
334 
DetechForwardType(HCtxForward ctxPoint)335 bool HdcForwardBase::DetechForwardType(HCtxForward ctxPoint)
336 {
337     string &sFType = ctxPoint->localArgs[0];
338     string &sNodeCfg = ctxPoint->localArgs[1];
339     // string to enum
340     if (sFType == "tcp") {
341         ctxPoint->type = FORWARD_TCP;
342     } else if (sFType == "dev") {
343         ctxPoint->type = FORWARD_DEVICE;
344     } else if (sFType == "localabstract") {
345         // daemon shell: /system/bin/socat abstract-listen:linux-abstract -
346         // daemon shell: /system/bin/socat - abstract-connect:linux-abstract
347         // host:   hdc fport tcp:8080 localabstract:linux-abstract
348         ctxPoint->type = FORWARD_ABSTRACT;
349     } else if (sFType == "localreserved") {
350         sNodeCfg = harmonyReservedSocketPrefix + sNodeCfg;
351         ctxPoint->type = FORWARD_RESERVED;
352     } else if (sFType == "localfilesystem") {
353         sNodeCfg = filesystemSocketPrefix + sNodeCfg;
354         ctxPoint->type = FORWARD_FILESYSTEM;
355     } else if (sFType == "jdwp") {
356         ctxPoint->type = FORWARD_JDWP;
357     } else if (sFType == "ark") {
358         ctxPoint->type = FORWARD_ARK;
359     } else {
360         return false;
361     }
362     return true;
363 }
364 
SetupTCPPoint(HCtxForward ctxPoint)365 bool HdcForwardBase::SetupTCPPoint(HCtxForward ctxPoint)
366 {
367     string &sNodeCfg = ctxPoint->localArgs[1];
368     int port = atoi(sNodeCfg.c_str());
369     ctxPoint->tcp.data = ctxPoint;
370     uv_tcp_init(loopTask, &ctxPoint->tcp);
371     struct sockaddr_in addr;
372     if (ctxPoint->masterSlave) {
373         uv_ip4_addr("127.0.0.1", port, &addr);  // loop interface
374         uv_tcp_bind(&ctxPoint->tcp, (const struct sockaddr *)&addr, 0);
375         if (uv_listen((uv_stream_t *)&ctxPoint->tcp, 4, ListenCallback)) {
376             ctxPoint->lastError = "TCP Port listen failed at " + sNodeCfg;
377             return false;
378         }
379     } else {
380         uv_ip4_addr("127.0.0.1", port, &addr);  // loop interface
381         uv_connect_t *conn = new(std::nothrow) uv_connect_t();
382         if (conn == nullptr) {
383             WRITE_LOG(LOG_FATAL, "SetupTCPPoint new conn failed");
384             return false;
385         }
386         conn->data = ctxPoint;
387         uv_tcp_connect(conn, (uv_tcp_t *)&ctxPoint->tcp, (const struct sockaddr *)&addr, ConnectTarget);
388     }
389     return true;
390 }
391 
SetupDevicePoint(HCtxForward ctxPoint)392 bool HdcForwardBase::SetupDevicePoint(HCtxForward ctxPoint)
393 {
394     uint8_t flag = 1;
395     string &sNodeCfg = ctxPoint->localArgs[1];
396     string resolvedPath = Base::CanonicalizeSpecPath(sNodeCfg);
397     if ((ctxPoint->fd = open(resolvedPath.c_str(), O_RDWR)) < 0) {
398         ctxPoint->lastError = "Open unix-dev failed";
399         flag = -1;
400     }
401     auto funcRead = [&](const void *a, uint8_t *b, const int c) -> bool {
402         HCtxForward ctx = (HCtxForward)a;
403         return SendToTask(ctx->id, CMD_FORWARD_DATA, b, c);
404     };
405     auto funcFinish = [&](const void *a, const bool b, const string c) -> bool {
406         HCtxForward ctx = (HCtxForward)a;
407         WRITE_LOG(LOG_DEBUG, "funcFinish id:%u ret:%d reason:%s", ctx->id, b, c.c_str());
408         FreeContext(ctx, 0, true);
409         return false;
410     };
411     ctxPoint->fdClass = new(std::nothrow) HdcFileDescriptor(loopTask, ctxPoint->fd, ctxPoint, funcRead, funcFinish);
412     if (ctxPoint->fdClass == nullptr) {
413         WRITE_LOG(LOG_FATAL, "SetupDevicePoint new ctxPoint->fdClass failed");
414         return false;
415     }
416     SetupPointContinue(ctxPoint, flag);
417     return true;
418 }
419 
LocalAbstractConnect(uv_pipe_t * pipe,string & sNodeCfg)420 bool HdcForwardBase::LocalAbstractConnect(uv_pipe_t *pipe, string &sNodeCfg)
421 {
422     bool abstractRet = false;
423 #ifndef _WIN32
424     int s = 0;
425     do {
426         if ((s = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
427             break;
428         }
429         fcntl(s, F_SETFD, FD_CLOEXEC);
430         struct sockaddr_un addr;
431         Base::ZeroStruct(addr);
432         int addrLen = sNodeCfg.size() + offsetof(struct sockaddr_un, sun_path) + 1;
433         addr.sun_family = AF_LOCAL;
434         addr.sun_path[0] = 0;
435 
436         if (memcpy_s(addr.sun_path + 1, sizeof(addr.sun_path) - 1, sNodeCfg.c_str(), sNodeCfg.size()) != EOK) {
437             break;
438         };
439         struct timeval timeout = { 3, 0 };
440         setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
441         if (connect(s, reinterpret_cast<struct sockaddr *>(&addr), addrLen) < 0) {
442             WRITE_LOG(LOG_FATAL, "LocalAbstractConnect failed errno:%d", errno);
443             break;
444         }
445         if (uv_pipe_open(pipe, s)) {
446             break;
447         }
448         abstractRet = true;
449     } while (false);
450     if (!abstractRet) {
451         Base::CloseFd(s);
452     }
453 #endif
454     return abstractRet;
455 }
456 
SetupFilePoint(HCtxForward ctxPoint)457 bool HdcForwardBase::SetupFilePoint(HCtxForward ctxPoint)
458 {
459     string &sNodeCfg = ctxPoint->localArgs[1];
460     ctxPoint->pipe.data = ctxPoint;
461     uv_pipe_init(loopTask, &ctxPoint->pipe, 0);
462     if (ctxPoint->masterSlave) {
463         if (ctxPoint->type == FORWARD_RESERVED || ctxPoint->type == FORWARD_FILESYSTEM) {
464             unlink(sNodeCfg.c_str());
465         }
466         if (uv_pipe_bind(&ctxPoint->pipe, sNodeCfg.c_str())) {
467             ctxPoint->lastError = "Unix pipe bind failed";
468             return false;
469         }
470         if (uv_listen((uv_stream_t *)&ctxPoint->pipe, 4, ListenCallback)) {
471             ctxPoint->lastError = "Unix pipe listen failed";
472             return false;
473         }
474     } else {
475         if (ctxPoint->type == FORWARD_ABSTRACT) {
476             bool abstractRet = LocalAbstractConnect(&ctxPoint->pipe, sNodeCfg);
477             SetupPointContinue(ctxPoint, abstractRet ? 0 : -1);
478             if (!abstractRet) {
479                 ctxPoint->lastError = "LocalAbstractConnect failed";
480                 return false;
481             }
482         } else {
483             uv_connect_t *connect = new(std::nothrow) uv_connect_t();
484             if (connect == nullptr) {
485                 WRITE_LOG(LOG_FATAL, "SetupFilePoint new connect failed");
486                 return false;
487             }
488             connect->data = ctxPoint;
489             uv_pipe_connect(connect, &ctxPoint->pipe, sNodeCfg.c_str(), ConnectTarget);
490         }
491     }
492     return true;
493 }
494 
SetupPoint(HCtxForward ctxPoint)495 bool HdcForwardBase::SetupPoint(HCtxForward ctxPoint)
496 {
497     bool ret = true;
498     if (!DetechForwardType(ctxPoint)) {
499         return false;
500     }
501     switch (ctxPoint->type) {
502         case FORWARD_TCP:
503             if (!SetupTCPPoint(ctxPoint)) {
504                 ret = false;
505             };
506             break;
507 #ifndef _WIN32
508         case FORWARD_DEVICE:
509             if (!SetupDevicePoint(ctxPoint)) {
510                 ret = false;
511             };
512             break;
513         case FORWARD_JDWP:
514             if (!SetupJdwpPoint(ctxPoint)) {
515                 ret = false;
516             };
517             break;
518         case FORWARD_ABSTRACT:
519         case FORWARD_RESERVED:
520         case FORWARD_FILESYSTEM:
521             if (!SetupFilePoint(ctxPoint)) {
522                 ret = false;
523             };
524             break;
525 #else
526         case FORWARD_DEVICE:
527         case FORWARD_JDWP:
528         case FORWARD_ABSTRACT:
529         case FORWARD_RESERVED:
530         case FORWARD_FILESYSTEM:
531             ctxPoint->lastError = "Not supoort forward-type";
532             ret = false;
533             break;
534 #endif
535         default:
536             ctxPoint->lastError = "Not supoort forward-type";
537             ret = false;
538             break;
539     }
540     return ret;
541 }
542 
BeginForward(const string & command,string & sError)543 bool HdcForwardBase::BeginForward(const string &command, string &sError)
544 {
545     bool ret = false;
546     int argc = 0;
547     char bufString[BUF_SIZE_SMALL] = "";
548     HCtxForward ctxPoint = (HCtxForward)MallocContext(true);
549     if (!ctxPoint) {
550         WRITE_LOG(LOG_FATAL, "MallocContext failed");
551         return false;
552     }
553     char **argv = Base::SplitCommandToArgs(command.c_str(), &argc);
554     if (argv == nullptr) {
555         WRITE_LOG(LOG_FATAL, "SplitCommandToArgs failed");
556         return false;
557     }
558     while (true) {
559         if (argc < CMD_ARG1_COUNT) {
560             break;
561         }
562         if (strlen(argv[0]) > BUF_SIZE_SMALL || strlen(argv[1]) > BUF_SIZE_SMALL) {
563             break;
564         }
565         if (!CheckNodeInfo(argv[0], ctxPoint->localArgs)) {
566             break;
567         }
568         if (!CheckNodeInfo(argv[1], ctxPoint->remoteArgs)) {
569             break;
570         }
571         ctxPoint->remoteParamenters = argv[1];
572         if (!SetupPoint(ctxPoint)) {
573             break;
574         }
575 
576         ret = true;
577         break;
578     }
579     sError = ctxPoint->lastError;
580     if (ret) {
581         // First 8-byte parameter bit
582         int maxBufSize = sizeof(bufString) - forwardParameterBufSize;
583         if (snprintf_s(bufString + forwardParameterBufSize, maxBufSize, maxBufSize - 1, "%s", argv[1]) > 0) {
584             SendToTask(ctxPoint->id, CMD_FORWARD_CHECK, reinterpret_cast<uint8_t *>(bufString),
585                        forwardParameterBufSize + strlen(bufString + forwardParameterBufSize) + 1);
586             taskCommand = command;
587         }
588     }
589     delete[](reinterpret_cast<char *>(argv));
590     return ret;
591 }
592 
FilterCommand(uint8_t * bufCmdIn,uint32_t * idOut,uint8_t ** pContentBuf)593 inline bool HdcForwardBase::FilterCommand(uint8_t *bufCmdIn, uint32_t *idOut, uint8_t **pContentBuf)
594 {
595     *pContentBuf = bufCmdIn + DWORD_SERIALIZE_SIZE;
596     *idOut = ntohl(*reinterpret_cast<uint32_t *>(bufCmdIn));
597     return true;
598 }
599 
SlaveConnect(uint8_t * bufCmd,bool bCheckPoint,string & sError)600 bool HdcForwardBase::SlaveConnect(uint8_t *bufCmd, bool bCheckPoint, string &sError)
601 {
602     bool ret = false;
603     char *content = nullptr;
604     uint32_t idSlaveOld = 0;
605     HCtxForward ctxPoint = (HCtxForward)MallocContext(false);
606     if (!ctxPoint) {
607         WRITE_LOG(LOG_FATAL, "MallocContext failed");
608         return false;
609     }
610     idSlaveOld = ctxPoint->id;
611     ctxPoint->checkPoint = bCheckPoint;
612     // refresh another id,8byte param
613     FilterCommand(bufCmd, &ctxPoint->id, reinterpret_cast<uint8_t **>(&content));
614     AdminContext(OP_UPDATE, idSlaveOld, ctxPoint);
615     content += forwardParameterBufSize;
616     if (!CheckNodeInfo(content, ctxPoint->localArgs)) {
617         WRITE_LOG(LOG_FATAL, "SlaveConnect CheckNodeInfo failed content:%s", content);
618         goto Finish;
619     }
620     if (!DetechForwardType(ctxPoint)) {
621         WRITE_LOG(LOG_FATAL, "SlaveConnect DetechForwardType failed content:%s", content);
622         goto Finish;
623     }
624     WRITE_LOG(LOG_DEBUG, "id:%u type:%d", ctxPoint->id, ctxPoint->type);
625     if (ctxPoint->type == FORWARD_ARK) {
626         if (ctxPoint->checkPoint) {
627             if (!SetupArkPoint(ctxPoint)) {
628                 sError = ctxPoint->lastError;
629                 WRITE_LOG(LOG_FATAL, "SlaveConnect SetupArkPoint failed content:%s", content);
630                 goto Finish;
631             }
632         } else {
633             SetupPointContinue(ctxPoint, 0);
634         }
635         ret = true;
636     } else {
637         if (!ctxPoint->checkPoint) {
638             if (!SetupPoint(ctxPoint)) {
639                 sError = ctxPoint->lastError;
640                 WRITE_LOG(LOG_FATAL, "SlaveConnect SetupPoint failed content:%s", content);
641                 goto Finish;
642             }
643         } else {
644             SetupPointContinue(ctxPoint, 0);
645         }
646         ret = true;
647     }
648 Finish:
649     if (!ret) {
650         FreeContext(ctxPoint, 0, true);
651     }
652     return ret;
653 }
654 
DoForwardBegin(HCtxForward ctx)655 bool HdcForwardBase::DoForwardBegin(HCtxForward ctx)
656 {
657     switch (ctx->type) {
658         case FORWARD_TCP:
659         case FORWARD_JDWP:  // jdwp use tcp ->socketpair->jvm
660             uv_tcp_nodelay((uv_tcp_t *)&ctx->tcp, 1);
661             uv_read_start((uv_stream_t *)&ctx->tcp, AllocForwardBuf, ReadForwardBuf);
662             break;
663         case FORWARD_ARK:
664             WRITE_LOG(LOG_DEBUG, "DoForwardBegin ark socketpair id:%u fds[0]:%d", ctx->id, fds[0]);
665             uv_tcp_init(loopTask, &ctx->tcp);
666             uv_tcp_open(&ctx->tcp, fds[0]);
667             uv_tcp_nodelay((uv_tcp_t *)&ctx->tcp, 1);
668             uv_read_start((uv_stream_t *)&ctx->tcp, AllocForwardBuf, ReadForwardBuf);
669             break;
670         case FORWARD_ABSTRACT:
671         case FORWARD_RESERVED:
672         case FORWARD_FILESYSTEM:
673             uv_read_start((uv_stream_t *)&ctx->pipe, AllocForwardBuf, ReadForwardBuf);
674             break;
675         case FORWARD_DEVICE: {
676             ctx->fdClass->StartWorkOnThread();
677             break;
678         }
679         default:
680             break;
681     }
682     ctx->ready = true;
683     return true;
684 }
685 
AdminContext(const uint8_t op,const uint32_t id,HCtxForward hInput)686 void *HdcForwardBase::AdminContext(const uint8_t op, const uint32_t id, HCtxForward hInput)
687 {
688     ctxPointMutex.lock();
689     void *hRet = nullptr;
690     map<uint32_t, HCtxForward> &mapCtx = mapCtxPoint;
691     switch (op) {
692         case OP_ADD:
693             mapCtx[id] = hInput;
694             break;
695         case OP_REMOVE:
696             mapCtx.erase(id);
697             break;
698         case OP_QUERY:
699             if (mapCtx.count(id)) {
700                 hRet = mapCtx[id];
701             }
702             break;
703         case OP_UPDATE:
704             mapCtx.erase(id);
705             mapCtx[hInput->id] = hInput;
706             break;
707         default:
708             break;
709     }
710     ctxPointMutex.unlock();
711     return hRet;
712 }
713 
SendCallbackForwardBuf(uv_write_t * req,int status)714 void HdcForwardBase::SendCallbackForwardBuf(uv_write_t *req, int status)
715 {
716     ContextForwardIO *ctxIO = (ContextForwardIO *)req->data;
717     HCtxForward ctx = reinterpret_cast<HCtxForward>(ctxIO->ctxForward);
718     if (status < 0 && !ctx->finish) {
719         WRITE_LOG(LOG_DEBUG, "SendCallbackForwardBuf ctx->type:%d, status:%d finish", ctx->type, status);
720         ctx->thisClass->FreeContext(ctx, 0, true);
721     }
722     delete[] ctxIO->bufIO;
723     delete ctxIO;
724     delete req;
725 }
726 
SendForwardBuf(HCtxForward ctx,uint8_t * bufPtr,const int size)727 int HdcForwardBase::SendForwardBuf(HCtxForward ctx, uint8_t *bufPtr, const int size)
728 {
729     int nRet = 0;
730     if (size > static_cast<int>(HDC_BUF_MAX_BYTES - 1)) {
731         WRITE_LOG(LOG_WARN, "SendForwardBuf size:%d > HDC_BUF_MAX_BYTES", size);
732         return -1;
733     }
734     if (size <= 0) {
735         WRITE_LOG(LOG_WARN, "SendForwardBuf failed size:%d", size);
736         return -1;
737     }
738     auto pDynBuf = new(std::nothrow) uint8_t[size];
739     if (!pDynBuf) {
740         return -1;
741     }
742     (void)memcpy_s(pDynBuf, size, bufPtr, size);
743     if (ctx->type == FORWARD_DEVICE) {
744         nRet = ctx->fdClass->WriteWithMem(pDynBuf, size);
745     } else {
746         auto ctxIO = new ContextForwardIO();
747         if (!ctxIO) {
748             delete[] pDynBuf;
749             return -1;
750         }
751         ctxIO->ctxForward = ctx;
752         ctxIO->bufIO = pDynBuf;
753         if (ctx->type == FORWARD_TCP || ctx->type == FORWARD_JDWP || ctx->type == FORWARD_ARK) {
754             nRet = Base::SendToStreamEx((uv_stream_t *)&ctx->tcp, pDynBuf, size, nullptr,
755                                         (void *)SendCallbackForwardBuf, (void *)ctxIO);
756         } else {
757             // FORWARD_ABSTRACT, FORWARD_RESERVED, FORWARD_FILESYSTEM,
758             nRet = Base::SendToStreamEx((uv_stream_t *)&ctx->pipe, pDynBuf, size, nullptr,
759                                         (void *)SendCallbackForwardBuf, (void *)ctxIO);
760         }
761     }
762     return nRet;
763 }
764 
CommandForwardCheckResult(HCtxForward ctx,uint8_t * payload)765 bool HdcForwardBase::CommandForwardCheckResult(HCtxForward ctx, uint8_t *payload)
766 {
767     bool ret = true;
768     bool bCheck = static_cast<bool>(payload);
769     LogMsg(bCheck ? MSG_OK : MSG_FAIL, "Forwardport result:%s", bCheck ? "OK" : "Failed");
770     if (bCheck) {
771         string mapInfo = taskInfo->serverOrDaemon ? "1|" : "0|";
772         mapInfo += taskCommand;
773         ctx->ready = true;
774         ServerCommand(CMD_FORWARD_SUCCESS, reinterpret_cast<uint8_t *>(const_cast<char *>(mapInfo.c_str())),
775                       mapInfo.size() + 1);
776     } else {
777         ret = false;
778         FreeContext(ctx, 0, false);
779     }
780     return ret;
781 }
782 
ForwardCommandDispatch(const uint16_t command,uint8_t * payload,const int payloadSize)783 bool HdcForwardBase::ForwardCommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize)
784 {
785     bool ret = true;
786     uint8_t *pContent = nullptr;
787     int sizeContent = 0;
788     uint32_t id = 0;
789     HCtxForward ctx = nullptr;
790     FilterCommand(payload, &id, &pContent);
791     sizeContent = payloadSize - DWORD_SERIALIZE_SIZE;
792     if (!(ctx = (HCtxForward)AdminContext(OP_QUERY, id, nullptr))) {
793         WRITE_LOG(LOG_WARN, "Query id:%u failed", id);
794         return true;
795     }
796     switch (command) {
797         case CMD_FORWARD_CHECK_RESULT: {
798             ret = CommandForwardCheckResult(ctx, pContent);
799             break;
800         }
801         case CMD_FORWARD_ACTIVE_MASTER: {
802             ret = DoForwardBegin(ctx);
803             break;
804         }
805         case CMD_FORWARD_DATA: {
806             if (ctx->finish) {
807                 break;
808             }
809             if (SendForwardBuf(ctx, pContent, sizeContent) < 0) {
810                 FreeContext(ctx, 0, true);
811             }
812             break;
813         }
814         case CMD_FORWARD_FREE_CONTEXT: {
815             FreeContext(ctx, 0, false);
816             break;
817         }
818         default:
819             ret = false;
820             break;
821     }
822     if (!ret) {
823         if (ctx) {
824             FreeContext(ctx, 0, true);
825         } else {
826             WRITE_LOG(LOG_DEBUG, "ctx==nullptr raw free");
827             TaskFinish();
828         }
829     }
830     return ret;
831 }
832 
CommandDispatch(const uint16_t command,uint8_t * payload,const int payloadSize)833 bool HdcForwardBase::CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize)
834 {
835     if (command != CMD_FORWARD_DATA) {
836         WRITE_LOG(LOG_DEBUG, "CommandDispatch command:%d payloadSize:%d", command, payloadSize);
837     }
838     bool ret = true;
839     string sError;
840     // prepare
841     if (command == CMD_FORWARD_INIT) {
842         string strCommand(reinterpret_cast<char *>(payload), payloadSize);
843         if (!BeginForward(strCommand, sError)) {
844             ret = false;
845             goto Finish;
846         }
847         return true;
848     } else if (command == CMD_FORWARD_CHECK) {
849         // Detect remote if it's reachable
850         if (!SlaveConnect(payload, true, sError)) {
851             ret = false;
852             goto Finish;
853         }
854         return true;
855     } else if (command == CMD_FORWARD_ACTIVE_SLAVE) {
856         // slave connect target port when activating
857         if (!SlaveConnect(payload, false, sError)) {
858             ret = false;
859             goto Finish;
860         }
861         return true;
862     }
863     if (!ForwardCommandDispatch(command, payload, payloadSize)) {
864         ret = false;
865         goto Finish;
866     }
867 Finish:
868     if (!ret) {
869         if (!sError.size()) {
870             LogMsg(MSG_FAIL, "Forward parament failed");
871         } else {
872             LogMsg(MSG_FAIL, const_cast<char *>(sError.c_str()));
873             WRITE_LOG(LOG_WARN, const_cast<char *>(sError.c_str()));
874         }
875     }
876     return ret;
877 }
878 }  // namespace Hdc
879