1 /* 2 * Copyright (C) 2021-2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef PASTE_BOARD_SERVICE_H 17 #define PASTE_BOARD_SERVICE_H 18 19 #include <system_ability_definition.h> 20 21 #include "bundle_mgr_proxy.h" 22 #include "clip/clip_plugin.h" 23 #include "common/block_object.h" 24 #include "distributed_module_config.h" 25 #include "eventcenter/event_center.h" 26 #include "ffrt_utils.h" 27 #include "i_entity_recognition_observer.h" 28 #include "input_manager.h" 29 #include "loader.h" 30 #include "pasteboard_account_state_subscriber.h" 31 #include "pasteboard_common_event_subscriber.h" 32 #include "pasteboard_dump_helper.h" 33 #include "pasteboard_service_stub.h" 34 #include "pasteboard_switch.h" 35 #include "privacy_kit.h" 36 #include "security_level.h" 37 #include "system_ability.h" 38 39 namespace OHOS { 40 namespace MiscServices { 41 constexpr int32_t ERROR_USERID = -1; 42 constexpr int32_t RESULT_OK = 0; 43 enum class ServiceRunningState { 44 STATE_NOT_START, 45 STATE_RUNNING 46 }; 47 struct AppInfo { 48 std::string bundleName = "com.pasteboard.default"; 49 int32_t tokenType = -1; 50 int32_t userId = ERROR_USERID; 51 uint32_t tokenId; 52 }; 53 54 struct HistoryInfo { 55 std::string time; 56 std::string bundleName; 57 std::string state; 58 std::string remote; 59 }; 60 61 struct PasteDateTime { 62 int32_t syncTime = 0; 63 int32_t errorCode = 0; 64 std::shared_ptr<PasteData> data; 65 }; 66 67 struct PasteDateResult { 68 int32_t syncTime = 0; 69 int32_t errorCode = 0; 70 }; 71 72 struct FocusedAppInfo { 73 int32_t windowId = 0; 74 sptr<IRemoteObject> abilityToken = nullptr; 75 }; 76 class InputEventCallback : public MMI::IInputEventConsumer { 77 public: 78 void OnInputEvent(std::shared_ptr<MMI::KeyEvent> keyEvent) const override; 79 void OnInputEvent(std::shared_ptr<MMI::PointerEvent> pointerEvent) const override; 80 void OnInputEvent(std::shared_ptr<MMI::AxisEvent> axisEvent) const override; 81 bool IsCtrlVProcess(uint32_t callingPid, bool isFocused); 82 void Clear(); 83 84 private: 85 static constexpr uint32_t WAIT_TIME_OUT = 100; 86 mutable int32_t windowPid_; 87 mutable uint64_t actionTime_; 88 mutable std::shared_mutex inputEventMutex_; 89 mutable std::shared_mutex blockMapMutex_; 90 mutable std::map<uint32_t, std::shared_ptr<BlockObject<bool>>> blockMap_; 91 }; 92 93 class PasteboardService final : public SystemAbility, public PasteboardServiceStub { 94 DECLARE_SYSTEM_ABILITY(PasteboardService) 95 96 public: 97 API_EXPORT PasteboardService(); 98 API_EXPORT ~PasteboardService(); 99 virtual void Clear() override; 100 virtual int32_t GetRecordValueByType(uint32_t dataId, uint32_t recordId, PasteDataEntry &value) override; 101 virtual int32_t GetPasteData(PasteData &data, int32_t &syncTime) override; 102 virtual bool HasPasteData() override; 103 virtual int32_t SetPasteData(PasteData &pasteData, const sptr<IPasteboardDelayGetter> delayGetter = nullptr, 104 const sptr<IPasteboardEntryGetter> entryGetter = nullptr) override; 105 virtual bool IsRemoteData() override; 106 virtual std::vector<std::string> GetMimeTypes() override; 107 virtual bool HasDataType(const std::string &mimeType) override; 108 virtual std::set<Pattern> DetectPatterns(const std::set<Pattern> &patternsToCheck) override; 109 virtual int32_t GetDataSource(std::string &bundleNme) override; 110 virtual int32_t SubscribeEntityObserver( 111 EntityType entityType, uint32_t expectedDataLength, const sptr<IEntityRecognitionObserver> &observer) override; 112 virtual int32_t UnsubscribeEntityObserver( 113 EntityType entityType, uint32_t expectedDataLength, const sptr<IEntityRecognitionObserver> &observer) override; 114 virtual void SubscribeObserver( 115 PasteboardObserverType type, const sptr<IPasteboardChangedObserver> &observer) override; 116 virtual void UnsubscribeObserver( 117 PasteboardObserverType type, const sptr<IPasteboardChangedObserver> &observer) override; 118 virtual void UnsubscribeAllObserver(PasteboardObserverType type) override; 119 virtual int32_t SetGlobalShareOption(const std::map<uint32_t, ShareOption> &globalShareOptions) override; 120 virtual int32_t RemoveGlobalShareOption(const std::vector<uint32_t> &tokenIds) override; 121 virtual std::map<uint32_t, ShareOption> GetGlobalShareOption(const std::vector<uint32_t> &tokenIds) override; 122 virtual int32_t SetAppShareOptions(const ShareOption &shareOptions) override; 123 virtual int32_t RemoveAppShareOptions() override; 124 virtual void OnStart() override; 125 virtual void OnStop() override; 126 virtual void PasteStart(const std::string &pasteId) override; 127 virtual void PasteComplete(const std::string &deviceId, const std::string &pasteId) override; 128 virtual int32_t GetRemoteDeviceName(std::string &deviceName, bool &isRemote) override; 129 virtual void ShowProgress(const std::string &progressKey, const sptr<IRemoteObject> &observer) override; 130 virtual int32_t RegisterClientDeathObserver(sptr<IRemoteObject> observer) override; 131 static int32_t currentUserId_; 132 static ScreenEvent currentScreenStatus; 133 size_t GetDataSize(PasteData &data) const; 134 int Dump(int fd, const std::vector<std::u16string> &args) override; 135 void NotifyDelayGetterDied(int32_t userId); 136 void NotifyEntryGetterDied(int32_t userId); 137 virtual int32_t GetChangeCount(uint32_t &changeCount) override; 138 void ChangeStoreStatus(int32_t userId); 139 void CloseDistributedStore(int32_t user, bool isNeedClear); 140 PastedSwitch switch_; 141 static int32_t GetCurrentAccountId(); 142 143 private: 144 std::mutex saMutex_; 145 using Event = ClipPlugin::GlobalEvent; 146 using ServiceListenerFunc = void (PasteboardService::*)(); 147 using GetProcessorFunc = IPasteDataProcessor& (*)(); 148 static constexpr const int32_t LISTENING_SERVICE[] = { DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, 149 WINDOW_MANAGER_SERVICE_ID, MEMORY_MANAGER_SA_ID }; 150 static constexpr const char *PLUGIN_NAME = "distributed_clip"; 151 static constexpr uint32_t PLAIN_INDEX = 0; 152 static constexpr uint32_t HTML_INDEX = 1; 153 static constexpr uint32_t URI_INDEX = 2; 154 static constexpr uint32_t WANT_INDEX = 3; 155 static constexpr uint32_t PIXELMAP_INDEX = 4; 156 static constexpr uint32_t MAX_INDEX_LENGTH = 8; 157 static constexpr const pid_t EDM_UID = 3057; 158 static constexpr const pid_t ROOT_UID = 0; 159 static constexpr uint32_t EXPIRATION_INTERVAL = 2; 160 static constexpr int MIN_TRANMISSION_TIME = 30 * 1000; // ms 161 static constexpr uint32_t SET_DISTRIBUTED_DATA_INTERVAL = 40 * 1000; // 40 seconds 162 static constexpr uint64_t ONE_HOUR_MILLISECONDS = 60 * 60 * 1000; 163 static constexpr uint32_t GET_REMOTE_DATA_WAIT_TIME = 30000; 164 bool SetPasteboardHistory(HistoryInfo &info); 165 bool IsFocusedApp(uint32_t tokenId); 166 void InitBundles(Loader &loader); 167 void SetInputMethodPid(pid_t callPid); 168 void ClearInputMethodPidByPid(pid_t callPid); 169 void ClearInputMethodPid(void); 170 FocusedAppInfo GetFocusedAppInfo(void) const; 171 class DelayGetterDeathRecipient final : public IRemoteObject::DeathRecipient { 172 public: 173 explicit DelayGetterDeathRecipient(int32_t userId, PasteboardService &service); 174 virtual ~DelayGetterDeathRecipient() = default; 175 void OnRemoteDied(const wptr<IRemoteObject> &remote) override; 176 177 private: 178 int32_t userId_ = ERROR_USERID; 179 PasteboardService &service_; 180 }; 181 182 class EntryGetterDeathRecipient final : public IRemoteObject::DeathRecipient { 183 public: 184 explicit EntryGetterDeathRecipient(int32_t userId, PasteboardService &service); 185 virtual ~EntryGetterDeathRecipient() = default; 186 void OnRemoteDied(const wptr<IRemoteObject> &remote) override; 187 188 private: 189 int32_t userId_ = ERROR_USERID; 190 PasteboardService &service_; 191 }; 192 193 class RemoteDataTaskManager { 194 public: 195 struct TaskContext { 196 std::atomic<bool> pasting_ = false; 197 ConcurrentMap<uint32_t, std::shared_ptr<BlockObject<bool>>> getDataBlocks_; 198 std::shared_ptr<PasteDateTime> data_; 199 }; 200 using DataTask = std::pair<std::shared_ptr<PasteboardService::RemoteDataTaskManager::TaskContext>, bool>; 201 DataTask GetRemoteDataTask(const Event &event); 202 void Notify(const Event &event, std::shared_ptr<PasteDateTime> data); 203 void ClearRemoteDataTask(const Event &event); 204 std::shared_ptr<PasteDateTime> WaitRemoteData(const Event &event); 205 206 private: 207 std::atomic<uint32_t> mapKey_ = 0; 208 std::mutex mutex_; 209 std::map<std::string, std::shared_ptr<TaskContext>> dataTasks_; 210 }; 211 212 struct classcomp { operatorclasscomp213 bool operator()(const sptr<IPasteboardChangedObserver> &l, const sptr<IPasteboardChangedObserver> &r) const 214 { 215 return l->AsObject() < r->AsObject(); 216 } 217 }; 218 struct EntityObserverInfo { 219 EntityType entityType; 220 uint32_t expectedDataLength; 221 uint32_t tokenId; 222 sptr<IEntityRecognitionObserver> observer; EntityObserverInfoEntityObserverInfo223 EntityObserverInfo(EntityType entityType_, uint32_t expectedDataLength_, uint32_t tokenId_, 224 sptr<IEntityRecognitionObserver> observer_) : entityType(entityType_), 225 expectedDataLength(expectedDataLength_), tokenId(tokenId_), observer(observer_) { } 226 }; 227 using ObserverMap = std::map<std::pair<int32_t, pid_t>, 228 std::shared_ptr<std::set<sptr<IPasteboardChangedObserver>, classcomp>>>; 229 uint32_t GetObserversSize(int32_t userId, pid_t pid, ObserverMap &observerMap); 230 uint32_t GetAllObserversSize(int32_t userId, pid_t pid); 231 void AddSysAbilityListener(); 232 int32_t Init(); 233 void InitScreenStatus(); 234 static ScreenEvent GetCurrentScreenStatus(); 235 std::string DumpHistory() const; 236 std::string DumpData(); 237 void ThawInputMethod(void); 238 bool IsNeedThaw(void); 239 int32_t ExtractEntity(const std::string &entity, std::string &location); 240 int32_t GetAllEntryPlainText(uint32_t dataId, uint32_t recordId, 241 std::vector<std::shared_ptr<PasteDataEntry>> &entries, std::string &primaryText); 242 std::string GetAllPrimaryText(const PasteData &pasteData); 243 void NotifyEntityObservers(std::string &entity, EntityType entityType, uint32_t dataLength); 244 void UnsubscribeAllEntityObserver(); 245 void NotifyObservers(std::string bundleName, PasteboardEventStatus status); 246 void InitServiceHandler(); 247 bool IsCopyable(uint32_t tokenId) const; 248 std::mutex imeMutex_; 249 pid_t imePid_ = -1; 250 bool hasImeObserver_ = false; 251 252 struct DistributedMemory { 253 std::mutex mutex; 254 bool isRunning = false; 255 std::shared_ptr<PasteData> data; 256 Event event; 257 }; 258 DistributedMemory setDistributedMemory_; 259 260 int32_t SaveData(PasteData &pasteData, const sptr<IPasteboardDelayGetter> delayGetter = nullptr, 261 const sptr<IPasteboardEntryGetter> entryGetter = nullptr); 262 void HandleDelayDataAndRecord(PasteData &pasteData, const sptr<IPasteboardDelayGetter> delayGetter, 263 const sptr<IPasteboardEntryGetter> entryGetter, const AppInfo &appInfo); 264 void RemovePasteData(const AppInfo &appInfo); 265 void SetPasteDataDot(PasteData &pasteData); 266 std::pair<int32_t, ClipPlugin::GlobalEvent> GetValidDistributeEvent(int32_t user); 267 int32_t GetSdkVersion(uint32_t tokenId); 268 bool IsPermissionGranted(const std::string &perm, uint32_t tokenId); 269 int32_t GetData(uint32_t tokenId, PasteData &data, int32_t &syncTime); 270 271 void GetPasteDataDot(PasteData &pasteData, const std::string &bundleName); 272 int32_t GetLocalData(const AppInfo &appInfo, PasteData &data); 273 int32_t GetRemoteData(int32_t userId, const Event &event, PasteData &data, int32_t &syncTime); 274 int32_t GetRemotePasteData(int32_t userId, const Event &event, PasteData &data, int32_t &syncTime); 275 int32_t GetDelayPasteRecord(int32_t userId, PasteData &data); 276 void GetDelayPasteData(int32_t userId, PasteData &data); 277 int32_t ProcessDelayHtmlEntry(PasteData &data, const std::string &targetBundle, PasteDataEntry &entry); 278 int32_t PostProcessDelayHtmlEntry(PasteData &data, const std::string &targetBundle, PasteDataEntry &entry); 279 std::vector<Uri> CheckUriPermission(PasteData &data, const std::string &targetBundleName); 280 int32_t GrantUriPermission(const std::vector<Uri> &grantUris, const std::string &targetBundleName); 281 void RevokeUriPermission(std::shared_ptr<PasteData> pasteData); 282 void GenerateDistributedUri(PasteData &data); 283 bool IsBundleOwnUriPermission(const std::string &bundleName, Uri &uri); 284 std::string GetAppLabel(uint32_t tokenId); 285 sptr<OHOS::AppExecFwk::IBundleMgr> GetAppBundleManager(); 286 void EstablishP2PLink(const std::string &networkId, const std::string &pasteId); 287 void CloseP2PLink(const std::string &networkId); 288 uint8_t GenerateDataType(PasteData &data); 289 bool HasDistributedDataType(const std::string &mimeType); 290 291 std::pair<std::shared_ptr<PasteData>, PasteDateResult> GetDistributedData(const Event &event, int32_t user); 292 int32_t GetDistributedDelayData(const Event &evt, uint8_t version, std::vector<uint8_t> &rawData); 293 int32_t GetDistributedDelayEntry(const Event &evt, uint32_t recordId, const std::string &utdId, 294 std::vector<uint8_t> &rawData); 295 int32_t ProcessDistributedDelayUri(int32_t userId, PasteData &data, PasteDataEntry &entry, 296 std::vector<uint8_t> &rawData); 297 int32_t ProcessDistributedDelayHtml(PasteData &data, PasteDataEntry &entry, std::vector<uint8_t> &rawData); 298 int32_t ProcessDistributedDelayEntry(PasteDataEntry &entry, std::vector<uint8_t> &rawData); 299 int32_t GetRemoteEntryValue(const AppInfo &appInfo, PasteData &data, PasteDataRecord &record, 300 PasteDataEntry &entry); 301 int32_t ProcessRemoteDelayHtml(const std::string &remoteDeviceId, const std::string &bundleName, 302 const std::vector<uint8_t> &rawData, PasteData &data, PasteDataRecord &record, PasteDataEntry &entry); 303 int32_t GetLocalEntryValue(int32_t userId, PasteData &data, PasteDataRecord &record, PasteDataEntry &entry); 304 int32_t GetFullDelayPasteData(int32_t userId, PasteData &data); 305 bool IsDisallowDistributed(); 306 bool SetDistributedData(int32_t user, PasteData &data); 307 bool SetCurrentDistributedData(PasteData &data, Event event); 308 bool SetCurrentData(Event event, PasteData &data); 309 void CleanDistributedData(int32_t user); 310 void OnConfigChange(bool isOn); 311 std::shared_ptr<ClipPlugin> GetClipPlugin(); 312 void IncreaseChangeCount(int32_t userId); 313 314 static std::string GetTime(); 315 bool IsDataAged(); 316 bool VerifyPermission(uint32_t tokenId); 317 int32_t IsDataVaild(PasteData &pasteData, uint32_t tokenId); 318 static AppInfo GetAppInfo(uint32_t tokenId); 319 static std::string GetAppBundleName(const AppInfo &appInfo); 320 static void SetLocalPasteFlag(bool isCrossPaste, uint32_t tokenId, PasteData &pasteData); 321 void RecognizePasteData(PasteData &pasteData); 322 void ShowHintToast(uint32_t tokenId, uint32_t pid); 323 void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; 324 void DMAdapterInit(); 325 void NotifySaStatus(); 326 void ReportUeCopyEvent(PasteData &pasteData, int32_t result); 327 328 ServiceRunningState state_; 329 std::shared_ptr<AppExecFwk::EventHandler> serviceHandler_; 330 std::mutex observerMutex_; 331 ObserverMap observerLocalChangedMap_; 332 ObserverMap observerRemoteChangedMap_; 333 ObserverMap observerEventMap_; 334 ClipPlugin::GlobalEvent currentEvent_; 335 ClipPlugin::GlobalEvent remoteEvent_; 336 ConcurrentMap<int32_t, std::shared_ptr<PasteData>> clips_; 337 ConcurrentMap<int32_t, uint32_t> clipChangeCount_; 338 ConcurrentMap<pid_t, std::vector<EntityObserverInfo>> entityObserverMap_; 339 ConcurrentMap<int32_t, std::pair<sptr<IPasteboardEntryGetter>, sptr<EntryGetterDeathRecipient>>> entryGetters_; 340 ConcurrentMap<int32_t, std::pair<sptr<IPasteboardDelayGetter>, sptr<DelayGetterDeathRecipient>>> delayGetters_; 341 ConcurrentMap<int32_t, uint64_t> copyTime_; 342 std::set<std::string> readBundles_; 343 std::shared_ptr<PasteBoardCommonEventSubscriber> commonEventSubscriber_ = nullptr; 344 std::shared_ptr<PasteBoardAccountStateSubscriber> accountStateSubscriber_ = nullptr; 345 346 std::recursive_mutex mutex; 347 std::shared_ptr<ClipPlugin> clipPlugin_ = nullptr; 348 std::atomic<uint16_t> sequenceId_ = 0; 349 std::atomic<uint32_t> dataId_ = 0; 350 std::atomic<uint32_t> delayTokenId_ = 0; 351 std::atomic<uint32_t> delayDataId_ = 0; 352 static std::mutex historyMutex_; 353 std::mutex bundleMutex_; 354 std::mutex readBundleMutex_; 355 static std::vector<std::string> dataHistory_; 356 static std::shared_ptr<Command> copyHistory; 357 static std::shared_ptr<Command> copyData; 358 std::atomic<bool> setting_ = false; 359 std::map<int32_t, ServiceListenerFunc> ServiceListenerFuncs_; 360 std::map<std::string, int> typeMap_ = { 361 {MIMETYPE_TEXT_PLAIN, PLAIN_INDEX }, 362 { MIMETYPE_TEXT_HTML, HTML_INDEX }, 363 { MIMETYPE_TEXT_URI, URI_INDEX }, 364 { MIMETYPE_TEXT_WANT, WANT_INDEX }, 365 { MIMETYPE_PIXELMAP, PIXELMAP_INDEX} 366 }; 367 368 std::shared_ptr<FFRTTimer> ffrtTimer_; 369 ConcurrentMap<std::string, ConcurrentMap<std::string, int32_t>> p2pMap_; 370 enum GlobalShareOptionSource { 371 MDM = 0, 372 APP = 1, 373 }; 374 375 struct GlobalShareOption { 376 GlobalShareOptionSource source; 377 ShareOption shareOption; 378 }; 379 380 ConcurrentMap<uint32_t, GlobalShareOption> globalShareOptions_; 381 382 void AddObserver(int32_t userId, const sptr<IPasteboardChangedObserver> &observer, ObserverMap &observerMap); 383 void RemoveSingleObserver( 384 int32_t userId, const sptr<IPasteboardChangedObserver> &observer, ObserverMap &observerMap); 385 void RemoveAllObserver(int32_t userId, ObserverMap &observerMap); 386 inline bool IsCallerUidValid(); 387 std::vector<std::string> GetLocalMimeTypes(); 388 bool HasLocalDataType(const std::string &mimeType); 389 void AddPermissionRecord(uint32_t tokenId, bool isReadGrant, bool isSecureGrant); 390 bool SubscribeKeyboardEvent(); 391 bool IsAllowSendData(); 392 void UpdateShareOption(PasteData &pasteData); 393 bool CheckMdmShareOption(PasteData &pasteData); 394 void PasteboardEventSubscriber(); 395 void CommonEventSubscriber(); 396 void AccountStateSubscriber(); 397 bool IsBasicType(const std::string &mimeType); 398 std::function<void(const OHOS::MiscServices::Event &)> RemotePasteboardChange(); 399 std::shared_ptr<InputEventCallback> inputEventCallback_; 400 DistributedModuleConfig moduleConfig_; 401 int32_t uid_ = -1; 402 RemoteDataTaskManager taskMgr_; 403 pid_t setPasteDataUId_ = 0; 404 static constexpr pid_t TEST_SERVER_UID = 3500; 405 std::mutex eventMutex_; 406 SecurityLevel securityLevel_; 407 class PasteboardDeathRecipient final : public IRemoteObject::DeathRecipient { 408 public: 409 PasteboardDeathRecipient(PasteboardService &service, sptr<IRemoteObject> observer, pid_t pid); 410 virtual ~PasteboardDeathRecipient() = default; 411 void OnRemoteDied(const wptr<IRemoteObject> &remote) override; 412 413 private: 414 PasteboardService &service_; 415 sptr<IRemoteObject> observer_; 416 pid_t pid_; 417 }; 418 int32_t AppExit(pid_t pid); 419 void RemoveObserverByPid(int32_t userId, pid_t pid, ObserverMap &observerMap); 420 ConcurrentMap<pid_t, sptr<PasteboardDeathRecipient>> clients_; 421 static constexpr pid_t INVALID_UID = -1; 422 static constexpr pid_t INVALID_PID = -1; 423 static constexpr uint32_t INVALID_TOKEN = 0; 424 static constexpr uint32_t MAX_OBSERVER_COUNT = 10; 425 }; 426 } // namespace MiscServices 427 } // namespace OHOS 428 #endif // PASTE_BOARD_SERVICE_H