1 /*
2  * Copyright (c) 2022-2024 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 
16 #include "daudio_util.h"
17 
18 #include <cstddef>
19 #include <ctime>
20 #include <iomanip>
21 #include <map>
22 #include <ostream>
23 #include <random>
24 #include <sstream>
25 #include <sstream>
26 #include <sys/time.h>
27 
28 #include "softbus_bus_center.h"
29 
30 #include "audio_event.h"
31 #include "daudio_constants.h"
32 #include "daudio_errorcode.h"
33 #include "daudio_log.h"
34 #include "parameter.h"
35 
36 #undef DH_LOG_TAG
37 #define DH_LOG_TAG "DAudioUtil"
38 
39 namespace OHOS {
40 namespace DistributedHardware {
41 using JsonTypeCheckFunc = bool (*)(const cJSON *jsonObj, const std::string &key);
42 constexpr int32_t WORD_WIDTH_8 = 8;
43 constexpr int32_t WORD_WIDTH_4 = 4;
44 constexpr size_t INT32_SHORT_ID_LENGTH = 20;
45 constexpr size_t INT32_MIN_ID_LENGTH = 3;
46 constexpr size_t INT32_PLAINTEXT_LENGTH = 4;
47 constexpr uint8_t MAX_KEY_DH_ID_LEN = 20;
48 
49 std::map<std::string, JsonTypeCheckFunc> typeCheckMap = {
50     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_TYPE, &DistributedHardware::IsInt32),
51     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_EVENT_CONTENT, &DistributedHardware::IsString),
52     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_DH_ID, &DistributedHardware::IsString),
53     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_REQID, &DistributedHardware::IsString),
54     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_VERSION, &DistributedHardware::IsString),
55     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_CHANGE_TYPE, &DistributedHardware::IsString),
56     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_DEV_ID, &DistributedHardware::IsString),
57     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_RESULT, &DistributedHardware::IsInt32),
58     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_EVENT_TYPE, &DistributedHardware::IsInt32),
59     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_AUDIO_PARAM, &DistributedHardware::IsAudioParam),
60     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_ATTRS, &DistributedHardware::IsString),
61     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_RANDOM_TASK_CODE, &DistributedHardware::IsString),
62     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_SAMPLING_RATE, &DistributedHardware::IsInt32),
63     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_CHANNELS, &DistributedHardware::IsInt32),
64     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_FORMAT, &DistributedHardware::IsInt32),
65     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_SOURCE_TYPE, &DistributedHardware::IsInt32),
66     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_CONTENT_TYPE, &DistributedHardware::IsInt32),
67     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_STREAM_USAGE, &DistributedHardware::IsInt32),
68     std::map<std::string, JsonTypeCheckFunc>::value_type(KEY_DATATYPE, &DistributedHardware::IsString),
69 };
70 
71 std::map<int32_t, std::string> eventNameMap = {
72     std::make_pair(EVENT_UNKNOWN, "EVENT_UNKNOWN"),
73     std::make_pair(OPEN_CTRL, "OPEN_CTRL"),
74     std::make_pair(CLOSE_CTRL, "CLOSE_CTRL"),
75     std::make_pair(CTRL_OPENED, "CTRL_OPENED"),
76     std::make_pair(CTRL_CLOSED, "CTRL_CLOSED"),
77     std::make_pair(NOTIFY_OPEN_CTRL_RESULT, "NOTIFY_OPEN_CTRL_RESULT"),
78     std::make_pair(NOTIFY_CLOSE_CTRL_RESULT, "NOTIFY_CLOSE_CTRL_RESULT"),
79     std::make_pair(DATA_OPENED, "DATA_OPENED"),
80     std::make_pair(DATA_CLOSED, "DATA_CLOSED"),
81 
82     std::make_pair(OPEN_SPEAKER, "OPEN_SPEAKER"),
83     std::make_pair(CLOSE_SPEAKER, "CLOSE_SPEAKER"),
84     std::make_pair(SPEAKER_OPENED, "SPEAKER_OPENED"),
85     std::make_pair(SPEAKER_CLOSED, "SPEAKER_CLOSED"),
86     std::make_pair(NOTIFY_OPEN_SPEAKER_RESULT, "NOTIFY_OPEN_SPEAKER_RESULT"),
87     std::make_pair(NOTIFY_CLOSE_SPEAKER_RESULT, "NOTIFY_CLOSE_SPEAKER_RESULT"),
88     std::make_pair(NOTIFY_HDF_SPK_DUMP, "NOTIFY_HDF_SPK_DUMP"),
89     std::make_pair(NOTIFY_HDF_MIC_DUMP, "NOTIFY_HDF_MIC_DUMP"),
90 
91     std::make_pair(OPEN_MIC, "OPEN_MIC"),
92     std::make_pair(CLOSE_MIC, "CLOSE_MIC"),
93     std::make_pair(MIC_OPENED, "MIC_OPENED"),
94     std::make_pair(MIC_CLOSED, "MIC_CLOSED"),
95     std::make_pair(NOTIFY_OPEN_MIC_RESULT, "NOTIFY_OPEN_MIC_RESULT"),
96     std::make_pair(NOTIFY_CLOSE_MIC_RESULT, "NOTIFY_CLOSE_MIC_RESULT"),
97 
98     std::make_pair(VOLUME_SET, "VOLUME_SET"),
99     std::make_pair(VOLUME_GET, "VOLUME_GET"),
100     std::make_pair(VOLUME_CHANGE, "VOLUME_CHANGE"),
101     std::make_pair(VOLUME_MIN_GET, "VOLUME_MIN_GET"),
102     std::make_pair(VOLUME_MAX_GET, "VOLUME_MAX_GET"),
103     std::make_pair(VOLUME_MUTE_SET, "VOLUME_MUTE_SET"),
104 
105     std::make_pair(AUDIO_FOCUS_CHANGE, "AUDIO_FOCUS_CHANGE"),
106     std::make_pair(AUDIO_RENDER_STATE_CHANGE, "AUDIO_RENDER_STATE_CHANGE"),
107 
108     std::make_pair(SET_PARAM, "SET_PARAM"),
109     std::make_pair(SEND_PARAM, "SEND_PARAM"),
110 
111     std::make_pair(AUDIO_ENCODER_ERR, "AUDIO_ENCODER_ERR"),
112     std::make_pair(AUDIO_DECODER_ERR, "AUDIO_DECODER_ERR"),
113 
114     std::make_pair(CHANGE_PLAY_STATUS, "CHANGE_PLAY_STATUS"),
115 
116     std::make_pair(MMAP_SPK_START, "MMAP_SPK_START"),
117     std::make_pair(MMAP_SPK_STOP, "MMAP_SPK_STOP"),
118     std::make_pair(MMAP_MIC_START, "MMAP_MIC_START"),
119     std::make_pair(MMAP_MIC_STOP, "MMAP_MIC_STOP"),
120     std::make_pair(AUDIO_START, "AUDIO_START"),
121     std::make_pair(AUDIO_STOP, "AUDIO_STOP")
122 };
123 
GetEventNameByType(const int32_t eventType)124 std::string GetEventNameByType(const int32_t eventType)
125 {
126     auto iter = eventNameMap.find(eventType);
127     if (iter == eventNameMap.end()) {
128         DHLOGE("Can't find matched eventname");
129         return "EVENT_UNKNOWN";
130     }
131     return iter->second;
132 }
133 
GetLocalDeviceNetworkId(std::string & networkId)134 int32_t GetLocalDeviceNetworkId(std::string &networkId)
135 {
136     NodeBasicInfo basicInfo = { { 0 } };
137     int32_t ret = GetLocalNodeDeviceInfo(PKG_NAME.c_str(), &basicInfo);
138     if (ret != DH_SUCCESS) {
139         DHLOGE("Failed to obtain the network ID of the local device. ret: %{public}d", ret);
140         return ret;
141     }
142 
143     networkId = std::string(basicInfo.networkId);
144     return DH_SUCCESS;
145 }
146 
GetRandomID()147 std::string GetRandomID()
148 {
149     static std::random_device rd;
150     static std::uniform_int_distribution<uint64_t> dist(0ULL, 0xFFFFFFFFFFFFFFFFULL);
151     uint64_t ab = dist(rd);
152     uint64_t cd = dist(rd);
153     uint32_t a, b, c, d;
154     std::stringstream ss;
155     ab = (ab & 0xFFFFFFFFFFFF0FFFULL) | 0x0000000000004000ULL;
156     cd = (cd & 0x3FFFFFFFFFFFFFFFULL) | 0x8000000000000000ULL;
157     a = (ab >> 32U);
158     b = (ab & 0xFFFFFFFFU);
159     c = (cd >> 32U);
160     d = (cd & 0xFFFFFFFFU);
161     ss << std::hex << std::nouppercase << std::setfill('0');
162     ss << std::setw(WORD_WIDTH_8) << (a);
163     ss << std::setw(WORD_WIDTH_4) << (b >> 16U);
164     ss << std::setw(WORD_WIDTH_4) << (b & 0xFFFFU);
165     ss << std::setw(WORD_WIDTH_4) << (c >> 16U);
166     ss << std::setw(WORD_WIDTH_4) << (c & 0xFFFFU);
167     ss << std::setw(WORD_WIDTH_8) << d;
168 
169     return ss.str();
170 }
171 
GetAnonyString(const std::string & value)172 std::string GetAnonyString(const std::string &value)
173 {
174     std::string res;
175     std::string tmpStr("******");
176     size_t strLen = value.length();
177     if (strLen < INT32_MIN_ID_LENGTH) {
178         return tmpStr;
179     }
180 
181     if (strLen <= INT32_SHORT_ID_LENGTH) {
182         res += value[0];
183         res += tmpStr;
184         res += value[strLen - 1];
185     } else {
186         res.append(value, 0, INT32_PLAINTEXT_LENGTH);
187         res += tmpStr;
188         res.append(value, strLen - INT32_PLAINTEXT_LENGTH, INT32_PLAINTEXT_LENGTH);
189     }
190 
191     return res;
192 }
193 
GetDevTypeByDHId(int32_t dhId)194 int32_t GetDevTypeByDHId(int32_t dhId)
195 {
196     DHLOGD("Get dev type by dhId: %{public}d.", dhId);
197     if (static_cast<uint32_t>(dhId) & 0x8000000) {
198         return AUDIO_DEVICE_TYPE_MIC;
199     } else if (static_cast<uint32_t>(dhId) & 0x7ffffff) {
200         return AUDIO_DEVICE_TYPE_SPEAKER;
201     }
202     return AUDIO_DEVICE_TYPE_UNKNOWN;
203 }
204 
GetCurrentTime(int64_t & tvSec,int64_t & tvNSec)205 void GetCurrentTime(int64_t &tvSec, int64_t &tvNSec)
206 {
207     struct timespec time;
208     if (clock_gettime(CLOCK_MONOTONIC, &time) < 0) {
209         DHLOGE("Get current time failed");
210     }
211     tvSec = time.tv_sec;
212     tvNSec = time.tv_nsec;
213 }
214 
GetNowTimeUs()215 int64_t GetNowTimeUs()
216 {
217     std::chrono::microseconds nowUs =
218         std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch());
219     return nowUs.count();
220 }
221 
GetAudioParamStr(const std::string & params,const std::string & key,std::string & value)222 int32_t GetAudioParamStr(const std::string &params, const std::string &key, std::string &value)
223 {
224     size_t step = key.size();
225     if (step >= params.size()) {
226         return ERR_DH_AUDIO_FAILED;
227     }
228     size_t pos = params.find(key);
229     if (pos == params.npos || params.at(pos + step) != '=') {
230         return ERR_DH_AUDIO_NOT_FOUND_KEY;
231     }
232     size_t splitPosEnd = params.find(';', pos);
233     if (splitPosEnd != params.npos) {
234         value = params.substr(pos + step + 1, splitPosEnd - pos - step - 1);
235     } else {
236         value = params.substr(pos + step + 1);
237     }
238     return DH_SUCCESS;
239 }
240 
GetAudioParamBool(const std::string & params,const std::string & key,bool & value)241 int32_t GetAudioParamBool(const std::string &params, const std::string &key, bool &value)
242 {
243     std::string val;
244     int32_t ret = GetAudioParamStr(params, key, val);
245     if (ret != DH_SUCCESS) {
246         DHLOGE("Get audio param string fail, error code %{public}d.", ret);
247         return ret;
248     }
249 
250     value = (val != "0");
251     return DH_SUCCESS;
252 }
253 
GetAudioParamInt(const std::string & params,const std::string & key,int32_t & value)254 int32_t GetAudioParamInt(const std::string &params, const std::string &key, int32_t &value)
255 {
256     std::string val = "0";
257     int32_t ret = GetAudioParamStr(params, key, val);
258     if (ret != DH_SUCCESS) {
259         DHLOGE("Get audio param string fail, error code %{public}d.", ret);
260         return ret;
261     }
262     if (!CheckIsNum(val)) {
263         DHLOGE("String is not number. str:%{public}s.", val.c_str());
264         return ERR_DH_AUDIO_NOT_SUPPORT;
265     }
266     value = std::atoi(val.c_str());
267     return DH_SUCCESS;
268 }
269 
IsString(const cJSON * jsonObj,const std::string & key)270 bool IsString(const cJSON *jsonObj, const std::string &key)
271 {
272     if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) {
273         DHLOGE("JSON parameter is invalid.");
274         return false;
275     }
276     cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, key.c_str());
277     if (paramValue == nullptr) {
278         DHLOGE("paramValue is null");
279         return false;
280     }
281 
282     if (cJSON_IsString(paramValue)) {
283         return true;
284     }
285     return false;
286 }
287 
IsInt32(const cJSON * jsonObj,const std::string & key)288 bool IsInt32(const cJSON *jsonObj, const std::string &key)
289 {
290     if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) {
291         DHLOGE("JSON parameter is invalid.");
292         return false;
293     }
294     cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, key.c_str());
295     if (paramValue == nullptr) {
296         DHLOGE("paramValue is null");
297         return false;
298     }
299 
300     if (cJSON_IsNumber(paramValue)) {
301         int value = paramValue->valueint;
302         if (INT32_MIN <= value && value <= INT32_MAX) {
303             return true;
304         }
305     }
306     return false;
307 }
308 
IsAudioParam(const cJSON * jsonObj,const std::string & key)309 bool IsAudioParam(const cJSON *jsonObj, const std::string &key)
310 {
311     if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) {
312         DHLOGE("JSON parameter is invalid.");
313         return false;
314     }
315     cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, key.c_str());
316     if (paramValue == nullptr || !cJSON_IsObject(paramValue)) {
317         DHLOGE("paramValue is null or is not object");
318         return false;
319     }
320 
321     return CJsonParamCheck(paramValue,
322         { KEY_SAMPLING_RATE, KEY_CHANNELS, KEY_FORMAT, KEY_SOURCE_TYPE, KEY_CONTENT_TYPE, KEY_STREAM_USAGE });
323 }
324 
CJsonParamCheck(const cJSON * jsonObj,const std::initializer_list<std::string> & keys)325 bool CJsonParamCheck(const cJSON *jsonObj, const std::initializer_list<std::string> &keys)
326 {
327     if (jsonObj == nullptr || !cJSON_IsObject(jsonObj)) {
328         DHLOGE("JSON parameter is invalid.");
329         return false;
330     }
331 
332     for (auto it = keys.begin(); it != keys.end(); it++) {
333         cJSON *paramValue = cJSON_GetObjectItemCaseSensitive(jsonObj, (*it).c_str());
334         if (paramValue == nullptr) {
335             DHLOGE("JSON parameter does not contain key: %{public}s", (*it).c_str());
336             return false;
337         }
338         auto iter = typeCheckMap.find(*it);
339         if (iter == typeCheckMap.end()) {
340             DHLOGE("Check is not supported yet, key %{public}s.", (*it).c_str());
341             return false;
342         }
343         JsonTypeCheckFunc &func = iter->second;
344         bool res = (*func)(jsonObj, *it);
345         if (!res) {
346             DHLOGE("The key %{public}s value format in JSON is illegal.", (*it).c_str());
347             return false;
348         }
349     }
350     return true;
351 }
352 
CalculateSampleNum(uint32_t sampleRate,uint32_t timems)353 int32_t CalculateSampleNum(uint32_t sampleRate, uint32_t timems)
354 {
355     return (sampleRate * timems) / AUDIO_MS_PER_SECOND;
356 }
357 
GetCurNano()358 int64_t GetCurNano()
359 {
360     int64_t result = -1;
361     struct timespec time;
362     clockid_t clockId = CLOCK_MONOTONIC;
363     int ret = clock_gettime(clockId, &time);
364     if (ret < 0) {
365         DHLOGE("GetCurNanoTime fail, ret: %{public}d", ret);
366         return result;
367     }
368     result = (time.tv_sec * AUDIO_NS_PER_SECOND) + time.tv_nsec;
369     return result;
370 }
371 
AbsoluteSleep(int64_t nanoTime)372 int32_t AbsoluteSleep(int64_t nanoTime)
373 {
374     int32_t ret = -1;
375     if (nanoTime <= 0) {
376         DHLOGE("AbsoluteSleep invalid sleep time : %{public}" PRId64" ns", nanoTime);
377         return ret;
378     }
379     struct timespec time;
380     time.tv_sec = nanoTime / AUDIO_NS_PER_SECOND;
381     time.tv_nsec = nanoTime - (time.tv_sec * AUDIO_NS_PER_SECOND);
382 
383     clockid_t clockId = CLOCK_MONOTONIC;
384     ret = clock_nanosleep(clockId, TIMER_ABSTIME, &time, nullptr);
385     if (ret != 0) {
386         DHLOGE("AbsoluteSleep may failed, ret is : %{public}d", ret);
387     }
388     return ret;
389 }
390 
CalculateOffset(const int64_t frameIndex,const int64_t framePeriodNs,const int64_t startTime)391 int64_t CalculateOffset(const int64_t frameIndex, const int64_t framePeriodNs, const int64_t startTime)
392 {
393     int64_t totalOffset = GetCurNano() - startTime;
394     return totalOffset - frameIndex * framePeriodNs;
395 }
396 
UpdateTimeOffset(const int64_t frameIndex,const int64_t framePeriodNs,int64_t & startTime)397 int64_t UpdateTimeOffset(const int64_t frameIndex, const int64_t framePeriodNs, int64_t &startTime)
398 {
399     int64_t timeOffset = 0;
400     if (frameIndex == 0) {
401         startTime = GetCurNano();
402     } else if (frameIndex % AUDIO_OFFSET_FRAME_NUM == 0) {
403         timeOffset = CalculateOffset(frameIndex, framePeriodNs, startTime);
404     }
405     return timeOffset;
406 }
407 
CheckIsNum(const std::string & jsonString)408 bool CheckIsNum(const std::string &jsonString)
409 {
410     if (jsonString.empty() || jsonString.size() > MAX_KEY_DH_ID_LEN) {
411         int32_t stringSize = static_cast<int32_t>(jsonString.size());
412         DHLOGE("Json string size %{public}d, is zero or too long.", stringSize);
413         return false;
414     }
415     for (char const &c : jsonString) {
416         if (!std::isdigit(c)) {
417             DHLOGE("Json string is not number.");
418             return false;
419         }
420     }
421     return true;
422 }
423 
CheckDevIdIsLegal(const std::string & devId)424 bool CheckDevIdIsLegal(const std::string &devId)
425 {
426     if (devId.empty() || devId.size() > DAUDIO_MAX_DEVICE_ID_LEN) {
427         int32_t stringSize = static_cast<int32_t>(devId.size());
428         DHLOGE("DevId size %{public}d, is zero or too long.", stringSize);
429         return false;
430     }
431     for (char const &c : devId) {
432         if (!std::isalnum(c)) {
433             DHLOGE("DevId is not number or letter.");
434             return false;
435         }
436     }
437     return true;
438 }
439 
IsOutDurationRange(int64_t startTime,int64_t endTime,int64_t lastStartTime)440 bool IsOutDurationRange(int64_t startTime, int64_t endTime, int64_t lastStartTime)
441 {
442     int64_t currentInterval = endTime - startTime;
443     int64_t twiceInterval = startTime - lastStartTime;
444     return (currentInterval > MAX_TIME_INTERVAL_US || twiceInterval > MAX_TIME_INTERVAL_US) ? true : false;
445 }
446 
GetCJsonString(const char * key,const char * value)447 std::string GetCJsonString(const char *key, const char *value)
448 {
449     cJSON *jParam = cJSON_CreateObject();
450     if (jParam == nullptr) {
451         DHLOGE("Failed to create cJSON object.");
452         return "Failed to create cJSON object.";
453     }
454     cJSON_AddStringToObject(jParam, key, value);
455     char *jsonData = cJSON_PrintUnformatted(jParam);
456     if (jsonData == nullptr) {
457         DHLOGE("Failed to create JSON data.");
458         cJSON_Delete(jParam);
459         return "Failed to create JSON data.";
460     }
461     std::string content(jsonData);
462     cJSON_Delete(jParam);
463     cJSON_free(jsonData);
464     DHLOGD("create cJSON success : %{public}s", content.c_str());
465     return content;
466 }
467 
ParseStringFromArgs(std::string args,const char * key)468 std::string ParseStringFromArgs(std::string args, const char *key)
469 {
470     DHLOGD("ParseStringFrom Args : %{public}s", args.c_str());
471     cJSON *jParam = cJSON_Parse(args.c_str());
472     if (jParam == nullptr) {
473         DHLOGE("Failed to parse JSON: %{public}s", cJSON_GetErrorPtr());
474         return "Failed to parse JSON";
475     }
476     if (!CJsonParamCheck(jParam, { key })) {
477         DHLOGE("Not found the key : %{public}s.", key);
478         cJSON_Delete(jParam);
479         return "Not found the key.";
480     }
481     cJSON *dhIdItem = cJSON_GetObjectItem(jParam, key);
482     if (dhIdItem == NULL || !cJSON_IsString(dhIdItem)) {
483         DHLOGE("Not found the value of the key : %{public}s.", key);
484         cJSON_Delete(jParam);
485         return "Not found the value.";
486     }
487     std::string content(dhIdItem->valuestring);
488     cJSON_Delete(jParam);
489     DHLOGD("Parsed string is: %{public}s.", content.c_str());
490     return content;
491 }
492 
493 template <typename T>
GetSysPara(const char * key,T & value)494 bool GetSysPara(const char *key, T &value)
495 {
496     CHECK_AND_RETURN_RET_LOG(key == nullptr, false, "key is nullptr");
497     char paraValue[30] = {0}; // 30 for system parameter
498     auto res = GetParameter(key, "-1", paraValue, sizeof(paraValue));
499 
500     CHECK_AND_RETURN_RET_LOG(res <= 0, false, "GetParameter fail, key:%{public}s res:%{public}d", key, res);
501     DHLOGI("GetSysPara key:%{public}s value:%{public}s", key, paraValue);
502     std::stringstream valueStr;
503     valueStr << paraValue;
504     valueStr >> value;
505     return true;
506 }
507 
508 template bool GetSysPara(const char *key, int32_t &value);
509 template bool GetSysPara(const char *key, uint32_t &value);
510 template bool GetSysPara(const char *key, int64_t &value);
511 template bool GetSysPara(const char *key, std::string &value);
512 
IsParamEnabled(const std::string & key,bool & isEnabled)513 bool IsParamEnabled(const std::string &key, bool &isEnabled)
514 {
515     // by default: old trans
516     int32_t policyFlag = 0;
517     if (GetSysPara(key.c_str(), policyFlag) && policyFlag == 1) {
518         isEnabled = true;
519         return true;
520     }
521     isEnabled = false;
522     return false;
523 }
524 
SaveFile(const std::string fileName,uint8_t * audioData,int32_t size)525 void SaveFile(const std::string fileName, uint8_t *audioData, int32_t size)
526 {
527     char path[PATH_MAX + 1] = {0x00};
528     if (fileName.length() > PATH_MAX || realpath(fileName.c_str(), path) == nullptr) {
529         DHLOGE("The file path is invalid.");
530         return;
531     }
532     std::ofstream ofs(path, std::ios::binary | std::ios::out | std::ios::app);
533     if (!ofs.is_open()) {
534         DHLOGE("open file failed");
535         return;
536     }
537     ofs.write(reinterpret_cast<char*>(audioData), size);
538     ofs.close();
539 }
540 
541 std::map<std::string, std::string> DumpFileUtil::g_lastPara = {};
542 
OpenDumpFileInner(const std::string & para,const std::string & fileName)543 FILE *DumpFileUtil::OpenDumpFileInner(const std::string &para, const std::string &fileName)
544 {
545     std::string filePath = DUMP_SERVICE_DIR + fileName;
546     std::string dumpPara;
547     FILE *dumpFile = nullptr;
548     bool res = GetSysPara(para.c_str(), dumpPara);
549     if (!res || dumpPara.empty()) {
550         DHLOGI("%{public}s is not set, dump dcamera is not required", para.c_str());
551         g_lastPara[para] = dumpPara;
552         return dumpFile;
553     }
554     DHLOGI("%{public}s = %{public}s, filePath: %{public}s", para.c_str(), dumpPara.c_str(), filePath.c_str());
555     if (dumpPara == "w") {
556         dumpFile = fopen(filePath.c_str(), "wb+");
557         CHECK_AND_RETURN_RET_LOG(dumpFile == nullptr, dumpFile, "Error opening dump file!");
558     } else if (dumpPara == "a") {
559         dumpFile = fopen(filePath.c_str(), "ab+");
560         CHECK_AND_RETURN_RET_LOG(dumpFile == nullptr, dumpFile, "Error opening dump file!");
561     }
562     g_lastPara[para] = dumpPara;
563     return dumpFile;
564 }
565 
WriteDumpFile(FILE * dumpFile,void * buffer,size_t bufferSize)566 void DumpFileUtil::WriteDumpFile(FILE *dumpFile, void *buffer, size_t bufferSize)
567 {
568     if (dumpFile == nullptr) {
569         return;
570     }
571     CHECK_AND_RETURN_LOG(buffer == nullptr, "Invalid write param");
572     size_t writeResult = fwrite(buffer, 1, bufferSize, dumpFile);
573     CHECK_AND_RETURN_LOG(writeResult != bufferSize, "Failed to write the file.");
574 }
575 
CloseDumpFile(FILE ** dumpFile)576 void DumpFileUtil::CloseDumpFile(FILE **dumpFile)
577 {
578     if (*dumpFile) {
579         fclose(*dumpFile);
580         *dumpFile = nullptr;
581     }
582 }
583 
ChangeDumpFileState(const std::string & para,FILE ** dumpFile,const std::string & filePath)584 void DumpFileUtil::ChangeDumpFileState(const std::string &para, FILE **dumpFile, const std::string &filePath)
585 {
586     CHECK_AND_RETURN_LOG(*dumpFile == nullptr, "Invalid file para");
587     CHECK_AND_RETURN_LOG(g_lastPara[para] != "w" || g_lastPara[para] != "a", "Invalid input para");
588     std::string dumpPara;
589     bool res = GetSysPara(para.c_str(), dumpPara);
590     if (!res || dumpPara.empty()) {
591         DHLOGE("get %{public}s fail", para.c_str());
592     }
593     if (g_lastPara[para] == "w" && dumpPara == "w") {
594         return;
595     }
596     CloseDumpFile(dumpFile);
597     OpenDumpFile(para, filePath, dumpFile);
598 }
599 
OpenDumpFile(const std::string & para,const std::string & fileName,FILE ** file)600 void DumpFileUtil::OpenDumpFile(const std::string &para, const std::string &fileName, FILE **file)
601 {
602     if (*file != nullptr) {
603         DumpFileUtil::ChangeDumpFileState(para, file, fileName);
604         return;
605     }
606 
607     if (para == DUMP_SERVER_PARA) {
608         *file = DumpFileUtil::OpenDumpFileInner(para, fileName);
609     }
610 }
611 } // namespace DistributedHardware
612 } // namespace OHOS