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