• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "data_collect_manager_service.h"
17 
18 #include <thread>
19 #include <vector>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 #include "accesstoken_kit.h"
26 #include "tokenid_kit.h"
27 #include "ipc_skeleton.h"
28 #include "string_ex.h"
29 
30 #include "acquire_data_subscribe_manager.h"
31 #include "bigdata.h"
32 #include "collector_manager.h"
33 #include "config_data_manager.h"
34 #include "data_collect_manager_callback_proxy.h"
35 #include "data_format.h"
36 #include "database_manager.h"
37 #include "data_collection.h"
38 #include "hiview_collector.h"
39 #include "risk_collect_define.h"
40 #include "security_guard_define.h"
41 #include "security_guard_log.h"
42 #include "security_guard_utils.h"
43 #include "system_ability_definition.h"
44 #include "task_handler.h"
45 #include "config_manager.h"
46 #include "risk_event_rdb_helper.h"
47 #include "model_cfg_marshalling.h"
48 #include "config_subscriber.h"
49 
50 
51 namespace OHOS::Security::SecurityGuard {
52 namespace {
53     constexpr int32_t TWO_ARGS = 2;
54     constexpr int32_t TIMEOUT_REPLY = 10000;
55     const std::string REPORT_PERMISSION = "ohos.permission.securityguard.REPORT_SECURITY_INFO";
56     const std::string REPORT_PERMISSION_NEW = "ohos.permission.REPORT_SECURITY_EVENT";
57     const std::string REQUEST_PERMISSION = "ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO";
58     const std::string MANAGE_CONFIG_PERMISSION = "ohos.permission.MANAGE_SECURITY_GUARD_CONFIG";
59     const std::string QUERY_SECURITY_EVENT_PERMISSION = "ohos.permission.QUERY_SECURITY_EVENT";
60     constexpr int32_t CFG_FILE_MAX_SIZE = 1 * 1024 * 1024;
61     constexpr int32_t CFG_FILE_BUFF_SIZE = 1 * 1024 * 1024 + 1;
62     const std::unordered_map<std::string, std::vector<std::string>> g_apiPermissionsMap {
63         {"RequestDataSubmit", {REPORT_PERMISSION, REPORT_PERMISSION_NEW}},
64         {"QuerySecurityEvent", {REPORT_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
65         {"CollectorStart", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
66         {"CollectorStop", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
67         {"Subscribe", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
68         {"UnSubscribe", {REQUEST_PERMISSION, QUERY_SECURITY_EVENT_PERMISSION}},
69         {"ConfigUpdate", {MANAGE_CONFIG_PERMISSION}}
70     };
71 }
72 
73 REGISTER_SYSTEM_ABILITY_BY_ID(DataCollectManagerService, DATA_COLLECT_MANAGER_SA_ID, true);
74 
DataCollectManagerService(int32_t saId,bool runOnCreate)75 DataCollectManagerService::DataCollectManagerService(int32_t saId, bool runOnCreate)
76     : SystemAbility(saId, runOnCreate)
77 {
78     SGLOGW("%{public}s", __func__);
79 }
80 
OnStart()81 void DataCollectManagerService::OnStart()
82 {
83     SGLOGI("%{public}s", __func__);
84     if (!Publish(this)) {
85         SGLOGE("Publish error");
86         return;
87     }
88     DatabaseManager::GetInstance().Init(); // Make sure the database is ready
89 
90     AddSystemAbilityListener(RISK_ANALYSIS_MANAGER_SA_ID);
91     AddSystemAbilityListener(DFX_SYS_HIVIEW_ABILITY_ID);
92     bool success = ConfigManager::InitConfig<EventConfig>();
93         if (!success) {
94         SGLOGE("init event config error");
95     }
96     std::vector<int64_t> eventIds = ConfigDataManager::GetInstance().GetAllEventIds();
97     std::vector<int64_t> onStartEventList;
98     for (int64_t eventId : eventIds) {
99         EventCfg eventCfg;
100         bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(eventId, eventCfg);
101         if (!isSuccess) {
102             SGLOGI("GetEventConfig error");
103         } else if (eventCfg.collectOnStart == 1) {
104             onStartEventList.push_back(eventId);
105         }
106     }
107     SecurityCollector::DataCollection::GetInstance().SecurityGuardSubscribeCollector(onStartEventList);
108 }
109 
OnStop()110 void DataCollectManagerService::OnStop()
111 {
112 }
113 
114 
Dump(int fd,const std::vector<std::u16string> & args)115 int DataCollectManagerService::Dump(int fd, const std::vector<std::u16string>& args)
116 {
117     SGLOGI("DataCollectManagerService Dump");
118     if (fd < 0) {
119         return BAD_PARAM;
120     }
121 
122     std::string arg0 = ((args.size() == 0) ? "" : Str16ToStr8(args.at(0)));
123     if (arg0.compare("-h") == 0) {
124         dprintf(fd, "Usage:\n");
125         dprintf(fd, "       -h: command help\n");
126         dprintf(fd, "       -i <EVENT_ID>: dump special eventId\n");
127     } else if (arg0.compare("-i") == 0) {
128         if (args.size() < TWO_ARGS) {
129             return BAD_PARAM;
130         }
131 
132         int64_t eventId;
133         bool isSuccess = SecurityGuardUtils::StrToI64(Str16ToStr8(args.at(1)), eventId);
134         if (!isSuccess) {
135             return BAD_PARAM;
136         }
137 
138         DumpEventInfo(fd, eventId);
139     }
140     return ERR_OK;
141 }
142 
DumpEventInfo(int fd,int64_t eventId)143 void DataCollectManagerService::DumpEventInfo(int fd, int64_t eventId)
144 {
145     SecEvent secEvent;
146     int code = DatabaseManager::GetInstance().QueryRecentEventByEventId(eventId, secEvent);
147     if (code != SUCCESS) {
148         SGLOGE("query event error, code=%{public}d", code);
149         return;
150     }
151     dprintf(fd, "eventId : %ld\n", secEvent.eventId);
152     dprintf(fd, "report time : %s\n", secEvent.date.c_str());
153     dprintf(fd, "report version : %s\n", secEvent.version.c_str());
154 }
155 
RequestDataSubmit(int64_t eventId,std::string & version,std::string & time,std::string & content)156 int32_t DataCollectManagerService::RequestDataSubmit(int64_t eventId, std::string &version, std::string &time,
157     std::string &content)
158 {
159     int32_t ret = IsApiHasPermission("RequestDataSubmit");
160     if (ret != SUCCESS) {
161         return ret;
162     }
163     if (!DataFormat::CheckRiskContent(content)) {
164         SGLOGE("CheckRiskContent error");
165         return BAD_PARAM;
166     }
167     SGLOGD("eventId=%{public}" PRId64 ", version=%{public}s, date=%{public}s", eventId, version.c_str(), time.c_str());
168     SecEvent event {
169         .eventId = eventId,
170         .version = version,
171         .date = time,
172         .content = content
173     };
174     TaskHandler::Task task = [event] () mutable {
175         int code = DatabaseManager::GetInstance().InsertEvent(USER_SOURCE, event);
176         if (code != SUCCESS) {
177             SGLOGE("insert event error, %{public}d", code);
178         }
179     };
180     TaskHandler::GetInstance()->AddTask(task);
181     return SUCCESS;
182 }
183 
RequestRiskData(std::string & devId,std::string & eventList,const sptr<IRemoteObject> & callback)184 int32_t DataCollectManagerService::RequestRiskData(std::string &devId, std::string &eventList,
185     const sptr<IRemoteObject> &callback)
186 {
187     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
188     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, REQUEST_PERMISSION);
189     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
190         SGLOGE("caller no permission");
191         return NO_PERMISSION;
192     }
193     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
194     if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
195         uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
196         if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
197             SGLOGE("not system app no permission");
198             return NO_SYSTEMCALL;
199         }
200     }
201     ObatinDataEvent event;
202     auto pid = IPCSkeleton::GetCallingPid();
203     event.pid = pid;
204     event.time = SecurityGuardUtils::GetDate();
205     SGLOGI("eventList=%{public}s", eventList.c_str());
206     auto promise = std::make_shared<std::promise<int32_t>>();
207     auto future = promise->get_future();
208     PushDataCollectTask(callback, eventList, devId, promise);
209     std::chrono::milliseconds span(TIMEOUT_REPLY);
210     if (future.wait_for(span) == std::future_status::timeout) {
211         SGLOGE("wait for result timeout");
212         event.size = 0;
213     } else {
214         event.size = future.get();
215     }
216     SGLOGI("ReportObatinDataEvent");
217     BigData::ReportObatinDataEvent(event);
218     return SUCCESS;
219 }
220 
GetSecEventsFromConditions(RequestCondition & condition)221 std::vector<SecEvent> DataCollectManagerService::GetSecEventsFromConditions(RequestCondition &condition)
222 {
223     std::vector<SecEvent> events;
224     if (condition.beginTime.empty() && condition.endTime.empty()) {
225         (void) DatabaseManager::GetInstance().QueryEventByEventId(RISK_TABLE, condition.riskEvent, events);
226     } else {
227         (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, condition.riskEvent, events,
228             condition.beginTime, condition.endTime);
229     }
230     return events;
231 }
232 
PushDataCollectTask(const sptr<IRemoteObject> & object,std::string conditions,std::string devId,std::shared_ptr<std::promise<int32_t>> promise)233 void DataCollectManagerService::PushDataCollectTask(const sptr<IRemoteObject> &object,
234     std::string conditions, std::string devId, std::shared_ptr<std::promise<int32_t>> promise)
235 {
236     TaskHandler::Task task = [object, conditions, devId, promise] () mutable {
237         auto proxy = iface_cast<DataCollectManagerCallbackProxy>(object);
238         if (proxy == nullptr) {
239             promise->set_value(0);
240             return;
241         }
242         RequestCondition reqCondition {};
243         DataFormat::ParseConditions(conditions, reqCondition);
244         if (reqCondition.riskEvent.empty() && reqCondition.auditEvent.empty()) {
245             SGLOGE("reqCondition no permission");
246             std::string empty;
247             proxy->ResponseRiskData(devId, empty, FINISH);
248             promise->set_value(0);
249             return;
250         }
251 
252         std::vector<SecEvent> events = GetSecEventsFromConditions(reqCondition);
253         int32_t curIndex = 0;
254         int32_t lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
255         auto maxIndex = static_cast<int32_t>(events.size());
256         promise->set_value(maxIndex);
257         SGLOGI("events size=%{public}d", maxIndex);
258         std::vector<SecEvent> dispatchVec;
259         while (lastIndex < maxIndex) {
260             dispatchVec.assign(events.begin() + curIndex, events.begin() + lastIndex);
261             std::string dispatch = nlohmann::json(dispatchVec).dump();
262             SGLOGD("dispatch size=%{public}d", (int)dispatch.size());
263             (void) proxy->ResponseRiskData(devId, dispatch, CONTINUE);
264             curIndex = lastIndex;
265             lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
266         }
267 
268         // last dispatch
269         dispatchVec.assign(events.begin() + curIndex, events.end());
270         std::string dispatch = nlohmann::json(dispatchVec).dump();
271         (void) proxy->ResponseRiskData(devId, dispatch, FINISH);
272         SGLOGI("ResponseRiskData FINISH");
273     };
274     TaskHandler::GetInstance()->AddTask(task);
275 }
276 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)277 void DataCollectManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
278 {
279     SGLOGI("OnAddSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
280 }
281 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)282 void DataCollectManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
283 {
284     SGLOGW("OnRemoveSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
285 }
286 
Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)287 int32_t DataCollectManagerService::Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
288     const sptr<IRemoteObject> &callback)
289 {
290     SGLOGD("DataCollectManagerService, start subscribe");
291     int32_t ret = IsApiHasPermission("Subscribe");
292     if (ret != SUCCESS) {
293         return ret;
294     }
295     std::lock_guard<std::mutex> lock(mutex_);
296     if (deathRecipient_ == nullptr) {
297         deathRecipient_ = new (std::nothrow) SubscriberDeathRecipient(this);
298         if (deathRecipient_ == nullptr) {
299             SGLOGE("no memory");
300             return NULL_OBJECT;
301         }
302     }
303     callback->AddDeathRecipient(deathRecipient_);
304     ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeRecord(subscribeInfo, callback);
305     SgSubscribeEvent event;
306     event.pid = IPCSkeleton::GetCallingPid();
307     event.time = SecurityGuardUtils::GetDate();
308     event.eventId = subscribeInfo.GetEvent().eventId;
309     event.ret = ret;
310     SGLOGI("DataCollectManagerService, InsertSubscribeRecord eventId=%{public}" PRId64 "", event.eventId);
311     BigData::ReportSgSubscribeEvent(event);
312     return ret;
313 }
314 
Unsubscribe(const sptr<IRemoteObject> & callback)315 int32_t DataCollectManagerService::Unsubscribe(const sptr<IRemoteObject> &callback)
316 {
317     int32_t ret = IsApiHasPermission("UnSubscribe");
318     if (ret != SUCCESS) {
319         return ret;
320     }
321     std::lock_guard<std::mutex> lock(mutex_);
322     if (deathRecipient_ != nullptr) {
323         callback->RemoveDeathRecipient(deathRecipient_);
324     }
325 
326     ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(callback);
327     SgUnsubscribeEvent event;
328     event.pid = IPCSkeleton::GetCallingPid();
329     event.time = SecurityGuardUtils::GetDate();
330     event.ret = ret;
331     SGLOGI("DataCollectManagerService, RemoveSubscribeRecord ret=%{public}d", ret);
332     BigData::ReportSgUnsubscribeEvent(event);
333     return ret;
334 }
335 
QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,SecurityCollector::SecurityEventRuler ruler)336 bool DataCollectManagerService::QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,
337     SecurityCollector::SecurityEventRuler ruler)
338 {
339     EventCfg config;
340     bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(ruler.GetEventId(), config);
341     if (!isSuccess) {
342         SGLOGE("GetEventConfig error");
343         return true;
344     }
345     std::vector<SecurityCollector::SecurityEvent> replyEvents;
346     std::vector<int64_t> eventIds{ruler.GetEventId()};
347     SGLOGD("eventType is %{public}u", config.eventType);
348     if (config.eventType == 1) { // query in collector
349         int32_t code = SecurityCollector::CollectorManager::GetInstance().QuerySecurityEvent(
350             {ruler}, replyEvents);
351         if (code != SUCCESS) {
352             proxy->OnError("QuerySecurityEvent failed");
353             return false;
354         }
355         proxy->OnQuery(replyEvents);
356     } else {
357         std::vector<SecEvent> events;
358         if (ruler.GetBeginTime().empty() && ruler.GetEndTime().empty()) {
359             (void) DatabaseManager::GetInstance().QueryEventByEventId(ruler.GetEventId(), events);
360         } else {
361             (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, eventIds, events,
362                 ruler.GetBeginTime(), ruler.GetEndTime());
363         }
364         std::transform(events.begin(), events.end(),
365             std::back_inserter(replyEvents), [] (SecEvent event) {
366             return SecurityCollector::SecurityEvent(event.eventId, event.version, event.content);
367         });
368         proxy->OnQuery(replyEvents);
369     }
370     return true;
371 }
372 
QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,const sptr<IRemoteObject> & callback)373 int32_t DataCollectManagerService::QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,
374     const sptr<IRemoteObject> &callback)
375 {
376     SGLOGE("enter QuerySecurityEvent");
377     int32_t ret = IsApiHasPermission("QuerySecurityEvent");
378     if (ret != SUCCESS) {
379         return ret;
380     }
381     auto proxy = iface_cast<ISecurityEventQueryCallback>(callback);
382     if (proxy == nullptr) {
383         SGLOGI("proxy is null");
384         return NULL_OBJECT;
385     }
386 
387     TaskHandler::Task task = [proxy, rulers] {
388         if (std::any_of(rulers.begin(), rulers.end(), [proxy] (auto const &ruler) {
389                 return !QueryEventByRuler(proxy, ruler);
390             })) {
391             return;
392         }
393         proxy->OnComplete();
394     };
395 
396     TaskHandler::GetInstance()->AddTask(task);
397     return SUCCESS;
398 }
399 
OnRemoteDied(const wptr<IRemoteObject> & remote)400 void DataCollectManagerService::SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
401 {
402     SGLOGE("enter");
403     if (remote == nullptr) {
404         SGLOGE("remote object is nullptr");
405         return;
406     }
407 
408     sptr<IRemoteObject> object = remote.promote();
409     if (object == nullptr) {
410         SGLOGE("object is nullptr");
411         return;
412     }
413     sptr<DataCollectManagerService> service = service_.promote();
414     if (service == nullptr) {
415         SGLOGE("service is nullptr");
416         return;
417     }
418     AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(object);
419     if (object->IsProxyObject() && service->deathRecipient_ != nullptr) {
420         object->RemoveDeathRecipient(service->deathRecipient_);
421     }
422     SGLOGE("end");
423 }
424 
CollectorStart(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)425 int32_t DataCollectManagerService::CollectorStart(
426     const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &callback)
427 {
428     SGLOGI("enter CollectorStart.");
429     int32_t code = IsApiHasPermission("CollectorStart");
430     if (code != SUCCESS) {
431         return code;
432     }
433     code = SecurityCollector::CollectorManager::GetInstance().CollectorStart(subscribeInfo);
434     if (code != SUCCESS) {
435         SGLOGI("CollectorStart failed, code=%{public}d", code);
436         return code;
437     }
438     return SUCCESS;
439 }
440 
CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)441 int32_t DataCollectManagerService::CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
442     const sptr<IRemoteObject> &callback)
443 {
444     SGLOGI("enter CollectorStop.");
445     int32_t code = IsApiHasPermission("CollectorStop");
446     if (code != SUCCESS) {
447         return code;
448     }
449     code = SecurityCollector::CollectorManager::GetInstance().CollectorStop(subscribeInfo);
450     if (code != SUCCESS) {
451         SGLOGI("CollectorStop failed, code=%{public}d", code);
452         return code;
453     }
454     return SUCCESS;
455 }
456 
IsApiHasPermission(const std::string & api)457 int32_t DataCollectManagerService::IsApiHasPermission(const std::string &api)
458 {
459     if (g_apiPermissionsMap.count(api) == 0) {
460         SGLOGE("api not in map");
461         return FAILED;
462     }
463     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
464     if (std::any_of(g_apiPermissionsMap.at(api).cbegin(), g_apiPermissionsMap.at(api).cend(),
465         [callerToken](const std::string &per) {
466         int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, per);
467         return code == AccessToken::PermissionState::PERMISSION_GRANTED;
468     })) {
469         AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
470         if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
471             uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
472             if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
473                 SGLOGE("not system app no permission");
474                 return NO_SYSTEMCALL;
475             }
476         }
477         return SUCCESS;
478     }
479     SGLOGE("caller no permission");
480     return NO_PERMISSION;
481 }
482 
WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo & info,const std::string & realPath)483 bool DataCollectManagerService::WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo &info,
484     const std::string &realPath)
485 {
486     int32_t fd = info.GetFd();
487     int32_t outputFd = dup(fd);
488     close(fd);
489     if (outputFd == -1) {
490         SGLOGE("dup fd fail reason %{public}s", strerror(errno));
491         return FAILED;
492     }
493     int32_t inputFd = open(realPath.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
494     if (inputFd < 0) {
495         close(outputFd);
496         SGLOGE("open file fail reason %{public}s", strerror(errno));
497         return FAILED;
498     }
499     auto buffer = std::make_unique<char []>(CFG_FILE_BUFF_SIZE);
500     if (buffer == nullptr) {
501         SGLOGE("new fail");
502         return NULL_OBJECT;
503     }
504     int offset = -1;
505     while ((offset = read(outputFd, buffer.get(), sizeof(buffer))) > 0) {
506         if (offset > CFG_FILE_MAX_SIZE || offset == 0) {
507             close(outputFd);
508             close(inputFd);
509             SGLOGE("file is empty or too large, len =  %{public}d", offset);
510             return BAD_PARAM;
511         }
512         if (write(inputFd, buffer.get(), offset) < 0) {
513             close(inputFd);
514             close(outputFd);
515             SGLOGE("write file to the tmp dir failed");
516             return FAILED;
517         }
518     }
519     close(inputFd);
520     fsync(outputFd);
521     close(outputFd);
522     return SUCCESS;
523 }
524 
ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo & info)525 int32_t DataCollectManagerService::ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &info)
526 {
527     SGLOGI("enter ConfigUpdate.");
528     int32_t code = IsApiHasPermission("ConfigUpdate");
529     if (code != SUCCESS) {
530         return code;
531     }
532     std::string realPath = CONFIG_ROOT_PATH + "tmp/" + info.GetFileName();
533     SGLOGI("config file is %{public}s, fd is %{public}d", realPath.c_str(), info.GetFd());
534     auto it = std::find_if(CONFIG_CACHE_FILES.begin(), CONFIG_CACHE_FILES.end(),
535         [realPath](const std::string &path) { return path == realPath; });
536     if (it ==  CONFIG_CACHE_FILES.end()) {
537         SGLOGE("file name err");
538         return BAD_PARAM;
539     }
540     int32_t ret = WriteRemoteFileToLocal(info, realPath);
541     if (ret != SUCCESS) {
542         SGLOGE("write remote file to local fail");
543         return ret;
544     }
545     if (!ConfigSubscriber::UpdateConfig(realPath)) {
546         SGLOGE("update config fail");
547         return FAILED;
548     }
549     return SUCCESS;
550 }
551 }
552