• 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_BASE_H
16 #define HDC_BASE_H
17 #include "common.h"
18 
19 #ifdef HDC_HILOG
20 #ifdef LOG_DOMAIN
21 #undef LOG_DOMAIN
22 #endif // LOG_DOMAIN
23 
24 #define LOG_DOMAIN 0xD002D13
25 #ifdef LOG_TAG
26 #undef LOG_TAG
27 #endif // LOG_TAG
28 
29 #define LOG_TAG "HDC_LOG"
30 
31 #define HDC_LOG_DEBUG(...) ((void)HILOG_IMPL(LOG_CORE, LogLevel::LOG_DEBUG, LOG_DOMAIN, LOG_TAG, __VA_ARGS__))
32 #define HDC_LOG_INFO(...) ((void)HILOG_IMPL(LOG_CORE, LogLevel::LOG_INFO, LOG_DOMAIN, LOG_TAG, __VA_ARGS__))
33 #define HDC_LOG_WARN(...) ((void)HILOG_IMPL(LOG_CORE, LogLevel::LOG_WARN, LOG_DOMAIN, LOG_TAG, __VA_ARGS__))
34 #define HDC_LOG_ERROR(...) ((void)HILOG_IMPL(LOG_CORE, LogLevel::LOG_ERROR, LOG_DOMAIN, LOG_TAG, __VA_ARGS__))
35 #define HDC_LOG_FATAL(...) ((void)HILOG_IMPL(LOG_CORE, LogLevel::LOG_FATAL, LOG_DOMAIN, LOG_TAG, __VA_ARGS__))
36 
37 #endif // HDC_HILOG
38 
39 namespace Hdc {
40 namespace Base {
41     uint8_t GetLogLevel();
42     extern bool g_isBackgroundServer;
43     extern uint8_t g_logLevel;
44     void SetLogLevel(const uint8_t logLevel);
45     uint8_t GetLogLevelByEnv();
46     void PrintMessage(const char *fmt, ...);
47     void PrintMessageAndWriteLog(const char *fmt, ...);
48     // tcpHandle can't be const as it's passed into uv_tcp_keepalive
49     void SetTcpOptions(uv_tcp_t *tcpHandle, int bufMaxSize = HDC_SOCKETPAIR_SIZE);
50 #ifdef HOST_OHOS
51     void SetUdsOptions(uv_pipe_t *udsHandle, int bufMaxSize = HDC_SOCKETPAIR_SIZE);
52 #endif
53     // Realloc need to update origBuf&origSize which can't be const
54     void ReallocBuf(uint8_t **origBuf, int *nOrigSize, size_t sizeWanted);
55     // handle&sendHandle must keep sync with uv_write
56     int SendToStreamEx(uv_stream_t *handleStream, const uint8_t *buf, const int bufLen, uv_stream_t *handleSend,
57                        const void *finishCallback, const void *pWriteReqData);
58     int SendToStream(uv_stream_t *handleStream, const uint8_t *buf, const int bufLen);
59     int SendToPollFd(int fd, const uint8_t *buf, const int bufLen);
60     // As an uv_write_cb it must keep the same as prototype
61     void SendCallback(uv_write_t *req, int status);
62     // As an uv_alloc_cb it must keep the same as prototype
63     void AllocBufferCallback(uv_handle_t *handle, size_t sizeSuggested, uv_buf_t *buf);
64     uint64_t GetRuntimeMSec();
65     string GetRandomString(const uint16_t expectedLen);
66 #ifndef HDC_HOST
67     string GetSecureRandomString(const uint16_t expectedLen);
68 #endif
69     int GetRandomNum(const int min, const int max);
70     uint32_t GetRandomU32();
71     uint64_t GetRandom(const uint64_t min = 0, const uint64_t max = UINT64_MAX);
72     uint32_t GetSecureRandom(void);
73     int ConnectKey2IPPort(const char *connectKey, char *outIP, uint16_t *outPort, size_t outSize);
74     // As an uv_work_cb it must keep the same as prototype
75     int StartWorkThread(uv_loop_t *loop, uv_work_cb pFuncWorkThread, uv_after_work_cb pFuncAfterThread,
76                         void *pThreadData);
77     // As an uv_work_cb it must keep the same as prototype
78     void FinishWorkThread(uv_work_t *req, int status);
79     int GetMaxBufSize();
80     bool TryCloseLoop(uv_loop_t *ptrLoop, const char *callerName);
81     bool TryCloseChildLoop(uv_loop_t *ptrLoop, const char *callerName);
82     void TryCloseHandle(const uv_handle_t *handle);
83     void TryCloseHandle(const uv_handle_t *handle, uv_close_cb closeCallBack);
84     void TryCloseHandle(const uv_handle_t *handle, bool alwaysCallback, uv_close_cb closeCallBack);
85     void DispUvStreamInfo(const uv_stream_t *handle, const char *prefix);
86     char **SplitCommandToArgs(const char *cmdStringLine, int *slotIndex);
87     bool RunPipeComand(const char *cmdString, char *outBuf, uint16_t sizeOutBuf, bool ignoreTailLf);
88     // results need to save in buf which can't be const
89     int ReadBinFile(const char *pathName, void **buf, const size_t bufLen);
90     int WriteBinFile(const char *pathName, const uint8_t *buf, const size_t bufLen, bool newFile = false);
91     void CloseIdleCallback(uv_handle_t *handle);
92     void CloseTimerCallback(uv_handle_t *handle);
93     int ProgramMutex(const char *procname, bool checkOrNew);
94     // result needs to save results which can't be const
95     void SplitString(const string &origString, const string &seq, vector<string> &resultStrings);
96     string GetShellPath();
97     uint64_t HostToNet(uint64_t val);
98     uint64_t NetToHost(uint64_t val);
99     string GetFullFilePath(string &s);
100     string GetPathWithoutFilename(const string &s);
101     int CreateSocketPair(int *fds);
102     void CloseSocketPair(int *fds);
103     int StringEndsWith(string s, string sub);
104     void BuildErrorString(const char *localPath, const char *op, const char *err, string &str);
105     const char *GetFileType(mode_t mode);
106     bool CheckDirectoryOrPath(const char *localPath, bool pathOrDir, bool readWrite, string &errStr, mode_t &fm);
107     bool CheckDirectoryOrPath(const char *localPath, bool pathOrDir, bool readWrite);
108     int Base64EncodeBuf(const uint8_t *input, const int length, uint8_t *bufOut);
109     vector<uint8_t> Base64Encode(const uint8_t *input, const int length);
110     int Base64DecodeBuf(const uint8_t *input, const int length, uint8_t *bufOut);
111     string Base64Decode(const uint8_t *input, const int length);
112     string UnicodeToUtf8(const char *src, bool reverse = false);
113     void ReverseBytes(void *start, int size);
114     string Convert2HexStr(uint8_t arr[], int length);
115     string CanonicalizeSpecPath(string &src);
116     bool TryCreateDirectory(const string &path, string &err);
117     // Just zero a POD type, such as a structure or union
118     // If it contains c++ struct such as stl-string or others, please use 'T = {}' to initialize struct
ZeroStruct(T & structBuf)119     template<class T> int ZeroStruct(T &structBuf)
120     {
121         return memset_s(&structBuf, sizeof(T), 0, sizeof(T));
122     }
123     // just zero a statically allocated array of POD or built-in types
ZeroArray(T (& arrayBuf)[N])124     template<class T, size_t N> int ZeroArray(T (&arrayBuf)[N])
125     {
126         return memset_s(arrayBuf, sizeof(T) * N, 0, sizeof(T) * N);
127     }
128     // just zero memory buf, such as pointer
ZeroBuf(T & arrayBuf,int size)129     template<class T> int ZeroBuf(T &arrayBuf, int size)
130     {
131         return memset_s(arrayBuf, size, 0, size);
132     }
133     // clang-format off
134     const string StringFormat(const char * const formater, ...);
135     const string StringFormat(const char * const formater, va_list &vaArgs);
136     // clang-format on
137     string GetVersion();
138     bool IdleUvTask(uv_loop_t *loop, void *data, uv_idle_cb cb);
139     bool TimerUvTask(uv_loop_t *loop, void *data, uv_timer_cb cb, int repeatTimeout = UV_DEFAULT_INTERVAL);
140     bool DelayDo(uv_loop_t *loop, const int delayMs, const uint8_t flag, string msg, void *data,
141                  std::function<void(const uint8_t, string &, const void *)> cb);
DelayDoSimple(uv_loop_t * loop,const int delayMs,std::function<void (const uint8_t,string &,const void *)> cb)142     inline bool DelayDoSimple(uv_loop_t *loop, const int delayMs,
143                               std::function<void(const uint8_t, string &, const void *)> cb)
144     {
145         return DelayDo(loop, delayMs, 0, "", nullptr, cb);
146     }
DoNextLoop(uv_loop_t * loop,void * data,std::function<void (const uint8_t,string &,const void *)> cb)147     inline bool DoNextLoop(uv_loop_t *loop, void *data, std::function<void(const uint8_t, string &, const void *)> cb)
148     {
149         return DelayDo(loop, 0, 0, "", data, cb);
150     }
151 
152     // Trim from right side
153     inline string &RightTrim(string &s, const string &w = WHITE_SPACES)
154     {
155         s.erase(s.find_last_not_of(w) + 1);
156         return s;
157     }
158 
159     // Trim from left side
160     inline string &LeftTrim(string &s, const string &w = WHITE_SPACES)
161     {
162         s.erase(0, s.find_first_not_of(w));
163         return s;
164     }
165 
166     // Trim from both sides
167     inline string &Trim(string &s, const string &w = WHITE_SPACES)
168     {
169         return LeftTrim(RightTrim(s, w), w);
170     }
171 
IsDigitString(const std::string & str)172     inline bool IsDigitString(const std::string& str)
173     {
174         return std::all_of(str.begin(), str.end(), ::isdigit);
175     }
176 
177     bool IsValidIpv4(const std::string& ip);
178 
179     // Trim from both sides and paired
180     string &ShellCmdTrim(string &cmd);
181 
182     string ReplaceAll(string str, const string from, const string to);
183     uint8_t CalcCheckSum(const uint8_t *data, int len);
184     string GetFileNameAny(string &path);
185     string GetCwd();
186     string GetTmpDir();
GetTarToolName()187     inline string GetTarToolName()
188     {
189         return LOG_COMPRESS_TOOL_NAME;
190     }
GetTarParams()191     inline string GetTarParams()
192     {
193         return LOG_COMPRESS_TOOL_PARAMS;
194     }
195     void GetTimeString(string& timeString);
196 #ifndef HDC_HILOG
197     void SetLogCache(bool enable);
198     void RemoveLogFile();
199     void RemoveLogCache();
200     void RollLogFile(const char *path);
201     void ChmodLogFile();
202     bool CreateLogDir();
203     bool CompressLogFile(string fileName);
204     void CompressLogFiles();
205     void RemoveOlderLogFiles();
206     vector<string> GetDirFileName();
207     string GetCompressLogFileName(string fileName);
208     uint32_t GetLogOverCount(vector<string> files, uint64_t limitDirSize);
209     string GetLogDirName();
210     string GetLogNameWithTime();
GetTarBinFile()211     inline string GetTarBinFile()
212     {
213 #ifdef _WIN32
214         return LOG_COMPRESS_TOOL_BIN_WIN32;
215 #else
216         return LOG_COMPRESS_TOOL_BIN_UNIX;
217 #endif
218     }
219 #endif
220     uv_os_sock_t DuplicateUvSocket(uv_tcp_t *tcp);
221 #ifdef HOST_OHOS
222     uv_os_sock_t DuplicateUvPipe(uv_pipe_t *pipe);
223 #endif
224     bool IsRoot();
225     char GetPathSep();
226     string GetHdcAbsolutePath();
227     bool IsAbsolutePath(string &path);
GetMaxBufSize()228     inline int GetMaxBufSize()
229     {
230         return MAX_SIZE_IOBUF;
231     }
GetUsbffsBulkSize()232     inline int GetUsbffsBulkSize()
233     {
234         return MAX_USBFFS_BULK;
235     }
GetMaxBufSizeStable()236     inline int GetMaxBufSizeStable()
237     {
238         return MAX_SIZE_IOBUF_STABLE;
239     }
GetUsbffsBulkSizeStable()240     inline int GetUsbffsBulkSizeStable()
241     {
242         return MAX_USBFFS_BULK_STABLE;
243     }
244 
245     int CloseFd(int &fd);
246     void InitProcess(void);
247     void DeInitProcess(void);
248 #ifdef HDC_SUPPORT_FLASHD
249     // deprecated, remove later
SetHdcProperty(const char * key,const char * value)250     inline bool SetHdcProperty(const char *key, const char *value)
251     {
252         return false;
253     }
254     // deprecated, remove later
GetHdcProperty(const char * key,char * value,uint16_t sizeOutBuf)255     inline bool GetHdcProperty(const char *key, char *value, uint16_t sizeOutBuf)
256     {
257         return false;
258     }
259 #endif
260 
261     int ReadFromFd(int fd, void *buf, size_t count);
262     int WriteToFd(int fd, const void *buf, size_t count);
263 
264     #define DAEOMN_AUTH_SUCCESS "SUCCESS"
265     #define DAEOMN_UNAUTHORIZED "DAEMON_UNAUTH"
266 
267     #define TLV_TAG_LEN 16
268     #define TLV_VAL_LEN 16
269     #define TLV_MIN_LEN (TLV_TAG_LEN + TLV_VAL_LEN)
270     #define TAG_DEVNAME "devname"
271     #define TAG_HOSTNAME "hostname"
272     #define TAG_PUBKEY "pubkey"
273     #define TAG_EMGMSG "emgmsg"
274     #define TAG_TOKEN "token"
275     #define TAG_DAEOMN_AUTHSTATUS "daemonauthstatus"
276     #define TAG_AUTH_TYPE "authtype"
277     #define TAG_FEATURE_SHELL_OPT "1200" // CMD_UNITY_EXECUTE_EX
278     #define TAG_SUPPORT_FEATURE "supportfeatures"
279     void TrimSubString(string &str, string substr);
280     bool TlvAppend(string &tlv, string tag, string val);
281     bool TlvToStringMap(string tlv, std::map<string, string> &tlvmap);
282     FILE *Fopen(const char *fileName, const char *mode);
283     void AddDeletedSessionId(uint32_t sessionId);
284     bool IsSessionDeleted(uint32_t sessionId);
285     bool CheckBundleName(const string &bundleName);
286     void CloseOpenFd(void);
287     const std::set<uint32_t> REGISTERD_TAG_SET = {
288         TAG_SHELL_BUNDLE,
289         TAG_SHELL_CMD,
290     };
291     bool CanPrintCmd(const uint16_t command);
292     void UpdateEnvCache();
293     #define FEATURE_HEARTBEAT "heartbeat"
294     #define FEATURE_ENCRYPT_TCP "encrypt_tcp"
295     using HdcFeatureSet = std::vector<std::string>;
296     const HdcFeatureSet& GetSupportFeature(void);
297     std::string FeatureToString(const HdcFeatureSet& feature);
298     void StringToFeatureSet(const std::string featureStr, HdcFeatureSet& features);
299     bool IsSupportFeature(const HdcFeatureSet& features, std::string feature);
300     void UpdateHeartbeatSwitchCache();
301     bool GetheartbeatSwitch();
302     bool WriteToFile(const std::string& fileName, const std::string &content, std::ios_base::openmode mode);
303     void UpdateCmdLogSwitch();
304     bool GetCmdLogSwitch();
305     std::string CmdLogStringFormat(uint32_t targetSessionId, const std::string& cmdStr);
306     void ProcessCmdLogs();
307     void UpdateEncrpytTCPCache();
308     bool GetEncrpytTCPSwitch();
309 }  // namespace base
310 }  // namespace Hdc
311 
312 #endif  // HDC_BASE_H
313