• 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 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
ZeroArray(T (& arrayBuf)[N])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
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
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
163     inline string &Trim(string &s, const string &w = WHITE_SPACES)
164     {
165         return LeftTrim(RightTrim(s, w), w);
166     }
167 
168     // Trim from both sides and paired
169     string &ShellCmdTrim(string &cmd);
170 
171     string ReplaceAll(string str, const string from, const string to);
172     uint8_t CalcCheckSum(const uint8_t *data, int len);
173     string GetFileNameAny(string &path);
174     string GetCwd();
175     string GetTmpDir();
176 #ifndef  HDC_HILOG
177     void SetLogCache(bool enable);
178     void RemoveLogFile();
179     void RemoveLogCache();
180     void RollLogFile(const char *path);
181     void ChmodLogFile();
182 #endif
183     uv_os_sock_t DuplicateUvSocket(uv_tcp_t *tcp);
184     bool IsRoot();
185     char GetPathSep();
186     string GetHdcAbsolutePath();
187     bool IsAbsolutePath(string &path);
GetMaxBufSize()188     inline int GetMaxBufSize()
189     {
190         return MAX_SIZE_IOBUF;
191     }
GetUsbffsBulkSize()192     inline int GetUsbffsBulkSize()
193     {
194         return MAX_USBFFS_BULK;
195     }
GetMaxBufSizeStable()196     inline int GetMaxBufSizeStable()
197     {
198         return MAX_SIZE_IOBUF_STABLE;
199     }
GetUsbffsBulkSizeStable()200     inline int GetUsbffsBulkSizeStable()
201     {
202         return MAX_USBFFS_BULK_STABLE;
203     }
204 
205     int CloseFd(int &fd);
206     void InitProcess(void);
207     void DeInitProcess(void);
208 #ifdef HDC_SUPPORT_FLASHD
209     // deprecated, remove later
SetHdcProperty(const char * key,const char * value)210     inline bool SetHdcProperty(const char *key, const char *value)
211     {
212         return false;
213     }
214     // deprecated, remove later
GetHdcProperty(const char * key,char * value,uint16_t sizeOutBuf)215     inline bool GetHdcProperty(const char *key, char *value, uint16_t sizeOutBuf)
216     {
217         return false;
218     }
219 #endif
220 
221     int ReadFromFd(int fd, void *buf, size_t count);
222     int WriteToFd(int fd, const void *buf, size_t count);
223 
224     #define DAEOMN_AUTH_SUCCESS "SUCCESS"
225     #define DAEOMN_UNAUTHORIZED "DAEMON_UNAUTH"
226 
227     #define TLV_TAG_LEN 16
228     #define TLV_VAL_LEN 16
229     #define TLV_MIN_LEN (TLV_TAG_LEN + TLV_VAL_LEN)
230     #define TAG_DEVNAME "devname"
231     #define TAG_HOSTNAME "hostname"
232     #define TAG_PUBKEY "pubkey"
233     #define TAG_EMGMSG "emgmsg"
234     #define TAG_TOKEN "token"
235     #define TAG_DAEOMN_AUTHSTATUS "daemonauthstatus"
236     #define TAG_AUTH_TYPE "authtype"
237     void TrimSubString(string &str, string substr);
238     bool TlvAppend(string &tlv, string tag, string val);
239     bool TlvToStringMap(string tlv, std::map<string, string> &tlvmap);
240     FILE *Fopen(const char *fileName, const char *mode);
241 }  // namespace base
242 }  // namespace Hdc
243 
244 #endif  // HDC_BASE_H
245