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