• 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 #ifndef HDC_SESSION_H
16 #define HDC_SESSION_H
17 #include <shared_mutex>
18 #include <sstream>
19 #include "common.h"
20 
21 namespace Hdc {
22 enum TaskType { TYPE_UNITY, TYPE_SHELL, TASK_FILE, TASK_FORWARD, TASK_APP, TASK_FLASHD };
23 
24 class HdcSessionBase {
25 public:
26     enum AuthType { AUTH_NONE, AUTH_TOKEN, AUTH_SIGNATURE, AUTH_PUBLICKEY, AUTH_OK, AUTH_FAIL };
27     struct SessionHandShake {
28         string banner; // must first index
29         // auth none
30         uint8_t authType;
31         uint32_t sessionId;
32         string connectKey;
33         string buf;
34         string version;
ToDebugStringSessionHandShake35         std::string ToDebugString()
36         {
37             std::ostringstream oss;
38             oss << "SessionHandShake [";
39             oss << " banner:" << banner;
40             oss << " sessionId:" << sessionId;
41             oss << " authType:" << unsigned(authType);
42             oss << " connectKey:" << Hdc::MaskString(connectKey);
43             oss << " version:" << version;
44             oss << "]";
45             return oss.str();
46         }
47     };
48 
49     struct CtrlStruct {
50         InnerCtrlCommand command;
51         uint32_t channelId;
52         uint8_t dataSize;
53         uint8_t data[BUF_SIZE_MICRO];
54     };
55     struct PayloadProtect {  // reserve for encrypt and decrypt
56         uint32_t channelId;
57         uint32_t commandFlag;
58         uint8_t checkSum;  // enable it will be lose about 20% speed
59         uint8_t vCode;
60     };
61 
62     HdcSessionBase(bool serverOrDaemonIn, size_t uvThreadSize = SIZE_THREAD_POOL);
63     virtual ~HdcSessionBase();
AttachChannel(HSession hSession,const uint32_t channelId)64     virtual void AttachChannel(HSession hSession, const uint32_t channelId)
65     {
66     }
DeatchChannel(HSession hSession,const uint32_t channelId)67     virtual void DeatchChannel(HSession hSession, const uint32_t channelId)
68     {
69     }
NotifyInstanceSessionFree(HSession hSession,bool freeOrClear)70     virtual void NotifyInstanceSessionFree(HSession hSession, bool freeOrClear)
71     {
72     }
RedirectToTask(HTaskInfo hTaskInfo,HSession hSession,const uint32_t channelId,const uint16_t command,uint8_t * payload,const int payloadSize)73     virtual bool RedirectToTask(HTaskInfo hTaskInfo, HSession hSession, const uint32_t channelId,
74                                 const uint16_t command, uint8_t *payload, const int payloadSize)
75     {
76         return true;
77     }
78     // Thread security interface for global stop programs
79     void PostStopInstanceMessage(bool restart = false);
80     void ReMainLoopForInstanceClear();
81     // server, Two parameters in front of call can be empty
82     void LogMsg(const uint32_t sessionId, const uint32_t channelId, MessageLevel level, const char *msg, ...);
83     static void AllocCallback(uv_handle_t *handle, size_t sizeWanted, uv_buf_t *buf);
84     static void MainAsyncCallback(uv_async_t *handle);
85     static void FinishWriteSessionTCP(uv_write_t *req, int status);
86     static void SessionWorkThread(uv_work_t *arg);
87     static void ReadCtrlFromSession(uv_poll_t *poll, int status, int events);
88     static void ReadCtrlFromMain(uv_poll_t *poll, int status, int events);
89     HSession QueryUSBDeviceRegister(void *pDev, uint8_t busIDIn, uint8_t devIDIn);
90     virtual HSession MallocSession(bool serverOrDaemon, const ConnType connType, void *classModule,
91                                    uint32_t sessionId = 0);
92     virtual void FreeSession(const uint32_t sessionId);
93     void WorkerPendding();
94     int OnRead(HSession hSession, uint8_t *bufPtr, const int bufLen);
95     int Send(const uint32_t sessionId, const uint32_t channelId, const uint16_t commandFlag, const uint8_t *data,
96              const int dataSize);
97     int SendByProtocol(HSession hSession, uint8_t *bufPtr, const int bufLen, bool echo = false);
98     virtual HSession AdminSession(const uint8_t op, const uint32_t sessionId, HSession hInput);
99     void AddDeletedSessionId(uint32_t sessionId);
100     bool IsSessionDeleted(uint32_t sessionId) const;
101     virtual int FetchIOBuf(HSession hSession, uint8_t *ioBuf, int read);
102     virtual void PushAsyncMessage(const uint32_t sessionId, const uint8_t method, const void *data, const int dataSize);
103     HTaskInfo AdminTask(const uint8_t op, HSession hSession, const uint32_t channelId, HTaskInfo hInput);
104     bool DispatchTaskData(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
105                           int payloadSize);
106     void EnumUSBDeviceRegister(void (*pCallBack)(HSession hSession));
107 #ifdef HDC_SUPPORT_UART
108     using UartKickoutZombie = const std::function<void(HSession hSession)>;
109     virtual void EnumUARTDeviceRegister(UartKickoutZombie);
110 #endif
111     void ClearOwnTasks(HSession hSession, const uint32_t channelIDInput);
FetchCommand(HSession hSession,const uint32_t channelId,const uint16_t command,uint8_t * payload,int payloadSize)112     virtual bool FetchCommand(HSession hSession, const uint32_t channelId, const uint16_t command, uint8_t *payload,
113                               int payloadSize)
114     {
115         return true;
116     }
ServerCommand(const uint32_t sessionId,const uint32_t channelId,const uint16_t command,uint8_t * bufPtr,const int size)117     virtual bool ServerCommand(const uint32_t sessionId, const uint32_t channelId, const uint16_t command,
118                                uint8_t *bufPtr, const int size)
119     {
120         return true;
121     }
RemoveInstanceTask(const uint8_t op,HTaskInfo hTask)122     virtual bool RemoveInstanceTask(const uint8_t op, HTaskInfo hTask)
123     {
124         return true;
125     }
WantRestart()126     bool WantRestart()
127     {
128         return wantRestart;
129     }
130     static vector<uint8_t> BuildCtrlString(InnerCtrlCommand command, uint32_t channelId, uint8_t *data, int dataSize);
131     uv_loop_t loopMain;
132     bool serverOrDaemon;
133     uv_async_t asyncMainLoop;
134     uv_rwlock_t mainAsync;
135     list<void *> lstMainThreadOP;
136     void *ctxUSB;
137 
138 protected:
139     struct PayloadHead {
140         uint8_t flag[2];
141         uint8_t reserve[2];  // encrypt'flag or others options
142         uint8_t protocolVer;
143         uint16_t headSize;
144         uint32_t dataSize;
145     } __attribute__((packed));
146     void ClearSessions();
JdwpNewFileDescriptor(const uint8_t * buf,const int bytesIO)147     virtual void JdwpNewFileDescriptor(const uint8_t *buf, const int bytesIO)
148     {
149     }
150     // must be define in haderfile, cannot in cpp file
151     template<class T>
TaskCommandDispatch(HTaskInfo hTaskInfo,uint8_t taskType,const uint16_t command,uint8_t * payload,const int payloadSize)152     bool TaskCommandDispatch(HTaskInfo hTaskInfo, uint8_t taskType, const uint16_t command, uint8_t *payload,
153                              const int payloadSize)
154     {
155         StartTraceScope("HdcSessionBase::TaskCommandDispatch");
156         bool ret = true;
157         T *ptrTask = nullptr;
158         if (!hTaskInfo->hasInitial) {
159             hTaskInfo->taskType = taskType;
160             ptrTask = new(std::nothrow) T(hTaskInfo);
161             if (ptrTask == nullptr) {
162                 return false;
163             }
164             hTaskInfo->hasInitial = true;
165             hTaskInfo->taskClass = ptrTask;
166         } else {
167             ptrTask = static_cast<T *>(hTaskInfo->taskClass);
168         }
169         if (!ptrTask->CommandDispatch(command, payload, payloadSize)) {
170             ptrTask->TaskFinish();
171         }
172         return ret;
173     }
DoTaskRemove(HTaskInfo hTaskInfo,const uint8_t op)174     template<class T> bool DoTaskRemove(HTaskInfo hTaskInfo, const uint8_t op)
175     {
176         T *ptrTask = static_cast<T *>(hTaskInfo->taskClass);
177         if (ptrTask == nullptr) {
178             return true;
179         }
180         if (op == OP_CLEAR) {
181             ptrTask->StopTask();
182         } else if (op == OP_REMOVE) {
183             if (!ptrTask->ReadyForRelease()) {
184                 return false;
185             }
186             delete ptrTask;
187         }
188         return true;
189     }
190     bool wantRestart;
191 
192 private:
ClearInstanceResource()193     virtual void ClearInstanceResource()
194     {
195     }
196     int DecryptPayload(HSession hSession, PayloadHead *payloadHeadBe, uint8_t *encBuf);
197     bool DispatchMainThreadCommand(HSession hSession, const CtrlStruct *ctrl);
198     bool DispatchSessionThreadCommand(HSession hSession, const uint8_t *baseBuf,
199                                       const int bytesIO);
200     void BeginRemoveTask(HTaskInfo hTask);
201     bool TryRemoveTask(HTaskInfo hTask);
202     void ReChildLoopForSessionClear(HSession hSession);
203     void FreeSessionContinue(HSession hSession);
204     static void FreeSessionFinally(uv_idle_t *handle);
205     static void AsyncMainLoopTask(uv_idle_t *handle);
206     static void FreeSessionOpeate(uv_timer_t *handle);
207     int MallocSessionByConnectType(HSession hSession);
208     void FreeSessionByConnectType(HSession hSession);
209     bool WorkThreadStartSession(HSession hSession);
210     void WorkThreadInitSession(HSession hSession, SessionHandShake &handshake);
211     uint32_t GetSessionPseudoUid();
212     bool NeedNewTaskInfo(const uint16_t command, bool &masterTask);
213     void DumpTasksInfo(map<uint32_t, HTaskInfo> &mapTask);
214 
215     map<uint32_t, HSession> mapSession;
216     std::set<uint32_t> deletedSessionIdSet;
217     std::queue<uint32_t> deletedSessionIdQueue;
218     mutable std::shared_mutex deletedSessionIdRecordMutex;
219     uv_rwlock_t lockMapSession;
220     std::atomic<uint32_t> sessionRef = 0;
221     const uint8_t payloadProtectStaticVcode = 0x09;
222     uv_thread_t threadSessionMain;
223     size_t threadPoolCount;
224 };
225 }  // namespace Hdc
226 #endif
227