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