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,bool isSync)156 int32_t DataCollectManagerService::RequestDataSubmit(int64_t eventId, std::string &version, std::string &time,
157     std::string &content, bool isSync)
158 {
159     SGLOGD("enter DataCollectManagerService RequestDataSubmit");
160     SGLOGD("isSync: %{public}s", isSync ? "true" : "false");
161     int32_t ret = IsApiHasPermission("RequestDataSubmit");
162     if (ret != SUCCESS) {
163         return ret;
164     }
165     if (!DataFormat::CheckRiskContent(content)) {
166         SGLOGE("CheckRiskContent error");
167         return BAD_PARAM;
168     }
169     SGLOGD("eventId=%{public}" PRId64 ", version=%{public}s, date=%{public}s", eventId, version.c_str(), time.c_str());
170     SecEvent event {
171         .eventId = eventId,
172         .version = version,
173         .date = time,
174         .content = content
175     };
176     TaskHandler::Task task = [event] () mutable {
177         int code = DatabaseManager::GetInstance().InsertEvent(USER_SOURCE, event);
178         if (code != SUCCESS) {
179             SGLOGE("insert event error, %{public}d", code);
180         }
181     };
182     TaskHandler::GetInstance()->AddTask(task);
183     return SUCCESS;
184 }
185 
RequestRiskData(std::string & devId,std::string & eventList,const sptr<IRemoteObject> & callback)186 int32_t DataCollectManagerService::RequestRiskData(std::string &devId, std::string &eventList,
187     const sptr<IRemoteObject> &callback)
188 {
189     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
190     int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, REQUEST_PERMISSION);
191     if (code != AccessToken::PermissionState::PERMISSION_GRANTED) {
192         SGLOGE("caller no permission");
193         return NO_PERMISSION;
194     }
195     AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
196     if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
197         uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
198         if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
199             SGLOGE("not system app no permission");
200             return NO_SYSTEMCALL;
201         }
202     }
203     ObatinDataEvent event;
204     auto pid = IPCSkeleton::GetCallingPid();
205     event.pid = pid;
206     event.time = SecurityGuardUtils::GetDate();
207     SGLOGI("eventList=%{public}s", eventList.c_str());
208     auto promise = std::make_shared<std::promise<int32_t>>();
209     auto future = promise->get_future();
210     PushDataCollectTask(callback, eventList, devId, promise);
211     std::chrono::milliseconds span(TIMEOUT_REPLY);
212     if (future.wait_for(span) == std::future_status::timeout) {
213         SGLOGE("wait for result timeout");
214         event.size = 0;
215     } else {
216         event.size = future.get();
217     }
218     SGLOGI("ReportObatinDataEvent");
219     BigData::ReportObatinDataEvent(event);
220     return SUCCESS;
221 }
222 
GetSecEventsFromConditions(RequestCondition & condition)223 std::vector<SecEvent> DataCollectManagerService::GetSecEventsFromConditions(RequestCondition &condition)
224 {
225     std::vector<SecEvent> events;
226     if (condition.beginTime.empty() && condition.endTime.empty()) {
227         (void) DatabaseManager::GetInstance().QueryEventByEventId(RISK_TABLE, condition.riskEvent, events);
228     } else {
229         (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, condition.riskEvent, events,
230             condition.beginTime, condition.endTime);
231     }
232     return events;
233 }
234 
PushDataCollectTask(const sptr<IRemoteObject> & object,std::string conditions,std::string devId,std::shared_ptr<std::promise<int32_t>> promise)235 void DataCollectManagerService::PushDataCollectTask(const sptr<IRemoteObject> &object,
236     std::string conditions, std::string devId, std::shared_ptr<std::promise<int32_t>> promise)
237 {
238     TaskHandler::Task task = [object, conditions, devId, promise] () mutable {
239         auto proxy = iface_cast<DataCollectManagerCallbackProxy>(object);
240         if (proxy == nullptr) {
241             promise->set_value(0);
242             return;
243         }
244         RequestCondition reqCondition {};
245         DataFormat::ParseConditions(conditions, reqCondition);
246         if (reqCondition.riskEvent.empty() && reqCondition.auditEvent.empty()) {
247             SGLOGE("reqCondition no permission");
248             std::string empty;
249             proxy->ResponseRiskData(devId, empty, FINISH);
250             promise->set_value(0);
251             return;
252         }
253 
254         std::vector<SecEvent> events = GetSecEventsFromConditions(reqCondition);
255         int32_t curIndex = 0;
256         int32_t lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
257         auto maxIndex = static_cast<int32_t>(events.size());
258         promise->set_value(maxIndex);
259         SGLOGI("events size=%{public}d", maxIndex);
260         std::vector<SecEvent> dispatchVec;
261         while (lastIndex < maxIndex) {
262             dispatchVec.assign(events.begin() + curIndex, events.begin() + lastIndex);
263             std::string dispatch = nlohmann::json(dispatchVec).dump();
264             SGLOGD("dispatch size=%{public}d", (int)dispatch.size());
265             (void) proxy->ResponseRiskData(devId, dispatch, CONTINUE);
266             curIndex = lastIndex;
267             lastIndex = curIndex + MAX_DISTRIBUTE_LENS;
268         }
269 
270         // last dispatch
271         dispatchVec.assign(events.begin() + curIndex, events.end());
272         std::string dispatch = nlohmann::json(dispatchVec).dump();
273         (void) proxy->ResponseRiskData(devId, dispatch, FINISH);
274         SGLOGI("ResponseRiskData FINISH");
275     };
276     TaskHandler::GetInstance()->AddTask(task);
277 }
278 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)279 void DataCollectManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
280 {
281     SGLOGI("OnAddSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
282 }
283 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)284 void DataCollectManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
285 {
286     SGLOGW("OnRemoveSystemAbility, systemAbilityId=%{public}d", systemAbilityId);
287 }
288 
Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)289 int32_t DataCollectManagerService::Subscribe(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
290     const sptr<IRemoteObject> &callback)
291 {
292     SGLOGD("DataCollectManagerService, start subscribe");
293     int32_t ret = IsApiHasPermission("Subscribe");
294     if (ret != SUCCESS) {
295         return ret;
296     }
297     std::lock_guard<std::mutex> lock(mutex_);
298     if (deathRecipient_ == nullptr) {
299         deathRecipient_ = new (std::nothrow) SubscriberDeathRecipient(this);
300         if (deathRecipient_ == nullptr) {
301             SGLOGE("no memory");
302             return NULL_OBJECT;
303         }
304     }
305     callback->AddDeathRecipient(deathRecipient_);
306     ret = AcquireDataSubscribeManager::GetInstance().InsertSubscribeRecord(subscribeInfo, callback);
307     SgSubscribeEvent event;
308     event.pid = IPCSkeleton::GetCallingPid();
309     event.time = SecurityGuardUtils::GetDate();
310     event.eventId = subscribeInfo.GetEvent().eventId;
311     event.ret = ret;
312     SGLOGI("DataCollectManagerService, InsertSubscribeRecord eventId=%{public}" PRId64 "", event.eventId);
313     BigData::ReportSgSubscribeEvent(event);
314     return ret;
315 }
316 
Unsubscribe(const sptr<IRemoteObject> & callback)317 int32_t DataCollectManagerService::Unsubscribe(const sptr<IRemoteObject> &callback)
318 {
319     int32_t ret = IsApiHasPermission("UnSubscribe");
320     if (ret != SUCCESS) {
321         return ret;
322     }
323     std::lock_guard<std::mutex> lock(mutex_);
324     if (deathRecipient_ != nullptr) {
325         callback->RemoveDeathRecipient(deathRecipient_);
326     }
327 
328     ret = AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(callback);
329     SgUnsubscribeEvent event;
330     event.pid = IPCSkeleton::GetCallingPid();
331     event.time = SecurityGuardUtils::GetDate();
332     event.ret = ret;
333     SGLOGI("DataCollectManagerService, RemoveSubscribeRecord ret=%{public}d", ret);
334     BigData::ReportSgUnsubscribeEvent(event);
335     return ret;
336 }
337 
QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,SecurityCollector::SecurityEventRuler ruler)338 bool DataCollectManagerService::QueryEventByRuler(sptr<ISecurityEventQueryCallback> proxy,
339     SecurityCollector::SecurityEventRuler ruler)
340 {
341     EventCfg config;
342     bool isSuccess = ConfigDataManager::GetInstance().GetEventConfig(ruler.GetEventId(), config);
343     if (!isSuccess) {
344         SGLOGE("GetEventConfig error");
345         return true;
346     }
347     std::vector<SecurityCollector::SecurityEvent> replyEvents;
348     std::vector<int64_t> eventIds{ruler.GetEventId()};
349     SGLOGD("eventType is %{public}u", config.eventType);
350     if (config.eventType == 1) { // query in collector
351         int32_t code = SecurityCollector::CollectorManager::GetInstance().QuerySecurityEvent(
352             {ruler}, replyEvents);
353         if (code != SUCCESS) {
354             proxy->OnError("QuerySecurityEvent failed");
355             return false;
356         }
357         proxy->OnQuery(replyEvents);
358     } else {
359         std::vector<SecEvent> events;
360         if (ruler.GetBeginTime().empty() && ruler.GetEndTime().empty()) {
361             (void) DatabaseManager::GetInstance().QueryEventByEventId(ruler.GetEventId(), events);
362         } else {
363             (void) DatabaseManager::GetInstance().QueryEventByEventIdAndDate(RISK_TABLE, eventIds, events,
364                 ruler.GetBeginTime(), ruler.GetEndTime());
365         }
366         std::transform(events.begin(), events.end(),
367             std::back_inserter(replyEvents), [] (SecEvent event) {
368             return SecurityCollector::SecurityEvent(event.eventId, event.version, event.content);
369         });
370         proxy->OnQuery(replyEvents);
371     }
372     return true;
373 }
374 
QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,const sptr<IRemoteObject> & callback)375 int32_t DataCollectManagerService::QuerySecurityEvent(std::vector<SecurityCollector::SecurityEventRuler> rulers,
376     const sptr<IRemoteObject> &callback)
377 {
378     SGLOGE("enter QuerySecurityEvent");
379     int32_t ret = IsApiHasPermission("QuerySecurityEvent");
380     if (ret != SUCCESS) {
381         return ret;
382     }
383     auto proxy = iface_cast<ISecurityEventQueryCallback>(callback);
384     if (proxy == nullptr) {
385         SGLOGI("proxy is null");
386         return NULL_OBJECT;
387     }
388 
389     TaskHandler::Task task = [proxy, rulers] {
390         if (std::any_of(rulers.begin(), rulers.end(), [proxy] (auto const &ruler) {
391                 return !QueryEventByRuler(proxy, ruler);
392             })) {
393             return;
394         }
395         proxy->OnComplete();
396     };
397 
398     TaskHandler::GetInstance()->AddTask(task);
399     return SUCCESS;
400 }
401 
OnRemoteDied(const wptr<IRemoteObject> & remote)402 void DataCollectManagerService::SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
403 {
404     SGLOGE("enter");
405     if (remote == nullptr) {
406         SGLOGE("remote object is nullptr");
407         return;
408     }
409 
410     sptr<IRemoteObject> object = remote.promote();
411     if (object == nullptr) {
412         SGLOGE("object is nullptr");
413         return;
414     }
415     sptr<DataCollectManagerService> service = service_.promote();
416     if (service == nullptr) {
417         SGLOGE("service is nullptr");
418         return;
419     }
420     AcquireDataSubscribeManager::GetInstance().RemoveSubscribeRecord(object);
421     if (object->IsProxyObject() && service->deathRecipient_ != nullptr) {
422         object->RemoveDeathRecipient(service->deathRecipient_);
423     }
424     SGLOGE("end");
425 }
426 
CollectorStart(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)427 int32_t DataCollectManagerService::CollectorStart(
428     const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &callback)
429 {
430     SGLOGI("enter CollectorStart.");
431     int32_t code = IsApiHasPermission("CollectorStart");
432     if (code != SUCCESS) {
433         return code;
434     }
435     code = SecurityCollector::CollectorManager::GetInstance().CollectorStart(subscribeInfo);
436     if (code != SUCCESS) {
437         SGLOGI("CollectorStart failed, code=%{public}d", code);
438         return code;
439     }
440     return SUCCESS;
441 }
442 
CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo & subscribeInfo,const sptr<IRemoteObject> & callback)443 int32_t DataCollectManagerService::CollectorStop(const SecurityCollector::SecurityCollectorSubscribeInfo &subscribeInfo,
444     const sptr<IRemoteObject> &callback)
445 {
446     SGLOGI("enter CollectorStop.");
447     int32_t code = IsApiHasPermission("CollectorStop");
448     if (code != SUCCESS) {
449         return code;
450     }
451     code = SecurityCollector::CollectorManager::GetInstance().CollectorStop(subscribeInfo);
452     if (code != SUCCESS) {
453         SGLOGI("CollectorStop failed, code=%{public}d", code);
454         return code;
455     }
456     return SUCCESS;
457 }
458 
IsApiHasPermission(const std::string & api)459 int32_t DataCollectManagerService::IsApiHasPermission(const std::string &api)
460 {
461     if (g_apiPermissionsMap.count(api) == 0) {
462         SGLOGE("api not in map");
463         return FAILED;
464     }
465     AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
466     if (std::any_of(g_apiPermissionsMap.at(api).cbegin(), g_apiPermissionsMap.at(api).cend(),
467         [callerToken](const std::string &per) {
468         int code = AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, per);
469         return code == AccessToken::PermissionState::PERMISSION_GRANTED;
470     })) {
471         AccessToken::ATokenTypeEnum tokenType = AccessToken::AccessTokenKit::GetTokenType(callerToken);
472         if (tokenType != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
473             uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID();
474             if (!AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
475                 SGLOGE("not system app no permission");
476                 return NO_SYSTEMCALL;
477             }
478         }
479         return SUCCESS;
480     }
481     SGLOGE("caller no permission");
482     return NO_PERMISSION;
483 }
484 
WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo & info,const std::string & realPath)485 bool DataCollectManagerService::WriteRemoteFileToLocal(const SecurityGuard::SecurityConfigUpdateInfo &info,
486     const std::string &realPath)
487 {
488     int32_t fd = info.GetFd();
489     int32_t outputFd = dup(fd);
490     close(fd);
491     if (outputFd == -1) {
492         SGLOGE("dup fd fail reason %{public}s", strerror(errno));
493         return FAILED;
494     }
495     int32_t inputFd = open(realPath.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
496     if (inputFd < 0) {
497         close(outputFd);
498         SGLOGE("open file fail reason %{public}s", strerror(errno));
499         return FAILED;
500     }
501     auto buffer = std::make_unique<char []>(CFG_FILE_BUFF_SIZE);
502     if (buffer == nullptr) {
503         SGLOGE("new fail");
504         return NULL_OBJECT;
505     }
506     int offset = -1;
507     while ((offset = read(outputFd, buffer.get(), sizeof(buffer))) > 0) {
508         if (offset > CFG_FILE_MAX_SIZE || offset == 0) {
509             close(outputFd);
510             close(inputFd);
511             SGLOGE("file is empty or too large, len =  %{public}d", offset);
512             return BAD_PARAM;
513         }
514         if (write(inputFd, buffer.get(), offset) < 0) {
515             close(inputFd);
516             close(outputFd);
517             SGLOGE("write file to the tmp dir failed");
518             return FAILED;
519         }
520     }
521     close(inputFd);
522     fsync(outputFd);
523     close(outputFd);
524     return SUCCESS;
525 }
526 
ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo & info)527 int32_t DataCollectManagerService::ConfigUpdate(const SecurityGuard::SecurityConfigUpdateInfo &info)
528 {
529     SGLOGI("enter ConfigUpdate.");
530     int32_t code = IsApiHasPermission("ConfigUpdate");
531     if (code != SUCCESS) {
532         return code;
533     }
534     std::string realPath = CONFIG_ROOT_PATH + "tmp/" + info.GetFileName();
535     SGLOGI("config file is %{public}s, fd is %{public}d", realPath.c_str(), info.GetFd());
536     auto it = std::find_if(CONFIG_CACHE_FILES.begin(), CONFIG_CACHE_FILES.end(),
537         [realPath](const std::string &path) { return path == realPath; });
538     if (it ==  CONFIG_CACHE_FILES.end()) {
539         SGLOGE("file name err");
540         return BAD_PARAM;
541     }
542     int32_t ret = WriteRemoteFileToLocal(info, realPath);
543     if (ret != SUCCESS) {
544         SGLOGE("write remote file to local fail");
545         return ret;
546     }
547     if (!ConfigSubscriber::UpdateConfig(realPath)) {
548         SGLOGE("update config fail");
549         return FAILED;
550     }
551     return SUCCESS;
552 }
553 }
554