• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 
16 #include "callback_manager.h"
17 
18 #include <future>
19 #include <thread>
20 #include <datetime_ex.h>
21 #include <pthread.h>
22 
23 #include "access_token.h"
24 #include "access_token_error.h"
25 #include "perm_state_callback_death_recipient.h"
26 
27 
28 namespace OHOS {
29 namespace Security {
30 namespace AccessToken {
31 namespace {
32 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "CallbackManager"};
33 static const uint32_t MAX_CALLBACK_SIZE = 1024;
34 #ifndef RESOURCESCHEDULE_FFRT_ENABLE
35 static const time_t MAX_TIMEOUT_SEC = 30;
36 static const int MAX_PTHREAD_NAME_LEN = 15; // pthread name max length
37 #endif
38 }
39 
GetInstance()40 CallbackManager& CallbackManager::GetInstance()
41 {
42     static CallbackManager instance;
43     return instance;
44 }
45 
CallbackManager()46 CallbackManager::CallbackManager() : callbackDeathRecipient_(sptr<IRemoteObject::DeathRecipient>(
47     new (std::nothrow) PermStateCallbackDeathRecipient()))
48 {
49 }
50 
~CallbackManager()51 CallbackManager::~CallbackManager()
52 {
53 }
54 
AddCallback(const PermStateChangeScope & scopeRes,const sptr<IRemoteObject> & callback)55 int32_t CallbackManager::AddCallback(const PermStateChangeScope& scopeRes, const sptr<IRemoteObject>& callback)
56 {
57     if (callback == nullptr) {
58         ACCESSTOKEN_LOG_ERROR(LABEL, "input is nullptr");
59         return AccessTokenError::ERR_PARAM_INVALID;
60     }
61     auto callbackScopePtr = std::make_shared<PermStateChangeScope>(scopeRes);
62 
63 #ifdef RESOURCESCHEDULE_FFRT_ENABLE
64     std::lock_guard<ffrt::mutex> lock(mutex_);
65 #else
66     std::lock_guard<std::mutex> lock(mutex_);
67 #endif
68     if (callbackInfoList_.size() >= MAX_CALLBACK_SIZE) {
69         ACCESSTOKEN_LOG_ERROR(LABEL, "callback size has reached limitation");
70         return AccessTokenError::ERR_CALLBACKS_EXCEED_LIMITATION;
71     }
72     callback->AddDeathRecipient(callbackDeathRecipient_);
73 
74     CallbackRecord recordInstance;
75     recordInstance.callbackObject_ = callback;
76     recordInstance.scopePtr_ = callbackScopePtr;
77 
78     callbackInfoList_.emplace_back(recordInstance);
79 
80     ACCESSTOKEN_LOG_INFO(LABEL, "recordInstance is added");
81     return RET_SUCCESS;
82 }
83 
RemoveCallback(const sptr<IRemoteObject> & callback)84 int32_t CallbackManager::RemoveCallback(const sptr<IRemoteObject>& callback)
85 {
86     if (callback == nullptr) {
87         ACCESSTOKEN_LOG_ERROR(LABEL, "callback is nullptr");
88         return AccessTokenError::ERR_PARAM_INVALID;
89     }
90 
91 #ifdef RESOURCESCHEDULE_FFRT_ENABLE
92     std::lock_guard<ffrt::mutex> lock(mutex_);
93 #else
94     std::lock_guard<std::mutex> lock(mutex_);
95 #endif
96 
97     for (auto it = callbackInfoList_.begin(); it != callbackInfoList_.end(); ++it) {
98         if (callback == (*it).callbackObject_) {
99             ACCESSTOKEN_LOG_INFO(LABEL, "find callback");
100             if (callbackDeathRecipient_ != nullptr) {
101                 callback->RemoveDeathRecipient(callbackDeathRecipient_);
102             }
103             (*it).callbackObject_ = nullptr;
104             callbackInfoList_.erase(it);
105             break;
106         }
107     }
108     ACCESSTOKEN_LOG_INFO(LABEL, "callbackInfoList_ %{public}u", (uint32_t)callbackInfoList_.size());
109     return RET_SUCCESS;
110 }
111 
CalledAccordingToTokenIdLlist(const std::vector<AccessTokenID> & tokenIDList,AccessTokenID tokenID)112 bool CallbackManager::CalledAccordingToTokenIdLlist(
113     const std::vector<AccessTokenID>& tokenIDList, AccessTokenID tokenID)
114 {
115     if (tokenIDList.empty()) {
116         return true;
117     }
118     return std::any_of(tokenIDList.begin(), tokenIDList.end(),
119         [tokenID](AccessTokenID id) { return id == tokenID; });
120 }
121 
CalledAccordingToPermLlist(const std::vector<std::string> & permList,const std::string & permName)122 bool CallbackManager::CalledAccordingToPermLlist(const std::vector<std::string>& permList, const std::string& permName)
123 {
124     if (permList.empty()) {
125         return true;
126     }
127     return std::any_of(permList.begin(), permList.end(),
128         [permName](const std::string& perm) { return perm == permName; });
129 }
130 
ExcuteAllCallback(std::vector<sptr<IRemoteObject>> & list,AccessTokenID tokenID,const std::string & permName,int32_t changeType)131 void CallbackManager::ExcuteAllCallback(std::vector<sptr<IRemoteObject>>& list, AccessTokenID tokenID,
132     const std::string& permName, int32_t changeType)
133 {
134     for (auto it = list.begin(); it != list.end(); ++it) {
135 #ifdef RESOURCESCHEDULE_FFRT_ENABLE
136         auto callbackSingle = [it, tokenID, permName, changeType]() {
137             auto callback = iface_cast<IPermissionStateCallback>(*it);
138             if (callback != nullptr) {
139                 ACCESSTOKEN_LOG_INFO(LABEL, "callback execute");
140                 PermStateChangeInfo resInfo;
141                 resInfo.permStateChangeType = changeType;
142                 resInfo.permissionName = permName;
143                 resInfo.tokenID = tokenID;
144                 callback->PermStateChangeCallback(resInfo);
145                 ACCESSTOKEN_LOG_INFO(LABEL, "callback execute end");
146             }
147         };
148         ffrt::submit(callbackSingle, {}, {}, ffrt::task_attr().qos(ffrt::qos_default));
149 #else
150         auto callback = iface_cast<IPermissionStateCallback>(*it);
151         if (callback != nullptr) {
152             ACCESSTOKEN_LOG_INFO(LABEL, "callback execute");
153             PermStateChangeInfo resInfo;
154             resInfo.permStateChangeType = changeType;
155             resInfo.permissionName = permName;
156             resInfo.tokenID = tokenID;
157             callback->PermStateChangeCallback(resInfo);
158         }
159 #endif
160     }
161 #ifdef RESOURCESCHEDULE_FFRT_ENABLE
162     ffrt::wait();
163 #endif
164 }
165 
GetCallbackObjectList(AccessTokenID tokenID,const std::string & permName,std::vector<sptr<IRemoteObject>> & list)166 void CallbackManager::GetCallbackObjectList(AccessTokenID tokenID, const std::string& permName,
167     std::vector<sptr<IRemoteObject>>& list)
168 {
169 #ifdef RESOURCESCHEDULE_FFRT_ENABLE
170     std::lock_guard<ffrt::mutex> lock(mutex_);
171 #else
172     std::lock_guard<std::mutex> lock(mutex_);
173 #endif
174     for (auto it = callbackInfoList_.begin(); it != callbackInfoList_.end(); ++it) {
175         std::shared_ptr<PermStateChangeScope> scopePtr = (*it).scopePtr_;
176         if (scopePtr == nullptr) {
177             ACCESSTOKEN_LOG_ERROR(LABEL, "scopePtr is nullptr");
178             continue;
179         }
180         if (!CalledAccordingToTokenIdLlist(scopePtr->tokenIDs, tokenID) ||
181             !CalledAccordingToPermLlist(scopePtr->permList, permName)) {
182                 ACCESSTOKEN_LOG_DEBUG(LABEL,
183                     "tokenID is %{public}u, permName is  %{public}s", tokenID, permName.c_str());
184                 continue;
185         }
186         list.emplace_back((*it).callbackObject_);
187     }
188 }
189 
ExecuteCallbackAsync(AccessTokenID tokenID,const std::string & permName,int32_t changeType)190 void CallbackManager::ExecuteCallbackAsync(AccessTokenID tokenID, const std::string& permName, int32_t changeType)
191 {
192     ACCESSTOKEN_LOG_INFO(LABEL, "entry");
193     auto callbackStart = [&]() {
194         ACCESSTOKEN_LOG_INFO(LABEL, "callbackStart");
195 #ifndef RESOURCESCHEDULE_FFRT_ENABLE
196         std::string name = "AtmCallback";
197         pthread_setname_np(pthread_self(), name.substr(0, MAX_PTHREAD_NAME_LEN).c_str());
198 #endif
199         std::vector<sptr<IRemoteObject>> list;
200         GetCallbackObjectList(tokenID, permName, list);
201         ExcuteAllCallback(list, tokenID, permName, changeType);
202     };
203 
204 #ifdef RESOURCESCHEDULE_FFRT_ENABLE
205     std::string taskName = "AtmCallback";
206     ffrt::task_handle h = ffrt::submit_h(callbackStart, {}, {},
207         ffrt::task_attr().qos(ffrt::qos_default).name(taskName.c_str()));
208     ffrt::wait({h});
209 #else
210     std::packaged_task<void()> callbackTask(callbackStart);
211     std::future<void> fut = callbackTask.get_future();
212     std::make_unique<std::thread>(std::move(callbackTask))->detach();
213 
214     ACCESSTOKEN_LOG_DEBUG(LABEL, "Waiting for the callback execution complete...");
215     std::future_status status = fut.wait_for(std::chrono::seconds(MAX_TIMEOUT_SEC));
216     if (status == std::future_status::timeout) {
217         ACCESSTOKEN_LOG_WARN(LABEL, "callbackTask callback execution timeout");
218         return;
219     }
220 #endif
221     ACCESSTOKEN_LOG_DEBUG(LABEL, "The callback execution is complete");
222 }
223 } // namespace AccessToken
224 } // namespace Security
225 } // namespace OHOS
226