• 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     uint64_t GetRandom(const uint64_t min = 0, const uint64_t max = UINT64_MAX);
67     uint32_t GetSecureRandom(void);
68     int ConnectKey2IPPort(const char *connectKey, char *outIP, uint16_t *outPort, size_t outSize);
69     // As an uv_work_cb it must keep the same as prototype
70     int StartWorkThread(uv_loop_t *loop, uv_work_cb pFuncWorkThread, uv_after_work_cb pFuncAfterThread,
71                         void *pThreadData);
72     // As an uv_work_cb it must keep the same as prototype
73     void FinishWorkThread(uv_work_t *req, int status);
74     int GetMaxBufSize();
75     bool TryCloseLoop(uv_loop_t *ptrLoop, const char *callerName);
76     bool TryCloseChildLoop(uv_loop_t *ptrLoop, const char *callerName);
77     void TryCloseHandle(const uv_handle_t *handle);
78     void TryCloseHandle(const uv_handle_t *handle, uv_close_cb closeCallBack);
79     void TryCloseHandle(const uv_handle_t *handle, bool alwaysCallback, uv_close_cb closeCallBack);
80     void DispUvStreamInfo(const uv_stream_t *handle, const char *prefix);
81     char **SplitCommandToArgs(const char *cmdStringLine, int *slotIndex);
82     bool RunPipeComand(const char *cmdString, char *outBuf, uint16_t sizeOutBuf, bool ignoreTailLf);
83     // results need to save in buf which can't be const
84     int ReadBinFile(const char *pathName, void **buf, const size_t bufLen);
85     int WriteBinFile(const char *pathName, const uint8_t *buf, const size_t bufLen, bool newFile = false);
86     void CloseIdleCallback(uv_handle_t *handle);
87     void CloseTimerCallback(uv_handle_t *handle);
88     int ProgramMutex(const char *procname, bool checkOrNew);
89     // result needs to save results which can't be const
90     void SplitString(const string &origString, const string &seq, vector<string> &resultStrings);
91     string GetShellPath();
92     uint64_t HostToNet(uint64_t val);
93     uint64_t NetToHost(uint64_t val);
94     string GetFullFilePath(string &s);
95     string GetPathWithoutFilename(const string &s);
96     int CreateSocketPair(int *fds);
97     void CloseSocketPair(int *fds);
98     int StringEndsWith(string s, string sub);
99     void BuildErrorString(const char *localPath, const char *op, const char *err, string &str);
100     const char *GetFileType(mode_t mode);
101     bool CheckDirectoryOrPath(const char *localPath, bool pathOrDir, bool readWrite, string &errStr, mode_t &fm);
102     bool CheckDirectoryOrPath(const char *localPath, bool pathOrDir, bool readWrite);
103     int Base64EncodeBuf(const uint8_t *input, const int length, uint8_t *bufOut);
104     vector<uint8_t> Base64Encode(const uint8_t *input, const int length);
105     int Base64DecodeBuf(const uint8_t *input, const int length, uint8_t *bufOut);
106     string Base64Decode(const uint8_t *input, const int length);
107     string UnicodeToUtf8(const char *src, bool reverse = false);
108     void ReverseBytes(void *start, int size);
109     string Convert2HexStr(uint8_t arr[], int length);
110     string CanonicalizeSpecPath(string &src);
111     bool TryCreateDirectory(const string &path, string &err);
112     // Just zero a POD type, such as a structure or union
113     // If it contains c++ struct such as stl-string or others, please use 'T = {}' to initialize struct
ZeroStruct(T & structBuf)114     template<class T> int ZeroStruct(T &structBuf)
115     {
116         return memset_s(&structBuf, sizeof(T), 0, sizeof(T));
117     }
118     // just zero a statically allocated array of POD or built-in types
ZeroArray(T (& arrayBuf)[N])119     template<class T, size_t N> int ZeroArray(T (&arrayBuf)[N])
120     {
121         return memset_s(arrayBuf, sizeof(T) * N, 0, sizeof(T) * N);
122     }
123     // just zero memory buf, such as pointer
ZeroBuf(T & arrayBuf,int size)124     template<class T> int ZeroBuf(T &arrayBuf, int size)
125     {
126         return memset_s(arrayBuf, size, 0, size);
127     }
128     // clang-format off
129     const string StringFormat(const char * const formater, ...);
130     const string StringFormat(const char * const formater, va_list &vaArgs);
131     // clang-format on
132     string GetVersion();
133     bool IdleUvTask(uv_loop_t *loop, void *data, uv_idle_cb cb);
134     bool TimerUvTask(uv_loop_t *loop, void *data, uv_timer_cb cb, int repeatTimeout = UV_DEFAULT_INTERVAL);
135     bool DelayDo(uv_loop_t *loop, const int delayMs, const uint8_t flag, string msg, void *data,
136                  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)137     inline bool DelayDoSimple(uv_loop_t *loop, const int delayMs,
138                               std::function<void(const uint8_t, string &, const void *)> cb)
139     {
140         return DelayDo(loop, delayMs, 0, "", nullptr, cb);
141     }
DoNextLoop(uv_loop_t * loop,void * data,std::function<void (const uint8_t,string &,const void *)> cb)142     inline bool DoNextLoop(uv_loop_t *loop, void *data, std::function<void(const uint8_t, string &, const void *)> cb)
143     {
144         return DelayDo(loop, 0, 0, "", data, cb);
145     }
146 
147     // Trim from right side
148     inline string &RightTrim(string &s, const string &w = WHITE_SPACES)
149     {
150         s.erase(s.find_last_not_of(w) + 1);
151         return s;
152     }
153 
154     // Trim from left side
155     inline string &LeftTrim(string &s, const string &w = WHITE_SPACES)
156     {
157         s.erase(0, s.find_first_not_of(w));
158         return s;
159     }
160 
161     // Trim from both sides
162     inline string &Trim(string &s, const string &w = WHITE_SPACES)
163     {
164         return LeftTrim(RightTrim(s, w), w);
165     }
166 
167     // Trim from both sides and paired
168     string &ShellCmdTrim(string &cmd);
169 
170     string ReplaceAll(string str, const string from, const string to);
171     uint8_t CalcCheckSum(const uint8_t *data, int len);
172     string GetFileNameAny(string &path);
173     string GetCwd();
174     string GetTmpDir();
175 #ifndef  HDC_HILOG
176     void SetLogCache(bool enable);
177     void RemoveLogFile();
178     void RemoveLogCache();
179     void RollLogFile(const char *path);
180     void ChmodLogFile();
181 #endif
182     uv_os_sock_t DuplicateUvSocket(uv_tcp_t *tcp);
183     bool IsRoot();
184     char GetPathSep();
185     string GetHdcAbsolutePath();
186     bool IsAbsolutePath(string &path);
GetMaxBufSize()187     inline int GetMaxBufSize()
188     {
189         return MAX_SIZE_IOBUF;
190     }
GetUsbffsBulkSize()191     inline int GetUsbffsBulkSize()
192     {
193         return MAX_USBFFS_BULK;
194     }
GetMaxBufSizeStable()195     inline int GetMaxBufSizeStable()
196     {
197         return MAX_SIZE_IOBUF_STABLE;
198     }
GetUsbffsBulkSizeStable()199     inline int GetUsbffsBulkSizeStable()
200     {
201         return MAX_USBFFS_BULK_STABLE;
202     }
203 
204     int CloseFd(int &fd);
205     void InitProcess(void);
206     void DeInitProcess(void);
207 #ifdef HDC_SUPPORT_FLASHD
208     // deprecated, remove later
SetHdcProperty(const char * key,const char * value)209     inline bool SetHdcProperty(const char *key, const char *value)
210     {
211         return false;
212     }
213     // deprecated, remove later
GetHdcProperty(const char * key,char * value,uint16_t sizeOutBuf)214     inline bool GetHdcProperty(const char *key, char *value, uint16_t sizeOutBuf)
215     {
216         return false;
217     }
218 #endif
219 
220     int ReadFromFd(int fd, void *buf, size_t count);
221     int WriteToFd(int fd, const void *buf, size_t count);
222 
223     #define DAEOMN_AUTH_SUCCESS "SUCCESS"
224     #define DAEOMN_UNAUTHORIZED "DAEMON_UNAUTH"
225 
226     #define TLV_TAG_LEN 16
227     #define TLV_VAL_LEN 16
228     #define TLV_MIN_LEN (TLV_TAG_LEN + TLV_VAL_LEN)
229     #define TAG_DEVNAME "devname"
230     #define TAG_HOSTNAME "hostname"
231     #define TAG_PUBKEY "pubkey"
232     #define TAG_EMGMSG "emgmsg"
233     #define TAG_TOKEN "token"
234     #define TAG_DAEOMN_AUTHSTATUS "daemonauthstatus"
235     #define TAG_AUTH_TYPE "authtype"
236     void TrimSubString(string &str, string substr);
237     bool TlvAppend(string &tlv, string tag, string val);
238     bool TlvToStringMap(string tlv, std::map<string, string> &tlvmap);
239     FILE *Fopen(const char *fileName, const char *mode);
240 }  // namespace base
241 }  // namespace Hdc
242 
243 #endif  // HDC_BASE_H
244