1 /*
2 * Copyright (C) 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 "wallpaper_service.h"
16
17 #include <fcntl.h>
18 #include <sys/prctl.h>
19 #include <sys/sendfile.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include <cerrno>
25 #include <chrono>
26 #include <cstdio>
27 #include <cstdlib>
28 #include <cstring>
29 #include <fstream>
30 #include <iostream>
31 #include <sstream>
32 #include <thread>
33
34 #include "bundle_mgr_interface.h"
35 #include "bundle_mgr_proxy.h"
36 #include "cJSON.h"
37 #include "color.h"
38 #include "color_picker.h"
39 #include "command.h"
40 #include "config_policy_utils.h"
41 #include "directory_ex.h"
42 #include "dump_helper.h"
43 #include "effect_errors.h"
44 #include "file_deal.h"
45 #include "file_ex.h"
46 #include "hilog_wrapper.h"
47 #include "hitrace_meter.h"
48 #include "image_packer.h"
49 #include "image_source.h"
50 #include "image_type.h"
51 #include "image_utils.h"
52 #include "iservice_registry.h"
53 #include "mem_mgr_client.h"
54 #include "mem_mgr_proxy.h"
55 #include "memory_guard.h"
56 #include "parameter.h"
57 #include "pixel_map.h"
58 #include "scene_board_judgement.h"
59 #include "system_ability_definition.h"
60 #include "tokenid_kit.h"
61 #include "uri.h"
62 #include "wallpaper_common.h"
63 #include "wallpaper_common_event_manager.h"
64 #include "wallpaper_manager_common_info.h"
65 #include "wallpaper_service_cb_proxy.h"
66 #include "want.h"
67 #include "window.h"
68
69 #ifndef THEME_SERVICE
70 #include "ability_manager_client.h"
71 #include "wallpaper_extension_ability_death_recipient.h"
72 #endif
73
74 namespace OHOS {
75 namespace WallpaperMgrService {
76 REGISTER_SYSTEM_ABILITY_BY_ID(WallpaperService, WALLPAPER_MANAGER_SERVICE_ID, true);
77
78 using namespace OHOS::Media;
79 using namespace OHOS::MiscServices;
80 using namespace OHOS::Security::AccessToken;
81 using namespace OHOS::AccountSA;
82
83 constexpr const char *WALLPAPER_SYSTEM_ORIG = "wallpaper_system_orig";
84 constexpr const char *WALLPAPER_HOME = "wallpaper_home";
85 constexpr const char *WALLPAPER_LOCK_ORIG = "wallpaper_lock_orig";
86 constexpr const char *WALLPAPER_LOCK = "wallpaper_lock";
87 constexpr const char *LIVE_WALLPAPER_SYSTEM_ORIG = "live_wallpaper_system_orig";
88 constexpr const char *LIVE_WALLPAPER_LOCK_ORIG = "live_wallpaper_lock_orig";
89 constexpr const char *CUSTOM_WALLPAPER_LOCK = "custom_lock.zip";
90 constexpr const char *CUSTOM_WALLPAPER_SYSTEM = "custom_system.zip";
91 constexpr const char *OHOS_WALLPAPER_BUNDLE_NAME = "com.ohos.launcher";
92 constexpr const char *SHOW_SYSTEM_SCREEN = "SHOW_SYSTEMSCREEN";
93 constexpr const char *SHOW_LOCK_SCREEN = "SHOW_LOCKSCREEN";
94 constexpr const char *SYSTEM_RES_TYPE = "SystemResType";
95 constexpr const char *LOCKSCREEN_RES_TYPE = "LockScreenResType";
96 constexpr const char *WALLPAPER_CHANGE = "wallpaperChange";
97 constexpr const char *COLOR_CHANGE = "colorChange";
98 constexpr const char *SCENEBOARD_BUNDLE_NAME = "com.ohos.sceneboard";
99
100 constexpr const char *WALLPAPER_USERID_PATH = "/data/service/el1/public/wallpaper/";
101 constexpr const char *WALLPAPER_SYSTEM_DIRNAME = "system";
102 constexpr const char *WALLPAPER_TMP_DIRNAME = "fwsettmp";
103 constexpr const char *WALLPAPER_LOCKSCREEN_DIRNAME = "lockscreen";
104 constexpr const char *WALLPAPER_DEFAULT_FILEFULLPATH = "/system/etc/wallpaperdefault.jpeg";
105 constexpr const char *WALLPAPER_DEFAULT_LOCK_FILEFULLPATH = "/system/etc/wallpaperlockdefault.jpeg";
106 constexpr const char *WALLPAPER_CROP_PICTURE = "crop_file";
107 constexpr const char *RESOURCE_PATH = "resource/themes/theme/";
108 constexpr const char *DEFAULT_PATH = "default/";
109 constexpr const char *MANIFEST = "manifest.json";
110 constexpr const char *RES = "resources/";
111 constexpr const char *HOME = "home/";
112 constexpr const char *LOCK = "lock/";
113 constexpr const char *BASE = "base/";
114 constexpr const char *LAND_PATH = "land/";
115 constexpr const char *HOME_UNFOLDED = "home/unfolded/";
116 constexpr const char *HOME_UNFOLDED2 = "home/unfolded2/";
117 constexpr const char *LOCK_UNFOLDED = "lock/unfolded/";
118 constexpr const char *LOCK_UNFOLDED2 = "lock/unfolded2/";
119 constexpr const char *IMAGE = "image";
120 constexpr const char *SRC = "src";
121 constexpr const char *NORMAL_LAND_WALLPAPER_HOME = "normal_land_wallpaper_home";
122 constexpr const char *UNFOLD1_PORT_WALLPAPER_HOME = "unfold1_port_wallpaper_home";
123 constexpr const char *UNFOLD1_LAND_WALLPAPER_HOME = "unfold1_land_wallpaper_home";
124 constexpr const char *UNFOLD2_PORT_WALLPAPER_HOME = "unfold2_port_wallpaper_home";
125 constexpr const char *UNFOLD2_LAND_WALLPAPER_HOME = "unfold2_land_wallpaper_home";
126 constexpr const char *NORMAL_LAND_WALLPAPER_LOCK = "normal_land_wallpaper_lock";
127 constexpr const char *UNFOLD1_PORT_WALLPAPER_LOCK = "unfold1_port_wallpaper_lock";
128 constexpr const char *UNFOLD1_LAND_WALLPAPER_LOCK = "unfold1_land_wallpaper_lock";
129 constexpr const char *UNFOLD2_PORT_WALLPAPER_LOCK = "unfold2_port_wallpaper_lock";
130 constexpr const char *UNFOLD2_LAND_WALLPAPER_LOCK = "unfold2_land_wallpaper_lock";
131 constexpr int64_t INIT_INTERVAL = 10000L;
132 constexpr int64_t DELAY_TIME = 1000L;
133 constexpr int64_t QUERY_USER_ID_INTERVAL = 300L;
134 constexpr int32_t FOO_MAX_LEN = 52428800;
135 constexpr int32_t MAX_RETRY_TIMES = 20;
136 constexpr int32_t QUERY_USER_MAX_RETRY_TIMES = 100;
137 constexpr int32_t DEFAULT_WALLPAPER_ID = -1;
138 constexpr int32_t DEFAULT_USER_ID = 0;
139 constexpr int32_t MAX_VIDEO_SIZE = 104857600;
140 constexpr int32_t OPTION_QUALITY = 100;
141 constexpr int32_t SCALE_SIZE = 100;
142
143 #ifndef THEME_SERVICE
144 constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100;
145 constexpr int32_t DEFAULT_VALUE = -1;
146 constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 50;
147 #endif
148
149 std::shared_ptr<AppExecFwk::EventHandler> WallpaperService::serviceHandler_;
150
WallpaperService(int32_t systemAbilityId,bool runOnCreate)151 WallpaperService::WallpaperService(int32_t systemAbilityId, bool runOnCreate)
152 : SystemAbility(systemAbilityId, runOnCreate), WallpaperServiceStub(true),
153 state_(ServiceRunningState::STATE_NOT_START)
154 {
155 }
156
WallpaperService()157 WallpaperService::WallpaperService() : WallpaperServiceStub(true), state_(ServiceRunningState::STATE_NOT_START)
158 {
159 }
160
~WallpaperService()161 WallpaperService::~WallpaperService()
162 {
163 }
164
Init()165 int32_t WallpaperService::Init()
166 {
167 InitQueryUserId(QUERY_USER_MAX_RETRY_TIMES);
168 bool ret = Publish(this);
169 if (!ret) {
170 HILOG_ERROR("Publish failed!");
171 ReporterFault(FaultType::SERVICE_FAULT, FaultCode::SF_SERVICE_UNAVAILABLE);
172 return -1;
173 }
174 HILOG_INFO("Publish success.");
175 state_ = ServiceRunningState::STATE_RUNNING;
176 #ifndef THEME_SERVICE
177 StartExtensionAbility(CONNECT_EXTENSION_MAX_RETRY_TIMES);
178 #endif
179 return NO_ERROR;
180 }
181
OnStart()182 void WallpaperService::OnStart()
183 {
184 HILOG_INFO("Enter OnStart.");
185 MemoryGuard cacheGuard;
186 if (state_ == ServiceRunningState::STATE_RUNNING) {
187 HILOG_ERROR("WallpaperService is already running.");
188 return;
189 }
190 InitData();
191 InitServiceHandler();
192 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
193 AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
194 auto cmd = std::make_shared<Command>(std::vector<std::string>({ "-all" }), "Show all",
195 [this](const std::vector<std::string> &input, std::string &output) -> bool {
196 output.append(
197 "WallpaperExtensionAbility\t: ExtensionInfo{" + std::string(OHOS_WALLPAPER_BUNDLE_NAME) + "}\n");
198 return true;
199 });
200 DumpHelper::GetInstance().RegisterCommand(cmd);
201 if (Init() != NO_ERROR) {
202 auto callback = [=]() { Init(); };
203 serviceHandler_->PostTask(callback, INIT_INTERVAL);
204 HILOG_ERROR("Init failed. Try again 10s later.");
205 }
206 return;
207 }
208
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)209 void WallpaperService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
210 {
211 HILOG_INFO("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
212 if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
213 int32_t times = 0;
214 RegisterSubscriber(times);
215 } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
216 int32_t pid = getpid();
217 Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 1, WALLPAPER_MANAGER_SERVICE_ID);
218 }
219 }
220
RegisterSubscriber(int32_t times)221 void WallpaperService::RegisterSubscriber(int32_t times)
222 {
223 MemoryGuard cacheGuard;
224 times++;
225 subscriber_ = std::make_shared<WallpaperCommonEventSubscriber>(*this);
226 bool subRes = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_);
227 if (!subRes && times <= MAX_RETRY_TIMES) {
228 HILOG_INFO("RegisterSubscriber failed!");
229 auto callback = [this, times]() { RegisterSubscriber(times); };
230 serviceHandler_->PostTask(callback, DELAY_TIME);
231 }
232 }
233
InitServiceHandler()234 void WallpaperService::InitServiceHandler()
235 {
236 HILOG_INFO("InitServiceHandler started.");
237 if (serviceHandler_ != nullptr) {
238 HILOG_ERROR("InitServiceHandler already init.");
239 return;
240 }
241 std::shared_ptr<AppExecFwk::EventRunner> runner =
242 AppExecFwk::EventRunner::Create("WallpaperService", AppExecFwk::ThreadMode::FFRT);
243 serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
244 }
245
OnStop()246 void WallpaperService::OnStop()
247 {
248 HILOG_INFO("OnStop started.");
249 if (state_ != ServiceRunningState::STATE_RUNNING) {
250 return;
251 }
252 serviceHandler_ = nullptr;
253 #ifndef THEME_SERVICE
254 connection_ = nullptr;
255 #endif
256 recipient_ = nullptr;
257 extensionRemoteObject_ = nullptr;
258 if (subscriber_ != nullptr) {
259 bool unSubscribeResult = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_);
260 subscriber_ = nullptr;
261 HILOG_INFO("UnregisterSubscriber end, unSubscribeResult = %{public}d", unSubscribeResult);
262 }
263 state_ = ServiceRunningState::STATE_NOT_START;
264 int32_t pid = getpid();
265 Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 0, WALLPAPER_MANAGER_SERVICE_ID);
266 }
267
InitData()268 void WallpaperService::InitData()
269 {
270 HILOG_INFO("WallpaperService::initData --> start.");
271 wallpaperId_ = DEFAULT_WALLPAPER_ID;
272 int32_t userId = DEFAULT_USER_ID;
273 systemWallpaperMap_.Clear();
274 lockWallpaperMap_.Clear();
275 wallpaperTmpFullPath_ = std::string(WALLPAPER_USERID_PATH) + std::string(WALLPAPER_TMP_DIRNAME);
276 wallpaperCropPath_ = std::string(WALLPAPER_USERID_PATH) + std::string(WALLPAPER_CROP_PICTURE);
277 {
278 std::lock_guard<std::mutex> lock(wallpaperColorMtx_);
279 systemWallpaperColor_ = 0;
280 lockWallpaperColor_ = 0;
281 }
282 currentUserId_ = userId;
283 wallpaperEventMap_.clear();
284 appBundleName_ = SCENEBOARD_BUNDLE_NAME;
285 InitUserDir(userId);
286 UpdataWallpaperMap(userId, WALLPAPER_SYSTEM);
287 UpdataWallpaperMap(userId, WALLPAPER_LOCKSCREEN);
288 LoadWallpaperState();
289 ClearRedundantFile(userId, WALLPAPER_SYSTEM, WALLPAPER_SYSTEM_ORIG);
290 ClearRedundantFile(userId, WALLPAPER_LOCKSCREEN, WALLPAPER_LOCK_ORIG);
291 }
292
293 #ifndef THEME_SERVICE
AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> & remoteObject)294 void WallpaperService::AddWallpaperExtensionDeathRecipient(const sptr<IRemoteObject> &remoteObject)
295 {
296 if (remoteObject != nullptr) {
297 std::lock_guard<std::mutex> lock(remoteObjectMutex_);
298 IPCObjectProxy *proxy = reinterpret_cast<IPCObjectProxy *>(remoteObject.GetRefPtr());
299 if (recipient_ == nullptr) {
300 recipient_ = sptr<IRemoteObject::DeathRecipient>(new WallpaperExtensionAbilityDeathRecipient(*this));
301 }
302 if (proxy != nullptr && !proxy->IsObjectDead()) {
303 HILOG_INFO("get remoteObject succeed.");
304 proxy->AddDeathRecipient(recipient_);
305 extensionRemoteObject_ = remoteObject;
306 }
307 }
308 }
309 #endif
310
RemoveExtensionDeathRecipient()311 void WallpaperService::RemoveExtensionDeathRecipient()
312 {
313 if (extensionRemoteObject_ != nullptr && recipient_ != nullptr) {
314 HILOG_INFO("Remove Extension DeathRecipient.");
315 std::lock_guard<std::mutex> lock(remoteObjectMutex_);
316 if (extensionRemoteObject_ != nullptr) {
317 extensionRemoteObject_->RemoveDeathRecipient(recipient_);
318 recipient_ = nullptr;
319 extensionRemoteObject_ = nullptr;
320 }
321 }
322 }
323
InitQueryUserId(int32_t times)324 void WallpaperService::InitQueryUserId(int32_t times)
325 {
326 times--;
327 bool ret = InitUsersOnBoot();
328 if (!ret && times > 0) {
329 HILOG_DEBUG("InitQueryUserId failed!");
330 auto callback = [this, times]() { InitQueryUserId(times); };
331 serviceHandler_->PostTask(callback, QUERY_USER_ID_INTERVAL);
332 }
333 }
334
335 #ifndef THEME_SERVICE
StartExtensionAbility(int32_t times)336 void WallpaperService::StartExtensionAbility(int32_t times)
337 {
338 times--;
339 bool ret = ConnectExtensionAbility();
340 if (!ret && times > 0 && serviceHandler_ != nullptr) {
341 HILOG_ERROR("StartExtensionAbilty failed, remainder of the times: %{public}d", times);
342 auto callback = [this, times]() { StartExtensionAbility(times); };
343 serviceHandler_->PostTask(callback, CONNECT_EXTENSION_INTERVAL);
344 }
345 }
346 #endif
347
InitUsersOnBoot()348 bool WallpaperService::InitUsersOnBoot()
349 {
350 std::vector<AccountSA::OsAccountInfo> osAccountInfos;
351 ErrCode errCode = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos);
352 if (errCode != ERR_OK || osAccountInfos.empty()) {
353 HILOG_ERROR("Query all created userIds failed, errCode:%{public}d", errCode);
354 return false;
355 }
356 for (const auto &osAccountInfo : osAccountInfos) {
357 int32_t userId = osAccountInfo.GetLocalId();
358 HILOG_INFO("InitUsersOnBoot Current userId: %{public}d", userId);
359 InitUserDir(userId);
360 UpdataWallpaperMap(userId, WALLPAPER_SYSTEM);
361 UpdataWallpaperMap(userId, WALLPAPER_LOCKSCREEN);
362 ClearRedundantFile(userId, WALLPAPER_SYSTEM, WALLPAPER_SYSTEM_ORIG);
363 ClearRedundantFile(userId, WALLPAPER_LOCKSCREEN, WALLPAPER_LOCK_ORIG);
364 }
365 return true;
366 }
367
ClearRedundantFile(int32_t userId,WallpaperType wallpaperType,std::string fileName)368 void WallpaperService::ClearRedundantFile(int32_t userId, WallpaperType wallpaperType, std::string fileName)
369 {
370 HILOG_DEBUG("ClearRedundantFile Current userId: %{public}d", userId);
371 std::string wallpaperFilePath = GetWallpaperDir(userId, wallpaperType) + "/" + fileName;
372 FileDeal::DeleteFile(wallpaperFilePath);
373 }
374
OnInitUser(int32_t userId)375 void WallpaperService::OnInitUser(int32_t userId)
376 {
377 if (userId < 0) {
378 HILOG_ERROR("userId error, userId = %{public}d", userId);
379 return;
380 }
381 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
382 if (FileDeal::IsFileExist(userDir)) {
383 std::lock_guard<std::mutex> lock(mtx_);
384 if (!FileDeal::DeleteDir(userDir, true)) {
385 HILOG_ERROR("Force remove user directory path failed, errno %{public}d", errno);
386 return;
387 }
388 }
389 if (!InitUserDir(userId)) {
390 return;
391 }
392 UpdataWallpaperMap(userId, WALLPAPER_SYSTEM);
393 UpdataWallpaperMap(userId, WALLPAPER_LOCKSCREEN);
394 HILOG_INFO("OnInitUser success, userId = %{public}d", userId);
395 }
396
InitUserDir(int32_t userId)397 bool WallpaperService::InitUserDir(int32_t userId)
398 {
399 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
400 if (!FileDeal::Mkdir(userDir)) {
401 HILOG_ERROR("Failed to create destination path, userId:%{public}d", userId);
402 return false;
403 }
404 std::string wallpaperSystemFilePath = userDir + "/" + WALLPAPER_SYSTEM_DIRNAME;
405 if (!FileDeal::Mkdir(wallpaperSystemFilePath)) {
406 HILOG_ERROR("Failed to create destination wallpaper system path, userId:%{public}d, type:%{public}s.", userId,
407 WALLPAPER_SYSTEM_DIRNAME);
408 return false;
409 }
410 std::string wallpaperLockScreenFilePath = userDir + "/" + WALLPAPER_LOCKSCREEN_DIRNAME;
411 if (!FileDeal::Mkdir(wallpaperLockScreenFilePath)) {
412 HILOG_ERROR("Failed to create destination wallpaper lockscreen path, userId:%{public}d, type:%{public}s.",
413 userId, WALLPAPER_LOCKSCREEN_DIRNAME);
414 return false;
415 }
416 return true;
417 }
418
RestoreUserResources(int32_t userId,WallpaperData & wallpaperData,WallpaperType wallpaperType)419 bool WallpaperService::RestoreUserResources(int32_t userId, WallpaperData &wallpaperData, WallpaperType wallpaperType)
420 {
421 if (!FileDeal::DeleteDir(GetWallpaperDir(userId, wallpaperType), false)) {
422 HILOG_ERROR("delete resources failed, userId:%{public}d, wallpaperType:%{public}d.", userId, wallpaperType);
423 return false;
424 }
425 std::string wallpaperPath = GetWallpaperDir(userId, wallpaperType);
426 wallpaperData = GetWallpaperDefaultPath(wallpaperType);
427 wallpaperData.userId = userId;
428 wallpaperData.allowBackup = true;
429 wallpaperData.resourceType = PICTURE;
430 wallpaperData.wallpaperId = DEFAULT_WALLPAPER_ID;
431 wallpaperData.liveWallpaperFile =
432 wallpaperPath + "/"
433 + (wallpaperType == WALLPAPER_SYSTEM ? LIVE_WALLPAPER_SYSTEM_ORIG : LIVE_WALLPAPER_LOCK_ORIG);
434 wallpaperData.customPackageUri =
435 wallpaperPath + "/" + (wallpaperType == WALLPAPER_SYSTEM ? CUSTOM_WALLPAPER_SYSTEM : CUSTOM_WALLPAPER_LOCK);
436 if (wallpaperData.wallpaperFile.empty()) {
437 HILOG_ERROR("get default path failed, userId:%{public}d, wallpaperType:%{public}d.", userId, wallpaperType);
438 return false;
439 }
440 HILOG_INFO("Restore user resources end.");
441 return true;
442 }
443
GetWallpaperDefaultPath(WallpaperType wallpaperType)444 WallpaperData WallpaperService::GetWallpaperDefaultPath(WallpaperType wallpaperType)
445 {
446 WallpaperData wallpaperData;
447 std::string manifest = MANIFEST;
448 std::string res = RES;
449 std::string base = BASE;
450 std::string land = LAND_PATH;
451 if (wallpaperType == WallpaperType::WALLPAPER_SYSTEM) {
452 wallpaperData.wallpaperFile = GetWallpaperPathInJson(HOME + manifest, HOME + base + res);
453 wallpaperData.normalLandFile = GetWallpaperPathInJson(HOME + base + land + manifest, HOME + base + land + res);
454 wallpaperData.unfoldedOnePortFile = GetWallpaperPathInJson(HOME_UNFOLDED + manifest, HOME_UNFOLDED + res);
455 wallpaperData.unfoldedOneLandFile =
456 GetWallpaperPathInJson(HOME_UNFOLDED + land + manifest, HOME_UNFOLDED + land + res);
457 wallpaperData.unfoldedTwoPortFile = GetWallpaperPathInJson(HOME_UNFOLDED2 + manifest, HOME_UNFOLDED2 + res);
458 wallpaperData.unfoldedTwoLandFile =
459 GetWallpaperPathInJson(HOME_UNFOLDED2 + land + manifest, HOME_UNFOLDED2 + land + res);
460 } else {
461 wallpaperData.wallpaperFile = GetWallpaperPathInJson(LOCK + manifest, LOCK + base + res);
462 wallpaperData.normalLandFile = GetWallpaperPathInJson(LOCK + base + land + manifest, LOCK + base + land + res);
463 wallpaperData.unfoldedOnePortFile = GetWallpaperPathInJson(LOCK_UNFOLDED + manifest, LOCK_UNFOLDED + res);
464 wallpaperData.unfoldedOneLandFile =
465 GetWallpaperPathInJson(LOCK_UNFOLDED + land + manifest, LOCK_UNFOLDED + land + res);
466 wallpaperData.unfoldedTwoPortFile = GetWallpaperPathInJson(LOCK_UNFOLDED2 + manifest, LOCK_UNFOLDED2 + res);
467 wallpaperData.unfoldedTwoLandFile =
468 GetWallpaperPathInJson(LOCK_UNFOLDED2 + land + manifest, LOCK_UNFOLDED2 + land + res);
469 }
470 if (wallpaperData.wallpaperFile.empty()) {
471 wallpaperData.wallpaperFile = (wallpaperType == WallpaperType::WALLPAPER_SYSTEM)
472 ? WALLPAPER_DEFAULT_FILEFULLPATH
473 : WALLPAPER_DEFAULT_LOCK_FILEFULLPATH;
474 }
475 return wallpaperData;
476 }
OnRemovedUser(int32_t userId)477 void WallpaperService::OnRemovedUser(int32_t userId)
478 {
479 if (userId < 0) {
480 HILOG_ERROR("userId error, userId = %{public}d", userId);
481 return;
482 }
483 ClearWallpaperLocked(userId, WALLPAPER_SYSTEM);
484 ClearWallpaperLocked(userId, WALLPAPER_LOCKSCREEN);
485 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
486 std::lock_guard<std::mutex> lock(mtx_);
487 if (!FileDeal::DeleteDir(userDir, true)) {
488 HILOG_ERROR("Force remove user directory path failed, errno %{public}d", errno);
489 }
490 HILOG_INFO("OnRemovedUser end, userId = %{public}d", userId);
491 }
492
OnSwitchedUser(int32_t userId)493 void WallpaperService::OnSwitchedUser(int32_t userId)
494 {
495 if (userId < 0) {
496 HILOG_ERROR("userId error, userId = %{public}d", userId);
497 return;
498 }
499 if (userId == currentUserId_) {
500 HILOG_ERROR("userId not switch, userId = %{public}d", userId);
501 return;
502 }
503 currentUserId_ = userId;
504 RemoveExtensionDeathRecipient();
505 #ifndef THEME_SERVICE
506 ConnectExtensionAbility();
507 #endif
508 std::string userDir = WALLPAPER_USERID_PATH + std::to_string(userId);
509 if (!FileDeal::IsFileExist(userDir)) {
510 HILOG_INFO("User file is not exist, userId = %{public}d", userId);
511 InitUserDir(userId);
512 UpdataWallpaperMap(userId, WALLPAPER_SYSTEM);
513 UpdataWallpaperMap(userId, WALLPAPER_LOCKSCREEN);
514 }
515 LoadWallpaperState();
516 SendWallpaperChangeEvent(userId, WALLPAPER_SYSTEM);
517 SendWallpaperChangeEvent(userId, WALLPAPER_LOCKSCREEN);
518 SaveColor(userId, WALLPAPER_SYSTEM);
519 SaveColor(userId, WALLPAPER_LOCKSCREEN);
520 HILOG_INFO("OnSwitchedUser end, newUserId = %{public}d", userId);
521 }
522
GetWallpaperDir(int32_t userId,WallpaperType wallpaperType)523 std::string WallpaperService::GetWallpaperDir(int32_t userId, WallpaperType wallpaperType)
524 {
525 std::string userIdPath = WALLPAPER_USERID_PATH + std::to_string(userId);
526 std::string wallpaperFilePath;
527 if (wallpaperType == WALLPAPER_SYSTEM) {
528 wallpaperFilePath = userIdPath + "/" + WALLPAPER_SYSTEM_DIRNAME;
529 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
530 wallpaperFilePath = userIdPath + "/" + WALLPAPER_LOCKSCREEN_DIRNAME;
531 }
532 return wallpaperFilePath;
533 }
534
GetFileNameFromMap(int32_t userId,WallpaperType wallpaperType,std::string & filePathName)535 bool WallpaperService::GetFileNameFromMap(int32_t userId, WallpaperType wallpaperType, std::string &filePathName)
536 {
537 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
538 : lockWallpaperMap_.Find(userId);
539 if (!iterator.first) {
540 HILOG_ERROR("system wallpaper already cleared.");
541 return false;
542 }
543 HILOG_DEBUG("GetFileNameFromMap resourceType : %{public}d", static_cast<int32_t>(iterator.second.resourceType));
544 switch (iterator.second.resourceType) {
545 case PICTURE:
546 filePathName = iterator.second.wallpaperFile;
547 break;
548 case VIDEO:
549 filePathName = iterator.second.liveWallpaperFile;
550 break;
551 case DEFAULT:
552 filePathName = iterator.second.wallpaperFile;
553 break;
554 case PACKAGE:
555 filePathName = iterator.second.customPackageUri;
556 break;
557 default:
558 filePathName = "";
559 break;
560 }
561 return filePathName != "";
562 }
563
GetPictureFileName(int32_t userId,WallpaperType wallpaperType,std::string & filePathName)564 bool WallpaperService::GetPictureFileName(int32_t userId, WallpaperType wallpaperType, std::string &filePathName)
565 {
566 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
567 : lockWallpaperMap_.Find(userId);
568 if (!iterator.first) {
569 HILOG_INFO("WallpaperType:%{public}d, WallpaperMap not found userId: %{public}d", wallpaperType, userId);
570 OnInitUser(userId);
571 iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
572 : lockWallpaperMap_.Find(userId);
573 }
574 filePathName = iterator.second.wallpaperFile;
575 HILOG_INFO("GetPictureFileName filePathName : %{public}s", filePathName.c_str());
576 return filePathName != "";
577 }
578
MakeWallpaperIdLocked()579 int32_t WallpaperService::MakeWallpaperIdLocked()
580 {
581 HILOG_INFO("MakeWallpaperIdLocked start.");
582 if (wallpaperId_ == INT32_MAX) {
583 wallpaperId_ = DEFAULT_WALLPAPER_ID;
584 }
585 return ++wallpaperId_;
586 }
587
UpdataWallpaperMap(int32_t userId,WallpaperType wallpaperType)588 void WallpaperService::UpdataWallpaperMap(int32_t userId, WallpaperType wallpaperType)
589 {
590 HILOG_INFO("updata wallpaperMap.");
591 std::string wallpaperPath = GetWallpaperDir(userId, wallpaperType);
592 std::string wallpaperFilePath =
593 wallpaperPath + "/" + (wallpaperType == WALLPAPER_SYSTEM ? WALLPAPER_HOME : WALLPAPER_LOCK);
594 ConcurrentMap<int32_t, WallpaperData> &wallpaperMap = [&]() -> ConcurrentMap<int32_t, WallpaperData>& {
595 if (wallpaperType == WALLPAPER_SYSTEM) {
596 return systemWallpaperMap_;
597 } else {
598 return lockWallpaperMap_;
599 }
600 }();
601 auto wallpaperData = GetWallpaperDefaultPath(wallpaperType);
602 wallpaperData.userId = userId;
603 wallpaperData.allowBackup = true;
604 wallpaperData.resourceType = PICTURE;
605 wallpaperData.wallpaperId = DEFAULT_WALLPAPER_ID;
606 wallpaperData.liveWallpaperFile =
607 wallpaperPath + "/"
608 + (wallpaperType == WALLPAPER_SYSTEM ? LIVE_WALLPAPER_SYSTEM_ORIG : LIVE_WALLPAPER_LOCK_ORIG);
609 wallpaperData.customPackageUri =
610 wallpaperPath + "/" + (wallpaperType == WALLPAPER_SYSTEM ? CUSTOM_WALLPAPER_SYSTEM : CUSTOM_WALLPAPER_LOCK);
611 if (FileDeal::IsFileExist(wallpaperFilePath)) {
612 wallpaperData.wallpaperFile = GetExistFilePath(
613 wallpaperPath + "/" + (wallpaperType == WALLPAPER_SYSTEM ? WALLPAPER_HOME : WALLPAPER_LOCK));
614 wallpaperData.normalLandFile = GetExistFilePath(
615 wallpaperPath + "/"
616 + (wallpaperType == WALLPAPER_SYSTEM ? NORMAL_LAND_WALLPAPER_HOME : NORMAL_LAND_WALLPAPER_LOCK));
617 wallpaperData.unfoldedOnePortFile = GetExistFilePath(
618 wallpaperPath + "/"
619 + (wallpaperType == WALLPAPER_SYSTEM ? UNFOLD1_PORT_WALLPAPER_HOME : UNFOLD1_PORT_WALLPAPER_LOCK));
620 wallpaperData.unfoldedOneLandFile = GetExistFilePath(
621 wallpaperPath + "/"
622 + (wallpaperType == WALLPAPER_SYSTEM ? UNFOLD1_LAND_WALLPAPER_HOME : UNFOLD1_LAND_WALLPAPER_LOCK));
623 wallpaperData.unfoldedTwoPortFile = GetExistFilePath(
624 wallpaperPath + "/"
625 + (wallpaperType == WALLPAPER_SYSTEM ? UNFOLD2_PORT_WALLPAPER_HOME : UNFOLD2_PORT_WALLPAPER_LOCK));
626 wallpaperData.unfoldedTwoLandFile = GetExistFilePath(
627 wallpaperPath + "/"
628 + (wallpaperType == WALLPAPER_SYSTEM ? UNFOLD2_LAND_WALLPAPER_HOME : UNFOLD2_LAND_WALLPAPER_LOCK));
629 }
630 wallpaperMap.InsertOrAssign(userId, wallpaperData);
631 }
632
GetColors(int32_t wallpaperType,std::vector<uint64_t> & colors)633 ErrCode WallpaperService::GetColors(int32_t wallpaperType, std::vector<uint64_t> &colors)
634 {
635 if (wallpaperType == WALLPAPER_SYSTEM) {
636 std::lock_guard<std::mutex> lock(wallpaperColorMtx_);
637 colors.emplace_back(systemWallpaperColor_);
638 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
639 std::lock_guard<std::mutex> lock(wallpaperColorMtx_);
640 colors.emplace_back(lockWallpaperColor_);
641 }
642 HILOG_INFO("GetColors Service End.");
643 return NO_ERROR;
644 }
645
GetColorsV9(int32_t wallpaperType,std::vector<uint64_t> & colors)646 ErrCode WallpaperService::GetColorsV9(int32_t wallpaperType, std::vector<uint64_t> &colors)
647 {
648 if (!IsSystemApp()) {
649 HILOG_ERROR("CallingApp is not SystemApp.");
650 return E_NOT_SYSTEM_APP;
651 }
652 return GetColors(wallpaperType, colors);
653 }
654
GetFile(int32_t wallpaperType,int & wallpaperFd)655 ErrCode WallpaperService::GetFile(int32_t wallpaperType, int &wallpaperFd)
656 {
657 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
658 HILOG_ERROR("GetPixelMap no get permission!");
659 return E_NO_PERMISSION;
660 }
661 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
662 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
663 return E_PARAMETERS_INVALID;
664 }
665 auto type = static_cast<WallpaperType>(wallpaperType);
666 int32_t userId = QueryActiveUserId();
667 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
668 ErrorCode ret = GetImageFd(userId, type, wallpaperFd);
669 HILOG_INFO("GetImageFd fd:%{public}d, ret:%{public}d", wallpaperFd, ret);
670 return ret;
671 }
672
CompareColor(const uint64_t & localColor,const ColorManager::Color & color)673 bool WallpaperService::CompareColor(const uint64_t &localColor, const ColorManager::Color &color)
674 {
675 return localColor == color.PackValue();
676 }
677
SaveColor(int32_t userId,WallpaperType wallpaperType)678 bool WallpaperService::SaveColor(int32_t userId, WallpaperType wallpaperType)
679 {
680 uint32_t errorCode = 0;
681 OHOS::Media::SourceOptions opts;
682 opts.formatHint = "image/jpeg";
683 std::string pathName;
684 if (!GetPictureFileName(userId, wallpaperType, pathName)) {
685 return false;
686 }
687 std::unique_ptr<OHOS::Media::ImageSource> imageSource =
688 OHOS::Media::ImageSource::CreateImageSource(pathName, opts, errorCode);
689 if (errorCode != 0 || imageSource == nullptr) {
690 HILOG_ERROR("CreateImageSource failed!");
691 return false;
692 }
693 OHOS::Media::DecodeOptions decodeOpts;
694 std::unique_ptr<PixelMap> wallpaperPixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode);
695 if (errorCode != 0 || wallpaperPixelMap == nullptr) {
696 HILOG_ERROR("CreatePixelMap failed!");
697 return false;
698 }
699 int32_t height = wallpaperPixelMap->GetHeight();
700 int32_t width = wallpaperPixelMap->GetWidth();
701 if (height != 0 && width != 0 && height > SCALE_SIZE && width > SCALE_SIZE) {
702 float scaleRatio = (height > width) ? static_cast<float>(SCALE_SIZE) / width
703 : static_cast<float>(SCALE_SIZE) / height;
704 wallpaperPixelMap->scale(scaleRatio, scaleRatio);
705 }
706 auto colorPicker = Rosen::ColorPicker::CreateColorPicker(std::move(wallpaperPixelMap), errorCode);
707 if (errorCode != 0) {
708 HILOG_ERROR("CreateColorPicker failed!");
709 return false;
710 }
711 auto color = ColorManager::Color();
712 uint32_t ret = colorPicker->GetMainColor(color);
713 if (ret != Rosen::SUCCESS) {
714 HILOG_ERROR("GetMainColor failed ret is : %{public}d", ret);
715 return false;
716 }
717 OnColorsChange(wallpaperType, color);
718 return true;
719 }
720
SetWallpaper(int fd,int32_t wallpaperType,int32_t length)721 ErrCode WallpaperService::SetWallpaper(int fd, int32_t wallpaperType, int32_t length)
722 {
723 StartAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
724 ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, PICTURE);
725 FinishAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
726 close(fd);
727 return wallpaperErrorCode;
728 }
729
SetWallpaperByPixelMap(const WallpaperRawData & wallpaperRawdata,int32_t wallpaperType)730 ErrCode WallpaperService::SetWallpaperByPixelMap(const WallpaperRawData &wallpaperRawdata, int32_t wallpaperType)
731 {
732 auto *rawData = (uint8_t *)wallpaperRawdata.data;
733 if (rawData == nullptr) {
734 HILOG_ERROR("rawData is nullptr!");
735 return E_FILE_ERROR;
736 }
737 std::vector<uint8_t> VectorPixelMap(rawData, rawData + wallpaperRawdata.size);
738 if (VectorPixelMap.size() == 0) {
739 HILOG_ERROR("VectorPixelMap is nullptr!");
740 return E_FILE_ERROR;
741 }
742 std::shared_ptr<OHOS::Media::PixelMap> pixelMap = std::shared_ptr<PixelMap>(PixelMap::DecodeTlv(VectorPixelMap));
743 if (pixelMap == nullptr) {
744 HILOG_ERROR("pixelMap is nullptr");
745 return E_FILE_ERROR;
746 }
747 StartAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
748 ErrorCode wallpaperErrorCode = SetWallpaperByPixelMap(pixelMap, wallpaperType, PICTURE);
749 FinishAsyncTrace(HITRACE_TAG_MISC, "SetWallpaper", static_cast<int32_t>(TraceTaskId::SET_WALLPAPER));
750 return wallpaperErrorCode;
751 }
752
SetWallpaperV9(int fd,int32_t wallpaperType,int32_t length)753 ErrCode WallpaperService::SetWallpaperV9(int fd, int32_t wallpaperType, int32_t length)
754 {
755 if (!IsSystemApp()) {
756 HILOG_ERROR("CallingApp is not SystemApp.");
757 close(fd);
758 return E_NOT_SYSTEM_APP;
759 }
760 return SetWallpaper(fd, wallpaperType, length);
761 }
762
SetWallpaperV9ByPixelMap(const WallpaperRawData & wallpaperRawdata,int32_t wallpaperType)763 ErrCode WallpaperService::SetWallpaperV9ByPixelMap(const WallpaperRawData &wallpaperRawdata, int32_t wallpaperType)
764 {
765 if (!IsSystemApp()) {
766 HILOG_INFO("CallingApp is not SystemApp.");
767 return E_NOT_SYSTEM_APP;
768 }
769 return SetWallpaperByPixelMap(wallpaperRawdata, wallpaperType);
770 }
771
SetWallpaperBackupData(int32_t userId,WallpaperResourceType resourceType,const std::string & uriOrPixelMap,WallpaperType wallpaperType)772 ErrorCode WallpaperService::SetWallpaperBackupData(
773 int32_t userId, WallpaperResourceType resourceType, const std::string &uriOrPixelMap, WallpaperType wallpaperType)
774 {
775 HILOG_INFO("set wallpaper and backup data Start.");
776 if (!OHOS::FileExists(uriOrPixelMap)) {
777 return E_DEAL_FAILED;
778 }
779 if (!FileDeal::DeleteDir(GetWallpaperDir(userId, wallpaperType), false)) {
780 return E_DEAL_FAILED;
781 }
782 WallpaperData wallpaperData;
783 bool ret = GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData);
784 if (!ret) {
785 HILOG_ERROR("GetWallpaperSafeLocked failed!");
786 return E_DEAL_FAILED;
787 }
788 if (resourceType == PICTURE || resourceType == DEFAULT) {
789 wallpaperData.wallpaperFile = GetWallpaperDir(userId, wallpaperType) + "/"
790 + (wallpaperType == WALLPAPER_SYSTEM ? WALLPAPER_HOME : WALLPAPER_LOCK);
791 }
792 wallpaperData.resourceType = resourceType;
793 wallpaperData.wallpaperId = MakeWallpaperIdLocked();
794 std::string wallpaperFile;
795 WallpaperService::GetWallpaperFile(resourceType, wallpaperData, wallpaperFile);
796 {
797 std::lock_guard<std::mutex> lock(mtx_);
798 if (!FileDeal::CopyFile(uriOrPixelMap, wallpaperFile)) {
799 HILOG_ERROR("CopyFile failed!");
800 FileDeal::DeleteFile(uriOrPixelMap);
801 return E_DEAL_FAILED;
802 }
803 if (!FileDeal::DeleteFile(uriOrPixelMap)) {
804 return E_DEAL_FAILED;
805 }
806 }
807 if (!SaveWallpaperState(userId, wallpaperType, resourceType)) {
808 HILOG_ERROR("Save wallpaper state failed!");
809 return E_DEAL_FAILED;
810 }
811 if (wallpaperType == WALLPAPER_SYSTEM) {
812 systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
813 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
814 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
815 }
816 if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
817 HILOG_ERROR("Send wallpaper state failed!");
818 return E_DEAL_FAILED;
819 }
820 return NO_ERROR;
821 }
822
GetWallpaperFile(WallpaperResourceType resourceType,const WallpaperData & wallpaperData,std::string & wallpaperFile)823 void WallpaperService::GetWallpaperFile(
824 WallpaperResourceType resourceType, const WallpaperData &wallpaperData, std::string &wallpaperFile)
825 {
826 switch (resourceType) {
827 case PICTURE:
828 wallpaperFile = wallpaperData.wallpaperFile;
829 break;
830 case DEFAULT:
831 wallpaperFile = wallpaperData.wallpaperFile;
832 break;
833 case VIDEO:
834 wallpaperFile = wallpaperData.liveWallpaperFile;
835 break;
836 case PACKAGE:
837 wallpaperFile = wallpaperData.customPackageUri;
838 break;
839 default:
840 HILOG_ERROR("Non-existent error type!");
841 break;
842 }
843 }
844
GetResType(int32_t userId,WallpaperType wallpaperType)845 WallpaperResourceType WallpaperService::GetResType(int32_t userId, WallpaperType wallpaperType)
846 {
847 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
848 auto iterator = lockWallpaperMap_.Find(userId);
849 if (iterator.first) {
850 return iterator.second.resourceType;
851 }
852 } else if (wallpaperType == WALLPAPER_SYSTEM) {
853 auto iterator = systemWallpaperMap_.Find(userId);
854 if (iterator.first) {
855 return iterator.second.resourceType;
856 }
857 }
858 return WallpaperResourceType::DEFAULT;
859 }
860
SendEvent(const std::string & eventType)861 ErrCode WallpaperService::SendEvent(const std::string &eventType)
862 {
863 HILOG_INFO("Send event start.");
864 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
865 HILOG_ERROR("Send event not set permission!");
866 return E_NO_PERMISSION;
867 }
868
869 int32_t userId = QueryActiveUserId();
870 WallpaperType wallpaperType;
871 WallpaperData data;
872 if (eventType == SHOW_SYSTEM_SCREEN) {
873 wallpaperType = WALLPAPER_SYSTEM;
874 } else if (eventType == SHOW_LOCK_SCREEN) {
875 wallpaperType = WALLPAPER_LOCKSCREEN;
876 } else {
877 HILOG_ERROR("Event type error!");
878 return E_PARAMETERS_INVALID;
879 }
880
881 if (!GetWallpaperSafeLocked(userId, wallpaperType, data)) {
882 HILOG_ERROR("Get wallpaper safe locked failed!");
883 return E_PARAMETERS_INVALID;
884 }
885 std::string uri;
886 GetFileNameFromMap(userId, WALLPAPER_SYSTEM, uri);
887 WallpaperChanged(wallpaperType, data.resourceType, uri);
888 return NO_ERROR;
889 }
890
SendWallpaperChangeEvent(int32_t userId,WallpaperType wallpaperType)891 bool WallpaperService::SendWallpaperChangeEvent(int32_t userId, WallpaperType wallpaperType)
892 {
893 WallpaperData wallpaperData;
894 if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
895 HILOG_ERROR("GetWallpaperSafeLocked failed!");
896 return false;
897 }
898 shared_ptr<WallpaperCommonEventManager> wallpaperCommonEventManager = make_shared<WallpaperCommonEventManager>();
899 if (wallpaperType == WALLPAPER_SYSTEM) {
900 HILOG_INFO("Send wallpaper system setting message.");
901 wallpaperCommonEventManager->SendWallpaperSystemSettingMessage(wallpaperData.resourceType);
902 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
903 HILOG_INFO("Send wallpaper lock setting message.");
904 wallpaperCommonEventManager->SendWallpaperLockSettingMessage(wallpaperData.resourceType);
905 }
906 HILOG_INFO("SetWallpaperBackupData callbackProxy_->OnCall start.");
907 if (callbackProxy_ != nullptr && (wallpaperData.resourceType == PICTURE || wallpaperData.resourceType == DEFAULT)) {
908 callbackProxy_->OnCall(wallpaperType);
909 }
910 std::string uri;
911 WallpaperChanged(wallpaperType, wallpaperData.resourceType, uri);
912 return true;
913 }
914
SetVideo(int fd,int32_t wallpaperType,int32_t length)915 ErrCode WallpaperService::SetVideo(int fd, int32_t wallpaperType, int32_t length)
916 {
917 if (!IsSystemApp()) {
918 HILOG_ERROR("current app is not SystemApp.");
919 close(fd);
920 return E_NOT_SYSTEM_APP;
921 }
922 StartAsyncTrace(HITRACE_TAG_MISC, "SetVideo", static_cast<int32_t>(TraceTaskId::SET_VIDEO));
923 ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, VIDEO);
924 FinishAsyncTrace(HITRACE_TAG_MISC, "SetVideo", static_cast<int32_t>(TraceTaskId::SET_VIDEO));
925 close(fd);
926 return wallpaperErrorCode;
927 }
928
SetCustomWallpaper(int fd,int32_t type,int32_t length)929 ErrCode WallpaperService::SetCustomWallpaper(int fd, int32_t type, int32_t length)
930 {
931 if (!IsSystemApp()) {
932 HILOG_ERROR("current app is not SystemApp.");
933 close(fd);
934 return E_NOT_SYSTEM_APP;
935 }
936 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
937 close(fd);
938 return E_NO_PERMISSION;
939 }
940 if (type != static_cast<int32_t>(WALLPAPER_LOCKSCREEN) && type != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
941 close(fd);
942 return E_PARAMETERS_INVALID;
943 }
944 StartAsyncTrace(HITRACE_TAG_MISC, "SetCustomWallpaper", static_cast<int32_t>(TraceTaskId::SET_CUSTOM_WALLPAPER));
945 int32_t userId = QueryActiveUserId();
946 WallpaperType wallpaperType = static_cast<WallpaperType>(type);
947 WallpaperData wallpaperData;
948 if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
949 HILOG_ERROR("GetWallpaper data failed!");
950 close(fd);
951 return E_DEAL_FAILED;
952 }
953 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
954 close(fd);
955 HILOG_ERROR("SceneBoard is not Enabled.");
956 return E_NO_PERMISSION;
957 }
958 if (!SaveWallpaperState(userId, wallpaperType, PACKAGE)) {
959 HILOG_ERROR("Save wallpaper state failed!");
960 close(fd);
961 return E_DEAL_FAILED;
962 }
963 ErrorCode wallpaperErrorCode = SetWallpaper(fd, wallpaperType, length, PACKAGE);
964 wallpaperData.resourceType = PACKAGE;
965 wallpaperData.wallpaperId = MakeWallpaperIdLocked();
966 if (wallpaperType == WALLPAPER_SYSTEM) {
967 systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
968 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
969 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
970 }
971 if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
972 HILOG_ERROR("Send wallpaper state failed!");
973 close(fd);
974 return E_DEAL_FAILED;
975 }
976 FinishAsyncTrace(HITRACE_TAG_MISC, "SetCustomWallpaper", static_cast<int32_t>(TraceTaskId::SET_CUSTOM_WALLPAPER));
977 close(fd);
978 return wallpaperErrorCode;
979 }
980
GetPixelMap(int32_t wallpaperType,int32_t & size,int & fd)981 ErrCode WallpaperService::GetPixelMap(int32_t wallpaperType, int32_t &size, int &fd)
982 {
983 HILOG_INFO("WallpaperService::getPixelMap start.");
984 if (!IsSystemApp()) {
985 HILOG_ERROR("CallingApp is not SystemApp.");
986 return E_NOT_SYSTEM_APP;
987 }
988 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
989 HILOG_ERROR("GetPixelMap no get permission!");
990 return E_NO_PERMISSION;
991 }
992 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
993 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
994 return E_PARAMETERS_INVALID;
995 }
996 auto type = static_cast<WallpaperType>(wallpaperType);
997 int32_t userId = QueryActiveUserId();
998 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
999 // current user's wallpaper is live video, not image
1000 WallpaperResourceType resType = GetResType(userId, type);
1001 if (resType != PICTURE && resType != DEFAULT) {
1002 HILOG_ERROR("Current user's wallpaper is live video, not image.");
1003 size = 0; // 0: empty file size
1004 fd = -1; // -1: invalid file description
1005 return NO_ERROR;
1006 }
1007 ErrorCode ret = GetImageSize(userId, type, size);
1008 if (ret != NO_ERROR) {
1009 HILOG_ERROR("GetImageSize failed!");
1010 return ret;
1011 }
1012 ret = GetImageFd(userId, type, fd);
1013 if (ret != NO_ERROR) {
1014 HILOG_ERROR("GetImageFd failed!");
1015 return ret;
1016 }
1017 return NO_ERROR;
1018 }
1019
GetPixelMapV9(int32_t wallpaperType,int32_t & size,int & fd)1020 ErrCode WallpaperService::GetPixelMapV9(int32_t wallpaperType, int32_t &size, int &fd)
1021 {
1022 return GetPixelMap(wallpaperType, size, fd);
1023 }
1024
GetWallpaperId(int32_t wallpaperType)1025 int32_t WallpaperService::GetWallpaperId(int32_t wallpaperType)
1026 {
1027 HILOG_INFO("WallpaperService::GetWallpaperId --> start.");
1028 int32_t iWallpaperId = -1;
1029 int32_t userId = QueryActiveUserId();
1030 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
1031 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1032 auto iterator = lockWallpaperMap_.Find(userId);
1033 if (iterator.first) {
1034 iWallpaperId = iterator.second.wallpaperId;
1035 }
1036 } else if (wallpaperType == WALLPAPER_SYSTEM) {
1037 auto iterator = systemWallpaperMap_.Find(userId);
1038 if (iterator.first) {
1039 iWallpaperId = iterator.second.wallpaperId;
1040 }
1041 }
1042 HILOG_INFO("WallpaperService::GetWallpaperId --> end ID[%{public}d]", iWallpaperId);
1043 return iWallpaperId;
1044 }
1045
IsChangePermitted(bool & isChangePermitted)1046 ErrCode WallpaperService::IsChangePermitted(bool &isChangePermitted)
1047 {
1048 HILOG_INFO("IsChangePermitted wallpaper Start.");
1049 isChangePermitted = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
1050 return NO_ERROR;
1051 }
1052
IsOperationAllowed(bool & isOperationAllowed)1053 ErrCode WallpaperService::IsOperationAllowed(bool &isOperationAllowed)
1054 {
1055 HILOG_INFO("IsOperationAllowed wallpaper Start.");
1056 isOperationAllowed = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
1057 return NO_ERROR;
1058 }
1059
ResetWallpaper(int32_t wallpaperType)1060 ErrCode WallpaperService::ResetWallpaper(int32_t wallpaperType)
1061 {
1062 HILOG_INFO("reset wallpaper Start.");
1063 bool permissionSet = CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER);
1064 if (!permissionSet) {
1065 HILOG_ERROR("reset wallpaper no set permission!");
1066 return E_NO_PERMISSION;
1067 }
1068 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
1069 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
1070 HILOG_ERROR("wallpaperType = %{public}d type not support ", wallpaperType);
1071 return E_PARAMETERS_INVALID;
1072 }
1073 WallpaperType type = static_cast<WallpaperType>(wallpaperType);
1074 int32_t userId = QueryActiveUserId();
1075 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
1076 if (!CheckUserPermissionById(userId)) {
1077 return E_USER_IDENTITY_ERROR;
1078 }
1079 ErrorCode wallpaperErrorCode = SetDefaultDataForWallpaper(userId, type);
1080 HILOG_INFO(" Set default data result[%{public}d]", wallpaperErrorCode);
1081 return wallpaperErrorCode;
1082 }
1083
ResetWallpaperV9(int32_t wallpaperType)1084 ErrCode WallpaperService::ResetWallpaperV9(int32_t wallpaperType)
1085 {
1086 if (!IsSystemApp()) {
1087 HILOG_ERROR("CallingApp is not SystemApp.");
1088 return E_NOT_SYSTEM_APP;
1089 }
1090 return ResetWallpaper(wallpaperType);
1091 }
1092
SetDefaultDataForWallpaper(int32_t userId,WallpaperType wallpaperType)1093 ErrorCode WallpaperService::SetDefaultDataForWallpaper(int32_t userId, WallpaperType wallpaperType)
1094 {
1095 WallpaperData wallpaperData;
1096 if (!GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData)) {
1097 return E_DEAL_FAILED;
1098 }
1099 if (!RestoreUserResources(userId, wallpaperData, wallpaperType)) {
1100 HILOG_ERROR("RestoreUserResources error!");
1101 return E_DEAL_FAILED;
1102 }
1103 if (!SaveWallpaperState(userId, wallpaperType, DEFAULT)) {
1104 HILOG_ERROR("Save wallpaper state failed!");
1105 return E_DEAL_FAILED;
1106 }
1107 wallpaperData.wallpaperId = DEFAULT_WALLPAPER_ID;
1108 wallpaperData.resourceType = DEFAULT;
1109 wallpaperData.allowBackup = true;
1110 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1111 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
1112 } else if (wallpaperType == WALLPAPER_SYSTEM) {
1113 systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
1114 }
1115 if (!SendWallpaperChangeEvent(userId, wallpaperType)) {
1116 HILOG_ERROR("Send wallpaper state failed!");
1117 return E_DEAL_FAILED;
1118 }
1119 SaveColor(userId, wallpaperType);
1120 return NO_ERROR;
1121 }
1122
On(const std::string & type,const sptr<IWallpaperEventListener> & listener)1123 ErrCode WallpaperService::On(const std::string &type, const sptr<IWallpaperEventListener> &listener)
1124 {
1125 HILOG_DEBUG("WallpaperService::On in.");
1126 if (listener == nullptr) {
1127 HILOG_ERROR("WallpaperService::On listener is null.");
1128 return E_DEAL_FAILED;
1129 }
1130 if (type == WALLPAPER_CHANGE && !IsSystemApp()) {
1131 HILOG_ERROR("current app is not SystemApp.");
1132 return E_NOT_SYSTEM_APP;
1133 }
1134 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1135 wallpaperEventMap_[type].insert_or_assign(IPCSkeleton::GetCallingTokenID(), listener);
1136 return NO_ERROR;
1137 }
1138
Off(const std::string & type,const sptr<IWallpaperEventListener> & listener)1139 ErrCode WallpaperService::Off(const std::string &type, const sptr<IWallpaperEventListener> &listener)
1140 {
1141 HILOG_DEBUG("WallpaperService::Off in.");
1142 (void)listener;
1143 if (type == WALLPAPER_CHANGE && !IsSystemApp()) {
1144 HILOG_ERROR("current app is not SystemApp.");
1145 return E_NOT_SYSTEM_APP;
1146 }
1147 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1148 auto iter = wallpaperEventMap_.find(type);
1149 if (iter != wallpaperEventMap_.end()) {
1150 auto it = iter->second.find(IPCSkeleton::GetCallingTokenID());
1151 if (it != iter->second.end()) {
1152 it->second = nullptr;
1153 iter->second.erase(it);
1154 }
1155 }
1156 return NO_ERROR;
1157 }
1158
RegisterWallpaperCallback(const sptr<IWallpaperCallback> & wallpaperCallback,bool & registerWallpaperCallback)1159 ErrCode WallpaperService::RegisterWallpaperCallback(
1160 const sptr<IWallpaperCallback> &wallpaperCallback, bool ®isterWallpaperCallback)
1161 {
1162 HILOG_INFO(" WallpaperService::RegisterWallpaperCallback.");
1163 callbackProxy_ = wallpaperCallback;
1164 registerWallpaperCallback = true;
1165 return NO_ERROR;
1166 }
1167
GetWallpaperSafeLocked(int32_t userId,WallpaperType wallpaperType,WallpaperData & wallpaperData)1168 bool WallpaperService::GetWallpaperSafeLocked(int32_t userId, WallpaperType wallpaperType, WallpaperData &wallpaperData)
1169 {
1170 HILOG_DEBUG("GetWallpaperSafeLocked start.");
1171 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1172 : lockWallpaperMap_.Find(userId);
1173 if (!iterator.first) {
1174 HILOG_INFO("No Lock wallpaper? Not tracking for lock-only");
1175 UpdataWallpaperMap(userId, wallpaperType);
1176 iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1177 : lockWallpaperMap_.Find(userId);
1178 if (!iterator.first) {
1179 HILOG_ERROR("Fail to get wallpaper data");
1180 return false;
1181 }
1182 }
1183 wallpaperData = iterator.second;
1184 ClearnWallpaperDataFile(wallpaperData);
1185 return true;
1186 }
1187
ClearWallpaperLocked(int32_t userId,WallpaperType wallpaperType)1188 void WallpaperService::ClearWallpaperLocked(int32_t userId, WallpaperType wallpaperType)
1189 {
1190 HILOG_INFO("Clear wallpaper Start.");
1191 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
1192 : lockWallpaperMap_.Find(userId);
1193 if (!iterator.first) {
1194 HILOG_ERROR("Lock wallpaper already cleared.");
1195 return;
1196 }
1197 if (!iterator.second.wallpaperFile.empty() || !iterator.second.liveWallpaperFile.empty()) {
1198 if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1199 lockWallpaperMap_.Erase(userId);
1200 } else if (wallpaperType == WALLPAPER_SYSTEM) {
1201 systemWallpaperMap_.Erase(userId);
1202 }
1203 }
1204 }
1205
CheckCallingPermission(const std::string & permissionName)1206 bool WallpaperService::CheckCallingPermission(const std::string &permissionName)
1207 {
1208 AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1209 int32_t result = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
1210 if (result != TypePermissionState::PERMISSION_GRANTED) {
1211 HILOG_ERROR("Check permission failed!");
1212 return false;
1213 }
1214 return true;
1215 }
1216
ReporterFault(FaultType faultType,FaultCode faultCode)1217 void WallpaperService::ReporterFault(FaultType faultType, FaultCode faultCode)
1218 {
1219 FaultMsg msg;
1220 msg.faultType = faultType;
1221 msg.errorCode = faultCode;
1222 ReportStatus nRet;
1223 if (faultType == FaultType::SERVICE_FAULT) {
1224 msg.moduleName = "WallpaperService";
1225 nRet = FaultReporter::ReportServiceFault(msg);
1226 } else {
1227 nRet = FaultReporter::ReportRuntimeFault(msg);
1228 }
1229
1230 if (nRet == ReportStatus::SUCCESS) {
1231 HILOG_INFO("ReporterFault success.");
1232 } else {
1233 HILOG_ERROR("ReporterFault failed!");
1234 }
1235 }
1236
Dump(int32_t fd,const std::vector<std::u16string> & args)1237 int32_t WallpaperService::Dump(int32_t fd, const std::vector<std::u16string> &args)
1238 {
1239 std::vector<std::string> argsStr;
1240 for (auto item : args) {
1241 argsStr.emplace_back(Str16ToStr8(item));
1242 }
1243
1244 if (DumpHelper::GetInstance().Dispatch(fd, argsStr)) {
1245 HILOG_ERROR("DumpHelper Dispatch failed!");
1246 return 0;
1247 }
1248 return 1;
1249 }
1250
1251 #ifndef THEME_SERVICE
ConnectExtensionAbility()1252 bool WallpaperService::ConnectExtensionAbility()
1253 {
1254 HILOG_DEBUG("ConnectAdapter.");
1255 MemoryGuard cacheGuard;
1256 AAFwk::Want want;
1257 want.SetElementName(OHOS_WALLPAPER_BUNDLE_NAME, "WallpaperExtAbility");
1258 ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect();
1259 if (errCode != ERR_OK) {
1260 HILOG_ERROR("connect ability server failed errCode=%{public}d", errCode);
1261 return false;
1262 }
1263 if (connection_ == nullptr) {
1264 connection_ = new WallpaperExtensionAbilityConnection(*this);
1265 }
1266 auto ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectExtensionAbility(want, connection_, DEFAULT_VALUE);
1267 HILOG_INFO("ConnectExtensionAbility errCode=%{public}d", ret);
1268 return ret;
1269 }
1270 #endif
1271
IsSystemApp()1272 bool WallpaperService::IsSystemApp()
1273 {
1274 HILOG_INFO("IsSystemApp start.");
1275 uint64_t tokenId = IPCSkeleton::GetCallingFullTokenID();
1276 return TokenIdKit::IsSystemAppByFullTokenID(tokenId);
1277 }
1278
IsNativeSa()1279 bool WallpaperService::IsNativeSa()
1280 {
1281 HILOG_INFO("IsNativeSa start.");
1282 AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
1283 return AccessTokenKit::GetTokenTypeFlag(tokenId) == TypeATokenTypeEnum::TOKEN_NATIVE;
1284 }
1285
GetImageFd(int32_t userId,WallpaperType wallpaperType,int32_t & fd)1286 ErrorCode WallpaperService::GetImageFd(int32_t userId, WallpaperType wallpaperType, int32_t &fd)
1287 {
1288 HILOG_INFO("WallpaperService::GetImageFd start.");
1289 std::string filePathName;
1290 if (!GetFileNameFromMap(userId, wallpaperType, filePathName)) {
1291 return E_DEAL_FAILED;
1292 }
1293 if (GetResType(userId, wallpaperType) == WallpaperResourceType::PACKAGE) {
1294 HILOG_INFO("The current wallpaper is a custom wallpaper");
1295 return NO_ERROR;
1296 }
1297 {
1298 std::lock_guard<std::mutex> lock(mtx_);
1299 fd = open(filePathName.c_str(), O_RDONLY, S_IREAD);
1300 }
1301 if (fd < 0) {
1302 HILOG_ERROR("Open file failed, errno %{public}d", errno);
1303 ReporterFault(FaultType::LOAD_WALLPAPER_FAULT, FaultCode::RF_FD_INPUT_FAILED);
1304 return E_DEAL_FAILED;
1305 }
1306 fdsan_exchange_owner_tag(fd, 0, WP_DOMAIN);
1307 HILOG_INFO("fd = %{public}d", fd);
1308 return NO_ERROR;
1309 }
1310
GetImageSize(int32_t userId,WallpaperType wallpaperType,int32_t & size)1311 ErrorCode WallpaperService::GetImageSize(int32_t userId, WallpaperType wallpaperType, int32_t &size)
1312 {
1313 HILOG_INFO("WallpaperService::GetImageSize start.");
1314 std::string filePathName;
1315 HILOG_INFO("userId = %{public}d", userId);
1316 if (!GetPictureFileName(userId, wallpaperType, filePathName)) {
1317 return E_DEAL_FAILED;
1318 }
1319
1320 if (!OHOS::FileExists(filePathName)) {
1321 HILOG_ERROR("file is not exist.");
1322 return E_NOT_FOUND;
1323 }
1324 std::lock_guard<std::mutex> lock(mtx_);
1325 FILE *fd = fopen(filePathName.c_str(), "rb");
1326 if (fd == nullptr) {
1327 HILOG_ERROR("fopen file failed, errno %{public}d", errno);
1328 return E_FILE_ERROR;
1329 }
1330 int32_t fend = fseek(fd, 0, SEEK_END);
1331 size = ftell(fd);
1332 int32_t fset = fseek(fd, 0, SEEK_SET);
1333 if (size <= 0 || fend != 0 || fset != 0) {
1334 HILOG_ERROR("ftell file failed or fseek file failed, errno %{public}d", errno);
1335 fclose(fd);
1336 return E_FILE_ERROR;
1337 }
1338 fclose(fd);
1339 return NO_ERROR;
1340 }
1341
QueryActiveUserId()1342 int32_t WallpaperService::QueryActiveUserId()
1343 {
1344 std::vector<int32_t> ids;
1345 ErrCode errCode = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
1346 if (errCode != ERR_OK || ids.empty()) {
1347 HILOG_ERROR("Query active userid failed, errCode: %{public}d,", errCode);
1348 return DEFAULT_USER_ID;
1349 }
1350 return ids[0];
1351 }
1352
CheckUserPermissionById(int32_t userId)1353 bool WallpaperService::CheckUserPermissionById(int32_t userId)
1354 {
1355 OsAccountInfo osAccountInfo;
1356 ErrCode errCode = OsAccountManager::QueryOsAccountById(userId, osAccountInfo);
1357 if (errCode != ERR_OK) {
1358 HILOG_ERROR("Query os account info failed, errCode: %{public}d", errCode);
1359 return false;
1360 }
1361 HILOG_INFO("osAccountInfo GetType: %{public}d", static_cast<int32_t>(osAccountInfo.GetType()));
1362 if (osAccountInfo.GetType() == OsAccountType::GUEST) {
1363 HILOG_ERROR("The guest does not have permissions.");
1364 return false;
1365 }
1366 return true;
1367 }
1368
SetWallpaper(int32_t fd,int32_t wallpaperType,int32_t length,WallpaperResourceType resourceType)1369 ErrorCode WallpaperService::SetWallpaper(
1370 int32_t fd, int32_t wallpaperType, int32_t length, WallpaperResourceType resourceType)
1371 {
1372 int32_t userId = QueryActiveUserId();
1373 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
1374 if (!CheckUserPermissionById(userId)) {
1375 return E_USER_IDENTITY_ERROR;
1376 }
1377 ErrorCode errCode = CheckValid(wallpaperType, length, resourceType);
1378 if (errCode != NO_ERROR) {
1379 return errCode;
1380 }
1381 std::string uri = wallpaperTmpFullPath_;
1382 char *paperBuf = new (std::nothrow) char[length]();
1383 if (paperBuf == nullptr) {
1384 return E_NO_MEMORY;
1385 }
1386 {
1387 std::lock_guard<std::mutex> lock(mtx_);
1388 if (read(fd, paperBuf, length) <= 0) {
1389 HILOG_ERROR("read fd failed!");
1390 delete[] paperBuf;
1391 return E_DEAL_FAILED;
1392 }
1393 mode_t mode = S_IRUSR | S_IWUSR;
1394 int32_t fdw = open(uri.c_str(), O_WRONLY | O_CREAT, mode);
1395 if (fdw < 0) {
1396 HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
1397 delete[] paperBuf;
1398 return E_DEAL_FAILED;
1399 }
1400 fdsan_exchange_owner_tag(fdw, 0, WP_DOMAIN);
1401 if (write(fdw, paperBuf, length) <= 0) {
1402 HILOG_ERROR("Write to fdw failed, errno %{public}d", errno);
1403 ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
1404 delete[] paperBuf;
1405 fdsan_close_with_tag(fdw, WP_DOMAIN);
1406 return E_DEAL_FAILED;
1407 }
1408 delete[] paperBuf;
1409 fdsan_close_with_tag(fdw, WP_DOMAIN);
1410 }
1411 WallpaperType type = static_cast<WallpaperType>(wallpaperType);
1412 ErrorCode wallpaperErrorCode = SetWallpaperBackupData(userId, resourceType, uri, type);
1413 if (resourceType == PICTURE) {
1414 SaveColor(userId, type);
1415 }
1416 return wallpaperErrorCode;
1417 }
1418
SetWallpaperByPixelMap(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,int32_t wallpaperType,WallpaperResourceType resourceType)1419 ErrorCode WallpaperService::SetWallpaperByPixelMap(
1420 std::shared_ptr<OHOS::Media::PixelMap> pixelMap, int32_t wallpaperType, WallpaperResourceType resourceType)
1421 {
1422 if (pixelMap == nullptr) {
1423 HILOG_ERROR("pixelMap is nullptr");
1424 return E_FILE_ERROR;
1425 }
1426 int32_t userId = QueryActiveUserId();
1427 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
1428 if (!CheckUserPermissionById(userId)) {
1429 return E_USER_IDENTITY_ERROR;
1430 }
1431 std::string uri = wallpaperTmpFullPath_;
1432 ErrorCode errCode = WritePixelMapToFile(pixelMap, uri, wallpaperType, resourceType);
1433 if (errCode != NO_ERROR) {
1434 HILOG_ERROR("WritePixelMapToFile failed!");
1435 return errCode;
1436 }
1437 WallpaperType type = static_cast<WallpaperType>(wallpaperType);
1438 ErrorCode wallpaperErrorCode = SetWallpaperBackupData(userId, resourceType, uri, type);
1439 if (resourceType == PICTURE) {
1440 SaveColor(userId, type);
1441 }
1442 return wallpaperErrorCode;
1443 }
1444
WritePixelMapToFile(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,std::string wallpaperTmpFullPath,int32_t wallpaperType,WallpaperResourceType resourceType)1445 ErrorCode WallpaperService::WritePixelMapToFile(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,
1446 std::string wallpaperTmpFullPath, int32_t wallpaperType, WallpaperResourceType resourceType)
1447 {
1448 if (pixelMap == nullptr) {
1449 HILOG_ERROR("pixelMap is nullptr");
1450 return E_FILE_ERROR;
1451 }
1452 std::stringbuf stringBuf;
1453 std::ostream ostream(&stringBuf);
1454 int32_t mapSize = WritePixelMapToStream(pixelMap, ostream);
1455 if (mapSize <= 0) {
1456 HILOG_ERROR("WritePixelMapToStream failed!");
1457 return E_WRITE_PARCEL_ERROR;
1458 }
1459 ErrorCode errCode = CheckValid(wallpaperType, mapSize, resourceType);
1460 if (errCode != NO_ERROR) {
1461 HILOG_ERROR("CheckValid failed!");
1462 return errCode;
1463 }
1464 char *buffer = new (std::nothrow) char[mapSize]();
1465 if (buffer == nullptr) {
1466 HILOG_ERROR("buffer failed!");
1467 return E_NO_MEMORY;
1468 }
1469 stringBuf.sgetn(buffer, mapSize);
1470 {
1471 std::lock_guard<std::mutex> lock(mtx_);
1472 mode_t mode = S_IRUSR | S_IWUSR;
1473 int32_t fdw = open(wallpaperTmpFullPath.c_str(), O_WRONLY | O_CREAT, mode);
1474 if (fdw < 0) {
1475 HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
1476 delete[] buffer;
1477 return E_DEAL_FAILED;
1478 }
1479 fdsan_exchange_owner_tag(fdw, 0, WP_DOMAIN);
1480 if (write(fdw, buffer, mapSize) <= 0) {
1481 HILOG_ERROR("Write to fdw failed, errno %{public}d", errno);
1482 ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
1483 delete[] buffer;
1484 fdsan_close_with_tag(fdw, WP_DOMAIN);
1485 return E_DEAL_FAILED;
1486 }
1487 delete[] buffer;
1488 fdsan_close_with_tag(fdw, WP_DOMAIN);
1489 }
1490 return NO_ERROR;
1491 }
1492
WritePixelMapToStream(std::shared_ptr<OHOS::Media::PixelMap> pixelMap,std::ostream & outputStream)1493 int64_t WallpaperService::WritePixelMapToStream(
1494 std::shared_ptr<OHOS::Media::PixelMap> pixelMap, std::ostream &outputStream)
1495 {
1496 if (pixelMap == nullptr) {
1497 HILOG_ERROR("pixelMap is nullptr");
1498 return 0;
1499 }
1500 OHOS::Media::ImagePacker imagePacker;
1501 OHOS::Media::PackOption option;
1502 option.format = "image/jpeg";
1503 option.quality = OPTION_QUALITY;
1504 option.numberHint = 1;
1505 std::set<std::string> formats;
1506 uint32_t ret = imagePacker.GetSupportedFormats(formats);
1507 if (ret != 0) {
1508 HILOG_ERROR("image packer get supported format failed, ret=%{public}u.", ret);
1509 }
1510
1511 imagePacker.StartPacking(outputStream, option);
1512 imagePacker.AddImage(*pixelMap);
1513 int64_t packedSize = 0;
1514 imagePacker.FinalizePacking(packedSize);
1515 HILOG_INFO("FrameWork WritePixelMapToStream End! packedSize=%{public}lld.", static_cast<long long>(packedSize));
1516 return packedSize;
1517 }
1518
OnColorsChange(WallpaperType wallpaperType,const ColorManager::Color & color)1519 void WallpaperService::OnColorsChange(WallpaperType wallpaperType, const ColorManager::Color &color)
1520 {
1521 std::vector<uint64_t> colors;
1522 if (wallpaperType == WALLPAPER_SYSTEM && !CompareColor(systemWallpaperColor_, color)) {
1523 {
1524 std::lock_guard<std::mutex> lock(wallpaperColorMtx_);
1525 systemWallpaperColor_ = color.PackValue();
1526 colors.emplace_back(systemWallpaperColor_);
1527 }
1528 NotifyColorChange(colors, WALLPAPER_SYSTEM);
1529 } else if (wallpaperType == WALLPAPER_LOCKSCREEN && !CompareColor(lockWallpaperColor_, color)) {
1530 {
1531 std::lock_guard<std::mutex> lock(wallpaperColorMtx_);
1532 lockWallpaperColor_ = color.PackValue();
1533 colors.emplace_back(lockWallpaperColor_);
1534 }
1535 NotifyColorChange(colors, WALLPAPER_LOCKSCREEN);
1536 }
1537 }
1538
CheckValid(int32_t wallpaperType,int32_t length,WallpaperResourceType resourceType)1539 ErrorCode WallpaperService::CheckValid(int32_t wallpaperType, int32_t length, WallpaperResourceType resourceType)
1540 {
1541 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_SET_WALLPAPER)) {
1542 HILOG_ERROR("SetWallpaper no set permission.");
1543 return E_NO_PERMISSION;
1544 }
1545 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
1546 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
1547 return E_PARAMETERS_INVALID;
1548 }
1549
1550 int32_t maxLength = resourceType == VIDEO ? MAX_VIDEO_SIZE : FOO_MAX_LEN;
1551 if (length <= 0) {
1552 return E_PARAMETERS_INVALID;
1553 }
1554 if (length > maxLength) {
1555 return E_PICTURE_OVERSIZED;
1556 }
1557 return NO_ERROR;
1558 }
1559
WallpaperChanged(WallpaperType wallpaperType,WallpaperResourceType resType,const std::string & uri)1560 bool WallpaperService::WallpaperChanged(
1561 WallpaperType wallpaperType, WallpaperResourceType resType, const std::string &uri)
1562 {
1563 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1564 auto it = wallpaperEventMap_.find(WALLPAPER_CHANGE);
1565 if (it != wallpaperEventMap_.end()) {
1566 for (auto iter = it->second.begin(); iter != it->second.end(); iter++) {
1567 if (iter->second == nullptr) {
1568 continue;
1569 }
1570 iter->second->OnWallpaperChange(wallpaperType, resType, uri);
1571 }
1572 return true;
1573 }
1574 return false;
1575 }
1576
NotifyColorChange(const std::vector<uint64_t> & colors,const WallpaperType & wallpaperType)1577 void WallpaperService::NotifyColorChange(const std::vector<uint64_t> &colors, const WallpaperType &wallpaperType)
1578 {
1579 std::lock_guard<std::mutex> autoLock(listenerMapMutex_);
1580 auto it = wallpaperEventMap_.find(COLOR_CHANGE);
1581 if (it != wallpaperEventMap_.end()) {
1582 for (auto iter = it->second.begin(); iter != it->second.end(); iter++) {
1583 if (iter->second == nullptr) {
1584 continue;
1585 }
1586 iter->second->OnColorsChange(colors, wallpaperType);
1587 }
1588 }
1589 }
1590
SaveWallpaperState(int32_t userId,WallpaperType wallpaperType,WallpaperResourceType resourceType)1591 bool WallpaperService::SaveWallpaperState(
1592 int32_t userId, WallpaperType wallpaperType, WallpaperResourceType resourceType)
1593 {
1594 WallpaperData systemData;
1595 WallpaperData lockScreenData;
1596 if (!GetWallpaperSafeLocked(userId, WALLPAPER_SYSTEM, systemData)
1597 || !GetWallpaperSafeLocked(userId, WALLPAPER_LOCKSCREEN, lockScreenData)) {
1598 return false;
1599 }
1600 cJSON *root = cJSON_CreateObject();
1601 if (root == nullptr) {
1602 HILOG_ERROR("create object failed.");
1603 return false;
1604 }
1605 int32_t systemResourceType = (wallpaperType == WALLPAPER_SYSTEM) ? static_cast<int32_t>(resourceType)
1606 : static_cast<int32_t>(systemData.resourceType);
1607
1608 int32_t lockScreenResourceType = (wallpaperType == WALLPAPER_SYSTEM)
1609 ? static_cast<int32_t>(lockScreenData.resourceType)
1610 : static_cast<int32_t>(resourceType);
1611
1612 if (cJSON_AddNumberToObject(root, SYSTEM_RES_TYPE, systemResourceType) == nullptr
1613 || cJSON_AddNumberToObject(root, LOCKSCREEN_RES_TYPE, lockScreenResourceType) == nullptr) {
1614 HILOG_ERROR("add number to object fail.");
1615 cJSON_Delete(root);
1616 return false;
1617 }
1618
1619 char *json = cJSON_Print(root);
1620 if (json == nullptr || json[0] == '\0') {
1621 HILOG_ERROR("write user config file failed. because json content is empty.");
1622 cJSON_Delete(root);
1623 return false;
1624 }
1625 cJSON_Delete(root);
1626
1627 if (!WriteWallpapercfgFile(json, userId)) {
1628 HILOG_ERROR("write wallpapercfg fail.");
1629 cJSON_free(json);
1630 return false;
1631 }
1632 cJSON_free(json);
1633 return true;
1634 }
1635
WriteWallpapercfgFile(char * wallpaperJson,int32_t userId)1636 bool WallpaperService::WriteWallpapercfgFile(char *wallpaperJson, int32_t userId)
1637 {
1638 std::string userPath = WALLPAPER_USERID_PATH + std::to_string(userId) + "/wallpapercfg";
1639 mode_t mode = S_IRUSR | S_IWUSR;
1640 int fd = open(userPath.c_str(), O_CREAT | O_WRONLY | O_SYNC, mode);
1641 if (fd <= 0) {
1642 HILOG_ERROR("open user config file failed! %{public}d", errno);
1643 return false;
1644 }
1645 fdsan_exchange_owner_tag(fd, 0, WP_DOMAIN);
1646 ssize_t size = write(fd, wallpaperJson, strlen(wallpaperJson));
1647 if (size <= 0) {
1648 HILOG_ERROR("write user config file failed!");
1649 fdsan_close_with_tag(fd, WP_DOMAIN);
1650 return false;
1651 }
1652 fdsan_close_with_tag(fd, WP_DOMAIN);
1653 return true;
1654 }
1655
LoadWallpaperState()1656 void WallpaperService::LoadWallpaperState()
1657 {
1658 int32_t userId = QueryActiveUserId();
1659 std::string userPath = WALLPAPER_USERID_PATH + std::to_string(userId) + "/wallpapercfg";
1660 int fd = open(userPath.c_str(), O_RDONLY, S_IREAD);
1661 if (fd <= 0) {
1662 HILOG_ERROR("open user config file failed!");
1663 return;
1664 }
1665 fdsan_exchange_owner_tag(fd, 0, WP_DOMAIN);
1666 const size_t len = 255;
1667 char buf[len] = { 0 };
1668 ssize_t size = read(fd, buf, len);
1669 if (size <= 0) {
1670 HILOG_ERROR("read user config file failed!");
1671 fdsan_close_with_tag(fd, WP_DOMAIN);
1672 return;
1673 }
1674 fdsan_close_with_tag(fd, WP_DOMAIN);
1675
1676 if (buf[0] == '\0') {
1677 return;
1678 }
1679 WallpaperData systemData;
1680 WallpaperData lockScreenData;
1681 if (!GetWallpaperSafeLocked(userId, WALLPAPER_SYSTEM, systemData)
1682 || !GetWallpaperSafeLocked(userId, WALLPAPER_LOCKSCREEN, lockScreenData)) {
1683 return;
1684 }
1685 cJSON *root = cJSON_Parse(buf);
1686 if (root == nullptr) {
1687 HILOG_ERROR("Failed to parse json.");
1688 return;
1689 }
1690 if (cJSON_GetObjectItemCaseSensitive(root, SYSTEM_RES_TYPE) != nullptr
1691 && cJSON_IsNumber(cJSON_GetObjectItemCaseSensitive(root, SYSTEM_RES_TYPE))) {
1692 systemData.resourceType =
1693 static_cast<WallpaperResourceType>(cJSON_GetObjectItemCaseSensitive(root, SYSTEM_RES_TYPE)->valueint);
1694 }
1695 if (cJSON_GetObjectItemCaseSensitive(root, LOCKSCREEN_RES_TYPE) != nullptr
1696 && cJSON_IsNumber(cJSON_GetObjectItemCaseSensitive(root, LOCKSCREEN_RES_TYPE))) {
1697 lockScreenData.resourceType =
1698 static_cast<WallpaperResourceType>(cJSON_GetObjectItemCaseSensitive(root, LOCKSCREEN_RES_TYPE)->valueint);
1699 }
1700 cJSON_Delete(root);
1701 }
1702
GetDefaultResDir()1703 std::string WallpaperService::GetDefaultResDir()
1704 {
1705 std::string resPath;
1706 CfgFiles *cfgFiles = GetCfgFiles(RESOURCE_PATH);
1707 if (cfgFiles != nullptr) {
1708 for (auto &cfgPath : cfgFiles->paths) {
1709 if (cfgPath != nullptr) {
1710 HILOG_DEBUG("GetCfgFiles path is :%{public}s", cfgPath);
1711 resPath = cfgPath + std::string(DEFAULT_PATH);
1712 break;
1713 }
1714 }
1715 FreeCfgFiles(cfgFiles);
1716 }
1717 return resPath;
1718 }
1719
GetWallpaperPathInJson(const std::string manifestName,const std::string filePath)1720 std::string WallpaperService::GetWallpaperPathInJson(const std::string manifestName, const std::string filePath)
1721 {
1722 std::string wallpaperPath;
1723 std::string resPath = GetDefaultResDir();
1724 if (resPath.empty() && !FileDeal::IsDirExist(resPath)) {
1725 HILOG_ERROR("wallpaperDefaultDir get failed!");
1726 return "";
1727 }
1728 std::string manifestFile = resPath + manifestName;
1729 std::ifstream file(manifestFile);
1730 if (!file.is_open()) {
1731 HILOG_ERROR("open fail:%{public}s", manifestFile.c_str());
1732 file.close();
1733 return "";
1734 }
1735 std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
1736 file.close();
1737 cJSON *root = cJSON_Parse(content.c_str());
1738 if (root == nullptr) {
1739 HILOG_ERROR("Failed to parse json.");
1740 return "";
1741 }
1742 cJSON *image = cJSON_GetObjectItemCaseSensitive(root, IMAGE);
1743 if (image != nullptr && cJSON_IsObject(image)) {
1744 cJSON *src = cJSON_GetObjectItemCaseSensitive(image, SRC);
1745 if (src != nullptr && cJSON_IsString(src)) {
1746 std::string srcValue = src->valuestring;
1747 cJSON_Delete(root);
1748 return GetExistFilePath(resPath + filePath + srcValue);
1749 }
1750 }
1751 cJSON_Delete(root);
1752 HILOG_ERROR("src not exist.");
1753 return "";
1754 }
1755
GetExistFilePath(const std::string & filePath)1756 std::string WallpaperService::GetExistFilePath(const std::string &filePath)
1757 {
1758 if (!FileDeal::IsFileExist(filePath)) {
1759 HILOG_ERROR("path file is not exist! %{public}s", filePath.c_str());
1760 return "";
1761 }
1762 return filePath;
1763 }
1764
CloseVectorFd(const std::vector<int> & fdVector)1765 void WallpaperService::CloseVectorFd(const std::vector<int> &fdVector)
1766 {
1767 for (auto &fd : fdVector) {
1768 if (fd >= 0) {
1769 close(fd);
1770 }
1771 }
1772 }
1773
CloseWallpaperInfoFd(const std::vector<WallpaperPictureInfo> & wallpaperPictureInfo)1774 void WallpaperService::CloseWallpaperInfoFd(const std::vector<WallpaperPictureInfo> &wallpaperPictureInfo)
1775 {
1776 for (auto &wallpaperInfo : wallpaperPictureInfo) {
1777 if (wallpaperInfo.fd >= 0) {
1778 close(wallpaperInfo.fd);
1779 }
1780 }
1781 }
1782
SetAllWallpapers(const WallpaperPictureInfoByParcel & wallpaperPictureInfoByParcel,int32_t wallpaperType,const std::vector<int> & fdVector)1783 ErrCode WallpaperService::SetAllWallpapers(const WallpaperPictureInfoByParcel &wallpaperPictureInfoByParcel,
1784 int32_t wallpaperType, const std::vector<int> &fdVector)
1785 {
1786 StartAsyncTrace(HITRACE_TAG_MISC, "SetAllWallpapers", static_cast<int32_t>(TraceTaskId::SET_ALL_WALLPAPERS));
1787 std::vector<WallpaperPictureInfo> wallpaperPictureInfo;
1788 wallpaperPictureInfo = wallpaperPictureInfoByParcel.wallpaperPictureInfo_;
1789 if (wallpaperPictureInfo.size() != fdVector.size() || fdVector.size() == 0) {
1790 HILOG_ERROR("wallpaperPictureInfo size = %{public}zu and fdVector size = %{public}zu is inconsistent",
1791 wallpaperPictureInfo.size(), fdVector.size());
1792 CloseVectorFd(fdVector);
1793 return E_DEAL_FAILED;
1794 }
1795 for (std::size_t i = 0; i < fdVector.size(); ++i) {
1796 wallpaperPictureInfo[i].fd = fdVector[i];
1797 }
1798 ErrorCode wallpaperErrorCode = SetAllWallpapers(wallpaperPictureInfo, wallpaperType, PICTURE);
1799 FinishAsyncTrace(HITRACE_TAG_MISC, "SetAllWallpapers", static_cast<int32_t>(TraceTaskId::SET_ALL_WALLPAPERS));
1800 CloseWallpaperInfoFd(wallpaperPictureInfo);
1801 return wallpaperErrorCode;
1802 }
1803
SetAllWallpapers(std::vector<WallpaperPictureInfo> allWallpaperInfos,int32_t wallpaperType,WallpaperResourceType resourceType)1804 ErrorCode WallpaperService::SetAllWallpapers(
1805 std::vector<WallpaperPictureInfo> allWallpaperInfos, int32_t wallpaperType, WallpaperResourceType resourceType)
1806 {
1807 StartAsyncTrace(HITRACE_TAG_MISC, "SetAllWallpapers", static_cast<int32_t>(TraceTaskId::SET_ALL_WALLPAPERS));
1808 if (!IsSystemApp() && !IsNativeSa()) {
1809 HILOG_ERROR("Is not SystemApp or NativeSA.");
1810 return E_NOT_SYSTEM_APP;
1811 }
1812 int32_t userId = QueryActiveUserId();
1813 HILOG_INFO("SetAllWallpapers userId: %{public}d", userId);
1814 if (!CheckUserPermissionById(userId)) {
1815 return E_USER_IDENTITY_ERROR;
1816 }
1817 ErrorCode errCode;
1818 for (auto &wallpaperInfo : allWallpaperInfos) {
1819 wallpaperInfo.tempPath = std::string(WALLPAPER_USERID_PATH) + GetFoldStateName(wallpaperInfo.foldState) + "_"
1820 + GetRotateStateName(wallpaperInfo.rotateState);
1821 errCode = CheckValid(wallpaperType, wallpaperInfo.length, resourceType);
1822 if (errCode != NO_ERROR) {
1823 return errCode;
1824 }
1825 errCode = WriteFdToFile(wallpaperInfo, wallpaperInfo.tempPath);
1826 if (errCode != NO_ERROR) {
1827 DeleteTempResource(allWallpaperInfos);
1828 HILOG_ERROR("WriteFdToFile failed!");
1829 return errCode;
1830 }
1831 }
1832 WallpaperType type = static_cast<WallpaperType>(wallpaperType);
1833 std::string wallpaperPath = GetWallpaperDir(userId, type);
1834 FileDeal::DeleteDir(wallpaperPath, false);
1835 errCode = UpdateWallpaperData(allWallpaperInfos, userId, type);
1836 if (errCode != NO_ERROR) {
1837 HILOG_ERROR("UpdateWallpaperData failed!");
1838 return errCode;
1839 }
1840 SaveColor(userId, type);
1841 if (!SendWallpaperChangeEvent(userId, type)) {
1842 HILOG_ERROR("Send wallpaper state failed!");
1843 return E_DEAL_FAILED;
1844 }
1845 FinishAsyncTrace(HITRACE_TAG_MISC, "SetAllWallpapers", static_cast<int32_t>(TraceTaskId::SET_ALL_WALLPAPERS));
1846 return errCode;
1847 }
1848
UpdateWallpaperData(std::vector<WallpaperPictureInfo> allWallpaperInfos,int32_t userId,WallpaperType wallpaperType)1849 ErrorCode WallpaperService::UpdateWallpaperData(
1850 std::vector<WallpaperPictureInfo> allWallpaperInfos, int32_t userId, WallpaperType wallpaperType)
1851 {
1852 ErrorCode errCode;
1853 WallpaperData wallpaperData;
1854 bool ret = GetWallpaperSafeLocked(userId, wallpaperType, wallpaperData);
1855 if (!ret) {
1856 HILOG_ERROR("GetWallpaperSafeLocked failed!");
1857 return E_DEAL_FAILED;
1858 }
1859 ClearnWallpaperDataFile(wallpaperData);
1860 errCode = SetAllWallpaperBackupData(allWallpaperInfos, userId, wallpaperType, wallpaperData);
1861 if (errCode != NO_ERROR) {
1862 DeleteTempResource(allWallpaperInfos);
1863 HILOG_ERROR("SetAllWallpaperBackupData failed!");
1864 return errCode;
1865 }
1866 wallpaperData.resourceType = PICTURE;
1867 wallpaperData.wallpaperId = MakeWallpaperIdLocked();
1868 if (wallpaperType == WALLPAPER_SYSTEM) {
1869 systemWallpaperMap_.InsertOrAssign(userId, wallpaperData);
1870 } else if (wallpaperType == WALLPAPER_LOCKSCREEN) {
1871 lockWallpaperMap_.InsertOrAssign(userId, wallpaperData);
1872 }
1873 return NO_ERROR;
1874 }
1875
WriteFdToFile(WallpaperPictureInfo & wallpaperPictureInfo,std::string & path)1876 ErrorCode WallpaperService::WriteFdToFile(WallpaperPictureInfo &wallpaperPictureInfo, std::string &path)
1877 {
1878 std::lock_guard<std::mutex> lock(mtx_);
1879 char *wallpaperBuffer = new (std::nothrow) char[wallpaperPictureInfo.length]();
1880 if (wallpaperBuffer == nullptr) {
1881 HILOG_ERROR("create wallpaperBuffer failed!");
1882 return E_NO_MEMORY;
1883 }
1884 if (read(wallpaperPictureInfo.fd, wallpaperBuffer, wallpaperPictureInfo.length) <= 0) {
1885 HILOG_ERROR("read fd failed!");
1886 delete[] wallpaperBuffer;
1887 return E_DEAL_FAILED;
1888 }
1889 mode_t mode = S_IRUSR | S_IWUSR;
1890 int32_t fdw = open(path.c_str(), O_WRONLY | O_CREAT, mode);
1891 if (fdw < 0) {
1892 HILOG_ERROR("Open wallpaper tmpFullPath failed, errno %{public}d", errno);
1893 delete[] wallpaperBuffer;
1894 return E_DEAL_FAILED;
1895 }
1896 fdsan_exchange_owner_tag(fdw, 0, WP_DOMAIN);
1897 if (write(fdw, wallpaperBuffer, wallpaperPictureInfo.length) <= 0) {
1898 HILOG_ERROR("Write to fdw failed, errno %{public}d", errno);
1899 ReporterFault(FaultType::SET_WALLPAPER_FAULT, FaultCode::RF_DROP_FAILED);
1900 delete[] wallpaperBuffer;
1901 fdsan_close_with_tag(fdw, WP_DOMAIN);
1902 return E_DEAL_FAILED;
1903 }
1904 delete[] wallpaperBuffer;
1905 fdsan_close_with_tag(fdw, WP_DOMAIN);
1906 return NO_ERROR;
1907 }
1908
SetAllWallpaperBackupData(std::vector<WallpaperPictureInfo> allWallpaperInfos,int32_t userId,WallpaperType wallpaperType,WallpaperData & wallpaperData)1909 ErrorCode WallpaperService::SetAllWallpaperBackupData(std::vector<WallpaperPictureInfo> allWallpaperInfos,
1910 int32_t userId, WallpaperType wallpaperType, WallpaperData &wallpaperData)
1911 {
1912 HILOG_INFO("set All wallpaper and backup data Start.");
1913 for (auto &wallpaperInfo : allWallpaperInfos) {
1914 if (!OHOS::FileExists(wallpaperInfo.tempPath)) {
1915 return E_DEAL_FAILED;
1916 }
1917 UpdateWallpaperDataFile(wallpaperInfo, userId, wallpaperType, wallpaperData);
1918 std::string wallpaperFile = GetWallpaperDataFile(wallpaperInfo, userId, wallpaperType);
1919 {
1920 std::lock_guard<std::mutex> lock(mtx_);
1921 if (!FileDeal::CopyFile(wallpaperInfo.tempPath, wallpaperFile)) {
1922 HILOG_ERROR("CopyFile failed!");
1923 FileDeal::DeleteFile(wallpaperInfo.tempPath);
1924 return E_DEAL_FAILED;
1925 }
1926 if (!FileDeal::DeleteFile(wallpaperInfo.tempPath)) {
1927 return E_DEAL_FAILED;
1928 }
1929 }
1930 }
1931 return NO_ERROR;
1932 }
1933
UpdateWallpaperDataFile(WallpaperPictureInfo & wallpaperPictureInfo,int32_t userId,WallpaperType wallpaperType,WallpaperData & wallpaperData)1934 void WallpaperService::UpdateWallpaperDataFile(WallpaperPictureInfo &wallpaperPictureInfo, int32_t userId,
1935 WallpaperType wallpaperType, WallpaperData &wallpaperData)
1936 {
1937 switch (static_cast<FoldState>(wallpaperPictureInfo.foldState)) {
1938 case FoldState::NORMAL:
1939 if (static_cast<RotateState>(wallpaperPictureInfo.rotateState) == RotateState::PORT) {
1940 wallpaperData.wallpaperFile = GetWallpaperDir(userId, wallpaperType) + "/"
1941 + (wallpaperType == WALLPAPER_SYSTEM ? WALLPAPER_HOME : WALLPAPER_LOCK);
1942 } else if (static_cast<RotateState>(wallpaperPictureInfo.rotateState) == RotateState::LAND) {
1943 wallpaperData.normalLandFile = GetWallpaperDataFile(wallpaperPictureInfo, userId, wallpaperType);
1944 }
1945 break;
1946
1947 case FoldState::UNFOLD_1:
1948 if (static_cast<RotateState>(wallpaperPictureInfo.rotateState) == RotateState::PORT) {
1949 wallpaperData.unfoldedOnePortFile = GetWallpaperDataFile(wallpaperPictureInfo, userId, wallpaperType);
1950 } else if (static_cast<RotateState>(wallpaperPictureInfo.rotateState) == RotateState::LAND) {
1951 wallpaperData.unfoldedOneLandFile = GetWallpaperDataFile(wallpaperPictureInfo, userId, wallpaperType);
1952 }
1953 break;
1954
1955 case FoldState::UNFOLD_2:
1956 if (static_cast<RotateState>(wallpaperPictureInfo.rotateState) == RotateState::PORT) {
1957 wallpaperData.unfoldedTwoPortFile = GetWallpaperDataFile(wallpaperPictureInfo, userId, wallpaperType);
1958 } else if (static_cast<RotateState>(wallpaperPictureInfo.rotateState) == RotateState::LAND) {
1959 wallpaperData.unfoldedTwoLandFile = GetWallpaperDataFile(wallpaperPictureInfo, userId, wallpaperType);
1960 }
1961 break;
1962 default:
1963 break;
1964 }
1965 }
1966
GetWallpaperDataFile(WallpaperPictureInfo & wallpaperPictureInfo,int32_t userId,WallpaperType wallpaperType)1967 std::string WallpaperService::GetWallpaperDataFile(
1968 WallpaperPictureInfo &wallpaperPictureInfo, int32_t userId, WallpaperType wallpaperType)
1969 {
1970 std::string wallpaperTypeName = wallpaperType == WALLPAPER_SYSTEM ? WALLPAPER_HOME : WALLPAPER_LOCK;
1971 std::string foldStateName = GetFoldStateName(wallpaperPictureInfo.foldState);
1972 std::string rotateStateName = GetRotateStateName(wallpaperPictureInfo.rotateState);
1973 if (foldStateName == "normal" && rotateStateName == "port") {
1974 return GetWallpaperDir(userId, wallpaperType) + "/" + wallpaperTypeName;
1975 }
1976 std::string wallpaperFile =
1977 GetWallpaperDir(userId, wallpaperType) + "/" + foldStateName + "_" + rotateStateName + "_" + wallpaperTypeName;
1978 return wallpaperFile;
1979 }
1980
ClearnWallpaperDataFile(WallpaperData & wallpaperData)1981 void WallpaperService::ClearnWallpaperDataFile(WallpaperData &wallpaperData)
1982 {
1983 wallpaperData.normalLandFile = "";
1984 wallpaperData.unfoldedOnePortFile = "";
1985 wallpaperData.unfoldedOneLandFile = "";
1986 wallpaperData.unfoldedTwoPortFile = "";
1987 wallpaperData.unfoldedTwoLandFile = "";
1988 }
1989
GetCorrespondWallpaper(int32_t wallpaperType,int32_t foldState,int32_t rotateState,int32_t & size,int & fd)1990 ErrCode WallpaperService::GetCorrespondWallpaper(
1991 int32_t wallpaperType, int32_t foldState, int32_t rotateState, int32_t &size, int &fd)
1992 {
1993 StartAsyncTrace(
1994 HITRACE_TAG_MISC, "GetCorrespondWallpaper", static_cast<int32_t>(TraceTaskId::GET_CORRESPOND_WALLPAPER));
1995 HILOG_DEBUG("WallpaperService::GetCorrespondWallpaper start.");
1996 if (!IsSystemApp()) {
1997 HILOG_ERROR("CallingApp is not SystemApp.");
1998 return E_NOT_SYSTEM_APP;
1999 }
2000 if (!CheckCallingPermission(WALLPAPER_PERMISSION_NAME_GET_WALLPAPER)) {
2001 HILOG_ERROR("GetPixelMap no get permission!");
2002 return E_NO_PERMISSION;
2003 }
2004 if (wallpaperType != static_cast<int32_t>(WALLPAPER_LOCKSCREEN)
2005 && wallpaperType != static_cast<int32_t>(WALLPAPER_SYSTEM)) {
2006 return E_PARAMETERS_INVALID;
2007 }
2008 auto type = static_cast<WallpaperType>(wallpaperType);
2009 int32_t userId = QueryActiveUserId();
2010 HILOG_INFO("QueryCurrentOsAccount userId: %{public}d", userId);
2011 // current user's wallpaper is live video, not image
2012 WallpaperResourceType resType = GetResType(userId, type);
2013 if (resType != PICTURE && resType != DEFAULT) {
2014 HILOG_ERROR("Current user's wallpaper is live video, not image.");
2015 size = 0; // 0: empty file size
2016 fd = -1; // -1: invalid file description
2017 return NO_ERROR;
2018 }
2019 ErrorCode ret = GetImageSize(userId, type, size, foldState, rotateState);
2020 if (ret != NO_ERROR) {
2021 HILOG_ERROR("GetImageSize failed!");
2022 return ret;
2023 }
2024 ret = GetImageFd(userId, type, fd, foldState, rotateState);
2025 if (ret != NO_ERROR) {
2026 HILOG_ERROR("GetImageFd failed!");
2027 return ret;
2028 }
2029 return NO_ERROR;
2030 }
2031
GetImageSize(int32_t userId,WallpaperType wallpaperType,int32_t & size,int32_t foldState,int32_t rotateState)2032 ErrorCode WallpaperService::GetImageSize(
2033 int32_t userId, WallpaperType wallpaperType, int32_t &size, int32_t foldState, int32_t rotateState)
2034 {
2035 HILOG_DEBUG("WallpaperService::GetImageSize start.");
2036 std::string filePathName;
2037 if (!GetWallpaperDataPath(userId, wallpaperType, filePathName, foldState, rotateState)) {
2038 return E_DEAL_FAILED;
2039 }
2040 HILOG_INFO("GetImageSize file: %{public}s", filePathName.c_str());
2041 if (!OHOS::FileExists(filePathName)) {
2042 HILOG_ERROR("file is not exist.");
2043 return E_NOT_FOUND;
2044 }
2045 std::lock_guard<std::mutex> lock(mtx_);
2046 FILE *fd = fopen(filePathName.c_str(), "rb");
2047 if (fd == nullptr) {
2048 HILOG_ERROR("fopen file failed, errno %{public}d", errno);
2049 return E_FILE_ERROR;
2050 }
2051 int32_t fend = fseek(fd, 0, SEEK_END);
2052 size = ftell(fd);
2053 int32_t fset = fseek(fd, 0, SEEK_SET);
2054 if (size <= 0 || fend != 0 || fset != 0) {
2055 HILOG_ERROR("ftell file failed or fseek file failed, errno %{public}d", errno);
2056 fclose(fd);
2057 return E_FILE_ERROR;
2058 }
2059 fclose(fd);
2060 return NO_ERROR;
2061 }
2062
GetImageFd(int32_t userId,WallpaperType wallpaperType,int32_t & fd,int32_t foldState,int32_t rotateState)2063 ErrorCode WallpaperService::GetImageFd(
2064 int32_t userId, WallpaperType wallpaperType, int32_t &fd, int32_t foldState, int32_t rotateState)
2065 {
2066 HILOG_DEBUG("WallpaperService::GetImageFd start.");
2067 std::string filePathName;
2068 if (!GetWallpaperDataPath(userId, wallpaperType, filePathName, foldState, rotateState)) {
2069 return E_DEAL_FAILED;
2070 }
2071 if (GetResType(userId, wallpaperType) == WallpaperResourceType::PACKAGE) {
2072 HILOG_INFO("The current wallpaper is a custom wallpaper");
2073 return NO_ERROR;
2074 }
2075 fd = open(filePathName.c_str(), O_RDONLY, S_IREAD);
2076 if (fd < 0) {
2077 HILOG_ERROR("Open file failed, errno %{public}d", errno);
2078 ReporterFault(FaultType::LOAD_WALLPAPER_FAULT, FaultCode::RF_FD_INPUT_FAILED);
2079 return E_DEAL_FAILED;
2080 }
2081 fdsan_exchange_owner_tag(fd, 0, WP_DOMAIN);
2082 HILOG_INFO("fd = %{public}d", fd);
2083 return NO_ERROR;
2084 }
2085
GetWallpaperDataPath(int32_t userId,WallpaperType wallpaperType,std::string & filePathName,int32_t foldState,int32_t rotateState)2086 bool WallpaperService::GetWallpaperDataPath(
2087 int32_t userId, WallpaperType wallpaperType, std::string &filePathName, int32_t foldState, int32_t rotateState)
2088 {
2089 auto iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
2090 : lockWallpaperMap_.Find(userId);
2091 if (!iterator.first) {
2092 HILOG_INFO("WallpaperType:%{public}d, WallpaperMap not found userId: %{public}d", wallpaperType, userId);
2093 OnInitUser(userId);
2094 iterator = wallpaperType == WALLPAPER_SYSTEM ? systemWallpaperMap_.Find(userId)
2095 : lockWallpaperMap_.Find(userId);
2096 }
2097 filePathName = GetWallpaperPath(foldState, rotateState, iterator.second);
2098 return filePathName != "";
2099 }
2100
GetWallpaperPath(int32_t foldState,int32_t rotateState,WallpaperData & wallpaperData)2101 std::string WallpaperService::GetWallpaperPath(int32_t foldState, int32_t rotateState, WallpaperData &wallpaperData)
2102 {
2103 std::string wallpaperFilePath;
2104 if (foldState == static_cast<int32_t>(FoldState::UNFOLD_2)) {
2105 if (rotateState == static_cast<int32_t>(RotateState::LAND)) {
2106 wallpaperFilePath = wallpaperData.unfoldedTwoLandFile;
2107 if (wallpaperFilePath != "") {
2108 return wallpaperFilePath;
2109 }
2110 }
2111 wallpaperFilePath = wallpaperData.unfoldedTwoPortFile;
2112 if (wallpaperFilePath != "") {
2113 return wallpaperFilePath;
2114 }
2115 wallpaperFilePath = wallpaperData.wallpaperFile;
2116 }
2117 if (foldState == static_cast<int32_t>(FoldState::UNFOLD_1)) {
2118 if (rotateState == static_cast<int32_t>(RotateState::LAND)) {
2119 wallpaperFilePath = wallpaperData.unfoldedOneLandFile;
2120 if (wallpaperFilePath != "") {
2121 return wallpaperFilePath;
2122 }
2123 }
2124 wallpaperFilePath = wallpaperData.unfoldedOnePortFile;
2125 if (wallpaperFilePath != "") {
2126 return wallpaperFilePath;
2127 }
2128 wallpaperFilePath = wallpaperData.wallpaperFile;
2129 }
2130 if (foldState == static_cast<int32_t>(FoldState::NORMAL)) {
2131 if (rotateState == static_cast<int32_t>(RotateState::LAND)) {
2132 wallpaperFilePath = wallpaperData.normalLandFile;
2133 if (wallpaperFilePath != "") {
2134 return wallpaperFilePath;
2135 }
2136 }
2137 wallpaperFilePath = wallpaperData.wallpaperFile;
2138 }
2139 return wallpaperFilePath;
2140 }
2141
DeleteTempResource(std::vector<WallpaperPictureInfo> & tempResourceFiles)2142 void WallpaperService::DeleteTempResource(std::vector<WallpaperPictureInfo> &tempResourceFiles)
2143 {
2144 for (auto &wallpaperFile : tempResourceFiles) {
2145 FileDeal::DeleteFile(wallpaperFile.tempPath);
2146 }
2147 }
2148
GetFoldStateName(FoldState foldState)2149 std::string WallpaperService::GetFoldStateName(FoldState foldState)
2150 {
2151 std::string foldStateName;
2152 switch (foldState) {
2153 case FoldState::NORMAL:
2154 foldStateName = "normal";
2155 break;
2156 case FoldState::UNFOLD_1:
2157 foldStateName = "unfold1";
2158 break;
2159 case FoldState::UNFOLD_2:
2160 foldStateName = "unfold2";
2161 break;
2162 default:
2163 break;
2164 }
2165 return foldStateName;
2166 }
2167
GetRotateStateName(RotateState rotateState)2168 std::string WallpaperService::GetRotateStateName(RotateState rotateState)
2169 {
2170 std::string rotateStateName;
2171 switch (rotateState) {
2172 case RotateState::PORT:
2173 rotateStateName = "port";
2174 break;
2175 case RotateState::LAND:
2176 rotateStateName = "land";
2177 break;
2178 default:
2179 break;
2180 }
2181 return rotateStateName;
2182 }
2183
IsDefaultWallpaperResource(int32_t userId,int32_t wallpaperType,bool & isDefaultWallpaperResource)2184 ErrCode WallpaperService::IsDefaultWallpaperResource(
2185 int32_t userId, int32_t wallpaperType, bool &isDefaultWallpaperResource)
2186 {
2187 HILOG_INFO("IsDefaultWallpaperResource start");
2188 if (wallpaperType == static_cast<int32_t>(WALLPAPER_SYSTEM)) {
2189 std::string wallpaperSystemPath = std::string(WALLPAPER_USERID_PATH) + std::to_string(userId) + "/"
2190 + std::string(WALLPAPER_SYSTEM_DIRNAME) + "/";
2191 if (!FileDeal::IsFileExistInDir(wallpaperSystemPath)) {
2192 HILOG_INFO("System is empty");
2193 isDefaultWallpaperResource = true;
2194 return NO_ERROR;
2195 }
2196 } else if (wallpaperType == static_cast<int32_t>(WALLPAPER_LOCKSCREEN)) {
2197 std::string wallpaperLockscreenPath = std::string(WALLPAPER_USERID_PATH) + std::to_string(userId) + "/"
2198 + std::string(WALLPAPER_LOCKSCREEN_DIRNAME) + "/";
2199 if (!FileDeal::IsFileExistInDir(wallpaperLockscreenPath)) {
2200 HILOG_INFO("Lockscreen is empty");
2201 isDefaultWallpaperResource = true;
2202 return NO_ERROR;
2203 }
2204 }
2205 isDefaultWallpaperResource = false;
2206 return NO_ERROR;
2207 }
2208
CallbackParcel(uint32_t code,MessageParcel & data,MessageParcel & reply,MessageOption & option)2209 int32_t WallpaperService::CallbackParcel(
2210 uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
2211 {
2212 switch (static_cast<IWallpaperServiceIpcCode>(code)) {
2213 case IWallpaperServiceIpcCode::COMMAND_GET_PIXEL_MAP: {
2214 return GetPixleMapParcel(data, reply, false);
2215 }
2216 case IWallpaperServiceIpcCode::COMMAND_GET_PIXEL_MAP_V9: {
2217 return GetPixleMapParcel(data, reply, true);
2218 }
2219 case IWallpaperServiceIpcCode::COMMAND_GET_CORRESPOND_WALLPAPER: {
2220 return GetCorrespondWallpaperParcel(data, reply);
2221 }
2222 case IWallpaperServiceIpcCode::COMMAND_GET_FILE: {
2223 return GetFileParcel(data, reply);
2224 }
2225 case IWallpaperServiceIpcCode::COMMAND_SET_WALLPAPER_BY_PIXEL_MAP: {
2226 return SetwallpaperByPixelMapParcel(data, reply, false);
2227 }
2228 case IWallpaperServiceIpcCode::COMMAND_SET_WALLPAPER_V9_BY_PIXEL_MAP: {
2229 return SetwallpaperByPixelMapParcel(data, reply, true);
2230 }
2231 default:
2232 return NO_ERROR;
2233 }
2234 }
2235
GetPixleMapParcel(MessageParcel & data,MessageParcel & reply,bool isSystemApi)2236 int32_t WallpaperService::GetPixleMapParcel(MessageParcel &data, MessageParcel &reply, bool isSystemApi)
2237 {
2238 std::u16string myDescriptor = WallpaperServiceStub::GetDescriptor();
2239 std::u16string remoteDescriptor = data.ReadInterfaceToken();
2240 if (myDescriptor != remoteDescriptor) {
2241 HILOG_ERROR("Remote descriptor not the same as local descriptor.");
2242 return E_CHECK_DESCRIPTOR_ERROR;
2243 }
2244 int32_t wallpaperType = data.ReadInt32();
2245 int32_t size;
2246 int fd = DEFAULT_WALLPAPER_ID;
2247 ErrCode errCode = E_UNKNOWN;
2248 if (isSystemApi) {
2249 errCode = GetPixelMapV9(wallpaperType, size, fd);
2250 } else {
2251 errCode = GetPixelMap(wallpaperType, size, fd);
2252 }
2253 if (!reply.WriteInt32(errCode)) {
2254 HILOG_ERROR("WriteInt32 fail!");
2255 if (fd > DEFAULT_WALLPAPER_ID) {
2256 fdsan_close_with_tag(fd, WP_DOMAIN);
2257 }
2258 return ERR_INVALID_VALUE;
2259 }
2260 if (!reply.WriteInt32(size)) {
2261 HILOG_ERROR("WriteInt32 fail!");
2262 if (fd > DEFAULT_WALLPAPER_ID) {
2263 fdsan_close_with_tag(fd, WP_DOMAIN);
2264 }
2265 return ERR_INVALID_DATA;
2266 }
2267 HILOG_ERROR("getpixelmap fd %{public}d!", fd);
2268 if (!reply.WriteFileDescriptor(fd)) {
2269 HILOG_ERROR("WriteFileDescriptor fail!");
2270 if (fd > DEFAULT_WALLPAPER_ID) {
2271 fdsan_close_with_tag(fd, WP_DOMAIN);
2272 }
2273 return ERR_INVALID_DATA;
2274 }
2275 if (fd > DEFAULT_WALLPAPER_ID) {
2276 fdsan_close_with_tag(fd, WP_DOMAIN);
2277 }
2278 if (errCode == NO_ERROR) {
2279 return E_OK;
2280 }
2281 return errCode;
2282 }
2283
GetCorrespondWallpaperParcel(MessageParcel & data,MessageParcel & reply)2284 int32_t WallpaperService::GetCorrespondWallpaperParcel(MessageParcel &data, MessageParcel &reply)
2285 {
2286 std::u16string myDescriptor = WallpaperServiceStub::GetDescriptor();
2287 std::u16string remoteDescriptor = data.ReadInterfaceToken();
2288 if (myDescriptor != remoteDescriptor) {
2289 HILOG_ERROR("Remote descriptor not the same as local descriptor.");
2290 return E_CHECK_DESCRIPTOR_ERROR;
2291 }
2292 int32_t wallpaperType = data.ReadInt32();
2293 int32_t foldState = data.ReadInt32();
2294 int32_t rotateState = data.ReadInt32();
2295 int32_t size;
2296 int fd = DEFAULT_WALLPAPER_ID;
2297 ErrCode errCode = GetCorrespondWallpaper(wallpaperType, foldState, rotateState, size, fd);
2298 if (!reply.WriteInt32(errCode)) {
2299 HILOG_ERROR("WriteInt32 fail!");
2300 if (fd > DEFAULT_WALLPAPER_ID) {
2301 fdsan_close_with_tag(fd, WP_DOMAIN);
2302 }
2303 return ERR_INVALID_VALUE;
2304 }
2305 if (!reply.WriteInt32(size)) {
2306 HILOG_ERROR("WriteInt32 fail!");
2307 if (fd > DEFAULT_WALLPAPER_ID) {
2308 fdsan_close_with_tag(fd, WP_DOMAIN);
2309 }
2310 return ERR_INVALID_DATA;
2311 }
2312 if (!reply.WriteFileDescriptor(fd)) {
2313 HILOG_ERROR("WriteFileDescriptor fail!");
2314 if (fd > DEFAULT_WALLPAPER_ID) {
2315 fdsan_close_with_tag(fd, WP_DOMAIN);
2316 }
2317 return ERR_INVALID_DATA;
2318 }
2319 if (fd > DEFAULT_WALLPAPER_ID) {
2320 fdsan_close_with_tag(fd, WP_DOMAIN);
2321 }
2322 if (errCode == NO_ERROR) {
2323 return E_OK;
2324 }
2325 return errCode;
2326 }
2327
GetFileParcel(MessageParcel & data,MessageParcel & reply)2328 int32_t WallpaperService::GetFileParcel(MessageParcel &data, MessageParcel &reply)
2329 {
2330 std::u16string myDescriptor = WallpaperServiceStub::GetDescriptor();
2331 std::u16string remoteDescriptor = data.ReadInterfaceToken();
2332 if (myDescriptor != remoteDescriptor) {
2333 HILOG_ERROR("Remote descriptor not the same as local descriptor.");
2334 return E_CHECK_DESCRIPTOR_ERROR;
2335 }
2336 int32_t wallpaperType = data.ReadInt32();
2337 int wallpaperFd = DEFAULT_WALLPAPER_ID;
2338 ErrCode errCode = GetFile(wallpaperType, wallpaperFd);
2339 if (!reply.WriteInt32(errCode)) {
2340 HILOG_ERROR("WriteInt32 fail!");
2341 if (wallpaperFd > DEFAULT_WALLPAPER_ID) {
2342 fdsan_close_with_tag(wallpaperFd, WP_DOMAIN);
2343 }
2344 return ERR_INVALID_VALUE;
2345 }
2346 if (!reply.WriteFileDescriptor(wallpaperFd)) {
2347 HILOG_ERROR("WriteFileDescriptor fail!");
2348 if (wallpaperFd > DEFAULT_WALLPAPER_ID) {
2349 fdsan_close_with_tag(wallpaperFd, WP_DOMAIN);
2350 }
2351 return ERR_INVALID_DATA;
2352 }
2353 HILOG_ERROR("GetFileParcel fd %{public}d!", wallpaperFd);
2354 if (wallpaperFd > DEFAULT_WALLPAPER_ID) {
2355 fdsan_close_with_tag(wallpaperFd, WP_DOMAIN);
2356 }
2357 if (errCode == NO_ERROR) {
2358 return E_OK;
2359 }
2360 return errCode;
2361 }
2362
SetwallpaperByPixelMapParcel(MessageParcel & data,MessageParcel & reply,bool isSystemApi)2363 int32_t WallpaperService::SetwallpaperByPixelMapParcel(MessageParcel &data, MessageParcel &reply, bool isSystemApi)
2364 {
2365 std::u16string myDescriptor = WallpaperServiceStub::GetDescriptor();
2366 std::u16string remoteDescriptor = data.ReadInterfaceToken();
2367 if (myDescriptor != remoteDescriptor) {
2368 HILOG_ERROR("Remote descriptor not the same as local descriptor.");
2369 return E_CHECK_DESCRIPTOR_ERROR;
2370 }
2371 WallpaperRawData wallpaperRawData;
2372 wallpaperRawData.size = data.ReadUint32();
2373 if (wallpaperRawData.size <= 0) {
2374 HILOG_ERROR("ReadUint32 fail!");
2375 return ERR_INVALID_VALUE;
2376 }
2377 wallpaperRawData.data = data.ReadRawData(wallpaperRawData.size);
2378 int32_t wallpaperType = data.ReadInt32();
2379 ErrCode errCode = E_UNKNOWN;
2380 if (isSystemApi) {
2381 errCode = SetWallpaperV9ByPixelMap(wallpaperRawData, wallpaperType);
2382 } else {
2383 errCode = SetWallpaperByPixelMap(wallpaperRawData, wallpaperType);
2384 }
2385 if (errCode == NO_ERROR) {
2386 return E_OK;
2387 }
2388 return errCode;
2389 }
2390 } // namespace WallpaperMgrService
2391 } // namespace OHOS
2392