1 /*
2 * Copyright (c) 2021-2022 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 #include "camera_util.h"
16 #include <cstdint>
17 #include <fstream>
18 #include <regex>
19 #include <securec.h>
20 #include <sys/stat.h>
21 #include <exception>
22 #include <parameter.h>
23 #include <parameters.h>
24 #include "camera_log.h"
25 #include "access_token.h"
26 #include "accesstoken_kit.h"
27 #include "privacy_kit.h"
28 #include "display.h"
29 #include "display_manager.h"
30 #include "display/composer/v1_1/display_composer_type.h"
31 #include "iservice_registry.h"
32 #include "bundle_mgr_interface.h"
33 #include "system_ability_definition.h"
34 #include "ipc_skeleton.h"
35 #include "tokenid_kit.h"
36
37 namespace OHOS {
38 namespace CameraStandard {
39 using namespace OHOS::HDI::Display::Composer::V1_1;
40 static bool g_tablet = false;
41
42 std::unordered_map<int32_t, int32_t> g_cameraToPixelFormat = {
43 {OHOS_CAMERA_FORMAT_RGBA_8888, GRAPHIC_PIXEL_FMT_RGBA_8888},
44 {OHOS_CAMERA_FORMAT_YCBCR_420_888, GRAPHIC_PIXEL_FMT_YCBCR_420_SP},
45 {OHOS_CAMERA_FORMAT_YCRCB_420_SP, GRAPHIC_PIXEL_FMT_YCRCB_420_SP}, // NV21
46 {OHOS_CAMERA_FORMAT_JPEG, GRAPHIC_PIXEL_FMT_BLOB},
47 {OHOS_CAMERA_FORMAT_YCBCR_P010, GRAPHIC_PIXEL_FMT_YCBCR_P010},
48 {OHOS_CAMERA_FORMAT_YCRCB_P010, GRAPHIC_PIXEL_FMT_YCRCB_P010},
49 {OHOS_CAMERA_FORMAT_YCBCR_420_SP, GRAPHIC_PIXEL_FMT_YCBCR_420_SP},
50 {OHOS_CAMERA_FORMAT_422_YUYV, GRAPHIC_PIXEL_FMT_YUYV_422_PKG},
51 {OHOS_CAMERA_FORMAT_422_UYVY, GRAPHIC_PIXEL_FMT_UYVY_422_PKG},
52 {OHOS_CAMERA_FORMAT_DEPTH_16, GRAPHIC_PIXEL_FMT_RGBA16_FLOAT},
53 {OHOS_CAMERA_FORMAT_DNG, GRAPHIC_PIXEL_FMT_BLOB},
54 {OHOS_CAMERA_FORMAT_DNG_XDRAW, GRAPHIC_PIXEL_FMT_BLOB},
55 {OHOS_CAMERA_FORMAT_MJPEG, GRAPHIC_PIXEL_FMT_BLOB},
56 };
57
58 std::map<int, std::string> g_cameraPos = {
59 {0, "Front"},
60 {1, "Back"},
61 {2, "Other"},
62 };
63
64 std::map<int, std::string> g_cameraType = {
65 {0, "Wide-Angle"},
66 {1, "Ultra-Wide"},
67 {2, "TelePhoto"},
68 {3, "TrueDepth"},
69 {4, "Logical"},
70 {5, "Unspecified"},
71 };
72
73 std::map<int, std::string> g_cameraConType = {
74 {0, "Builtin"},
75 {1, "USB-Plugin"},
76 {2, "Remote"},
77 };
78
79 std::map<int, std::string> g_cameraFormat = {
80 {1, "RGBA_8888"},
81 {2, "YCBCR_420_888"},
82 {3, "YCRCB_420_SP"},
83 {4, "YCBCR_420_SP"},
84 {5, "JPEG"},
85 {6, "YCBCR_P010"},
86 {7, "YCRCB_P010"},
87 {8, "DNG"},
88 {9, "422_YUYV"},
89 };
90
91 std::map<int, std::string> g_cameraFocusMode = {
92 {0, "Manual"},
93 {1, "Continuous-Auto"},
94 {2, "Auto"},
95 {3, "Locked"},
96 };
97
98 std::map<int, std::string> g_cameraExposureMode = {
99 {0, "Manual"},
100 {1, "Continuous-Auto"},
101 {2, "Locked"},
102 {3, "Auto"},
103 };
104
105 std::map<int, std::string> g_cameraFlashMode = {
106 {0, "Close"},
107 {1, "Open"},
108 {2, "Auto"},
109 {3, "Always-Open"},
110 };
111
112 std::map<int, std::string> g_cameraVideoStabilizationMode = {
113 {0, "Off"},
114 {1, "Low"},
115 {2, "Middle"},
116 {3, "High"},
117 {4, "Auto"},
118 };
119
120 std::map<int, std::string> g_cameraPrelaunchAvailable = {
121 {0, "False"},
122 {1, "True"},
123 };
124
125 std::map<int, std::string> g_cameraQuickThumbnailAvailable = {
126 {0, "False"},
127 {1, "True"},
128 };
129
130 std::map<int, std::string> g_cameraQualityPrioritization = {
131 {0, "HighQuality "},
132 {1, "PowerBalance "},
133 };
134
135 bool g_cameraDebugOn = false;
136
HdiToCameraErrorType(OHOS::HDI::Camera::V1_3::ErrorType type)137 int32_t HdiToCameraErrorType(OHOS::HDI::Camera::V1_3::ErrorType type)
138 {
139 enum CamServiceError err = CAMERA_UNKNOWN_ERROR;
140
141 switch (type) {
142 case HDI::Camera::V1_3::FATAL_ERROR:
143 err = CAMERA_DEVICE_FATAL_ERROR;
144 break;
145 case HDI::Camera::V1_3::REQUEST_TIMEOUT:
146 err = CAMERA_DEVICE_REQUEST_TIMEOUT;
147 break;
148 case HDI::Camera::V1_3::DRIVER_ERROR:
149 err = CAMERA_DEVICE_DRIVER_ERROR;
150 break;
151 case HDI::Camera::V1_3::DEVICE_PREEMPT:
152 err = CAMERA_DEVICE_PREEMPTED;
153 break;
154 case HDI::Camera::V1_3::DEVICE_DISCONNECT:
155 err = CAMERA_DEVICE_DISCONNECT;
156 break;
157 case HDI::Camera::V1_3::SENSOR_DATA_ERROR:
158 err = CAMERA_DEVICE_SENSOR_DATA_ERROR;
159 break;
160 case HDI::Camera::V1_3::DCAMERA_ERROR_BEGIN:
161 err = CAMERA_DCAMERA_ERROR_BEGIN;
162 break;
163 case HDI::Camera::V1_3::DCAMERA_ERROR_DEVICE_IN_USE:
164 err = CAMERA_DCAMERA_ERROR_DEVICE_IN_USE;
165 break;
166 case HDI::Camera::V1_3::DCAMERA_ERROR_NO_PERMISSION:
167 err = CAMERA_DCAMERA_ERROR_NO_PERMISSION;
168 break;
169 default:
170 MEDIA_ERR_LOG("HdiToCameraType() error type from hdi: %{public}d", type);
171 break;
172 }
173 return err;
174 }
175
HdiToServiceError(OHOS::HDI::Camera::V1_0::CamRetCode ret)176 int32_t HdiToServiceError(OHOS::HDI::Camera::V1_0::CamRetCode ret)
177 {
178 enum CamServiceError err = CAMERA_UNKNOWN_ERROR;
179
180 switch (ret) {
181 case HDI::Camera::V1_0::NO_ERROR:
182 err = CAMERA_OK;
183 break;
184 case HDI::Camera::V1_0::CAMERA_BUSY:
185 err = CAMERA_DEVICE_BUSY;
186 break;
187 case HDI::Camera::V1_0::INVALID_ARGUMENT:
188 err = CAMERA_INVALID_ARG;
189 break;
190 case HDI::Camera::V1_0::CAMERA_CLOSED:
191 err = CAMERA_DEVICE_CLOSED;
192 break;
193 default:
194 MEDIA_ERR_LOG("HdiToServiceError() error code from hdi: %{public}d", ret);
195 break;
196 }
197 return err;
198 }
199
HdiToServiceErrorV1_2(HDI::Camera::V1_2::CamRetCode ret)200 int32_t HdiToServiceErrorV1_2(HDI::Camera::V1_2::CamRetCode ret)
201 {
202 enum CamServiceError err = CAMERA_UNKNOWN_ERROR;
203
204 switch (ret) {
205 case HDI::Camera::V1_2::NO_ERROR:
206 err = CAMERA_OK;
207 break;
208 case HDI::Camera::V1_2::CAMERA_BUSY:
209 err = CAMERA_DEVICE_BUSY;
210 break;
211 case HDI::Camera::V1_2::INVALID_ARGUMENT:
212 err = CAMERA_INVALID_ARG;
213 break;
214 case HDI::Camera::V1_2::CAMERA_CLOSED:
215 err = CAMERA_DEVICE_CLOSED;
216 break;
217 case HDI::Camera::V1_2::DEVICE_ERROR:
218 err = CAMERA_DEVICE_ERROR;
219 break;
220 case HDI::Camera::V1_2::NO_PERMISSION:
221 err = CAMERA_NO_PERMISSION;
222 break;
223 case HDI::Camera::V1_2::DEVICE_CONFLICT:
224 err = CAMERA_DEVICE_CONFLICT;
225 break;
226 default:
227 MEDIA_ERR_LOG("HdiToServiceErrorV1_2() error code from hdi: %{public}d", ret);
228 break;
229 }
230 return err;
231 }
232
CreateMsg(const char * format,...)233 std::string CreateMsg(const char* format, ...)
234 {
235 va_list args;
236 va_start(args, format);
237 char msg[MAX_STRING_SIZE] = {0};
238 if (vsnprintf_s(msg, sizeof(msg), sizeof(msg) - 1, format, args) < 0) {
239 MEDIA_ERR_LOG("failed to call vsnprintf_s");
240 va_end(args);
241 return "";
242 }
243 va_end(args);
244 return msg;
245 }
246
IsHapTokenId(uint32_t tokenId)247 bool IsHapTokenId(uint32_t tokenId)
248 {
249 return Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) ==
250 Security::AccessToken::ATokenTypeEnum::TOKEN_HAP;
251 }
252
IsValidMode(int32_t opMode,std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility)253 bool IsValidMode(int32_t opMode, std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility)
254 {
255 if (opMode == 0 || opMode == 1 || opMode == 2) { // 0 is normal mode, 1 is capture mode, 2 is video mode
256 MEDIA_INFO_LOG("operationMode:%{public}d", opMode);
257 return true;
258 }
259 camera_metadata_item_t item;
260 int ret = Camera::FindCameraMetadataItem(cameraAbility->get(), OHOS_ABILITY_CAMERA_MODES, &item);
261 if (ret != CAM_META_SUCCESS || item.count == 0) {
262 MEDIA_ERR_LOG("Failed to find stream extend configuration in camera ability with return code %{public}d", ret);
263 ret = Camera::FindCameraMetadataItem(cameraAbility->get(),
264 OHOS_ABILITY_STREAM_AVAILABLE_BASIC_CONFIGURATIONS, &item);
265 if (ret == CAM_META_SUCCESS && item.count != 0) {
266 MEDIA_INFO_LOG("basic config no need valid mode");
267 return true;
268 }
269 return false;
270 }
271
272 for (uint32_t i = 0; i < item.count; i++) {
273 if (opMode == item.data.u8[i]) {
274 MEDIA_INFO_LOG("operationMode:%{public}d found in supported streams", opMode);
275 return true;
276 }
277 }
278 MEDIA_ERR_LOG("operationMode:%{public}d not found in supported streams", opMode);
279 return false;
280 }
281
DumpMetadata(std::shared_ptr<OHOS::Camera::CameraMetadata> cameraSettings)282 void DumpMetadata(std::shared_ptr<OHOS::Camera::CameraMetadata> cameraSettings)
283 {
284 CHECK_RETURN(cameraSettings == nullptr);
285 auto srcHeader = cameraSettings->get();
286 CHECK_RETURN(srcHeader == nullptr);
287 auto srcItemCount = srcHeader->item_count;
288 camera_metadata_item_t item;
289 for (uint32_t index = 0; index < srcItemCount; index++) {
290 int ret = OHOS::Camera::GetCameraMetadataItem(srcHeader, index, &item);
291 CHECK_RETURN_ELOG(ret != CAM_META_SUCCESS, "Failed to get metadata item at index: %{public}d", index);
292 const char *name = OHOS::Camera::GetCameraMetadataItemName(item.item);
293 CHECK_RETURN_ELOG(name == nullptr, "U8ItemToString: get u8 item name fail!");
294 if (item.data_type == META_TYPE_BYTE) {
295 for (size_t k = 0; k < item.count; k++) {
296 MEDIA_DEBUG_LOG("tag index:%d, name:%s, value:%d", item.index, name, (uint8_t)(item.data.u8[k]));
297 }
298 } else if (item.data_type == META_TYPE_INT32) {
299 for (size_t k = 0; k < item.count; k++) {
300 MEDIA_DEBUG_LOG("tag index:%d, name:%s, value:%d", item.index, name, (int32_t)(item.data.i32[k]));
301 }
302 } else if (item.data_type == META_TYPE_UINT32) {
303 for (size_t k = 0; k < item.count; k++) {
304 MEDIA_DEBUG_LOG("tag index:%d, name:%s, value:%d", item.index, name, (uint32_t)(item.data.ui32[k]));
305 }
306 } else if (item.data_type == META_TYPE_FLOAT) {
307 for (size_t k = 0; k < item.count; k++) {
308 MEDIA_DEBUG_LOG("tag index:%d, name:%s, value:%f", item.index, name, (float)(item.data.f[k]));
309 }
310 } else if (item.data_type == META_TYPE_INT64) {
311 for (size_t k = 0; k < item.count; k++) {
312 MEDIA_DEBUG_LOG("tag index:%d, name:%s, value:%lld", item.index, name, (long long)(item.data.i64[k]));
313 }
314 } else if (item.data_type == META_TYPE_DOUBLE) {
315 for (size_t k = 0; k < item.count; k++) {
316 MEDIA_DEBUG_LOG("tag index:%d, name:%s, value:%lf", item.index, name, (double)(item.data.d[k]));
317 }
318 } else {
319 MEDIA_DEBUG_LOG("tag index:%d, name:%s", item.index, name);
320 }
321 }
322 }
323
GetClientBundle(int uid)324 std::string GetClientBundle(int uid)
325 {
326 std::string bundleName = "";
327 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
328 CHECK_RETURN_RET_ELOG(samgr == nullptr, bundleName, "GetClientBundle Get ability manager failed");
329
330 sptr<IRemoteObject> object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
331 CHECK_RETURN_RET_ELOG(object == nullptr, bundleName, "GetClientBundle object is NULL.");
332
333 sptr<OHOS::AppExecFwk::IBundleMgr> bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
334 CHECK_RETURN_RET_ELOG(bms == nullptr, bundleName, "GetClientBundle bundle manager service is NULL.");
335
336 auto result = bms->GetNameForUid(uid, bundleName);
337 if (result != ERR_OK) {
338 MEDIA_DEBUG_LOG("GetClientBundle GetBundleNameForUid fail");
339 return "";
340 }
341 MEDIA_INFO_LOG("bundle name is %{public}s ", bundleName.c_str());
342
343 return bundleName;
344 }
345
GetClientNameByToken(int tokenIdNum)346 std::string GetClientNameByToken(int tokenIdNum)
347 {
348 using namespace Security::AccessToken;
349 AccessTokenID tokenId = static_cast<AccessTokenID>(tokenIdNum);
350 ATokenTypeEnum tokenType = AccessTokenKit::GetTokenType(tokenId);
351 if (tokenType == TOKEN_HAP) {
352 HapTokenInfoExt hapTokenInfo = {};
353 int ret = AccessTokenKit::GetHapTokenInfoExtension(tokenId, hapTokenInfo);
354 CHECK_RETURN_RET_ELOG(ret != 0, "unknown", "GetHapTokenInfoExtension fail, ret %{public}d", ret);
355 return hapTokenInfo.baseInfo.bundleName;
356 } else if (tokenType == TOKEN_NATIVE) {
357 NativeTokenInfo nativeTokenInfo = {};
358 int ret = AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
359 CHECK_RETURN_RET_ELOG(ret != 0, "unknown", "GetNativeTokenInfo fail, ret %{public}d", ret);
360 return nativeTokenInfo.processName;
361 } else {
362 MEDIA_ERR_LOG("unexpected token type %{public}d", tokenType);
363 return "unknown";
364 }
365 }
366
JudgmentPriority(const pid_t & pid,const pid_t & pidCompared)367 int32_t JudgmentPriority(const pid_t& pid, const pid_t& pidCompared)
368 {
369 return PRIORITY_LEVEL_SAME;
370 }
371
IsSameClient(const pid_t & pid,const pid_t & pidCompared)372 bool IsSameClient(const pid_t& pid, const pid_t& pidCompared)
373 {
374 return (pid == pidCompared);
375 }
376
IsInForeGround(const uint32_t callerToken)377 bool IsInForeGround(const uint32_t callerToken)
378 {
379 bool isAllowed = true;
380 if (IPCSkeleton::GetCallingUid() == 0) {
381 MEDIA_DEBUG_LOG("HCameraService::IsInForeGround isAllowed!");
382 return isAllowed;
383 }
384 if (IsHapTokenId(callerToken)) {
385 isAllowed = Security::AccessToken::PrivacyKit::IsAllowedUsingPermission(callerToken, OHOS_PERMISSION_CAMERA);
386 }
387 return isAllowed;
388 }
389
IsCameraNeedClose(const uint32_t callerToken,const pid_t & pid,const pid_t & pidCompared)390 bool IsCameraNeedClose(const uint32_t callerToken, const pid_t& pid, const pid_t& pidCompared)
391 {
392 bool needClose = !(IsInForeGround(callerToken) && (JudgmentPriority(pid, pidCompared) != PRIORITY_LEVEL_HIGHER));
393 if (Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken) ==
394 Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
395 needClose = true;
396 }
397 MEDIA_INFO_LOG("IsCameraNeedClose pid = %{public}d, IsInForeGround = %{public}d, TokenType = %{public}d, "
398 "needClose = %{public}d",
399 pid, IsInForeGround(callerToken),
400 Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken), needClose);
401 return needClose;
402 }
403
CheckPermission(const std::string permissionName,uint32_t callerToken)404 int32_t CheckPermission(const std::string permissionName, uint32_t callerToken)
405 {
406 int permissionResult
407 = OHOS::Security::AccessToken::TypePermissionState::PERMISSION_DENIED;
408 Security::AccessToken::ATokenTypeEnum tokenType
409 = OHOS::Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
410 if ((tokenType == OHOS::Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE)
411 || (tokenType == OHOS::Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)) {
412 permissionResult = OHOS::Security::AccessToken::AccessTokenKit::VerifyAccessToken(
413 callerToken, permissionName);
414 } else {
415 MEDIA_ERR_LOG("HCameraService::CheckPermission: Unsupported Access Token Type");
416 return CAMERA_INVALID_ARG;
417 }
418
419 if (permissionResult != OHOS::Security::AccessToken::TypePermissionState::PERMISSION_GRANTED) {
420 MEDIA_ERR_LOG("HCameraService::CheckPermission: Permission to Access Camera Denied!!!!");
421 return CAMERA_NO_PERMISSION;
422 } else {
423 MEDIA_DEBUG_LOG("HCameraService::CheckPermission: Permission to Access Camera Granted!!!!");
424 }
425 return CAMERA_OK;
426 }
427
AddCameraPermissionUsedRecord(const uint32_t callingTokenId,const std::string permissionName)428 void AddCameraPermissionUsedRecord(const uint32_t callingTokenId, const std::string permissionName)
429 {
430 int32_t successCout = 1;
431 int32_t failCount = 0;
432 int32_t ret = Security::AccessToken::PrivacyKit::AddPermissionUsedRecord(callingTokenId, permissionName,
433 successCout, failCount);
434 MEDIA_INFO_LOG("AddPermissionUsedRecord");
435 if (ret != CAMERA_OK) {
436 MEDIA_ERR_LOG("AddPermissionUsedRecord failed.");
437 }
438 }
439
IsVerticalDevice()440 bool IsVerticalDevice()
441 {
442 bool isVerticalDevice = true;
443 auto display = OHOS::Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
444
445 CHECK_RETURN_RET_ELOG(display == nullptr, isVerticalDevice, "IsVerticalDevice GetDefaultDisplay failed");
446 MEDIA_DEBUG_LOG("GetDefaultDisplay:W(%{public}d),H(%{public}d),Orientation(%{public}d),Rotation(%{public}d)",
447 display->GetWidth(), display->GetHeight(), display->GetOrientation(), display->GetRotation());
448 bool isScreenVertical = display->GetRotation() == OHOS::Rosen::Rotation::ROTATION_0 ||
449 display->GetRotation() == OHOS::Rosen::Rotation::ROTATION_180;
450 bool isScreenHorizontal = display->GetRotation() == OHOS::Rosen::Rotation::ROTATION_90 ||
451 display->GetRotation() == OHOS::Rosen::Rotation::ROTATION_270;
452 isVerticalDevice = (isScreenVertical && (display->GetWidth() < display->GetHeight())) ||
453 (isScreenHorizontal && (display->GetWidth() > display->GetHeight()));
454 return isVerticalDevice;
455 }
456
GetStreamRotation(int32_t & sensorOrientation,camera_position_enum_t & cameraPosition,int & disPlayRotation,std::string & deviceClass)457 int32_t GetStreamRotation(int32_t& sensorOrientation, camera_position_enum_t& cameraPosition, int& disPlayRotation,
458 std::string& deviceClass)
459 {
460 int32_t streamRotation = sensorOrientation;
461 int degrees = 0;
462
463 switch (disPlayRotation) {
464 case DISPALY_ROTATE_0: degrees = STREAM_ROTATE_0; break;
465 case DISPALY_ROTATE_1: degrees = STREAM_ROTATE_90; break;
466 case DISPALY_ROTATE_2: degrees = STREAM_ROTATE_180; break;
467 case DISPALY_ROTATE_3: degrees = STREAM_ROTATE_270; break; // 逆时针转90
468 }
469
470 g_tablet = (deviceClass == "tablet");
471 if (cameraPosition == OHOS_CAMERA_POSITION_FRONT) {
472 sensorOrientation = g_tablet ? sensorOrientation + STREAM_ROTATE_90 : sensorOrientation;
473 streamRotation = (STREAM_ROTATE_360 + sensorOrientation - degrees) % STREAM_ROTATE_360;
474 } else {
475 sensorOrientation = g_tablet ? sensorOrientation - STREAM_ROTATE_90 : sensorOrientation;
476 streamRotation = (sensorOrientation + degrees) % STREAM_ROTATE_360;
477 streamRotation = (STREAM_ROTATE_360 - streamRotation) % STREAM_ROTATE_360;
478 }
479 MEDIA_DEBUG_LOG("SetStreamTransform filp streamRotation %{public}d, rotate %{public}d",
480 streamRotation, disPlayRotation);
481 return streamRotation;
482 }
483
CheckSystemApp()484 bool CheckSystemApp()
485 {
486 Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
487 Security::AccessToken::ATokenTypeEnum tokenType =
488 Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
489 if (tokenType != Security::AccessToken::TOKEN_HAP) {
490 MEDIA_DEBUG_LOG("Caller is not a application.");
491 return true;
492 }
493 uint64_t accessTokenId = IPCSkeleton::GetCallingFullTokenID();
494 bool isSystemApplication = Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(accessTokenId);
495 MEDIA_DEBUG_LOG("isSystemApplication:%{public}d", isSystemApplication);
496 return isSystemApplication;
497 }
498
SplitString(const std::string & input,char delimiter)499 std::vector<std::string> SplitString(const std::string& input, char delimiter)
500 {
501 std::vector<std::string> result;
502 std::stringstream ss(input);
503 std::string token;
504
505 while (std::getline(ss, token, delimiter)) {
506 result.push_back(token);
507 }
508 return result;
509 }
510
GetTimestamp()511 int64_t GetTimestamp()
512 {
513 auto now = std::chrono::system_clock::now();
514 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
515 return duration.count();
516 }
517
GetFileStream(const std::string & filepath)518 std::string GetFileStream(const std::string &filepath)
519 {
520 char *canonicalPath = realpath(filepath.c_str(), nullptr);
521 CHECK_RETURN_RET(canonicalPath == nullptr, NULL);
522 std::ifstream file(canonicalPath, std::ios::in | std::ios::binary);
523 free(canonicalPath);
524 // 文件流的异常处理,不能用try catch的形式
525 if (!file) {
526 MEDIA_INFO_LOG("Failed to open the file!");
527 return NULL;
528 }
529 std::stringstream infile;
530 infile << file.rdbuf();
531 const std::string fileString = infile.str();
532 if (fileString.empty()) {
533 return NULL;
534 }
535 return fileString;
536 }
537
SplitStringWithPattern(const std::string & str,const char & pattern)538 std::vector<std::string> SplitStringWithPattern(const std::string &str, const char& pattern)
539 {
540 std::stringstream iss(str);
541 std::vector<std::string> result;
542 std::string token;
543 while (getline(iss, token, pattern)) {
544 result.emplace_back(token);
545 }
546 return result;
547 }
548
TrimString(std::string & inputStr)549 void TrimString(std::string &inputStr)
550 {
551 inputStr.erase(inputStr.begin(),
552 std::find_if(inputStr.begin(), inputStr.end(), [](unsigned char ch) { return !std::isspace(ch); }));
553 inputStr.erase(
554 std::find_if(inputStr.rbegin(), inputStr.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(),
555 inputStr.end());
556 }
557
RemoveFile(const std::string & path)558 bool RemoveFile(const std::string& path)
559 {
560 char *canonicalPath = realpath(path.c_str(), nullptr);
561 CHECK_RETURN_RET(canonicalPath == nullptr, false);
562 if (remove(canonicalPath) == 0) {
563 free(canonicalPath);
564 MEDIA_INFO_LOG("File removed successfully.");
565 return true;
566 }
567 free(canonicalPath);
568 return false;
569 }
570
CheckPathExist(const char * path)571 bool CheckPathExist(const char *path)
572 {
573 char *canonicalPath = realpath(path, nullptr);
574 CHECK_RETURN_RET_ELOG(canonicalPath == nullptr, false, "CheckPathExist path is nullptr");
575 std::ifstream profileStream(canonicalPath);
576 free(canonicalPath);
577 return profileStream.good();
578 }
579
isIntegerRegex(const std::string & input)580 bool isIntegerRegex(const std::string& input)
581 {
582 size_t start = 0;
583 if (input.empty()) {
584 return false;
585 }
586 if (input[0] == '-' && input.size() > 1) {
587 start = 1; // deal negative sign
588 }
589 for (size_t i = start; i < input.size(); ++i) {
590 if (!std::isdigit(input[i])) {
591 return false;
592 }
593 }
594 return true;
595 }
596
GetValidCameraId(std::string & cameraId)597 std::string GetValidCameraId(std::string& cameraId)
598 {
599 std::string cameraIdTemp = cameraId;
600 size_t pos = cameraId.find('/');
601 if (pos == std::string::npos) {
602 return cameraId;
603 }
604 cameraIdTemp = cameraId.substr(pos + 1);
605 return cameraIdTemp;
606 }
607
ControlCenterMapToString(const std::map<std::string,std::array<float,CONTROL_CENTER_DATA_SIZE>> & data)608 std::string ControlCenterMapToString(const std::map<std::string, std::array<float, CONTROL_CENTER_DATA_SIZE>> &data)
609 {
610 std::ostringstream oss;
611 bool firstEntry = true;
612 for (const auto& [key, arr] : data) {
613 if (!firstEntry) oss << ';';
614 firstEntry = false;
615 oss << key << ':'
616 << std::setprecision(CONTROL_CENTER_DATA_PRECISION) << arr[CONTROL_CENTER_STATUS_INDEX] << ','
617 << std::setprecision(CONTROL_CENTER_DATA_PRECISION) << arr[CONTROL_CENTER_BEAUTY_INDEX] << ','
618 << std::setprecision(CONTROL_CENTER_DATA_PRECISION) << arr[CONTROL_CENTER_APERTURE_INDEX];
619 }
620 return oss.str();
621 }
622
StringToControlCenterMap(const std::string & str)623 std::map<std::string, std::array<float, CONTROL_CENTER_DATA_SIZE>> StringToControlCenterMap(const std::string& str)
624 {
625 std::map<std::string, std::array<float, CONTROL_CENTER_DATA_SIZE>> result;
626 std::istringstream iss(str);
627 std::string entry;
628
629 while (std::getline(iss, entry, ';')) {
630 if (entry.empty()) {
631 continue;
632 }
633 size_t colonPos = entry.find(':');
634 if (colonPos == std::string::npos) {
635 continue;
636 }
637 std::string key = entry.substr(0, colonPos);
638 std::string valuesStr = entry.substr(colonPos + 1);
639
640 std::istringstream vss(valuesStr);
641 std::array<float, CONTROL_CENTER_DATA_SIZE> arr;
642 std::string numStr;
643 int index = 0;
644 bool valid = true;
645
646 while (std::getline(vss, numStr, ',') && index < CONTROL_CENTER_DATA_SIZE) {
647 arr[index++] = std::stof(numStr);
648 }
649
650 if (valid && index == CONTROL_CENTER_DATA_SIZE && vss.eof()) {
651 result[key] = arr;
652 }
653 }
654 return result;
655 }
656 } // namespace CameraStandard
657 } // namespace OHOS
658