1 /*
2 * Copyright (C) 2021-2023 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 "pasteboard_service.h"
16
17 #include <bitset>
18 #include <unistd.h>
19
20 #include "ability_manager_client.h"
21 #include "tokenid_kit.h"
22 #include "accesstoken_kit.h"
23 #include "account_manager.h"
24 #include "calculate_time_consuming.h"
25 #include "common_event_manager.h"
26 #include "dev_profile.h"
27 #include "device/dm_adapter.h"
28 #include "dfx_code_constant.h"
29 #include "dfx_types.h"
30 #include "distributed_file_daemon_manager.h"
31 #include "eventcenter/pasteboard_event.h"
32 #include "eventcenter/event_center.h"
33 #include "hiview_adapter.h"
34 #include "iservice_registry.h"
35 #include "loader.h"
36 #include "mem_mgr_client.h"
37 #include "mem_mgr_proxy.h"
38 #include "int_wrapper.h"
39 #include "long_wrapper.h"
40 #include "native_token_info.h"
41 #include "os_account_manager.h"
42 #include "parameters.h"
43 #include "pasteboard_dialog.h"
44 #include "paste_data_entry.h"
45 #include "pasteboard_event_dfx.h"
46 #include "pasteboard_event_ue.h"
47 #include "pasteboard_error.h"
48 #include "pasteboard_trace.h"
49 #include "pasteboard_utils.h"
50 #include "remote_file_share.h"
51 #include "reporter.h"
52 #ifdef PB_SCREENLOCK_MGR_ENABLE
53 #include "screenlock_manager.h"
54 #endif
55 #include "tokenid_kit.h"
56 #include "uri_permission_manager_client.h"
57 #ifdef SCENE_BOARD_ENABLE
58 #include "window_manager_lite.h"
59 #else
60 #include "window_manager.h"
61 #endif
62
63 #ifdef WITH_DLP
64 #include "dlp_permission_kit.h"
65 #endif // WITH_DLP
66
67 namespace OHOS {
68 namespace MiscServices {
69 using namespace Rosen;
70 using namespace std::chrono;
71 using namespace Storage::DistributedFile;
72 using namespace RadarReporter;
73 using namespace UeReporter;
74 namespace {
75 constexpr const int GET_WRONG_SIZE = 0;
76 constexpr const size_t MAX_URI_COUNT = 500;
77 constexpr const int32_t COMMON_USERID = 0;
78 const std::int32_t INIT_INTERVAL = 10000L;
79 constexpr const char* PASTEBOARD_SERVICE_NAME = "PasteboardService";
80 constexpr const char* FAIL_TO_GET_TIME_STAMP = "FAIL_TO_GET_TIME_STAMP";
81 constexpr const char* SECURE_PASTE_PERMISSION = "ohos.permission.SECURE_PASTE";
82 constexpr const char* READ_PASTEBOARD_PERMISSION = "ohos.permission.READ_PASTEBOARD";
83 constexpr const char* TRANSMIT_CONTROL_PROP_KEY = "persist.distributed_scene.datafiles_trans_ctrl";
84 constexpr const char *MANAGE_PASTEBOARD_APP_SHARE_OPTION_PERMISSION =
85 "ohos.permission.MANAGE_PASTEBOARD_APP_SHARE_OPTION";
86
87 const std::int32_t INVAILD_VERSION = -1;
88 const std::int32_t ADD_PERMISSION_CHECK_SDK_VERSION = 12;
89 const std::int32_t CTRLV_EVENT_SIZE = 2;
90 const std::int32_t CONTROL_TYPE_ALLOW_SEND_RECEIVE = 1;
91
92 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(new PasteboardService());
93 } // namespace
94 using namespace Security::AccessToken;
95 using namespace OHOS::AppFileService::ModuleRemoteFileShare;
96 std::mutex PasteboardService::historyMutex_;
97 std::vector<std::string> PasteboardService::dataHistory_;
98 std::shared_ptr<Command> PasteboardService::copyHistory;
99 std::shared_ptr<Command> PasteboardService::copyData;
100 int32_t PasteboardService::currentUserId = ERROR_USERID;
101 ScreenEvent PasteboardService::currentScreenStatus = ScreenEvent::Default;
102
PasteboardService()103 PasteboardService::PasteboardService()
104 : SystemAbility(PASTEBOARD_SERVICE_ID, true), state_(ServiceRunningState::STATE_NOT_START)
105 {
106 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "PasteboardService Start.");
107 ServiceListenerFunc_[static_cast<int32_t>(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID)] =
108 &PasteboardService::DMAdapterInit;
109 ServiceListenerFunc_[static_cast<int32_t>(MEMORY_MANAGER_SA_ID)] = &PasteboardService::NotifySaStatus;
110 }
111
~PasteboardService()112 PasteboardService::~PasteboardService()
113 {
114 clients_.Clear();
115 }
116
Init()117 int32_t PasteboardService::Init()
118 {
119 if (!Publish(this)) {
120 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "OnStart register to system ability manager failed.");
121 auto userId = GetCurrentAccountId();
122 Reporter::GetInstance().PasteboardFault().Report({ userId, "ERR_INVALID_OPTION" });
123 return static_cast<int32_t>(PasteboardError::INVALID_OPTION_ERROR);
124 }
125 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Init Success.");
126 state_ = ServiceRunningState::STATE_RUNNING;
127 InitScreenStatus();
128 return ERR_OK;
129 }
130
InitScreenStatus()131 void PasteboardService::InitScreenStatus()
132 {
133 #ifdef PB_SCREENLOCK_MGR_ENABLE
134 auto isScreenLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked();
135 PasteboardService::currentScreenStatus = isScreenLocked ? ScreenEvent::ScreenLocked : ScreenEvent::ScreenUnlocked;
136 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "screen status is %{public}d",
137 PasteboardService::currentScreenStatus);
138 #else
139 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "PB_SCREENLOCK_MGR_ENABLE not defined");
140 return;
141 #endif
142 }
143
OnStart()144 void PasteboardService::OnStart()
145 {
146 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "PasteboardService OnStart.");
147 if (state_ == ServiceRunningState::STATE_RUNNING) {
148 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "PasteboardService is already running.");
149 return;
150 }
151
152 InitServiceHandler();
153 auto appInfo = GetAppInfo(IPCSkeleton::GetCallingTokenID());
154 Loader loader;
155 loader.LoadComponents();
156 bundles_ = loader.LoadBundles();
157 uid_ = loader.LoadUid();
158 moduleConfig_.Init();
159 auto ret = DATASL_OnStart();
160 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "datasl on start ret:%{public}d", ret);
161 moduleConfig_.Watch(std::bind(&PasteboardService::OnConfigChange, this, std::placeholders::_1));
162 AddSysAbilityListener();
163
164 if (Init() != ERR_OK) {
165 auto callback = [this]() { Init(); };
166 serviceHandler_->PostTask(callback, INIT_INTERVAL);
167 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "Init failed. Try again 10s later.");
168 return;
169 }
170 switch_.Init();
171 copyHistory = std::make_shared<Command>(std::vector<std::string>{ "--copy-history" },
172 "Dump access history last ten times.",
173 [this](const std::vector<std::string> &input, std::string &output) -> bool {
174 output = DumpHistory();
175 return true;
176 });
177
178 copyData = std::make_shared<Command>(std::vector<std::string>{ "--data" }, "Show copy data details.",
179 [this](const std::vector<std::string> &input, std::string &output) -> bool {
180 output = DumpData();
181 return true;
182 });
183
184 PasteboardDumpHelper::GetInstance().RegisterCommand(copyHistory);
185 PasteboardDumpHelper::GetInstance().RegisterCommand(copyData);
186
187 CommonEventSubscriber();
188 PasteboardEventSubscriber();
189 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Start PasteboardService success.");
190 EventCenter::GetInstance().Subscribe(OHOS::MiscServices::Event::EVT_REMOTE_CHANGE, RemotePasteboardChange());
191 HiViewAdapter::StartTimerThread();
192 ffrtTimer_ = std::make_shared<FFRTTimer>("pasteboard_service");
193 return;
194 }
195
OnStop()196 void PasteboardService::OnStop()
197 {
198 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "OnStop Started.");
199 if (state_ != ServiceRunningState::STATE_RUNNING) {
200 return;
201 }
202 serviceHandler_ = nullptr;
203 state_ = ServiceRunningState::STATE_NOT_START;
204 DMAdapter::GetInstance().UnInitialize();
205 if (commonEventSubscriber_ != nullptr) {
206 EventFwk::CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_);
207 }
208 moduleConfig_.DeInit();
209 switch_.DeInit();
210 EventCenter::GetInstance().Unsubscribe(PasteboardEvent::DISCONNECT);
211 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "OnStop End.");
212 EventCenter::GetInstance().Unsubscribe(OHOS::MiscServices::Event::EVT_REMOTE_CHANGE);
213 Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 0, PASTEBOARD_SERVICE_ID);
214 }
215
AddSysAbilityListener()216 void PasteboardService::AddSysAbilityListener()
217 {
218 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "begin.");
219 for (uint32_t i = 0; i < sizeof(LISTENING_SERVICE) / sizeof(LISTENING_SERVICE[0]); i++) {
220 auto ret = AddSystemAbilityListener(LISTENING_SERVICE[i]);
221 PASTEBOARD_HILOGD(
222 PASTEBOARD_MODULE_SERVICE, "ret = %{public}d, serviceId = %{public}d.", ret, LISTENING_SERVICE[i]);
223 }
224 }
225
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)226 void PasteboardService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
227 {
228 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "systemAbilityId = %{public}d added!", systemAbilityId);
229 auto itFunc = ServiceListenerFunc_.find(systemAbilityId);
230 if (itFunc != ServiceListenerFunc_.end()) {
231 auto ServiceListenerFunc = itFunc->second;
232 if (ServiceListenerFunc != nullptr) {
233 (this->*ServiceListenerFunc)();
234 }
235 }
236 }
237
DelayGetterDeathRecipient(int32_t userId,PasteboardService & service)238 PasteboardService::DelayGetterDeathRecipient::DelayGetterDeathRecipient(int32_t userId, PasteboardService &service)
239 : userId_(userId), service_(service)
240 {
241 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Construct Delay Getter Death Recipient");
242 }
243
OnRemoteDied(const wptr<IRemoteObject> & remote)244 void PasteboardService::DelayGetterDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
245 {
246 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "start");
247 (void) remote;
248 service_.NotifyDelayGetterDied(userId_);
249 }
250
NotifyDelayGetterDied(int32_t userId)251 void PasteboardService::NotifyDelayGetterDied(int32_t userId)
252 {
253 if (userId == ERROR_USERID) {
254 return;
255 }
256 delayGetters_.Erase(userId);
257 }
258
EntryGetterDeathRecipient(int32_t userId,PasteboardService & service)259 PasteboardService::EntryGetterDeathRecipient::EntryGetterDeathRecipient(int32_t userId, PasteboardService &service)
260 : userId_(userId), service_(service)
261 {
262 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Construct Entry Getter Death Recipient");
263 }
264
OnRemoteDied(const wptr<IRemoteObject> & remote)265 void PasteboardService::EntryGetterDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
266 {
267 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "start");
268 (void) remote;
269 service_.NotifyEntryGetterDied(userId_);
270 }
271
NotifyEntryGetterDied(int32_t userId)272 void PasteboardService::NotifyEntryGetterDied(int32_t userId)
273 {
274 if (userId == ERROR_USERID) {
275 return;
276 }
277 entryGetters_.Erase(userId);
278 }
279
DMAdapterInit()280 void PasteboardService::DMAdapterInit()
281 {
282 auto appInfo = GetAppInfo(IPCSkeleton::GetCallingTokenID());
283 DMAdapter::GetInstance().Initialize(appInfo.bundleName);
284 }
285
NotifySaStatus()286 void PasteboardService::NotifySaStatus()
287 {
288 Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 1, PASTEBOARD_SERVICE_ID);
289 }
290
ReportUeCopyEvent(PasteData & pasteData,int32_t result)291 void PasteboardService::ReportUeCopyEvent(PasteData &pasteData, int32_t result)
292 {
293 auto appInfo = GetAppInfo(IPCSkeleton::GetCallingTokenID());
294 auto res = (result == static_cast<int32_t>(PasteboardError::E_OK)) ? UeReporter::E_OK_OPERATION : result;
295 UE_REPORT(UeReporter::UE_COPY, GenerateDataType(pasteData), appInfo.bundleName, res,
296 DMAdapter::GetInstance().GetLocalDeviceType());
297 }
298
InitServiceHandler()299 void PasteboardService::InitServiceHandler()
300 {
301 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "InitServiceHandler started.");
302 if (serviceHandler_ != nullptr) {
303 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "Already init.");
304 return;
305 }
306 std::shared_ptr<AppExecFwk::EventRunner> runner =
307 AppExecFwk::EventRunner::Create(PASTEBOARD_SERVICE_NAME, AppExecFwk::ThreadMode::FFRT);
308 serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
309
310 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "InitServiceHandler Succeeded.");
311 }
312
Clear()313 void PasteboardService::Clear()
314 {
315 auto userId = GetCurrentAccountId();
316 if (userId == ERROR_USERID) {
317 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
318 return;
319 }
320 RADAR_REPORT(DFX_CLEAR_PASTEBOARD, DFX_MANUAL_CLEAR, DFX_SUCCESS);
321 auto it = clips_.Find(userId);
322 if (it.first) {
323 RevokeUriPermission(it.second);
324 clips_.Erase(userId);
325 auto appInfo = GetAppInfo(IPCSkeleton::GetCallingTokenID());
326 std::string bundleName = GetAppBundleName(appInfo);
327 NotifyObservers(bundleName, PasteboardEventStatus::PASTEBOARD_CLEAR);
328 }
329 CleanDistributedData(userId);
330 }
331
GetRecordValueByType(uint32_t dataId,uint32_t recordId,PasteDataEntry & value)332 int32_t PasteboardService::GetRecordValueByType(uint32_t dataId, uint32_t recordId, PasteDataEntry& value)
333 {
334 auto tokenId = IPCSkeleton::GetCallingTokenID();
335 auto callPid = IPCSkeleton::GetCallingPid();
336 if (!VerifyPermission(tokenId)) {
337 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "check permission failed, calling pid is %{public}d", callPid);
338 return static_cast<int32_t>(PasteboardError::PERMISSION_VERIFICATION_ERROR);
339 }
340 auto appInfo = GetAppInfo(tokenId);
341 auto clip = clips_.Find(appInfo.userId);
342 auto tempTime = copyTime_.Find(appInfo.userId);
343 auto entryGetter = entryGetters_.Find(appInfo.userId);
344 if (!clip.first || !tempTime.first || !entryGetter.first) {
345 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "pasteboard has no data or entry getter");
346 return static_cast<int32_t>(PasteboardError::NO_DATA_ERROR);
347 }
348 auto data = clip.second;
349 if (dataId != data->GetDataId()) {
350 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
351 "get record value fail, data is out time, pre dataId is %{public}d, cur dataId is %{public}d",
352 dataId, data->GetDataId());
353 return static_cast<int32_t>(PasteboardError::TIMEOUT_ERROR);
354 }
355 auto getter = entryGetter.second;
356 if (getter.first == nullptr) {
357 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
358 "entry getter is nullptr, dataId is %{public}d, recordId is %{public}d", dataId, recordId);
359 return static_cast<int32_t>(PasteboardError::OTHER_ERROR);
360 }
361 auto result = getter.first->GetRecordValueByType(recordId, value);
362 if (result != static_cast<int32_t>(PasteboardError::E_OK)) {
363 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
364 "get record value fail, dataId is %{public}d, recordId is %{public}d", dataId, recordId);
365 return result;
366 }
367 clips_.ComputeIfPresent(appInfo.userId, [dataId, recordId, value](auto, auto &data) {
368 if (dataId != data->GetDataId()) {
369 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
370 "set record value fail, data is out time, pre dataId is %{public}d, cur dataId is %{public}d",
371 dataId, data->GetDataId());
372 return true;
373 }
374 auto record = data->GetRecordAt(recordId - 1);
375 if (record != nullptr) {
376 record->AddEntry(value.GetUtdId(), std::make_shared<PasteDataEntry>(value));
377 }
378 return true;
379 });
380 return static_cast<int32_t>(PasteboardError::E_OK);
381 }
382
IsDefaultIME(const AppInfo & appInfo)383 bool PasteboardService::IsDefaultIME(const AppInfo &appInfo)
384 {
385 if (appInfo.tokenType != ATokenTypeEnum::TOKEN_HAP) {
386 return true;
387 }
388 if (bundles_.empty()) {
389 return true;
390 }
391 auto it = find(bundles_.begin(), bundles_.end(), appInfo.bundleName);
392 if (it != bundles_.end()) {
393 return true;
394 }
395
396 return false;
397 }
398
VerifyPermission(uint32_t tokenId)399 bool PasteboardService::VerifyPermission(uint32_t tokenId)
400 {
401 auto version = GetSdkVersion(tokenId);
402 auto callPid = IPCSkeleton::GetCallingPid();
403 if (version == INVAILD_VERSION) {
404 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
405 "get hap version failed, callPid is %{public}d, tokenId is %{public}d", callPid, tokenId);
406 return false;
407 }
408 auto isReadGrant = IsPermissionGranted(READ_PASTEBOARD_PERMISSION, tokenId);
409 auto isSecureGrant = IsPermissionGranted(SECURE_PASTE_PERMISSION, tokenId);
410 AddPermissionRecord(tokenId, isReadGrant, isSecureGrant);
411 auto isPrivilegeApp = IsDefaultIME(GetAppInfo(tokenId));
412 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE,
413 "isReadGrant is %{public}d, isSecureGrant is %{public}d, isPrivilegeApp is %{public}d", isReadGrant,
414 isSecureGrant, isPrivilegeApp);
415 bool isCtrlVAction = false;
416 if (inputEventCallback_ != nullptr) {
417 isCtrlVAction = inputEventCallback_->IsCtrlVProcess(callPid, IsFocusedApp(tokenId));
418 inputEventCallback_->Clear();
419 }
420 auto isGrant = isReadGrant || isSecureGrant || isPrivilegeApp || isCtrlVAction;
421 if (!isGrant && version >= ADD_PERMISSION_CHECK_SDK_VERSION) {
422 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "no permisssion, callPid is %{public}d, version is %{public}d",
423 callPid, version);
424 return false;
425 }
426 return true;
427 }
428
IsDataVaild(PasteData & pasteData,uint32_t tokenId)429 int32_t PasteboardService::IsDataVaild(PasteData &pasteData, uint32_t tokenId)
430 {
431 if (pasteData.IsDraggedData() || !pasteData.IsValid()) {
432 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "data is invalid");
433 return static_cast<int32_t>(PasteboardError::INVALID_PARAM_ERROR);
434 }
435 if (IsDataAged()) {
436 return static_cast<int32_t>(PasteboardError::DATA_EXPIRED_ERROR);
437 }
438 auto screenStatus = GetCurrentScreenStatus();
439 if (pasteData.GetScreenStatus() > screenStatus) {
440 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "current screen is %{public}d, set data screen is %{public}d.",
441 screenStatus, pasteData.GetScreenStatus());
442 return static_cast<int32_t>(PasteboardError::CROSS_BORDER_ERROR);
443 }
444 switch (pasteData.GetShareOption()) {
445 case ShareOption::InApp: {
446 if (pasteData.GetTokenId() != tokenId) {
447 PASTEBOARD_HILOGW(PASTEBOARD_MODULE_SERVICE, "InApp check failed.");
448 return static_cast<int32_t>(PasteboardError::PERMISSION_VERIFICATION_ERROR);
449 }
450 break;
451 }
452 case ShareOption::LocalDevice: {
453 break;
454 }
455 case ShareOption::CrossDevice: {
456 break;
457 }
458 default: {
459 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
460 "tokenId = 0x%{public}x, shareOption = %{public}d is error.", tokenId, pasteData.GetShareOption());
461 return static_cast<int32_t>(PasteboardError::INVALID_DATA_ERROR);
462 }
463 }
464 return static_cast<int32_t>(PasteboardError::E_OK);
465 }
466
GetSdkVersion(uint32_t tokenId)467 int32_t PasteboardService::GetSdkVersion(uint32_t tokenId)
468 {
469 if (AccessTokenKit::GetTokenTypeFlag(tokenId) != ATokenTypeEnum::TOKEN_HAP) {
470 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "caller is not application");
471 return 0;
472 }
473 HapTokenInfo hapTokenInfo;
474 auto ret = AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo);
475 if (ret != 0) {
476 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "GetHapTokenInfo fail, tokenid is %{public}d, ret is %{public}d.",
477 tokenId, ret);
478 return INVAILD_VERSION;
479 }
480 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "ver:%{public}d.", hapTokenInfo.apiVersion);
481 return hapTokenInfo.apiVersion;
482 }
483
IsPermissionGranted(const std::string & perm,uint32_t tokenId)484 bool PasteboardService::IsPermissionGranted(const std::string& perm, uint32_t tokenId)
485 {
486 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "check grant permission, perm=%{public}s", perm.c_str());
487 int32_t result = AccessTokenKit::VerifyAccessToken(tokenId, perm);
488 if (result == PermissionState::PERMISSION_DENIED) {
489 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "permission denied");
490 return false;
491 }
492 return true;
493 }
494
IsDataAged()495 bool PasteboardService::IsDataAged()
496 {
497 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "IsDataAged start");
498 auto userId = GetCurrentAccountId();
499 if (userId == ERROR_USERID) {
500 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
501 return true;
502 }
503 auto it = copyTime_.Find(userId);
504 if (!it.first) {
505 return true;
506 }
507 uint64_t copyTime = it.second;
508 auto curTime = static_cast<uint64_t>(duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
509 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "copyTime = %{public}" PRIu64, copyTime);
510 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "curTime = %{public}" PRIu64, curTime);
511 if (curTime > copyTime && curTime - copyTime > ONE_HOUR_MILLISECONDS) {
512 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "data is out of the time");
513 auto data = clips_.Find(userId);
514 if (data.first) {
515 RevokeUriPermission(data.second);
516 clips_.Erase(userId);
517 }
518 copyTime_.Erase(userId);
519 RADAR_REPORT(DFX_CLEAR_PASTEBOARD, DFX_AUTO_CLEAR, DFX_SUCCESS);
520 return true;
521 }
522 return false;
523 }
524
GetAppInfo(uint32_t tokenId)525 AppInfo PasteboardService::GetAppInfo(uint32_t tokenId)
526 {
527 AppInfo info;
528 info.tokenId = tokenId;
529 info.tokenType = AccessTokenKit::GetTokenTypeFlag(tokenId);
530 info.userId = GetCurrentAccountId();
531 switch (info.tokenType) {
532 case ATokenTypeEnum::TOKEN_HAP: {
533 HapTokenInfo hapInfo;
534 if (AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo) != 0) {
535 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "get hap token info fail.");
536 return info;
537 }
538 info.bundleName = hapInfo.bundleName;
539 break;
540 }
541 case ATokenTypeEnum::TOKEN_NATIVE:
542 case ATokenTypeEnum::TOKEN_SHELL: {
543 NativeTokenInfo tokenInfo;
544 if (AccessTokenKit::GetNativeTokenInfo(tokenId, tokenInfo) != 0) {
545 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "get native token info fail.");
546 return info;
547 }
548 info.bundleName = tokenInfo.processName;
549 break;
550 }
551 default: {
552 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "tokenType = %{public}d not match.", info.tokenType);
553 }
554 }
555 return info;
556 }
557
GetAppBundleName(const AppInfo & appInfo)558 std::string PasteboardService::GetAppBundleName(const AppInfo &appInfo)
559 {
560 std::string bundleName;
561 if (appInfo.userId != ERROR_USERID) {
562 bundleName = appInfo.bundleName;
563 } else {
564 bundleName = "error";
565 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "GetAppInfo error");
566 }
567 return bundleName;
568 }
569
SetLocalPasteFlag(bool isCrossPaste,uint32_t tokenId,PasteData & pasteData)570 void PasteboardService::SetLocalPasteFlag(bool isCrossPaste, uint32_t tokenId, PasteData &pasteData)
571 {
572 pasteData.SetLocalPasteFlag(!isCrossPaste && tokenId == pasteData.GetTokenId());
573 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "isLocalPaste = %{public}d.", pasteData.IsLocalPaste());
574 }
575
GetPasteData(PasteData & data,int32_t & syncTime)576 int32_t PasteboardService::GetPasteData(PasteData &data, int32_t &syncTime)
577 {
578 PasteboardTrace tracer("PasteboardService GetPasteData");
579 auto tokenId = IPCSkeleton::GetCallingTokenID();
580 auto callPid = IPCSkeleton::GetCallingPid();
581 auto appInfo = GetAppInfo(tokenId);
582 bool developerMode = OHOS::system::GetBoolParameter("const.security.developermode.state", false);
583 bool isTestServerSetPasteData = developerMode && setPasteDataUId_ == TESE_SERVER_UID;
584 if (!VerifyPermission(tokenId) && !isTestServerSetPasteData) {
585 RADAR_REPORT(DFX_GET_PASTEBOARD, DFX_CHECK_GET_AUTHORITY, DFX_SUCCESS, GET_DATA_APP, appInfo.bundleName,
586 RadarReporter::CONCURRENT_ID, data.GetPasteId());
587 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "check permission failed, callingPid is %{public}d", callPid);
588 return static_cast<int32_t>(PasteboardError::PERMISSION_VERIFICATION_ERROR);
589 }
590 auto ret = GetData(tokenId, data, syncTime);
591 UE_REPORT(UeReporter::UE_PASTE, GenerateDataType(data), appInfo.bundleName,
592 (ret == static_cast<int32_t>(PasteboardError::E_OK)) ? UeReporter::E_OK_OPERATION : ret,
593 DMAdapter::GetInstance().GetLocalDeviceType(), UeReporter::CROSS_FLAG, data.IsRemote());
594 if (ret != static_cast<int32_t>(PasteboardError::E_OK)) {
595 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
596 "data is invalid, ret is %{public}d, callPid is %{public}d, tokenId is %{public}d", ret, callPid, tokenId);
597 }
598 return ret;
599 }
600
AddPermissionRecord(uint32_t tokenId,bool isReadGrant,bool isSecureGrant)601 void PasteboardService::AddPermissionRecord(uint32_t tokenId, bool isReadGrant, bool isSecureGrant)
602 {
603 if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) {
604 return;
605 }
606 bool isGrant = isReadGrant || isSecureGrant;
607 if (!isGrant) {
608 return;
609 }
610 auto permUsedType = static_cast<PermissionUsedType>(AccessTokenKit::GetUserGrantedPermissionUsedType(tokenId,
611 isSecureGrant ? SECURE_PASTE_PERMISSION : READ_PASTEBOARD_PERMISSION));
612 AddPermParamInfo info;
613 info.tokenId = tokenId;
614 info.permissionName = READ_PASTEBOARD_PERMISSION;
615 info.successCount = 1;
616 info.failCount = 0;
617 info.type = permUsedType;
618 int32_t result = PrivacyKit::AddPermissionUsedRecord(info);
619 if (result != RET_SUCCESS) {
620 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "add record failed, result is %{public}d", result);
621 }
622 return;
623 }
624
GetData(uint32_t tokenId,PasteData & data,int32_t & syncTime)625 int32_t PasteboardService::GetData(uint32_t tokenId, PasteData &data, int32_t &syncTime)
626 {
627 CalculateTimeConsuming::SetBeginTime();
628 auto appInfo = GetAppInfo(tokenId);
629 int32_t result = static_cast<int32_t>(PasteboardError::E_OK);
630 std::string peerNetId = "";
631 std::string peerUdid = "";
632 std::string pasteId = data.GetPasteId();
633 auto event = GetValidDistributeEvent(appInfo.userId);
634 if (!event.first || GetCurrentScreenStatus() != ScreenEvent::ScreenUnlocked) {
635 result = GetLocalData(appInfo, data);
636 } else {
637 result = GetRemoteData(appInfo.userId, event.second, data, syncTime);
638 peerNetId = event.second.deviceId;
639 peerUdid = DMAdapter::GetInstance().GetUdidByNetworkId(peerNetId);
640 }
641 if (observerEventMap_.size() != 0) {
642 std::string targetBundleName = GetAppBundleName(appInfo);
643 NotifyObservers(targetBundleName, PasteboardEventStatus::PASTEBOARD_READ);
644 }
645 RADAR_REPORT(DFX_GET_PASTEBOARD, DFX_GET_DATA_INFO, DFX_SUCCESS, CONCURRENT_ID, pasteId, GET_DATA_APP,
646 appInfo.bundleName, GET_DATA_TYPE, GenerateDataType(data), LOCAL_DEV_TYPE,
647 DMAdapter::GetInstance().GetLocalDeviceType(), PEER_NET_ID, PasteboardDfxUntil::GetAnonymousID(peerNetId),
648 PEER_UDID, PasteboardDfxUntil::GetAnonymousID(peerUdid));
649 if (result != static_cast<int32_t>(PasteboardError::E_OK)) {
650 return result;
651 }
652 int64_t fileSize = GetFileSize(data);
653 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "fileSize=%{public}" PRId64", isremote=%{public}d", fileSize,
654 static_cast<int>(data.IsRemote()));
655 if (data.IsRemote() && fileSize > 0) {
656 data.SetPasteId(pasteId);
657 data.deviceId_ = event.second.deviceId;
658 EstablishP2PLink(data.deviceId_, data.GetPasteId());
659 }
660 GetPasteDataDot(data, appInfo.bundleName);
661 return GrantUriPermission(data, appInfo.bundleName);
662 }
663
GetFileSize(PasteData & data)664 int64_t PasteboardService::GetFileSize(PasteData &data)
665 {
666 int64_t fileSize = 0L;
667 auto value = data.GetProperty().additions.GetParam(PasteData::REMOTE_FILE_SIZE_LONG);
668 AAFwk::ILong *ao = AAFwk::ILong::Query(value);
669 if (ao != nullptr) {
670 fileSize = AAFwk::Long::Unbox(ao);
671 } else {
672 fileSize = data.GetProperty().additions.GetIntParam(PasteData::REMOTE_FILE_SIZE, -1);
673 }
674 return fileSize;
675 }
676
GetRemoteDataTask(const Event & event)677 PasteboardService::RemoteDataTaskManager::DataTask PasteboardService::RemoteDataTaskManager::GetRemoteDataTask(const
678 Event &event)
679 {
680 auto key = event.deviceId + std::to_string(event.seqId);
681 std::lock_guard<std::mutex> lock(mutex_);
682 auto it = dataTasks_.find(key);
683 if (it == dataTasks_.end()) {
684 it = dataTasks_.emplace(key, std::make_shared<TaskContext>()).first;
685 }
686
687 if (it == dataTasks_.end()) {
688 return std::make_pair(nullptr, false);
689 }
690
691 return std::make_pair(it->second, it->second->pasting_.exchange(true));
692 }
693
Notify(const Event & event,std::shared_ptr<PasteDateTime> data)694 void PasteboardService::RemoteDataTaskManager::Notify(const Event &event, std::shared_ptr<PasteDateTime> data)
695 {
696 auto key = event.deviceId + std::to_string(event.seqId);
697 std::lock_guard<std::mutex> lock(mutex_);
698 auto it = dataTasks_.find(key);
699 if (it == dataTasks_.end()) {
700 return;
701 }
702 auto& task = it->second;
703 task->data_ = data;
704 task->getDataBlocks_.ForEach([](const auto& key, auto value) -> bool {
705 value->SetValue(true);
706 return false;
707 });
708 }
709
WaitRemoteData(const Event & event)710 std::shared_ptr<PasteDateTime> PasteboardService::RemoteDataTaskManager::WaitRemoteData(const Event &event)
711 {
712 std::shared_ptr<PasteboardService::RemoteDataTaskManager::TaskContext> task;
713 {
714 auto key = event.deviceId + std::to_string(event.seqId);
715 std::lock_guard<std::mutex> lock(mutex_);
716 auto it = dataTasks_.find(key);
717 if (it == dataTasks_.end()) {
718 return nullptr;
719 }
720
721 task = it->second;
722 }
723
724 auto key = ++mapKey_;
725 auto block = std::make_shared<BlockObject<bool>>(GET_REMOTE_DATA_WAIT_TIME);
726 task->getDataBlocks_.InsertOrAssign(key, block);
727 block->GetValue();
728
729 task->getDataBlocks_.Erase(key);
730 return task->data_;
731 }
732
ClearRemoteDataTask(const Event & event)733 void PasteboardService::RemoteDataTaskManager::ClearRemoteDataTask(const Event &event)
734 {
735 auto key = event.deviceId + std::to_string(event.seqId);
736 std::lock_guard<std::mutex> lock(mutex_);
737 dataTasks_.erase(key);
738 }
739
GetRemoteData(int32_t userId,const Event & event,PasteData & data,int32_t & syncTime)740 int32_t PasteboardService::GetRemoteData(int32_t userId, const Event &event, PasteData &data, int32_t &syncTime)
741 {
742 syncTime = -1;
743 auto [task, isPasting] = taskMgr_.GetRemoteDataTask(event);
744 if (task == nullptr) {
745 return static_cast<int32_t>(PasteboardError::REMOTE_TASK_ERROR);
746 }
747
748 if (isPasting) {
749 auto value = taskMgr_.WaitRemoteData(event);
750 if (value != nullptr && value->data != nullptr) {
751 syncTime = value->syncTime;
752 data = *(value->data);
753 return static_cast<int32_t>(PasteboardError::E_OK);
754 }
755 return static_cast<int32_t>(PasteboardError::TASK_PROCESSING);
756 }
757
758 auto curEvent = GetValidDistributeEvent(userId);
759 if (!curEvent.first || !(curEvent.second == event)) {
760 auto it = clips_.Find(userId);
761 if (it.first) {
762 data = *it.second;
763 }
764 taskMgr_.ClearRemoteDataTask(event);
765 int32_t res = it.first ? static_cast<int32_t>(PasteboardError::E_OK) :
766 static_cast<int32_t>(PasteboardError::INVALID_EVENT_ERROR);
767 return res;
768 }
769
770 return GetRemotePasteData(userId, event, data, syncTime);
771 }
772
GetRemotePasteData(int32_t userId,const Event & event,PasteData & data,int32_t & syncTime)773 int32_t PasteboardService::GetRemotePasteData(int32_t userId, const Event &event, PasteData &data, int32_t &syncTime)
774 {
775 auto block = std::make_shared<BlockObject<std::shared_ptr<PasteDateTime>>>(GET_REMOTE_DATA_WAIT_TIME);
776 std::thread thread([this, event, block, userId]() mutable {
777 auto result = GetDistributedData(event, userId);
778 auto validEvent = GetValidDistributeEvent(userId);
779 std::shared_ptr<PasteDateTime> pasteDataTime = std::make_shared<PasteDateTime>();
780 if (result.first != nullptr) {
781 result.first->SetRemote(true);
782 if (validEvent.second == event) {
783 clips_.InsertOrAssign(userId, result.first);
784 auto curTime = static_cast<uint64_t>(duration_cast<milliseconds>(system_clock::now().time_since_epoch())
785 .count());
786 copyTime_.InsertOrAssign(userId, curTime);
787 }
788 pasteDataTime->syncTime = result.second.syncTime;
789 pasteDataTime->data = result.first;
790 pasteDataTime->errorCode = result.second.errorCode;
791 taskMgr_.Notify(event, pasteDataTime);
792 } else {
793 pasteDataTime->data = nullptr;
794 pasteDataTime->errorCode = result.second.errorCode;
795 taskMgr_.Notify(event, pasteDataTime);
796 }
797 block->SetValue(pasteDataTime);
798 taskMgr_.ClearRemoteDataTask(event);
799 });
800 thread.detach();
801 auto value = block->GetValue();
802 if (value != nullptr && value->data != nullptr) {
803 syncTime = value->syncTime;
804 data = std::move(*(value->data));
805 return value->errorCode;
806 } else if (value != nullptr && value->data == nullptr) {
807 return value->errorCode;
808 }
809 return static_cast<int32_t>(PasteboardError::TIMEOUT_ERROR);
810 }
811
GetLocalData(const AppInfo & appInfo,PasteData & data)812 int32_t PasteboardService::GetLocalData(const AppInfo &appInfo, PasteData &data)
813 {
814 std::string pasteId = data.GetPasteId();
815 auto it = clips_.Find(appInfo.userId);
816 auto tempTime = copyTime_.Find(appInfo.userId);
817 if (!it.first || !tempTime.first) {
818 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "no data.");
819 return static_cast<int32_t>(PasteboardError::NO_DATA_ERROR);
820 }
821 auto ret = IsDataVaild(*(it.second), appInfo.tokenId);
822 if (ret != static_cast<int32_t>(PasteboardError::E_OK)) {
823 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "paste data is invaild. ret is %{public}d", ret);
824 return ret;
825 }
826 data = *(it.second);
827 auto originBundleName = it.second->GetBundleName();
828 auto isDelayData = it.second->IsDelayData();
829 if (isDelayData) {
830 GetDelayPasteData(appInfo, data);
831 RADAR_REPORT(DFX_GET_PASTEBOARD, DFX_CHECK_GET_DELAY_PASTE, DFX_SUCCESS, CONCURRENT_ID, pasteId);
832 }
833 bool isDelayRecordPadding = false;
834 if (it.second->IsDelayRecord()) {
835 isDelayRecordPadding = GetDelayPasteRecord(appInfo, data);
836 }
837 data.SetBundleName(appInfo.bundleName);
838 auto result = copyTime_.Find(appInfo.userId);
839 if (!result.first) {
840 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "userId not found");
841 return static_cast<int32_t>(PasteboardError::INVALID_USERID_ERROR);
842 }
843 auto curTime = result.second;
844 if (tempTime.second == curTime) {
845 bool isNotify = false;
846 clips_.ComputeIfPresent(appInfo.userId, [&data, &isNotify, &isDelayRecordPadding](auto &key, auto &value) {
847 if (value->IsDelayData() || (value->IsDelayRecord() && isDelayRecordPadding)) {
848 value = std::make_shared<PasteData>(data);
849 isNotify = true;
850 }
851 return true;
852 });
853 if (isNotify) {
854 NotifyObservers(originBundleName, PasteboardEventStatus::PASTEBOARD_WRITE);
855 }
856 }
857 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "GetPasteData success.");
858 SetLocalPasteFlag(data.IsRemote(), appInfo.tokenId, data);
859 return static_cast<int32_t>(PasteboardError::E_OK);
860 }
861
GetDelayPasteData(const AppInfo & appInfo,PasteData & data)862 void PasteboardService::GetDelayPasteData(const AppInfo &appInfo, PasteData &data)
863 {
864 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "get delay data start");
865 delayGetters_.ComputeIfPresent(appInfo.userId, [this, &data](auto, auto &delayGetter) {
866 PasteData delayData;
867 if (delayGetter.first != nullptr) {
868 delayGetter.first->GetPasteData("", delayData);
869 }
870 if (delayGetter.second != nullptr) {
871 delayGetter.first->AsObject()->RemoveDeathRecipient(delayGetter.second);
872 }
873 delayData.SetDelayData(false);
874 delayData.SetBundleName(data.GetBundleName());
875 delayData.SetOrginAuthority(data.GetOrginAuthority());
876 delayData.SetTime(data.GetTime());
877 delayData.SetTokenId(data.GetTokenId());
878 CheckAppUriPermission(delayData);
879 SetWebViewPasteData(delayData, data.GetBundleName());
880 data = delayData;
881 return false;
882 });
883 }
884
GetDelayPasteRecord(const AppInfo & appInfo,PasteData & data)885 bool PasteboardService::GetDelayPasteRecord(const AppInfo &appInfo, PasteData &data)
886 {
887 auto entryGetter = entryGetters_.Find(appInfo.userId);
888 if (!entryGetter.first) {
889 PASTEBOARD_HILOGW(PASTEBOARD_MODULE_SERVICE, "entryGetter.first is null");
890 return false;
891 }
892 auto getter = entryGetter.second;
893 if (getter.first == nullptr) {
894 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "entry getter is nullptr, dataId is %{public}d", data.GetDataId());
895 return false;
896 }
897 bool isPadding = false;
898 for (auto record : data.AllRecords()) {
899 if (!(record->HasEmptyEntry())) {
900 PASTEBOARD_HILOGW(PASTEBOARD_MODULE_SERVICE, "record do not has empty value.");
901 continue;
902 }
903 if (!record->IsDelayRecord()) {
904 PASTEBOARD_HILOGW(PASTEBOARD_MODULE_SERVICE, "record is not DelayRecord.");
905 continue;
906 }
907 auto entries = record->GetEntries();
908 if (entries.empty()) {
909 PASTEBOARD_HILOGW(PASTEBOARD_MODULE_SERVICE, "record size is 0.");
910 continue;
911 }
912 if (!std::holds_alternative<std::monostate>(entries[0]->GetValue())) {
913 continue;
914 }
915 auto result = getter.first->GetRecordValueByType(record->GetRecordId(), *entries[0]);
916 if (result != static_cast<int32_t>(PasteboardError::E_OK)) {
917 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
918 "get record value fail, dataId is %{public}d, recordId is %{public}d", data.GetDataId(),
919 record->GetRecordId());
920 continue;
921 }
922 record->AddEntry(entries[0]->GetUtdId(), entries[0]);
923 isPadding = true;
924 }
925 return isPadding;
926 }
927
EstablishP2PLink(const std::string & networkId,const std::string & pasteId)928 void PasteboardService::EstablishP2PLink(const std::string &networkId, const std::string &pasteId)
929 {
930 #ifdef PB_DEVICE_MANAGER_ENABLE
931 auto callPid = IPCSkeleton::GetCallingPid();
932 p2pMap_.Compute(networkId, [pasteId, callPid] (const auto& key, auto& value) {
933 value.Compute(pasteId, [callPid] (const auto& key, auto& value) {
934 value = callPid;
935 return true;
936 });
937 return true;
938 });
939 if (ffrtTimer_ != nullptr) {
940 FFRTTask task = [this, networkId, pasteId] {
941 PasteComplete(networkId, pasteId);
942 };
943 ffrtTimer_->SetTimer(pasteId, task, MIN_TRANMISSION_TIME);
944 }
945 DmDeviceInfo remoteDevice;
946 auto ret = DMAdapter::GetInstance().GetRemoteDeviceInfo(networkId, remoteDevice);
947 if (ret != static_cast<int32_t>(PasteboardError::E_OK)) {
948 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "remote device is not exist");
949 p2pMap_.Erase(networkId);
950 return;
951 }
952 auto plugin = GetClipPlugin();
953 if (plugin == nullptr) {
954 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "plugin is not exist");
955 p2pMap_.Erase(networkId);
956 return;
957 }
958 auto status = DistributedFileDaemonManager::GetInstance().OpenP2PConnection(remoteDevice);
959 if (status != RESULT_OK) {
960 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "open p2p error, status:%{public}d", status);
961 p2pMap_.Erase(networkId);
962 return;
963 }
964 status = plugin->PublishServiceState(networkId, ClipPlugin::ServiceStatus::CONNECT_SUCC);
965 if (status != RESULT_OK) {
966 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "Publish state connect_succ error, status:%{public}d", status);
967 }
968 #endif
969 }
970
CloseP2PLink(const std::string & networkId)971 void PasteboardService::CloseP2PLink(const std::string &networkId)
972 {
973 #ifdef PB_DEVICE_MANAGER_ENABLE
974 DmDeviceInfo remoteDevice;
975 auto ret = DMAdapter::GetInstance().GetRemoteDeviceInfo(networkId, remoteDevice);
976 if (ret != static_cast<int32_t>(PasteboardError::E_OK)) {
977 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "remote device is not exist");
978 return;
979 }
980 auto status = DistributedFileDaemonManager::GetInstance().CloseP2PConnection(remoteDevice);
981 if (status != RESULT_OK) {
982 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "close p2p error, status:%{public}d", status);
983 }
984 auto plugin = GetClipPlugin();
985 if (plugin == nullptr) {
986 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "plugin is not exist");
987 return;
988 }
989 status = plugin->PublishServiceState(networkId, ClipPlugin::ServiceStatus::IDLE);
990 if (status != RESULT_OK) {
991 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "Publish state idle error, status:%{public}d", status);
992 }
993 #endif
994 }
995
PasteStart(const std::string & pasteId)996 void PasteboardService::PasteStart(const std::string &pasteId)
997 {
998 if (ffrtTimer_ != nullptr) {
999 ffrtTimer_->CancelTimer(pasteId);
1000 }
1001 }
1002
PasteComplete(const std::string & deviceId,const std::string & pasteId)1003 void PasteboardService::PasteComplete(const std::string &deviceId, const std::string &pasteId)
1004 {
1005 if (deviceId.empty()) {
1006 return;
1007 }
1008 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "deviceId is %{public}.6s, taskId is %{public}s",
1009 deviceId.c_str(), pasteId.c_str());
1010 RADAR_REPORT(RadarReporter::DFX_GET_PASTEBOARD, RadarReporter::DFX_DISTRIBUTED_FILE_END, RadarReporter::DFX_SUCCESS,
1011 RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::CONCURRENT_ID, pasteId);
1012 p2pMap_.ComputeIfPresent(deviceId, [pasteId, deviceId, this] (const auto& key, auto& value) {
1013 value.ComputeIfPresent(pasteId, [deviceId] (const auto& key, auto& value) {
1014 return false;
1015 });
1016 if (value.Empty()) {
1017 CloseP2PLink(deviceId);
1018 return false;
1019 }
1020 return true;
1021 });
1022 }
1023
GrantUriPermission(PasteData & data,const std::string & targetBundleName)1024 int32_t PasteboardService::GrantUriPermission(PasteData &data, const std::string &targetBundleName)
1025 {
1026 std::vector<Uri> grantUris;
1027 CheckUriPermission(data, grantUris, targetBundleName);
1028 if (grantUris.size() == 0) {
1029 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "no uri.");
1030 return static_cast<int32_t>(PasteboardError::E_OK);
1031 }
1032 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "uri size: %{public}u, targetBundleName is %{public}s",
1033 static_cast<uint32_t>(grantUris.size()), targetBundleName.c_str());
1034 size_t offset = 0;
1035 size_t length = grantUris.size();
1036 size_t count = MAX_URI_COUNT;
1037 bool grantSuccess = true;
1038 while (length > offset) {
1039 if (length - offset < MAX_URI_COUNT) {
1040 count = length - offset;
1041 }
1042 auto sendValues = std::vector<Uri>(grantUris.begin() + offset, grantUris.begin() + offset + count);
1043 auto permissionCode = AAFwk::UriPermissionManagerClient::GetInstance().GrantUriPermissionPrivileged(sendValues,
1044 AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION, targetBundleName);
1045 if (permissionCode == 0 && readBundles_.count(targetBundleName) == 0) {
1046 readBundles_.insert(targetBundleName);
1047 }
1048 grantSuccess = grantSuccess && (permissionCode == 0);
1049 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "permissionCode is %{public}d", permissionCode);
1050 offset += count;
1051 }
1052 return grantSuccess ? static_cast<int32_t>(PasteboardError::E_OK) :
1053 static_cast<int32_t>(PasteboardError::URI_GRANT_ERROR);
1054 }
1055
CheckUriPermission(PasteData & data,std::vector<Uri> & grantUris,const std::string & targetBundleName)1056 void PasteboardService::CheckUriPermission(PasteData &data, std::vector<Uri> &grantUris,
1057 const std::string &targetBundleName)
1058 {
1059 for (size_t i = 0; i < data.GetRecordCount(); i++) {
1060 auto item = data.GetRecordAt(i);
1061 if (item == nullptr || (!data.IsRemote() && targetBundleName.compare(data.GetOrginAuthority()) == 0)) {
1062 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "local dev & local app");
1063 continue;
1064 }
1065 std::shared_ptr<OHOS::Uri> uri = nullptr;
1066 if (!item->isConvertUriFromRemote && !item->GetConvertUri().empty()) {
1067 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "clear local disUri");
1068 item->SetConvertUri("");
1069 }
1070 if (item->isConvertUriFromRemote && !item->GetConvertUri().empty()) {
1071 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "get remote disUri");
1072 uri = std::make_shared<OHOS::Uri>(item->GetConvertUri());
1073 } else if (!item->isConvertUriFromRemote && item->GetOrginUri() != nullptr) {
1074 uri = item->GetOrginUri();
1075 }
1076 auto hasGrantUriPermission = item->HasGrantUriPermission();
1077 if (uri == nullptr || (!IsBundleOwnUriPermission(data.GetOrginAuthority(), *uri) && !hasGrantUriPermission)) {
1078 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "uri is null:%{public}d, not grant permission: %{public}d.",
1079 uri == nullptr, hasGrantUriPermission);
1080 continue;
1081 }
1082 grantUris.emplace_back(*uri);
1083 }
1084 }
1085
RevokeUriPermission(std::shared_ptr<PasteData> pasteData)1086 void PasteboardService::RevokeUriPermission(std::shared_ptr<PasteData> pasteData)
1087 {
1088 if (readBundles_.size() == 0 || pasteData == nullptr) {
1089 return;
1090 }
1091 decltype(readBundles_) bundles(std::move(readBundles_));
1092 readBundles_.clear();
1093 std::thread thread([pasteData, bundles] () {
1094 auto& permissionClient = AAFwk::UriPermissionManagerClient::GetInstance();
1095 for (size_t i = 0; i < pasteData->GetRecordCount(); i++) {
1096 auto item = pasteData->GetRecordAt(i);
1097 if (item == nullptr || item->GetOrginUri() == nullptr) {
1098 continue;
1099 }
1100 Uri &uri = *(item->GetOrginUri());
1101 for (std::set<std::string>::iterator it = bundles.begin(); it != bundles.end(); it++) {
1102 auto permissionCode = permissionClient.RevokeUriPermissionManually(uri, *it);
1103 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "permissionCode is %{public}d", permissionCode);
1104 }
1105 }
1106 });
1107 thread.detach();
1108 }
1109
IsBundleOwnUriPermission(const std::string & bundleName,Uri & uri)1110 bool PasteboardService::IsBundleOwnUriPermission(const std::string &bundleName, Uri &uri)
1111 {
1112 auto authority = uri.GetAuthority();
1113 if (bundleName.compare(authority) != 0) {
1114 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "grant error, uri:%{public}s, orgin:%{public}s",
1115 authority.c_str(), bundleName.c_str());
1116 return false;
1117 }
1118 return true;
1119 }
1120
CheckAppUriPermission(PasteData & data)1121 void PasteboardService::CheckAppUriPermission(PasteData &data)
1122 {
1123 std::vector<std::string> uris;
1124 std::vector<size_t> indexs;
1125 std::vector<bool> checkResults;
1126 for (size_t i = 0; i < data.GetRecordCount(); i++) {
1127 auto item = data.GetRecordAt(i);
1128 if (item == nullptr || item->GetOrginUri() == nullptr) {
1129 continue;
1130 }
1131 auto uri = item->GetOrginUri()->ToString();
1132 uris.emplace_back(uri);
1133 indexs.emplace_back(i);
1134 }
1135 if (uris.empty()) {
1136 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "no uri.");
1137 return;
1138 }
1139 size_t offset = 0;
1140 size_t length = uris.size();
1141 size_t count = MAX_URI_COUNT;
1142 while (length > offset) {
1143 if (length - offset < MAX_URI_COUNT) {
1144 count = length - offset;
1145 }
1146 auto sendValues = std::vector<std::string>(uris.begin() + offset, uris.begin() + offset + count);
1147 std::vector<bool> ret = AAFwk::UriPermissionManagerClient::GetInstance().CheckUriAuthorization(sendValues,
1148 AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION, data.GetTokenId());
1149 checkResults.insert(checkResults.end(), ret.begin(), ret.end());
1150 offset += count;
1151 }
1152 for (size_t i = 0; i < indexs.size(); i++) {
1153 auto item = data.GetRecordAt(indexs[i]);
1154 if (item == nullptr || item->GetOrginUri() == nullptr) {
1155 continue;
1156 }
1157 item->SetGrantUriPermission(checkResults[i]);
1158 }
1159 }
1160
ShowHintToast(uint32_t tokenId,uint32_t pid)1161 void PasteboardService::ShowHintToast(uint32_t tokenId, uint32_t pid)
1162 {
1163 PasteBoardDialog::ToastMessageInfo message;
1164 message.appName = GetAppLabel(tokenId);
1165 PasteBoardDialog::GetInstance().ShowToast(message);
1166 }
1167
HasPasteData()1168 bool PasteboardService::HasPasteData()
1169 {
1170 auto userId = GetCurrentAccountId();
1171 if (userId == ERROR_USERID) {
1172 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
1173 return false;
1174 }
1175
1176 if (GetCurrentScreenStatus() == ScreenEvent::ScreenUnlocked) {
1177 auto evt = GetValidDistributeEvent(userId);
1178 if (evt.first) {
1179 return true;
1180 }
1181 }
1182
1183 auto it = clips_.Find(userId);
1184 if (it.first && (it.second != nullptr)) {
1185 auto tokenId = IPCSkeleton::GetCallingTokenID();
1186 auto ret = IsDataVaild(*(it.second), tokenId);
1187 if (ret != static_cast<int32_t>(PasteboardError::E_OK)) {
1188 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
1189 "pasteData is invalid, tokenId: %{public}d, userId: %{public}d,"
1190 "ret is %{public}d", tokenId, userId, ret);
1191 return false;
1192 }
1193 return true;
1194 }
1195 return false;
1196 }
1197
SetPasteData(PasteData & pasteData,const sptr<IPasteboardDelayGetter> delayGetter,const sptr<IPasteboardEntryGetter> entryGetter)1198 int32_t PasteboardService::SetPasteData(PasteData &pasteData, const sptr<IPasteboardDelayGetter> delayGetter,
1199 const sptr<IPasteboardEntryGetter> entryGetter)
1200 {
1201 auto data = std::make_shared<PasteData>(pasteData);
1202 return SavePasteData(data, delayGetter, entryGetter);
1203 }
1204
SaveData(std::shared_ptr<PasteData> & pasteData,sptr<IPasteboardDelayGetter> delayGetter,sptr<IPasteboardEntryGetter> entryGetter)1205 int32_t PasteboardService::SaveData(std::shared_ptr<PasteData> &pasteData,
1206 sptr<IPasteboardDelayGetter> delayGetter, sptr<IPasteboardEntryGetter> entryGetter)
1207 {
1208 PasteboardTrace tracer("PasteboardService, SetPasteData");
1209 auto tokenId = IPCSkeleton::GetCallingTokenID();
1210 if (!IsCopyable(tokenId)) {
1211 RADAR_REPORT(DFX_SET_PASTEBOARD, DFX_CHECK_SET_AUTHORITY, DFX_SUCCESS);
1212 return static_cast<int32_t>(PasteboardError::PROHIBIT_COPY);
1213 }
1214 if (setting_.exchange(true)) {
1215 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "is setting.");
1216 return static_cast<int32_t>(PasteboardError::TASK_PROCESSING);
1217 }
1218 CalculateTimeConsuming::SetBeginTime();
1219 auto appInfo = GetAppInfo(tokenId);
1220 if (appInfo.userId == ERROR_USERID) {
1221 setting_.store(false);
1222 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
1223 return static_cast<int32_t>(PasteboardError::INVALID_USERID_ERROR);
1224 }
1225 setPasteDataUId_ = IPCSkeleton::GetCallingUid();
1226 RemovePasteData(appInfo);
1227 pasteData->SetBundleName(appInfo.bundleName);
1228 pasteData->SetOrginAuthority(appInfo.bundleName);
1229 std::string time = GetTime();
1230 pasteData->SetTime(time);
1231 pasteData->SetScreenStatus(GetCurrentScreenStatus());
1232 pasteData->SetTokenId(tokenId);
1233 auto dataId = ++dataId_;
1234 pasteData->SetDataId(dataId);
1235 for (auto &record : pasteData->AllRecords()) {
1236 record->SetDataId(dataId);
1237 }
1238 UpdateShareOption(*pasteData);
1239 SetWebViewPasteData(*pasteData, appInfo.bundleName);
1240 CheckAppUriPermission(*pasteData);
1241 clips_.InsertOrAssign(appInfo.userId, pasteData);
1242 RADAR_REPORT(DFX_SET_PASTEBOARD, DFX_CHECK_SET_DELAY_COPY, static_cast<int>(pasteData->IsDelayData()), SET_DATA_APP,
1243 appInfo.bundleName, LOCAL_DEV_TYPE, DMAdapter::GetInstance().GetLocalDeviceType());
1244 HandleDelayDataAndRecord(pasteData, delayGetter, entryGetter, appInfo);
1245 auto curTime = static_cast<uint64_t>(duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1246 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "curTime = %{public}" PRIu64, curTime);
1247 copyTime_.InsertOrAssign(appInfo.userId, curTime);
1248 if (!(pasteData->IsDelayData())) {
1249 SetDistributedData(appInfo.userId, *pasteData);
1250 NotifyObservers(appInfo.bundleName, PasteboardEventStatus::PASTEBOARD_WRITE);
1251 }
1252 SetPasteDataDot(*pasteData);
1253 setting_.store(false);
1254 SubscribeKeyboardEvent();
1255 return static_cast<int32_t>(PasteboardError::E_OK);
1256 }
1257
HandleDelayDataAndRecord(std::shared_ptr<PasteData> & pasteData,sptr<IPasteboardDelayGetter> delayGetter,sptr<IPasteboardEntryGetter> entryGetter,const AppInfo & appInfo)1258 void PasteboardService::HandleDelayDataAndRecord(std::shared_ptr<PasteData> &pasteData,
1259 sptr<IPasteboardDelayGetter> delayGetter, sptr<IPasteboardEntryGetter> entryGetter, const AppInfo& appInfo)
1260 {
1261 if (pasteData->IsDelayData()) {
1262 sptr<DelayGetterDeathRecipient> deathRecipient =
1263 new (std::nothrow) DelayGetterDeathRecipient(appInfo.userId, *this);
1264 delayGetter->AsObject()->AddDeathRecipient(deathRecipient);
1265 delayGetters_.InsertOrAssign(appInfo.userId, std::make_pair(delayGetter, deathRecipient));
1266 }
1267 if (pasteData->IsDelayRecord()) {
1268 sptr<EntryGetterDeathRecipient> deathRecipient =
1269 new (std::nothrow) EntryGetterDeathRecipient(appInfo.userId, *this);
1270 entryGetter->AsObject()->AddDeathRecipient(deathRecipient);
1271 entryGetters_.InsertOrAssign(appInfo.userId, std::make_pair(entryGetter, deathRecipient));
1272 }
1273 }
1274
IsBasicType(const std::string & mimeType)1275 bool PasteboardService::IsBasicType(const std::string &mimeType)
1276 {
1277 if (mimeType == MIMETYPE_TEXT_HTML || mimeType == MIMETYPE_TEXT_PLAIN || mimeType == MIMETYPE_TEXT_URI) {
1278 return true;
1279 }
1280 return false;
1281 }
1282
GetMimeTypes()1283 std::vector<std::string> PasteboardService::GetMimeTypes()
1284 {
1285 if (GetCurrentScreenStatus() == ScreenEvent::ScreenUnlocked) {
1286 auto userId = GetCurrentAccountId();
1287 auto event = GetValidDistributeEvent(userId);
1288 if (event.first) {
1289 PasteData data;
1290 int32_t syncTime = 0;
1291 int32_t ret = GetRemoteData(userId, event.second, data, syncTime);
1292 PASTEBOARD_CHECK_AND_RETURN_RET_LOGE(ret == static_cast<int32_t>(PasteboardError::E_OK), {},
1293 PASTEBOARD_MODULE_SERVICE, "get remote data failed, ret=%{public}d", ret);
1294 }
1295 }
1296 return GetLocalMimeTypes();
1297 }
1298
HasDataType(const std::string & mimeType)1299 bool PasteboardService::HasDataType(const std::string &mimeType)
1300 {
1301 if (GetCurrentScreenStatus() == ScreenEvent::ScreenUnlocked) {
1302 auto userId = GetCurrentAccountId();
1303 auto event = GetValidDistributeEvent(userId);
1304 if (event.first) {
1305 auto it = std::find(event.second.dataType.begin(), event.second.dataType.end(), mimeType);
1306 if (it != event.second.dataType.end()) {
1307 return true;
1308 }
1309 if (IsBasicType(mimeType)) {
1310 return false;
1311 }
1312 PasteData data;
1313 int32_t syncTime = 0;
1314 if (GetRemoteData(userId, event.second, data, syncTime) != static_cast<int32_t>(PasteboardError::E_OK)) {
1315 return false;
1316 }
1317 }
1318 }
1319 return HasLocalDataType(mimeType);
1320 }
1321
DetectPatterns(const std::set<Pattern> & patternsToCheck)1322 std::set<Pattern> PasteboardService::DetectPatterns(const std::set<Pattern> &patternsToCheck)
1323 {
1324 bool hasPlain = HasLocalDataType(MIMETYPE_TEXT_PLAIN);
1325 bool hasHTML = HasLocalDataType(MIMETYPE_TEXT_HTML);
1326 if (!hasHTML && !hasPlain) {
1327 return {};
1328 }
1329 int32_t userId = GetCurrentAccountId();
1330 auto it = clips_.Find(userId);
1331 if (!it.first) {
1332 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "error, no PasteData!");
1333 return {};
1334 }
1335 std::shared_ptr<PasteData> pasteData = it.second;
1336 return OHOS::MiscServices::PatternDetection::Detect(patternsToCheck, *pasteData, hasHTML, hasPlain);
1337 }
1338
GetValidDistributeEvent(int32_t user)1339 std::pair<bool, ClipPlugin::GlobalEvent> PasteboardService::GetValidDistributeEvent(int32_t user)
1340 {
1341 Event evt;
1342 auto plugin = GetClipPlugin();
1343 if (plugin == nullptr) {
1344 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "plugin is nullptr ");
1345 return std::make_pair(false, evt);
1346 }
1347 auto events = plugin->GetTopEvents(1, user);
1348 if (events.empty()) {
1349 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "events empty.");
1350 return std::make_pair(false, evt);
1351 }
1352
1353 evt = events[0];
1354 if (evt.deviceId == DMAdapter::GetInstance().GetLocalNetworkId() ||
1355 evt.expiration < currentEvent_.expiration) {
1356 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "get local data.");
1357 return std::make_pair(false, evt);
1358 }
1359 if (evt.account != AccountManager::GetInstance().GetCurrentAccount()) {
1360 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "account error.");
1361 return std::make_pair(false, evt);
1362 }
1363
1364 if (evt.deviceId == currentEvent_.deviceId && evt.seqId == currentEvent_.seqId &&
1365 evt.expiration == currentEvent_.expiration) {
1366 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "get same remote data.");
1367 return std::make_pair(false, evt);
1368 }
1369
1370 uint64_t curTime =
1371 static_cast<uint64_t>(duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1372 if ((curTime < evt.expiration) && (evt.status == ClipPlugin::EVT_NORMAL)) {
1373 return std::make_pair(true, evt);
1374 }
1375
1376 return std::make_pair(false, evt);
1377 }
1378
GetLocalMimeTypes()1379 std::vector<std::string> PasteboardService::GetLocalMimeTypes()
1380 {
1381 auto userId = GetCurrentAccountId();
1382 auto it = clips_.Find(userId);
1383 if (!it.first) {
1384 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "can not find data. userId: %{public}d", userId);
1385 return {};
1386 }
1387 if (it.second == nullptr) {
1388 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "data is nullptr. userId: %{public}d", userId);
1389 return {};
1390 }
1391 auto tokenId = IPCSkeleton::GetCallingTokenID();
1392 auto ret = IsDataVaild(*(it.second), tokenId);
1393 if (ret != static_cast<int32_t>(PasteboardError::E_OK)) {
1394 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
1395 "pasteData is invalid, tokenId is %{public}d, userId: %{public}d, ret is %{public}d",
1396 tokenId, userId, ret);
1397 return {};
1398 }
1399 return it.second->GetMimeTypesWithEntry();
1400 }
1401
HasLocalDataType(const std::string & mimeType)1402 bool PasteboardService::HasLocalDataType(const std::string &mimeType)
1403 {
1404 auto userId = GetCurrentAccountId();
1405 auto it = clips_.Find(userId);
1406 if (!it.first) {
1407 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "can not find data. userId: %{public}d, mimeType: %{public}s",
1408 userId, mimeType.c_str());
1409 return false;
1410 }
1411 if (it.second == nullptr) {
1412 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "data is nullptr. userId: %{public}d, mimeType: %{public}s",
1413 userId, mimeType.c_str());
1414 return false;
1415 }
1416 auto tokenId = IPCSkeleton::GetCallingTokenID();
1417 auto ret = IsDataVaild(*(it.second), tokenId);
1418 if (ret != static_cast<int32_t>(PasteboardError::E_OK)) {
1419 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "pasteData is invalid, tokenId is %{public}d, userId: %{public}d,"
1420 "mimeType: %{public}s, ret is %{public}d", tokenId, userId, mimeType.c_str(), ret);
1421 return false;
1422 }
1423 auto screenStatus = GetCurrentScreenStatus();
1424 if (it.second->GetScreenStatus() > screenStatus) {
1425 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "current screen is %{public}d, set data screen is %{public}d."
1426 "userId: %{public}d, mimeType: %{public}s",
1427 screenStatus, it.second->GetScreenStatus(), userId, mimeType.c_str());
1428 return false;
1429 }
1430 std::vector<std::string> mimeTypes = it.second->GetMimeTypes();
1431 auto isWebData = it.second->GetTag() == PasteData::WEBVIEW_PASTEDATA_TAG;
1432 auto isExistType = std::find(mimeTypes.begin(), mimeTypes.end(), mimeType) != mimeTypes.end();
1433 if (isWebData) {
1434 return mimeType == MIMETYPE_TEXT_HTML && isExistType;
1435 }
1436 return isExistType;
1437 }
1438
IsRemoteData()1439 bool PasteboardService::IsRemoteData()
1440 {
1441 auto userId = GetCurrentAccountId();
1442 if (userId == ERROR_USERID) {
1443 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId is error ");
1444 return false;
1445 }
1446 auto it = clips_.Find(userId);
1447 if (!it.first) {
1448 auto evt = GetValidDistributeEvent(userId);
1449 return evt.first;
1450 }
1451 return it.second->IsRemote();
1452 }
1453
GetDataSource(std::string & bundleName)1454 int32_t PasteboardService::GetDataSource(std::string &bundleName)
1455 {
1456 auto userId = GetCurrentAccountId();
1457 if (userId == ERROR_USERID) {
1458 return static_cast<int32_t>(PasteboardError::INVALID_USERID_ERROR);
1459 }
1460 auto it = clips_.Find(userId);
1461 if (!it.first) {
1462 return static_cast<int32_t>(PasteboardError::NO_USER_DATA_ERROR);
1463 }
1464 auto data = it.second;
1465 if (data->IsRemote()) {
1466 return static_cast<int32_t>(PasteboardError::REMOTE_EXCEPTION);
1467 }
1468 auto tokenId = data->GetTokenId();
1469 bundleName = GetAppLabel(tokenId);
1470 return static_cast<int32_t>(PasteboardError::E_OK);
1471 }
1472
SavePasteData(std::shared_ptr<PasteData> & pasteData,sptr<IPasteboardDelayGetter> delayGetter,sptr<IPasteboardEntryGetter> entryGetter)1473 int32_t PasteboardService::SavePasteData(std::shared_ptr<PasteData> &pasteData,
1474 sptr<IPasteboardDelayGetter> delayGetter, sptr<IPasteboardEntryGetter> entryGetter)
1475 {
1476 auto ret = SaveData(pasteData, delayGetter, entryGetter);
1477 ReportUeCopyEvent(*pasteData, ret);
1478 return ret;
1479 }
1480
RemovePasteData(const AppInfo & appInfo)1481 void PasteboardService::RemovePasteData(const AppInfo &appInfo)
1482 {
1483 clips_.ComputeIfPresent(appInfo.userId, [this](auto, auto &clip) {
1484 RevokeUriPermission(clip);
1485 return false;
1486 });
1487 delayGetters_.ComputeIfPresent(appInfo.userId, [](auto, auto &delayGetter) {
1488 RADAR_REPORT(DFX_SET_PASTEBOARD, DFX_CHECK_SET_DELAY_COPY, DFX_SUCCESS, COVER_DELAY_DATA, DFX_SUCCESS);
1489 if (delayGetter.first != nullptr && delayGetter.second != nullptr) {
1490 delayGetter.first->AsObject()->RemoveDeathRecipient(delayGetter.second);
1491 }
1492 return false;
1493 });
1494 entryGetters_.ComputeIfPresent(appInfo.userId, [](auto, auto &entryGetter) {
1495 if (entryGetter.first != nullptr && entryGetter.second != nullptr) {
1496 entryGetter.first->AsObject()->RemoveDeathRecipient(entryGetter.second);
1497 }
1498 return false;
1499 });
1500 }
1501
SetWebViewPasteData(PasteData & pasteData,const std::string & bundleName)1502 void PasteboardService::SetWebViewPasteData(PasteData &pasteData, const std::string &bundleName)
1503 {
1504 if (pasteData.GetTag() != PasteData::WEBVIEW_PASTEDATA_TAG) {
1505 return;
1506 }
1507 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "PasteboardService for webview.");
1508 for (auto &item : pasteData.AllRecords()) {
1509 if (item->GetUri() == nullptr || item->GetFrom() == 0 || item->GetRecordId() == item->GetFrom()) {
1510 continue;
1511 }
1512 std::shared_ptr<Uri> uri = item->GetUri();
1513 std::string puri = uri->ToString();
1514 if (puri.substr(0, PasteData::IMG_LOCAL_URI.size()) == PasteData::IMG_LOCAL_URI &&
1515 puri.find(PasteData::FILE_SCHEME_PREFIX + PasteData::PATH_SHARE) == std::string::npos) {
1516 std::string path = uri->GetPath();
1517 std::string newUriStr = PasteData::FILE_SCHEME_PREFIX + bundleName + path;
1518 item->SetUri(std::make_shared<OHOS::Uri>(newUriStr));
1519 }
1520 }
1521 }
1522
GetCurrentAccountId()1523 int32_t PasteboardService::GetCurrentAccountId()
1524 {
1525 if (currentUserId != ERROR_USERID) {
1526 return currentUserId;
1527 }
1528 std::vector<int32_t> accountIds;
1529 auto ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds);
1530 if (ret != ERR_OK || accountIds.empty()) {
1531 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "query active user failed errCode=%{public}d", ret);
1532 return ERROR_USERID;
1533 }
1534 currentUserId = accountIds.front();
1535 return currentUserId;
1536 }
1537
GetCurrentScreenStatus()1538 ScreenEvent PasteboardService::GetCurrentScreenStatus()
1539 {
1540 if (currentScreenStatus != ScreenEvent::Default) {
1541 return currentScreenStatus;
1542 }
1543
1544 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "query current screen status failed.");
1545 return ScreenEvent::Default;
1546 }
1547
IsCopyable(uint32_t tokenId) const1548 bool PasteboardService::IsCopyable(uint32_t tokenId) const
1549 {
1550 #ifdef WITH_DLP
1551 bool copyable = false;
1552 auto ret = Security::DlpPermission::DlpPermissionKit::QueryDlpFileCopyableByTokenId(copyable, tokenId);
1553 if (ret != 0 || !copyable) {
1554 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "tokenId = 0x%{public}x ret = %{public}d, copyable = %{public}d.",
1555 tokenId, ret, copyable);
1556 return false;
1557 }
1558 #endif
1559 return true;
1560 }
1561
SubscribeObserver(PasteboardObserverType type,const sptr<IPasteboardChangedObserver> & observer)1562 void PasteboardService::SubscribeObserver(PasteboardObserverType type,
1563 const sptr<IPasteboardChangedObserver> &observer)
1564 {
1565 bool isEventType = static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_EVENT);
1566 int32_t userId = isEventType ? COMMON_USERID : GetCurrentAccountId();
1567 if (userId == ERROR_USERID) {
1568 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
1569 return;
1570 }
1571 if (static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_LOCAL)) {
1572 AddObserver(userId, observer, observerLocalChangedMap_);
1573 }
1574
1575 if (static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_REMOTE)) {
1576 AddObserver(userId, observer, observerRemoteChangedMap_);
1577 }
1578
1579 if (isEventType && IsCallerUidValid()) {
1580 AddObserver(userId, observer, observerEventMap_);
1581 }
1582 }
1583
UnsubscribeObserver(PasteboardObserverType type,const sptr<IPasteboardChangedObserver> & observer)1584 void PasteboardService::UnsubscribeObserver(PasteboardObserverType type,
1585 const sptr<IPasteboardChangedObserver> &observer)
1586 {
1587 bool isEventType = static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_EVENT);
1588 int32_t userId = isEventType ? COMMON_USERID : GetCurrentAccountId();
1589 if (userId == ERROR_USERID) {
1590 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
1591 return;
1592 }
1593 if (static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_LOCAL)) {
1594 RemoveSingleObserver(userId, observer, observerLocalChangedMap_);
1595 }
1596
1597 if (static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_REMOTE)) {
1598 RemoveSingleObserver(userId, observer, observerRemoteChangedMap_);
1599 }
1600
1601 if (isEventType && IsCallerUidValid()) {
1602 RemoveSingleObserver(userId, observer, observerEventMap_);
1603 }
1604 }
1605
UnsubscribeAllObserver(PasteboardObserverType type)1606 void PasteboardService::UnsubscribeAllObserver(PasteboardObserverType type)
1607 {
1608 bool isEventType = static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_EVENT);
1609 int32_t userId = isEventType ? COMMON_USERID : GetCurrentAccountId();
1610 if (userId == ERROR_USERID) {
1611 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
1612 return;
1613 }
1614 if (static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_LOCAL)) {
1615 RemoveAllObserver(userId, observerLocalChangedMap_);
1616 }
1617
1618 if (static_cast<uint32_t>(type) & static_cast<uint32_t>(PasteboardObserverType::OBSERVER_REMOTE)) {
1619 RemoveAllObserver(userId, observerRemoteChangedMap_);
1620 }
1621
1622 if (isEventType && IsCallerUidValid()) {
1623 RemoveAllObserver(userId, observerEventMap_);
1624 }
1625 }
1626
AddObserver(int32_t userId,const sptr<IPasteboardChangedObserver> & observer,ObserverMap & observerMap)1627 void PasteboardService::AddObserver(int32_t userId, const sptr<IPasteboardChangedObserver> &observer,
1628 ObserverMap &observerMap)
1629 {
1630 if (observer == nullptr) {
1631 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "observer null.");
1632 return;
1633 }
1634 std::lock_guard<std::mutex> lock(observerMutex_);
1635 auto it = observerMap.find(userId);
1636 std::shared_ptr<std::set<sptr<IPasteboardChangedObserver>, classcomp>> observers;
1637 if (it != observerMap.end()) {
1638 observers = it->second;
1639 } else {
1640 observers = std::make_shared<std::set<sptr<IPasteboardChangedObserver>, classcomp>>();
1641 observerMap.insert(std::make_pair(userId, observers));
1642 }
1643 observers->insert(observer);
1644 RADAR_REPORT(DFX_OBSERVER, DFX_ADD_OBSERVER, DFX_SUCCESS);
1645 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "observers->size = %{public}u.",
1646 static_cast<unsigned int>(observers->size()));
1647 }
1648
RemoveSingleObserver(int32_t userId,const sptr<IPasteboardChangedObserver> & observer,ObserverMap & observerMap)1649 void PasteboardService::RemoveSingleObserver(int32_t userId, const sptr<IPasteboardChangedObserver> &observer,
1650 ObserverMap &observerMap)
1651 {
1652 if (observer == nullptr) {
1653 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "observer null.");
1654 return;
1655 }
1656 std::lock_guard<std::mutex> lock(observerMutex_);
1657 auto it = observerMap.find(userId);
1658 if (it == observerMap.end()) {
1659 return;
1660 }
1661 auto observers = it->second;
1662 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "observers size: %{public}u.",
1663 static_cast<unsigned int>(observers->size()));
1664 auto eraseNum = observers->erase(observer);
1665 RADAR_REPORT(DFX_OBSERVER, DFX_REMOVE_SINGLE_OBSERVER, DFX_SUCCESS);
1666 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "observers size = %{public}u, eraseNum = %{public}zu",
1667 static_cast<unsigned int>(observers->size()), eraseNum);
1668 }
1669
RemoveAllObserver(int32_t userId,ObserverMap & observerMap)1670 void PasteboardService::RemoveAllObserver(int32_t userId, ObserverMap &observerMap)
1671 {
1672 std::lock_guard<std::mutex> lock(observerMutex_);
1673 auto it = observerMap.find(userId);
1674 if (it == observerMap.end()) {
1675 PASTEBOARD_HILOGW(PASTEBOARD_MODULE_SERVICE, "observer empty.");
1676 return;
1677 }
1678 auto observers = it->second;
1679 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "observers size: %{public}u.",
1680 static_cast<unsigned int>(observers->size()));
1681 auto eraseNum = observerMap.erase(userId);
1682 RADAR_REPORT(DFX_OBSERVER, DFX_REMOVE_ALL_OBSERVER, DFX_SUCCESS);
1683 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "observers size = %{public}u, eraseNum = %{public}zu",
1684 static_cast<unsigned int>(observers->size()), eraseNum);
1685 }
1686
SetGlobalShareOption(const std::map<uint32_t,ShareOption> & globalShareOptions)1687 int32_t PasteboardService::SetGlobalShareOption(const std::map<uint32_t, ShareOption> &globalShareOptions)
1688 {
1689 if (!IsCallerUidValid()) {
1690 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "No Permission");
1691 return static_cast<int32_t>(PasteboardError::PERMISSION_VERIFICATION_ERROR);
1692 }
1693 for (const auto &[tokenId, shareOption] : globalShareOptions) {
1694 GlobalShareOption option = {.source = MDM, .shareOption = shareOption};
1695 globalShareOptions_.InsertOrAssign(tokenId, option);
1696 }
1697 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Set %{public}zu global shareOption.", globalShareOptions.size());
1698 return ERR_OK;
1699 }
1700
RemoveGlobalShareOption(const std::vector<uint32_t> & tokenIds)1701 int32_t PasteboardService::RemoveGlobalShareOption(const std::vector<uint32_t> &tokenIds)
1702 {
1703 if (!IsCallerUidValid()) {
1704 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "No Permission");
1705 return static_cast<int32_t>(PasteboardError::PERMISSION_VERIFICATION_ERROR);
1706 }
1707 int32_t count = 0;
1708 for (const uint32_t &tokenId : tokenIds) {
1709 globalShareOptions_.ComputeIfPresent(tokenId, [&count](const uint32_t &key, GlobalShareOption &value) {
1710 count++;
1711 return false;
1712 });
1713 }
1714 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Remove %{public}d global shareOption.", count);
1715 return ERR_OK;
1716 }
1717
GetGlobalShareOption(const std::vector<uint32_t> & tokenIds)1718 std::map<uint32_t, ShareOption> PasteboardService::GetGlobalShareOption(const std::vector<uint32_t> &tokenIds)
1719 {
1720 if (!IsCallerUidValid()) {
1721 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "No Permission");
1722 return {};
1723 }
1724 std::map<uint32_t, ShareOption> result;
1725 if (tokenIds.empty()) {
1726 globalShareOptions_.ForEach([&result](const uint32_t &key, GlobalShareOption &value) {
1727 result[key] = value.shareOption;
1728 return false;
1729 });
1730 return result;
1731 }
1732 for (const uint32_t &tokenId : tokenIds) {
1733 globalShareOptions_.ComputeIfPresent(tokenId, [&result](const uint32_t &key, GlobalShareOption &value) {
1734 result[key] = value.shareOption;
1735 return true;
1736 });
1737 }
1738 return result;
1739 }
1740
SetAppShareOptions(const ShareOption & shareOptions)1741 int32_t PasteboardService::SetAppShareOptions(const ShareOption &shareOptions)
1742 {
1743 auto fullTokenId = IPCSkeleton::GetCallingFullTokenID();
1744 auto tokenId = IPCSkeleton::GetCallingTokenID();
1745 if (!OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
1746 if (shareOptions != InApp) {
1747 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "param is invalid");
1748 return static_cast<int32_t>(PasteboardError::INVALID_PARAM_ERROR);
1749 }
1750 auto isManageGrant = IsPermissionGranted(MANAGE_PASTEBOARD_APP_SHARE_OPTION_PERMISSION, tokenId);
1751 if (!isManageGrant) {
1752 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "No permission, token id: 0x%{public}x.", tokenId);
1753 return static_cast<int32_t>(PasteboardError::PERMISSION_VERIFICATION_ERROR);
1754 }
1755 }
1756 GlobalShareOption option = {.source = APP, .shareOption = shareOptions};
1757 auto isAbsent = globalShareOptions_.ComputeIfAbsent(tokenId, [&option](const uint32_t &tokenId) {
1758 return option;
1759 });
1760 if (!isAbsent) {
1761 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "Settings already exist, token id: 0x%{public}x.", tokenId);
1762 return static_cast<int32_t>(PasteboardError::INVALID_OPERATION_ERROR);
1763 }
1764 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Set token id: 0x%{public}x share options: %{public}d success.",
1765 tokenId, shareOptions);
1766 return 0;
1767 }
1768
RemoveAppShareOptions()1769 int32_t PasteboardService::RemoveAppShareOptions()
1770 {
1771 auto fullTokenId = IPCSkeleton::GetCallingFullTokenID();
1772 auto tokenId = IPCSkeleton::GetCallingTokenID();
1773 if (!OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
1774 auto isManageGrant = IsPermissionGranted(MANAGE_PASTEBOARD_APP_SHARE_OPTION_PERMISSION, tokenId);
1775 if (!isManageGrant) {
1776 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "No permission, token id: 0x%{public}x.", tokenId);
1777 return static_cast<int32_t>(PasteboardError::PERMISSION_VERIFICATION_ERROR);
1778 }
1779 }
1780 std::map<uint32_t, GlobalShareOption> result;
1781 globalShareOptions_.ComputeIfPresent(tokenId, [&result](const uint32_t &key, GlobalShareOption &value) {
1782 result[key] = value;
1783 return true;
1784 });
1785 if (!result.empty()) {
1786 if (result[tokenId].source == APP) {
1787 globalShareOptions_.Erase(tokenId);
1788 PASTEBOARD_HILOGI(
1789 PASTEBOARD_MODULE_SERVICE, "Remove token id: 0x%{public}x share options success.", tokenId);
1790 return 0;
1791 } else {
1792 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Can not remove token id: 0x%{public}x.", tokenId);
1793 return 0;
1794 }
1795 }
1796 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "This token id: 0x%{public}x not set.", tokenId);
1797 return 0;
1798 }
1799
UpdateShareOption(PasteData & pasteData)1800 void PasteboardService::UpdateShareOption(PasteData &pasteData)
1801 {
1802 globalShareOptions_.ComputeIfPresent(
1803 pasteData.GetTokenId(), [&pasteData](const uint32_t &tokenId, GlobalShareOption &option) {
1804 pasteData.SetShareOption(option.shareOption);
1805 return true;
1806 });
1807 }
1808
CheckMdmShareOption(PasteData & pasteData)1809 bool PasteboardService::CheckMdmShareOption(PasteData &pasteData)
1810 {
1811 bool result = false;
1812 globalShareOptions_.ComputeIfPresent(
1813 pasteData.GetTokenId(), [&result](const uint32_t &tokenId, GlobalShareOption &option) {
1814 if (option.source == MDM) {
1815 result = true;
1816 }
1817 return true;
1818 });
1819 return result;
1820 }
1821
IsCallerUidValid()1822 inline bool PasteboardService::IsCallerUidValid()
1823 {
1824 pid_t callingUid = IPCSkeleton::GetCallingUid();
1825 if (callingUid == EDM_UID || (uid_ != -1 && callingUid == uid_)) {
1826 return true;
1827 }
1828 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "callingUid error: %{public}d.", callingUid);
1829 return false;
1830 }
1831
NotifyObservers(std::string bundleName,PasteboardEventStatus status)1832 void PasteboardService::NotifyObservers(std::string bundleName, PasteboardEventStatus status)
1833 {
1834 std::thread thread([this, bundleName, status] () {
1835 std::lock_guard<std::mutex> lock(observerMutex_);
1836 for (auto &observers : observerLocalChangedMap_) {
1837 for (const auto &observer : *(observers.second)) {
1838 if (status != PasteboardEventStatus::PASTEBOARD_READ) {
1839 observer->OnPasteboardChanged();
1840 }
1841 }
1842 }
1843 for (auto &observers : observerEventMap_) {
1844 for (const auto &observer : *(observers.second)) {
1845 observer->OnPasteboardEvent(bundleName, static_cast<int32_t>(status));
1846 }
1847 }
1848 });
1849 thread.detach();
1850 }
1851
GetDataSize(PasteData & data) const1852 size_t PasteboardService::GetDataSize(PasteData &data) const
1853 {
1854 if (data.GetRecordCount() != 0) {
1855 size_t counts = data.GetRecordCount() - 1;
1856 std::shared_ptr<PasteDataRecord> records = data.GetRecordAt(counts);
1857 std::string text = records->ConvertToText();
1858 size_t textSize = text.size();
1859 return textSize;
1860 }
1861 return GET_WRONG_SIZE;
1862 }
1863
SetPasteboardHistory(HistoryInfo & info)1864 bool PasteboardService::SetPasteboardHistory(HistoryInfo &info)
1865 {
1866 std::string history = std::move(info.time) + " " + std::move(info.bundleName) + " " + std::move(info.state) + " " +
1867 " " + std::move(info.remote);
1868 constexpr const size_t DATA_HISTORY_SIZE = 10;
1869 std::lock_guard<decltype(historyMutex_)> lg(historyMutex_);
1870 if (dataHistory_.size() == DATA_HISTORY_SIZE) {
1871 dataHistory_.erase(dataHistory_.begin());
1872 }
1873 dataHistory_.push_back(std::move(history));
1874 return true;
1875 }
1876
Dump(int fd,const std::vector<std::u16string> & args)1877 int PasteboardService::Dump(int fd, const std::vector<std::u16string> &args)
1878 {
1879 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
1880 const int maxUid = 10000;
1881 if (uid > maxUid) {
1882 return 0;
1883 }
1884
1885 std::vector<std::string> argsStr;
1886 for (auto item : args) {
1887 argsStr.emplace_back(Str16ToStr8(item));
1888 }
1889
1890 if (PasteboardDumpHelper::GetInstance().Dump(fd, argsStr)) {
1891 return 0;
1892 }
1893 return 0;
1894 }
1895
GetTime()1896 std::string PasteboardService::GetTime()
1897 {
1898 constexpr int USEC_TO_MSEC = 1000;
1899 time_t timeSeconds = time(0);
1900 if (timeSeconds == -1) {
1901 return FAIL_TO_GET_TIME_STAMP;
1902 }
1903 struct tm nowTime;
1904 localtime_r(&timeSeconds, &nowTime);
1905
1906 struct timeval timeVal = { 0, 0 };
1907 gettimeofday(&timeVal, nullptr);
1908
1909 std::string targetTime = std::to_string(nowTime.tm_year + 1900) + "-" + std::to_string(nowTime.tm_mon + 1) + "-" +
1910 std::to_string(nowTime.tm_mday) + " " + std::to_string(nowTime.tm_hour) + ":" +
1911 std::to_string(nowTime.tm_min) + ":" + std::to_string(nowTime.tm_sec) + "." +
1912 std::to_string(timeVal.tv_usec / USEC_TO_MSEC);
1913 return targetTime;
1914 }
1915
DumpHistory() const1916 std::string PasteboardService::DumpHistory() const
1917 {
1918 std::string result;
1919 std::lock_guard<decltype(historyMutex_)> lg(historyMutex_);
1920 if (!dataHistory_.empty()) {
1921 result.append("Access history last ten times: ").append("\n");
1922 for (auto iter = dataHistory_.rbegin(); iter != dataHistory_.rend(); ++iter) {
1923 result.append(" ").append(*iter).append("\n");
1924 }
1925 } else {
1926 result.append("Access history fail! dataHistory_ no data.").append("\n");
1927 }
1928 return result;
1929 }
1930
DumpData()1931 std::string PasteboardService::DumpData()
1932 {
1933 auto userId = GetCurrentAccountId();
1934 if (userId == ERROR_USERID) {
1935 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "query active user failed.");
1936 return "";
1937 }
1938 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "id = %{public}d", userId);
1939 auto it = clips_.Find(userId);
1940 std::string result;
1941 if (it.first && it.second != nullptr) {
1942 size_t recordCounts = it.second->GetRecordCount();
1943 auto property = it.second->GetProperty();
1944 std::string shareOption;
1945 PasteData::ShareOptionToString(property.shareOption, shareOption);
1946 std::string sourceDevice;
1947 if (property.isRemote) {
1948 sourceDevice = "remote";
1949 } else {
1950 sourceDevice = "local";
1951 }
1952 result.append("|Owner : ")
1953 .append(property.bundleName)
1954 .append("\n")
1955 .append("|Timestamp : ")
1956 .append(property.setTime)
1957 .append("\n")
1958 .append("|Share Option: ")
1959 .append(shareOption)
1960 .append("\n")
1961 .append("|Record Count: ")
1962 .append(std::to_string(recordCounts))
1963 .append("\n")
1964 .append("|Mime types : {");
1965 if (!property.mimeTypes.empty()) {
1966 for (size_t i = 0; i < property.mimeTypes.size(); ++i) {
1967 result.append(property.mimeTypes[i]).append(",");
1968 }
1969 }
1970 result.append("}").append("\n").append("|source device: ").append(sourceDevice);
1971 } else {
1972 result.append("No copy data.").append("\n");
1973 }
1974 return result;
1975 }
1976
IsFocusedApp(uint32_t tokenId)1977 bool PasteboardService::IsFocusedApp(uint32_t tokenId)
1978 {
1979 if (AccessTokenKit::GetTokenTypeFlag(tokenId) != ATokenTypeEnum::TOKEN_HAP) {
1980 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "caller is not application");
1981 return true;
1982 }
1983 FocusChangeInfo info;
1984 #ifdef SCENE_BOARD_ENABLE
1985 WindowManagerLite::GetInstance().GetFocusWindowInfo(info);
1986 #else
1987 WindowManager::GetInstance().GetFocusWindowInfo(info);
1988 #endif
1989 auto callPid = IPCSkeleton::GetCallingPid();
1990 if (callPid == info.pid_) {
1991 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "pid is same, it is focused app");
1992 return true;
1993 }
1994 bool isFocused = false;
1995 auto ret = AAFwk::AbilityManagerClient::GetInstance()->CheckUIExtensionIsFocused(tokenId, isFocused);
1996 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "check result:%{public}d, isFocused:%{public}d", ret, isFocused);
1997 return ret == NO_ERROR && isFocused;
1998 }
1999
SetPasteDataDot(PasteData & pasteData)2000 void PasteboardService::SetPasteDataDot(PasteData &pasteData)
2001 {
2002 auto bundleName = pasteData.GetBundleName();
2003 HistoryInfo info{ pasteData.GetTime(), bundleName, "set", "" };
2004 SetPasteboardHistory(info);
2005
2006 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "SetPasteData Report!");
2007 Reporter::GetInstance().PasteboardBehaviour().Report(
2008 { static_cast<int>(BehaviourPasteboardState::BPS_COPY_STATE), bundleName });
2009
2010 int state = static_cast<int>(StatisticPasteboardState::SPS_COPY_STATE);
2011 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "SetPasteData GetDataSize!");
2012 size_t dataSize = GetDataSize(pasteData);
2013 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "SetPasteData timeC!");
2014 CalculateTimeConsuming timeC(dataSize, state);
2015 }
2016
GetPasteDataDot(PasteData & pasteData,const std::string & bundleName)2017 void PasteboardService::GetPasteDataDot(PasteData &pasteData, const std::string &bundleName)
2018 {
2019 std::string remote;
2020 if (pasteData.IsRemote()) {
2021 remote = "remote";
2022 }
2023 std::string time = GetTime();
2024 HistoryInfo info{ time, bundleName, "get", remote };
2025 SetPasteboardHistory(info);
2026 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "GetPasteData Report!");
2027 int pState = StatisticPasteboardState::SPS_INVALID_STATE;
2028 int bState = BehaviourPasteboardState::BPS_INVALID_STATE;
2029 if (pasteData.IsRemote()) {
2030 pState = static_cast<int>(StatisticPasteboardState::SPS_REMOTE_PASTE_STATE);
2031 bState = static_cast<int>(BehaviourPasteboardState::BPS_REMOTE_PASTE_STATE);
2032 } else {
2033 pState = static_cast<int>(StatisticPasteboardState::SPS_PASTE_STATE);
2034 bState = static_cast<int>(BehaviourPasteboardState::BPS_PASTE_STATE);
2035 };
2036
2037 Reporter::GetInstance().PasteboardBehaviour().Report({ bState, bundleName });
2038
2039 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "GetPasteData GetDataSize");
2040 size_t dataSize = GetDataSize(pasteData);
2041 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "GetPasteData timeC");
2042 CalculateTimeConsuming timeC(dataSize, pState);
2043 }
2044
GetDistributedData(const Event & event,int32_t user)2045 std::pair<std::shared_ptr<PasteData>, PasteDateResult> PasteboardService::GetDistributedData(const Event &event,
2046 int32_t user)
2047 {
2048 auto clipPlugin = GetClipPlugin();
2049 PasteDateResult pasteDateResult;
2050 if (clipPlugin == nullptr) {
2051 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "clipPlugin null.");
2052 pasteDateResult.syncTime = -1;
2053 pasteDateResult.errorCode = static_cast<int32_t>(PasteboardError::REMOTE_TASK_ERROR);
2054 return std::make_pair(nullptr, pasteDateResult);
2055 }
2056 std::vector<uint8_t> rawData;
2057 auto result = clipPlugin->GetPasteData(event, rawData);
2058 if (result.first != 0) {
2059 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "get data failed");
2060 Reporter::GetInstance().PasteboardFault().Report({ user, "GET_REMOTE_DATA_FAILED" });
2061 pasteDateResult.syncTime = -1;
2062 pasteDateResult.errorCode = result.first;
2063 return std::make_pair(nullptr, pasteDateResult);
2064 }
2065
2066 currentEvent_ = std::move(event);
2067 std::shared_ptr<PasteData> pasteData = std::make_shared<PasteData>();
2068 pasteData->Decode(rawData);
2069 pasteData->ReplaceShareUri(user);
2070 pasteData->SetOrginAuthority(pasteData->GetBundleName());
2071 for (size_t i = 0; i < pasteData->GetRecordCount(); i++) {
2072 auto item = pasteData->GetRecordAt(i);
2073 if (item == nullptr || item->GetConvertUri().empty()) {
2074 continue;
2075 }
2076 item->isConvertUriFromRemote = true;
2077 }
2078 pasteDateResult.syncTime = result.second;
2079 pasteDateResult.errorCode = static_cast<int32_t>(PasteboardError::E_OK);
2080 return std::make_pair(pasteData, pasteDateResult);
2081 }
2082
IsAllowSendData()2083 bool PasteboardService::IsAllowSendData()
2084 {
2085 auto contralType = system::GetIntParameter(TRANSMIT_CONTROL_PROP_KEY, CONTROL_TYPE_ALLOW_SEND_RECEIVE, INT_MIN,
2086 INT_MAX);
2087 if (contralType != CONTROL_TYPE_ALLOW_SEND_RECEIVE) {
2088 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "control type is: %{public}d.", contralType);
2089 return false;
2090 }
2091 return true;
2092 }
2093
GenerateDataType(PasteData & data)2094 uint8_t PasteboardService::GenerateDataType(PasteData &data)
2095 {
2096 std::vector<std::string> mimeTypes = data.GetMimeTypes();
2097 if (mimeTypes.empty()) {
2098 return 0;
2099 }
2100 std::bitset<MAX_INDEX_LENGTH> dataType(0);
2101 for (size_t i = 0; i < mimeTypes.size(); i++) {
2102 auto it = typeMap_.find(mimeTypes[i]);
2103 if (it == typeMap_.end()) {
2104 continue;
2105 }
2106 auto index = it->second;
2107 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "mimetype is exist index=%{public}d", index);
2108 if (it->second == HTML_INDEX && data.GetTag() == PasteData::WEBVIEW_PASTEDATA_TAG) {
2109 dataType.reset();
2110 dataType.set(index);
2111 break;
2112 }
2113 dataType.set(index);
2114 }
2115 auto types = dataType.to_ulong();
2116 uint8_t value = types & 0xff;
2117 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "value = %{public}d", value);
2118 return value;
2119 }
2120
SetDistributedData(int32_t user,PasteData & data)2121 bool PasteboardService::SetDistributedData(int32_t user, PasteData &data)
2122 {
2123 if (!IsAllowSendData()) {
2124 return false;
2125 }
2126 ShareOption shareOpt = data.GetShareOption();
2127 PASTEBOARD_CHECK_AND_RETURN_RET_LOGE(shareOpt != InApp, false, PASTEBOARD_MODULE_SERVICE,
2128 "data share option is in app, dataId:%{public}u", data.GetDataId());
2129 if (CheckMdmShareOption(data)) {
2130 PASTEBOARD_CHECK_AND_RETURN_RET_LOGE(shareOpt != LocalDevice, false, PASTEBOARD_MODULE_SERVICE,
2131 "data share option is local device, dataId:%{public}u", data.GetDataId());
2132 }
2133 auto networkId = DMAdapter::GetInstance().GetLocalNetworkId();
2134 PASTEBOARD_CHECK_AND_RETURN_RET_LOGE(!networkId.empty(), false, PASTEBOARD_MODULE_SERVICE, "networkId is empty.");
2135 auto clipPlugin = GetClipPlugin();
2136 if (clipPlugin == nullptr) {
2137 RADAR_REPORT(DFX_SET_PASTEBOARD, DFX_CHECK_ONLINE_DEVICE, DFX_SUCCESS);
2138 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "clip plugin is null, dataId:%{public}u", data.GetDataId());
2139 return false;
2140 }
2141 RADAR_REPORT(DFX_SET_PASTEBOARD, DFX_LOAD_DISTRIBUTED_PLUGIN, DFX_SUCCESS);
2142 Event event;
2143 event.user = user;
2144 event.seqId = ++sequenceId_;
2145 auto expiration =
2146 duration_cast<milliseconds>((system_clock::now() + minutes(EXPIRATION_INTERVAL)).time_since_epoch()).count();
2147 event.expiration = static_cast<uint64_t>(expiration);
2148 event.deviceId = networkId;
2149 event.account = AccountManager::GetInstance().GetCurrentAccount();
2150 event.status = ClipPlugin::EVT_NORMAL;
2151 event.dataType = data.GetMimeTypes();
2152 currentEvent_ = event;
2153 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "dataId:%{public}u, seqId:%{public}hu, expiration:%{public}" PRIu64,
2154 data.GetDataId(), event.seqId, event.expiration);
2155 std::thread thread([this, clipPlugin, event, user, data]() mutable {
2156 if (data.IsDelayRecord()) {
2157 GetFullDelayPasteData(user, data);
2158 }
2159 GenerateDistributedUri(data);
2160 std::vector<uint8_t> rawData;
2161 if (!data.Encode(rawData)) {
2162 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
2163 "distributed data encode failed, dataId:%{public}u, seqId:%{public}hu", data.GetDataId(), event.seqId);
2164 } else {
2165 clipPlugin->SetPasteData(event, rawData);
2166 }
2167 });
2168 thread.detach();
2169 return true;
2170 }
2171
GetFullDelayPasteData(int32_t userId,PasteData & data)2172 void PasteboardService::GetFullDelayPasteData(int32_t userId, PasteData &data)
2173 {
2174 PASTEBOARD_HILOGD(PASTEBOARD_MODULE_SERVICE, "start, userId is %{public}d", userId);
2175 auto entryGetter = entryGetters_.Find(userId);
2176 if (!entryGetter.first) {
2177 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "entry getter is nullptr, userId is %{public}d", userId);
2178 return;
2179 }
2180 auto getter = entryGetter.second;
2181 if (getter.first == nullptr) {
2182 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "entry getter is nullptr, dataId is %{public}d", data.GetDataId());
2183 return;
2184 }
2185 for (auto record : data.AllRecords()) {
2186 if (!record->IsDelayRecord()) {
2187 continue;
2188 }
2189 auto recordId = record->GetRecordId();
2190 auto mimeType = record->GetMimeType();
2191 for (auto entry : record->GetEntries()) {
2192 if (!std::holds_alternative<std::monostate>(entry->GetValue())) {
2193 continue;
2194 }
2195 auto result = getter.first->GetRecordValueByType(recordId, *entry);
2196 if (result != static_cast<int32_t>(PasteboardError::E_OK)) {
2197 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
2198 "get record value fail, dataId is %{public}d, recordId is %{public}d, mimeType is %{public}s",
2199 data.GetDataId(), record->GetRecordId(), entry->GetMimeType().c_str());
2200 continue;
2201 }
2202 if (entry->GetMimeType() == mimeType) {
2203 record->AddEntry(entry->GetUtdId(), std::make_shared<PasteDataEntry>(*entry));
2204 }
2205 }
2206 }
2207 clips_.ComputeIfPresent(userId, [&data](auto, auto &value) {
2208 if (data.GetDataId() != value->GetDataId()) {
2209 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE,
2210 "set data fail, data is out time, pre dataId is %{public}d, cur dataId is %{public}d",
2211 data.GetDataId(), value->GetDataId());
2212 return true;
2213 }
2214 value = std::make_shared<PasteData>(data);
2215 return true;
2216 });
2217 }
2218
GenerateDistributedUri(PasteData & data)2219 void PasteboardService::GenerateDistributedUri(PasteData &data)
2220 {
2221 std::vector<std::string> uris;
2222 std::vector<size_t> indexs;
2223 auto userId = GetCurrentAccountId();
2224 if (userId == ERROR_USERID) {
2225 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "userId invalid.");
2226 return;
2227 }
2228 for (size_t i = 0; i < data.GetRecordCount(); i++) {
2229 auto item = data.GetRecordAt(i);
2230 if (item == nullptr || item->GetOrginUri() == nullptr) {
2231 continue;
2232 }
2233 Uri uri = *(item->GetOrginUri());
2234 if (!IsBundleOwnUriPermission(data.GetOrginAuthority(), uri) && !item->HasGrantUriPermission()) {
2235 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "orginuri=%{public}s, no permission", uri.ToString().c_str());
2236 continue;
2237 }
2238 uris.emplace_back(uri.ToString());
2239 indexs.emplace_back(i);
2240 }
2241 size_t fileSize = 0;
2242 std::unordered_map<std::string, HmdfsUriInfo> dfsUris;
2243 if (!uris.empty()) {
2244 int ret = RemoteFileShare::GetDfsUrisFromLocal(uris, userId, dfsUris);
2245 if (ret != 0 || dfsUris.empty()) {
2246 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "Get remoteUri failed, ret = %{public}d, userId: %{public}d,"
2247 "uri size:%{public}zu.", ret, userId, uris.size());
2248 return;
2249 }
2250 for (size_t i = 0; i < indexs.size(); i++) {
2251 auto item = data.GetRecordAt(indexs[i]);
2252 if (item == nullptr || item->GetOrginUri() == nullptr) {
2253 continue;
2254 }
2255 auto it = dfsUris.find(item->GetOrginUri()->ToString());
2256 if (it != dfsUris.end()) {
2257 item->SetConvertUri(it->second.uriStr);
2258 fileSize += it->second.fileSize;
2259 }
2260 }
2261 }
2262 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "file size: %{public}zu", fileSize);
2263 int32_t fileIntSize = (fileSize > INT_MAX) ? INT_MAX : static_cast<int32_t>(fileSize);
2264 data.SetAddition(PasteData::REMOTE_FILE_SIZE, AAFwk::Integer::Box(fileIntSize));
2265 data.SetAddition(PasteData::REMOTE_FILE_SIZE_LONG, AAFwk::Long::Box(fileSize));
2266 }
2267
GetClipPlugin()2268 std::shared_ptr<ClipPlugin> PasteboardService::GetClipPlugin()
2269 {
2270 auto isOn = moduleConfig_.IsOn();
2271 if (isOn) {
2272 auto securityLevel = securityLevel_.GetDeviceSecurityLevel();
2273 if (securityLevel < DATA_SEC_LEVEL3) {
2274 return nullptr;
2275 }
2276 }
2277 std::lock_guard<decltype(mutex)> lockGuard(mutex);
2278 if (!isOn || clipPlugin_ != nullptr) {
2279 return clipPlugin_;
2280 }
2281 auto release = [this](ClipPlugin *plugin) {
2282 std::lock_guard<decltype(mutex)> lockGuard(mutex);
2283 ClipPlugin::DestroyPlugin(PLUGIN_NAME, plugin);
2284 };
2285
2286 clipPlugin_ = std::shared_ptr<ClipPlugin>(ClipPlugin::CreatePlugin(PLUGIN_NAME), release);
2287 return clipPlugin_;
2288 }
2289
CleanDistributedData(int32_t user)2290 bool PasteboardService::CleanDistributedData(int32_t user)
2291 {
2292 auto clipPlugin = GetClipPlugin();
2293 if (clipPlugin == nullptr) {
2294 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "clipPlugin null.");
2295 return true;
2296 }
2297 clipPlugin->Clear(user);
2298 return true;
2299 }
2300
OnConfigChange(bool isOn)2301 void PasteboardService::OnConfigChange(bool isOn)
2302 {
2303 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "ConfigChange isOn: %{public}d.", isOn);
2304 p2pMap_.Clear();
2305 std::lock_guard<decltype(mutex)> lockGuard(mutex);
2306 if (!isOn) {
2307 clipPlugin_ = nullptr;
2308 return;
2309 }
2310 auto securityLevel = securityLevel_.GetDeviceSecurityLevel();
2311 if (securityLevel < DATA_SEC_LEVEL3) {
2312 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, "device sec level is %{public}u less than 3.", securityLevel);
2313 return;
2314 }
2315 if (clipPlugin_ != nullptr) {
2316 return;
2317 }
2318 SubscribeKeyboardEvent();
2319 auto release = [this](ClipPlugin *plugin) {
2320 std::lock_guard<decltype(mutex)> lockGuard(mutex);
2321 ClipPlugin::DestroyPlugin(PLUGIN_NAME, plugin);
2322 };
2323
2324 clipPlugin_ = std::shared_ptr<ClipPlugin>(ClipPlugin::CreatePlugin(PLUGIN_NAME), release);
2325 }
2326
GetAppLabel(uint32_t tokenId)2327 std::string PasteboardService::GetAppLabel(uint32_t tokenId)
2328 {
2329 auto iBundleMgr = GetAppBundleManager();
2330 if (iBundleMgr == nullptr) {
2331 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, " Failed to cast bundle mgr service.");
2332 return PasteBoardDialog::DEFAULT_LABEL;
2333 }
2334 AppInfo info = GetAppInfo(tokenId);
2335 AppExecFwk::ApplicationInfo appInfo;
2336 auto result = iBundleMgr->GetApplicationInfo(info.bundleName, 0, info.userId, appInfo);
2337 if (!result) {
2338 return PasteBoardDialog::DEFAULT_LABEL;
2339 }
2340 auto &resource = appInfo.labelResource;
2341 auto label = iBundleMgr->GetStringById(resource.bundleName, resource.moduleName, resource.id, info.userId);
2342 return label.empty() ? PasteBoardDialog::DEFAULT_LABEL : label;
2343 }
2344
GetAppBundleManager()2345 sptr<AppExecFwk::IBundleMgr> PasteboardService::GetAppBundleManager()
2346 {
2347 auto systemAbilityManager = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2348 if (systemAbilityManager == nullptr) {
2349 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, " Failed to get SystemAbilityManager.");
2350 return nullptr;
2351 }
2352 auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2353 if (remoteObject == nullptr) {
2354 PASTEBOARD_HILOGE(PASTEBOARD_MODULE_SERVICE, " Failed to get bundle mgr service.");
2355 return nullptr;
2356 }
2357 return OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
2358 }
2359
OnReceiveEvent(const EventFwk::CommonEventData & data)2360 void PasteBoardCommonEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data)
2361 {
2362 auto want = data.GetWant();
2363 std::string action = want.GetAction();
2364 if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
2365 std::lock_guard<std::mutex> lock(mutex_);
2366 int32_t userId = data.GetCode();
2367 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "user id switched: %{public}d", userId);
2368 PasteboardService::currentUserId = userId;
2369 } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) {
2370 std::lock_guard<std::mutex> lock(mutex_);
2371 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "screen is locked");
2372 PasteboardService::currentScreenStatus = ScreenEvent::ScreenLocked;
2373 } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED) {
2374 std::lock_guard<std::mutex> lock(mutex_);
2375 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "screen is unlocked");
2376 PasteboardService::currentScreenStatus = ScreenEvent::ScreenUnlocked;
2377 }
2378 }
2379
SubscribeKeyboardEvent()2380 bool PasteboardService::SubscribeKeyboardEvent()
2381 {
2382 std::lock_guard<std::mutex> lock(eventMutex_);
2383 if (inputEventCallback_ != nullptr) {
2384 return true;
2385 }
2386 inputEventCallback_ = std::make_shared<InputEventCallback>();
2387 int32_t monitorId =
2388 MMI::InputManager::GetInstance()->AddMonitor(std::static_pointer_cast<MMI::IInputEventConsumer>(
2389 inputEventCallback_));
2390 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "add monitor ret is: %{public}d", monitorId);
2391 return monitorId >= 0;
2392 }
2393
PasteboardEventSubscriber()2394 void PasteboardService::PasteboardEventSubscriber()
2395 {
2396 EventCenter::GetInstance().Subscribe(PasteboardEvent::DISCONNECT,
2397 [this](const OHOS::MiscServices::Event& event) {
2398 auto &evt = static_cast<const PasteboardEvent &>(event);
2399 auto networkId = evt.GetNetworkId();
2400 if (networkId.empty()) {
2401 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "networkId is empty.");
2402 return;
2403 }
2404 p2pMap_.EraseIf([networkId, this](auto &key, auto &value) {
2405 if (key == networkId) {
2406 CloseP2PLink(networkId);
2407 return true;
2408 }
2409 return false;
2410 });
2411 });
2412 }
2413
CommonEventSubscriber()2414 void PasteboardService::CommonEventSubscriber()
2415 {
2416 if (commonEventSubscriber_ != nullptr) {
2417 return;
2418 }
2419 EventFwk::MatchingSkills matchingSkills;
2420 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
2421 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED);
2422 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
2423 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
2424 commonEventSubscriber_ = std::make_shared<PasteBoardCommonEventSubscriber>(subscribeInfo);
2425 EventFwk::CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_);
2426 }
2427
AppExit(pid_t pid)2428 int32_t PasteboardService::AppExit(pid_t pid)
2429 {
2430 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "pid %{public}d exit.", pid);
2431 std::vector<std::string> networkIds;
2432 p2pMap_.EraseIf([pid, &networkIds, this](auto &networkId, auto &pidMap) {
2433 pidMap.EraseIf([pid, this](auto &key, auto &value) {
2434 if (value == pid) {
2435 PasteStart(key);
2436 return true;
2437 }
2438 return false;
2439 });
2440 if (pidMap.Empty()) {
2441 networkIds.emplace_back(networkId);
2442 return true;
2443 }
2444 return false;
2445 });
2446 for (const auto& id: networkIds) {
2447 CloseP2PLink(id);
2448 }
2449 clients_.Erase(pid);
2450 return ERR_OK;
2451 }
2452
OnRemoteDied(const wptr<IRemoteObject> & remote)2453 void PasteboardService::PasteboardDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
2454 {
2455 (void) remote;
2456 service_.AppExit(pid_);
2457 }
2458
PasteboardDeathRecipient(PasteboardService & service,sptr<IRemoteObject> observer,pid_t pid)2459 PasteboardService::PasteboardDeathRecipient::PasteboardDeathRecipient(PasteboardService &service,
2460 sptr<IRemoteObject> observer, pid_t pid)
2461 : service_(service), observer_(observer), pid_(pid)
2462 {
2463 PASTEBOARD_HILOGI(PASTEBOARD_MODULE_SERVICE, "Construct Pasteboard Client Death Recipient, pid: %{public}d", pid);
2464 }
2465
RegisterClientDeathObserver(sptr<IRemoteObject> observer)2466 int32_t PasteboardService::RegisterClientDeathObserver(sptr<IRemoteObject> observer)
2467 {
2468 pid_t pid = IPCSkeleton::GetCallingPid();
2469 sptr<PasteboardDeathRecipient> deathRecipient =
2470 new (std::nothrow) PasteboardDeathRecipient(*this, observer, pid);
2471 observer->AddDeathRecipient(deathRecipient);
2472 clients_.InsertOrAssign(pid, std::move(deathRecipient));
2473 return ERR_OK;
2474 }
2475
RemotePasteboardChange()2476 std::function<void(const OHOS::MiscServices::Event &)> PasteboardService::RemotePasteboardChange()
2477 {
2478 return [this](const OHOS::MiscServices::Event &event) {
2479 (void)event;
2480 std::lock_guard<std::mutex> lock(observerMutex_);
2481 for (auto &observers : observerRemoteChangedMap_) {
2482 for (const auto &observer : *(observers.second)) {
2483 observer->OnPasteboardChanged();
2484 }
2485 }
2486 };
2487 }
2488
OnInputEvent(std::shared_ptr<MMI::KeyEvent> keyEvent) const2489 void InputEventCallback::OnInputEvent(std::shared_ptr<MMI::KeyEvent> keyEvent) const
2490 {
2491 auto keyItems = keyEvent->GetKeyItems();
2492 if (keyItems.size() != CTRLV_EVENT_SIZE) {
2493 return;
2494 }
2495 if (((keyItems[0].GetKeyCode() == MMI::KeyEvent::KEYCODE_CTRL_LEFT) ||
2496 (keyItems[0].GetKeyCode() == MMI::KeyEvent::KEYCODE_CTRL_RIGHT)) &&
2497 keyItems[1].GetKeyCode() == MMI::KeyEvent::KEYCODE_V) {
2498 int32_t windowId = keyEvent->GetTargetWindowId();
2499 std::unique_lock<std::shared_mutex> lock(inputEventMutex_);
2500 windowPid_ = MMI::InputManager::GetInstance()->GetWindowPid(windowId);
2501 actionTime_ = static_cast<uint64_t>(duration_cast<milliseconds>(system_clock::now().time_since_epoch())
2502 .count());
2503 }
2504 }
2505
OnInputEvent(std::shared_ptr<MMI::PointerEvent> pointerEvent) const2506 void InputEventCallback::OnInputEvent(std::shared_ptr<MMI::PointerEvent> pointerEvent) const
2507 {
2508 }
2509
OnInputEvent(std::shared_ptr<MMI::AxisEvent> axisEvent) const2510 void InputEventCallback::OnInputEvent(std::shared_ptr<MMI::AxisEvent> axisEvent) const
2511 {
2512 }
2513
IsCtrlVProcess(uint32_t callingPid,bool isFocused)2514 bool InputEventCallback::IsCtrlVProcess(uint32_t callingPid, bool isFocused)
2515 {
2516 std::shared_lock<std::shared_mutex> lock(inputEventMutex_);
2517 auto curTime = static_cast<uint64_t>(duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
2518 return (callingPid == static_cast<uint32_t>(windowPid_) || isFocused) && curTime - actionTime_ < EVENT_TIME_OUT;
2519 }
2520
Clear()2521 void InputEventCallback::Clear()
2522 {
2523 std::unique_lock<std::shared_mutex> lock(inputEventMutex_);
2524 actionTime_ = 0;
2525 windowPid_ = 0;
2526 }
2527 } // namespace MiscServices
2528 } // namespace OHOS
2529