• 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 "net_stats_cached.h"
17 
18 #include <cinttypes>
19 #include <initializer_list>
20 #include <list>
21 #include <pthread.h>
22 
23 #include "net_conn_client.h"
24 #include "net_mgr_log_wrapper.h"
25 #include "net_stats_constants.h"
26 #include "net_stats_data_handler.h"
27 #include "net_stats_database_defines.h"
28 #include "net_stats_database_helper.h"
29 #include "netsys_controller.h"
30 #include "bpf_stats.h"
31 #include "ffrt_inner.h"
32 #include "os_account_manager.h"
33 
34 namespace OHOS {
35 namespace NetManagerStandard {
36 using namespace NetStatsDatabaseDefines;
37 namespace {
38 constexpr const char *IFACE_LO = "lo";
39 constexpr const char *INSTALL_SOURCE_DEFAULT = "default";
40 const std::string CELLULAR_IFACE_NAME = "rmnet";
41 } // namespace
42 const int8_t RETRY_TIME = 3;
43 
NetStatsCached()44 NetStatsCached::NetStatsCached()
45 {
46     isDisplayTrafficAncoList = CommonUtils::IsNeedDisplayTrafficAncoList();
47 }
48 
StartCached()49 int32_t NetStatsCached::StartCached()
50 {
51     auto retBackup = CreatNetStatsTables(NET_STATS_DATABASE_BACK_PATH);
52     if (retBackup != NETMANAGER_SUCCESS) {
53         NETMGR_LOG_E("CreatNetStatsTables error. ret: %{public}d", retBackup);
54     }
55     auto ret = CreatNetStatsTables(NET_STATS_DATABASE_PATH);
56     if (ret != NETMANAGER_SUCCESS) {
57         NETMGR_LOG_E("CreatNetStatsTables error. ret: %{public}d", ret);
58         return ret;
59     }
60 
61 #ifndef UNITTEST_FORBID_FFRT
62     cacheTimer_ = std::make_unique<FfrtTimer>();
63     writeTimer_ = std::make_unique<FfrtTimer>();
64     cacheTimer_->StartPro(cycleThreshold_, this, [](void *netStatsCachedPtr) -> void {
65         if (netStatsCachedPtr != nullptr) {
66             NetStatsCached *netStatsCached = reinterpret_cast<NetStatsCached *>(netStatsCachedPtr);
67             netStatsCached->CacheStats();
68         } else {
69             NETMGR_LOG_E("not NetStatsCached obj");
70         }
71     });
72     writeTimer_->StartPro(STATS_PACKET_CYCLE_MS, this, [](void *netStatsCachedPtr) -> void {
73         NETMGR_LOG_I("NetStatsCached write timer start");
74         if (netStatsCachedPtr != nullptr) {
75             NetStatsCached *netStatsCached = reinterpret_cast<NetStatsCached *>(netStatsCachedPtr);
76             netStatsCached->WriteStats();
77             auto handler = std::make_unique<NetStatsDataHandler>();
78             bool ret = handler->BackupNetStatsData(NET_STATS_DATABASE_PATH, NET_STATS_DATABASE_BACK_PATH);
79             if (!ret) {
80                 NETMGR_LOG_E("BackupNetStatsData error");
81             }
82         } else {
83             NETMGR_LOG_E("not NetStatsCached obj");
84         }
85     });
86 #endif
87     return ret;
88 }
89 
CreatNetStatsTables(const std::string & tableName)90 int32_t NetStatsCached::CreatNetStatsTables(const std::string &tableName)
91 {
92     NETMGR_LOG_I("Create table : %{public}s", tableName.c_str());
93     auto helper = std::make_unique<NetStatsDatabaseHelper>(tableName);
94     int8_t curRetryTimes = 0;
95     int32_t ret = -1;
96     while (curRetryTimes < RETRY_TIME) {
97         NETMGR_LOG_I("Create table times: %{public}d", curRetryTimes + 1);
98         ret = helper->CreateTable(VERSION_TABLE, VERSION_TABLE_CREATE_PARAM);
99         if (ret != NETMANAGER_SUCCESS) {
100             NETMGR_LOG_E("Create version table failed");
101             curRetryTimes++;
102             continue;
103         }
104         ret = helper->CreateTable(UID_TABLE, UID_TABLE_CREATE_PARAM);
105         if (ret != NETMANAGER_SUCCESS) {
106             NETMGR_LOG_E("Create uid table failed");
107             curRetryTimes++;
108             continue;
109         }
110         ret = helper->CreateTable(IFACE_TABLE, IFACE_TABLE_CREATE_PARAM);
111         if (ret != NETMANAGER_SUCCESS) {
112             NETMGR_LOG_E("Create iface table failed");
113             curRetryTimes++;
114             continue;
115         }
116         ret = helper->CreateTable(UID_SIM_TABLE, UID_SIM_TABLE_CREATE_PARAM);
117         if (ret != NETMANAGER_SUCCESS) {
118             NETMGR_LOG_E("Create uid_sim table failed");
119             curRetryTimes++;
120             continue;
121         }
122         break;
123     }
124     if (ret != NETMANAGER_SUCCESS) {
125         NETMGR_LOG_E("Create table failed");
126         return STATS_ERR_CREATE_TABLE_FAIL;
127     }
128     helper->Upgrade();
129     NETMGR_LOG_I("Create table end: %{public}s", tableName.c_str());
130     return NETMANAGER_SUCCESS;
131 }
132 
GetUidStatsCached(std::vector<NetStatsInfo> & uidStatsInfo)133 void NetStatsCached::GetUidStatsCached(std::vector<NetStatsInfo> &uidStatsInfo)
134 {
135     std::lock_guard<ffrt::mutex> lock(lock_);
136     uidStatsInfo.insert(uidStatsInfo.end(), stats_.GetUidStatsInfo().begin(), stats_.GetUidStatsInfo().end());
137 }
138 
GetUidSimStatsCached(std::vector<NetStatsInfo> & uidSimStatsInfo)139 void NetStatsCached::GetUidSimStatsCached(std::vector<NetStatsInfo> &uidSimStatsInfo)
140 {
141     std::lock_guard<ffrt::mutex> lock(lock_);
142     std::vector<NetStatsInfo> tmpList;
143     std::transform(stats_.GetUidSimStatsInfo().begin(), stats_.GetUidSimStatsInfo().end(), std::back_inserter(tmpList),
144                    [](NetStatsInfo &info) {
145                        NetStatsInfo tmpInfo = info;
146                        return tmpInfo;
147                    });
148     tmpList.erase(std::remove_if(tmpList.begin(), tmpList.end(), [](const auto &item) {
149                       return item.flag_ <= STATS_DATA_FLAG_DEFAULT || item.flag_ >= STATS_DATA_FLAG_LIMIT;
150                   }), tmpList.end());
151     std::transform(tmpList.begin(), tmpList.end(), std::back_inserter(uidSimStatsInfo), [this](NetStatsInfo &info) {
152         if (!isDisplayTrafficAncoList) {
153             if (info.flag_ == STATS_DATA_FLAG_SIM2) {
154                 info.uid_ = SIM2_UID;
155             } else if (info.flag_ == STATS_DATA_FLAG_SIM) {
156                 info.uid_ = Sim_UID;
157             }
158         } else {
159             if (info.flag_ == STATS_DATA_FLAG_SIM_BASIC) {
160                 info.uid_ = Sim_UID;
161             } else if (info.flag_ == STATS_DATA_FLAG_SIM2_BASIC) {
162                 info.uid_ = SIM2_UID;
163             }
164         }
165         return info;
166     });
167 }
168 
GetUidPushStatsCached(std::vector<NetStatsInfo> & uidPushStatsInfo)169 void NetStatsCached::GetUidPushStatsCached(std::vector<NetStatsInfo> &uidPushStatsInfo)
170 {
171     std::lock_guard<ffrt::mutex> lock(lock_);
172     uidPushStatsInfo.insert(uidPushStatsInfo.end(), uidPushStatsInfo_.begin(), uidPushStatsInfo_.end());
173 }
174 
GetAllPushStatsCached(std::vector<NetStatsInfo> & uidPushStatsInfo)175 void NetStatsCached::GetAllPushStatsCached(std::vector<NetStatsInfo> &uidPushStatsInfo)
176 {
177     std::lock_guard<ffrt::mutex> lock(lock_);
178     uidPushStatsInfo.insert(uidPushStatsInfo.end(), allPushStatsInfo_.begin(), allPushStatsInfo_.end());
179 }
180 
GetIfaceStatsCached(std::vector<NetStatsInfo> & ifaceStatsInfo)181 void NetStatsCached::GetIfaceStatsCached(std::vector<NetStatsInfo> &ifaceStatsInfo)
182 {
183     std::lock_guard<ffrt::mutex> lock(lock_);
184     ifaceStatsInfo.insert(ifaceStatsInfo.end(), stats_.GetIfaceStatsInfo().begin(), stats_.GetIfaceStatsInfo().end());
185 }
186 
SetAppStats(const PushStatsInfo & info)187 void NetStatsCached::SetAppStats(const PushStatsInfo &info)
188 {
189     std::lock_guard<ffrt::mutex> lock(lock_);
190     NetStatsInfo stats;
191     stats.uid_ = info.uid_;
192     stats.iface_ = info.iface_;
193     stats.date_ = info.endTime_;
194     stats.rxBytes_ = info.rxBytes_;
195     stats.txBytes_ = info.txBytes_;
196     stats.rxPackets_ = info.rxBytes_ > 0 ? 1 : 0;
197     stats.txPackets_ = info.txBytes_ > 0 ? 1 : 0;
198     if (info.netBearType_ == BEARER_CELLULAR) {
199         stats.ident_ = std::to_string(info.simId_);
200     }
201     stats.userId_ = info.userId_;
202     NETMGR_LOG_D("SetAppStats info=%{public}s", stats.UidData().c_str());
203     uidPushStatsInfo_.push_back(std::move(stats));
204 }
205 
GetKernelStats(std::vector<NetStatsInfo> & statsInfo)206 void NetStatsCached::GetKernelStats(std::vector<NetStatsInfo> &statsInfo)
207 {
208     NETMGR_LOG_I("GetKernelStats");
209     std::lock_guard<ffrt::mutex> lock(lock_);
210     GetKernelUidStats(statsInfo);
211     GetKernelUidSimStats(statsInfo);
212 }
213 
GetIncreasedStats(const NetStatsInfo & info)214 NetStatsInfo NetStatsCached::GetIncreasedStats(const NetStatsInfo &info)
215 {
216     auto findRet = std::find_if(lastUidStatsInfo_.begin(), lastUidStatsInfo_.end(),
217                                 [&info](const NetStatsInfo &lastInfo) { return info.Equals(lastInfo); });
218     if (findRet == lastUidStatsInfo_.end()) {
219         return info;
220     }
221     return info - *findRet;
222 }
223 
GetIncreasedSimStats(const NetStatsInfo & info)224 NetStatsInfo NetStatsCached::GetIncreasedSimStats(const NetStatsInfo &info)
225 {
226     auto findRet = std::find_if(lastUidSimStatsInfo_.begin(), lastUidSimStatsInfo_.end(),
227                                 [&info](const NetStatsInfo &lastInfo) { return info.Equals(lastInfo); });
228     if (findRet == lastUidSimStatsInfo_.end()) {
229         return info;
230     }
231     return info - *findRet;
232 }
233 
CacheUidStats()234 void NetStatsCached::CacheUidStats()
235 {
236     std::vector<NetStatsInfo> statsInfos;
237     NetsysController::GetInstance().GetAllStatsInfo(statsInfos);
238     if (statsInfos.empty()) {
239         NETMGR_LOG_W("No stats need to save");
240         return;
241     }
242 
243     ifaceNameIdentMap_.Iterate([&statsInfos](const std::string &k, const std::string &v) {
244         std::for_each(statsInfos.begin(), statsInfos.end(), [&k, &v](NetStatsInfo &item) {
245             if (item.iface_ == k) {
246                 item.ident_ = v;
247             }
248         });
249     });
250 
251     std::for_each(statsInfos.begin(), statsInfos.end(), [this](NetStatsInfo &info) {
252         if (info.iface_ == IFACE_LO) {
253             return;
254         }
255         if (info.uid_ > 0) {
256             info.userId_ = info.uid_ / USER_ID_DIVIDOR;
257         }
258         auto findRet = std::find_if(lastUidStatsInfo_.begin(), lastUidStatsInfo_.end(),
259                                     [this, &info](const NetStatsInfo &lastInfo) { return info.Equals(lastInfo); });
260         if (findRet == lastUidStatsInfo_.end()) {
261             stats_.PushUidStats(info);
262             return;
263         }
264         auto currentStats = info - *findRet;
265         stats_.PushUidStats(currentStats);
266     });
267     lastUidStatsInfo_.swap(statsInfos);
268 }
269 
CacheAppStats()270 void NetStatsCached::CacheAppStats()
271 {
272     std::vector<NetStatsInfo> pushInfos;
273     std::for_each(uidPushStatsInfo_.begin(), uidPushStatsInfo_.end(), [&pushInfos](NetStatsInfo &info) {
274         auto findRet = std::find_if(pushInfos.begin(), pushInfos.end(),
275                                     [&info](const NetStatsInfo &item) { return info.Equals(item); });
276         if (findRet == pushInfos.end()) {
277             pushInfos.push_back(info);
278             return;
279         }
280         *findRet += info;
281     });
282     std::for_each(pushInfos.begin(), pushInfos.end(), [this](auto &item) {
283         stats_.PushUidStats(item);
284         auto findRet = std::find_if(allPushStatsInfo_.begin(), allPushStatsInfo_.end(),
285                                     [&item](const NetStatsInfo &info) {
286                                         return info.Equals(item) && info.ident_ == item.ident_;
287                                     });
288         if (findRet == allPushStatsInfo_.end()) {
289             allPushStatsInfo_.push_back(item);
290             return;
291         }
292         *findRet += item;
293     });
294     uidPushStatsInfo_.clear();
295 }
296 
CacheUidSimStats()297 void NetStatsCached::CacheUidSimStats()
298 {
299     NETMGR_LOG_I("CacheUidSimStats");
300     std::vector<NetStatsInfo> statsInfos;
301     NetsysController::GetInstance().GetAllSimStatsInfo(statsInfos);
302     if (statsInfos.empty()) {
303         NETMGR_LOG_W("No stats need to save");
304         return;
305     }
306 
307     ifaceNameIdentMap_.Iterate([&statsInfos](const std::string &k, const std::string &v) {
308         std::for_each(statsInfos.begin(), statsInfos.end(), [&k, &v](NetStatsInfo &item) {
309             if (item.iface_ == k) {
310                 item.ident_ = v;
311             }
312         });
313     });
314     uidStatsFlagMap_.Iterate([&statsInfos](const uint32_t &k, const NetStatsDataFlag &v) {
315         std::for_each(statsInfos.begin(), statsInfos.end(), [&k, &v](NetStatsInfo &item) {
316             if (item.uid_ == k) {
317                 item.flag_ = v;
318             }
319         });
320     });
321 
322     std::for_each(statsInfos.begin(), statsInfos.end(), [this](NetStatsInfo &info) {
323         if (info.iface_ == IFACE_LO) {
324             return;
325         }
326         if (info.flag_ <= STATS_DATA_FLAG_DEFAULT || info.flag_ >= STATS_DATA_FLAG_LIMIT) {
327             info.flag_ = GetUidStatsFlag(info.uid_);
328         }
329         if (info.uid_ > 0) {
330             info.userId_ = info.uid_ / USER_ID_DIVIDOR;
331         }
332         auto findRet = std::find_if(lastUidSimStatsInfo_.begin(), lastUidSimStatsInfo_.end(),
333                                     [this, &info](const NetStatsInfo &lastInfo) { return info.Equals(lastInfo); });
334         if (findRet == lastUidSimStatsInfo_.end()) {
335             stats_.PushUidSimStats(info);
336             return;
337         }
338         auto currentStats = info - *findRet;
339         stats_.PushUidSimStats(currentStats);
340     });
341     lastUidSimStatsInfo_.swap(statsInfos);
342 }
343 
CacheIfaceStats()344 void NetStatsCached::CacheIfaceStats()
345 {
346     std::vector<std::string> ifNameList = NetsysController::GetInstance().InterfaceGetList();
347     std::for_each(ifNameList.begin(), ifNameList.end(), [this](const auto &ifName) {
348         if (ifName == IFACE_LO) {
349             return;
350         }
351         NetStatsInfo statsInfo;
352         statsInfo.iface_ = ifName;
353         NetsysController::GetInstance().GetIfaceStats(statsInfo.rxBytes_,
354                                                       static_cast<uint32_t>(StatsType::STATS_TYPE_RX_BYTES), ifName);
355         NetsysController::GetInstance().GetIfaceStats(statsInfo.rxPackets_,
356                                                       static_cast<uint32_t>(StatsType::STATS_TYPE_RX_PACKETS), ifName);
357         NetsysController::GetInstance().GetIfaceStats(statsInfo.txBytes_,
358                                                       static_cast<uint32_t>(StatsType::STATS_TYPE_TX_BYTES), ifName);
359         NetsysController::GetInstance().GetIfaceStats(statsInfo.txPackets_,
360                                                       static_cast<uint32_t>(StatsType::STATS_TYPE_TX_PACKETS), ifName);
361         auto findRet = lastIfaceStatsMap_.find(ifName);
362         if (findRet == lastIfaceStatsMap_.end()) {
363             stats_.PushIfaceStats(statsInfo);
364             lastIfaceStatsMap_[ifName] = statsInfo;
365             return;
366         }
367         auto currentStats = statsInfo - findRet->second;
368         stats_.PushIfaceStats(currentStats);
369         lastIfaceStatsMap_[ifName] = statsInfo;
370     });
371 }
372 
CacheStats()373 void NetStatsCached::CacheStats()
374 {
375     std::lock_guard<ffrt::mutex> lock(lock_);
376     NETMGR_LOG_I("cacheStats");
377     CacheUidStats();
378     CacheAppStats();
379     CacheUidSimStats();
380     CacheIfaceStats();
381 #ifdef SUPPORT_NETWORK_SHARE
382     CacheIptablesStats();
383 #endif
384 }
385 
WriteStats()386 void NetStatsCached::WriteStats()
387 {
388     std::lock_guard<ffrt::mutex> lock(lock_);
389     NETMGR_LOG_I("writeStats");
390     WriteUidStats();
391     WriteUidSimStats();
392     WriteIfaceStats();
393 #ifdef SUPPORT_NETWORK_SHARE
394     WriteIptablesStats();
395     writeDate_ = CommonUtils::GetCurrentSecond();
396 #endif
397 }
398 
399 #ifdef SUPPORT_NETWORK_SHARE
GetWriteDateTime()400 uint64_t NetStatsCached::GetWriteDateTime()
401 {
402     return writeDate_;
403 }
404 #endif
405 
WriteIfaceStats()406 void NetStatsCached::WriteIfaceStats()
407 {
408     if (!(CheckIfaceStor() || isForce_)) {
409         return;
410     }
411     auto handler = std::make_unique<NetStatsDataHandler>();
412     handler->WriteStatsData(stats_.GetIfaceStatsInfo(), NetStatsDatabaseDefines::IFACE_TABLE);
413     handler->DeleteByDate(NetStatsDatabaseDefines::IFACE_TABLE, 0, CommonUtils::GetCurrentSecond() - dateCycle_);
414     stats_.ResetIfaceStats();
415 }
416 
WriteUidStats()417 void NetStatsCached::WriteUidStats()
418 {
419     if (!(CheckUidStor() || isForce_)) {
420         return;
421     }
422 
423     std::for_each(stats_.GetUidStatsInfo().begin(), stats_.GetUidStatsInfo().end(), [this](NetStatsInfo &info) {
424         if (info.uid_ == uninstalledUid_) {
425             info.flag_ = STATS_DATA_FLAG_UNINSTALLED;
426         }
427         if (info.userId_ != curDefaultUserId_ && info.userId_ != SYSTEM_DEFAULT_USERID &&
428             info.userId_ != curPrivateUserId_) {
429             info.flag_ = STATS_DATA_FLAG_UNINSTALLED;
430         }
431     });
432     auto handler = std::make_unique<NetStatsDataHandler>();
433     handler->WriteStatsData(stats_.GetUidStatsInfo(), NetStatsDatabaseDefines::UID_TABLE);
434     handler->DeleteByDate(NetStatsDatabaseDefines::UID_TABLE, 0, CommonUtils::GetCurrentSecond() - dateCycle_);
435     stats_.ResetUidStats();
436 }
437 
WriteUidSimStats()438 void NetStatsCached::WriteUidSimStats()
439 {
440     if (!(CheckUidSimStor() || isForce_)) {
441         return;
442     }
443     std::for_each(stats_.GetUidSimStatsInfo().begin(), stats_.GetUidSimStatsInfo().end(), [this](NetStatsInfo &info) {
444         if (info.uid_ == uninstalledUid_) {
445             info.flag_ = STATS_DATA_FLAG_UNINSTALLED;
446         }
447     });
448     auto handler = std::make_unique<NetStatsDataHandler>();
449     handler->WriteStatsData(stats_.GetUidSimStatsInfo(), NetStatsDatabaseDefines::UID_SIM_TABLE);
450     handler->DeleteByDate(NetStatsDatabaseDefines::UID_SIM_TABLE, 0, CommonUtils::GetCurrentSecond() - dateCycle_);
451     stats_.ResetUidSimStats();
452 }
453 
454 #ifdef SUPPORT_NETWORK_SHARE
WriteIptablesStats()455 void NetStatsCached::WriteIptablesStats()
456 {
457     if (!(CheckIptablesStor() || isForce_)) {
458         return;
459     }
460     auto handler = std::make_unique<NetStatsDataHandler>();
461     handler->WriteStatsData(stats_.GetIptablesStatsInfo(), NetStatsDatabaseDefines::UID_TABLE);
462     handler->DeleteByDate(NetStatsDatabaseDefines::UID_TABLE, 0, CommonUtils::GetCurrentSecond() - dateCycle_);
463     stats_.ResetIptablesStats();
464 }
465 #endif
466 
LoadIfaceNameIdentMaps()467 void NetStatsCached::LoadIfaceNameIdentMaps()
468 {
469     int32_t ret = NetConnClient::GetInstance().GetIfaceNameIdentMaps(NetBearType::BEARER_CELLULAR, ifaceNameIdentMap_);
470     if (ret != NETMANAGER_SUCCESS) {
471         NETMGR_LOG_E("GetIfaceNameIdentMaps error. ret=%{public}d", ret);
472     }
473 }
474 
SetCycleThreshold(uint32_t threshold)475 void NetStatsCached::SetCycleThreshold(uint32_t threshold)
476 {
477     NETMGR_LOG_D("Current cycle threshold has changed current is : %{public}d", threshold);
478     cycleThreshold_ = threshold;
479 #ifndef UNITTEST_FORBID_FFRT
480     cacheTimer_ = std::make_unique<FfrtTimer>();
481     cacheTimer_->Start(cycleThreshold_, [this]() { CacheStats(); });
482 #endif
483 }
484 
ForceUpdateStats()485 void NetStatsCached::ForceUpdateStats()
486 {
487     isForce_ = true;
488     std::function<void()> netCachedStats = [this] () {
489         isExec_ = true;
490         CacheStats();
491         WriteStats();
492         isForce_ = false;
493         LoadIfaceNameIdentMaps();
494         isExec_ = false;
495     };
496     if (!isExec_) {
497         ffrt::submit(std::move(netCachedStats), {}, {}, ffrt::task_attr().name("NetCachedStats"));
498     }
499 }
500 
ForceUpdateStatsAndBackupDB(const std::string & sourceDb,const std::string & backupDb)501 void NetStatsCached::ForceUpdateStatsAndBackupDB(const std::string &sourceDb, const std::string &backupDb)
502 {
503     NETMGR_LOG_I("ForceUpdateStatsAndBackupDB");
504     isForce_ = true;
505     std::function<void()> netCachedStats = [this, sourceDb, backupDb] () {
506         isExecBackUp_ = true;
507         CacheStats();
508         WriteStats();
509         isForce_ = false;
510         LoadIfaceNameIdentMaps();
511         isExecBackUp_ = false;
512         auto handler = std::make_unique<NetStatsDataHandler>();
513         bool ret = handler->BackupNetStatsData(sourceDb, backupDb);
514         if (!ret) {
515             NETMGR_LOG_E("BackupNetStatsData error");
516         }
517     };
518     if (!isExecBackUp_) {
519         ffrt::submit(std::move(netCachedStats), {}, {}, ffrt::task_attr().name("NetCachedStats_backup"));
520     }
521 }
522 
ForceArchiveStats(uint32_t uid)523 ffrt::task_handle NetStatsCached::ForceArchiveStats(uint32_t uid)
524 {
525     NETMGR_LOG_I("ForceArchiveStats");
526     std::function<void()> netCachedStats = [this, uid]() {
527         CacheStats();
528         {
529             std::lock_guard<ffrt::mutex> lock(lock_);
530             isForce_ = true;
531             uninstalledUid_ = uid;
532             WriteUidStats();
533             WriteUidSimStats();
534             uninstalledUid_ = -1;
535             isForce_ = false;
536         }
537         DeleteUidStats(uid);
538         DeleteUidSimStats(uid);
539         DeleteUidStatsFlag(uid);
540         DeleteUidSimSampleBundle(uid);
541         if (GetUidSimSampleBundlesSize() == 0) {
542             uidStatsFlagMap_.Clear();
543         }
544     };
545     return ffrt::submit_h(std::move(netCachedStats), {}, {}, ffrt::task_attr().name("NetForceArchiveStats"));
546 }
547 
Reset()548 void NetStatsCached::Reset() {}
549 
ForceCachedStats()550 void NetStatsCached::ForceCachedStats()
551 {
552     NETMGR_LOG_E("ForceCachedStats");
553     std::lock_guard<ffrt::mutex> lock(lock_);
554     CacheUidSimStats();
555     WriteUidSimStats();
556 }
557 
SetUidSimSampleBundle(uint32_t uid,const SampleBundleInfo & info)558 void NetStatsCached::SetUidSimSampleBundle(uint32_t uid, const SampleBundleInfo &info)
559 {
560     if (!info.Valid()) {
561         NETMGR_LOG_W("SetUidSimSampleBundle invalid. info[%{public}u, %{public}s]", uid, info.ToString().c_str());
562         return;
563     }
564     uidSimSampleBundleMap_.EnsureInsert(uid, info);
565 }
566 
DeleteUidSimSampleBundle(uint32_t uid)567 void NetStatsCached::DeleteUidSimSampleBundle(uint32_t uid)
568 {
569     uidSimSampleBundleMap_.Erase(uid);
570 }
571 
GetUidSimSampleBundle(uint32_t uid)572 std::optional<SampleBundleInfo> NetStatsCached::GetUidSimSampleBundle(uint32_t uid)
573 {
574     SampleBundleInfo info;
575     if (uidSimSampleBundleMap_.Find(uid, info)) {
576         return info;
577     }
578     return std::nullopt;
579 }
580 
GetUidSimSampleBundlesSize()581 uint32_t NetStatsCached::GetUidSimSampleBundlesSize()
582 {
583     return static_cast<uint32_t>(uidSimSampleBundleMap_.Size());
584 }
585 
SetUidStatsFlag(std::unordered_map<uint32_t,SampleBundleInfo> & sampleBundleMap)586 void NetStatsCached::SetUidStatsFlag(std::unordered_map<uint32_t, SampleBundleInfo> &sampleBundleMap)
587 {
588     if (sampleBundleMap.empty()) {
589         NETMGR_LOG_W("SetUidStatsFlag sampleBundleMap is empty");
590         return;
591     }
592     bool isExistSim = false;
593     bool isExistSim2 = false;
594     IsExistInUidSimSampleBundleMap(isExistSim, isExistSim2);
595     std::optional<SampleBundleInfo> earlySampleBundleOpt = GetEarlySampleBundleInfo();
596     for (auto iter = sampleBundleMap.begin(); iter != sampleBundleMap.end(); ++iter) {
597         if (!iter->second.Valid()) {
598             NETMGR_LOG_W("SetUidStatsFlag sampleBundleInfo is invalid. [%{public}s]", iter->second.ToString().c_str());
599             continue;
600         }
601         if (isDisplayTrafficAncoList) {
602             if (CommonUtils::IsSim(iter->second.bundleName_) || CommonUtils::IsSimAnco(iter->second.bundleName_)) {
603                 uidStatsFlagMap_.EnsureInsert(iter->first, STATS_DATA_FLAG_SIM_BASIC);
604                 continue;
605             } else if (CommonUtils::IsSim2(iter->second.bundleName_) ||
606                 CommonUtils::IsSim2Anco(iter->second.bundleName_)) {
607                 uidStatsFlagMap_.EnsureInsert(iter->first, STATS_DATA_FLAG_SIM2_BASIC);
608                 continue;
609             }
610         }
611         if (CommonUtils::IsInstallSourceFromSim2(iter->second.installSource_)) {
612             uidStatsFlagMap_.EnsureInsert(iter->first,
613                                           isExistSim2 ? STATS_DATA_FLAG_SIM2 : STATS_DATA_FLAG_DEFAULT);
614         } else if (CommonUtils::IsInstallSourceFromSim(iter->second.installSource_)) {
615             uidStatsFlagMap_.EnsureInsert(iter->first, isExistSim ? STATS_DATA_FLAG_SIM : STATS_DATA_FLAG_DEFAULT);
616         } else if (iter->second.installSource_ == INSTALL_SOURCE_DEFAULT) {
617             if (!isExistSim && !isExistSim2) {
618                 uidStatsFlagMap_.EnsureInsert(iter->first, STATS_DATA_FLAG_DEFAULT);
619                 continue;
620             }
621             if (earlySampleBundleOpt.has_value() &&
622                 CommonUtils::IsSim2(earlySampleBundleOpt.value().bundleName_) && isExistSim2) {
623                 uidStatsFlagMap_.EnsureInsert(iter->first,
624                     isDisplayTrafficAncoList ? STATS_DATA_FLAG_SIM2_BASIC : STATS_DATA_FLAG_SIM2);
625             } else if (isExistSim) {
626                 uidStatsFlagMap_.EnsureInsert(iter->first,
627                     isDisplayTrafficAncoList ? STATS_DATA_FLAG_SIM_BASIC : STATS_DATA_FLAG_SIM);
628             } else {
629                 uidStatsFlagMap_.EnsureInsert(iter->first, STATS_DATA_FLAG_DEFAULT);
630             }
631         }
632     }
633 }
634 
DeleteUidStatsFlag(uint32_t uid)635 void NetStatsCached::DeleteUidStatsFlag(uint32_t uid)
636 {
637     uidStatsFlagMap_.Erase(uid);
638 }
639 
ClearUidStatsFlag()640 void NetStatsCached::ClearUidStatsFlag()
641 {
642     ForceCachedStats();
643     uidStatsFlagMap_.Clear();
644 }
645 
GetUidStatsFlag(uint32_t uid)646 NetStatsDataFlag NetStatsCached::GetUidStatsFlag(uint32_t uid)
647 {
648     NetStatsDataFlag flag = STATS_DATA_FLAG_DEFAULT;
649     if (uidStatsFlagMap_.Find(uid, flag)) {
650         return flag;
651     }
652     if (uidSimSampleBundleMap_.Size() < 1) {
653         uidStatsFlagMap_.EnsureInsert(uid, flag);
654         return flag;
655     }
656     bool isExistSim = false;
657     uidSimSampleBundleMap_.Iterate([&isExistSim](const uint32_t &k, const SampleBundleInfo &v) {
658         if (CommonUtils::IsSim(v.bundleName_)) {
659             isExistSim = true;
660         }
661     });
662     flag = isExistSim ? (isDisplayTrafficAncoList ? STATS_DATA_FLAG_SIM_BASIC : STATS_DATA_FLAG_SIM) :
663         STATS_DATA_FLAG_DEFAULT;
664     uidStatsFlagMap_.EnsureInsert(uid, flag);
665     return flag;
666 }
667 
GetEarlySampleBundleInfo()668 std::optional<SampleBundleInfo> NetStatsCached::GetEarlySampleBundleInfo()
669 {
670     std::map<uint32_t, SampleBundleInfo> tmp;
671     uidSimSampleBundleMap_.Iterate([&tmp](uint32_t uid, const SampleBundleInfo &info) { tmp.emplace(uid, info); });
672     auto earlySampleBundle = std::max_element(
673         tmp.begin(), tmp.end(), [](std::pair<uint32_t, SampleBundleInfo> l, std::pair<uint32_t, SampleBundleInfo> r) {
674             return l.second.installTime_ > r.second.installTime_;
675         });
676     if (earlySampleBundle != tmp.end()) {
677         return earlySampleBundle->second;
678     } else {
679         NETMGR_LOG_W("SetUidStatsFlag earlySampleBundle is not exist.");
680         return std::nullopt;
681     }
682 }
683 
IsExistInUidSimSampleBundleMap(bool & isExistSim,bool & isExistSim2)684 void NetStatsCached::IsExistInUidSimSampleBundleMap(bool &isExistSim, bool &isExistSim2)
685 {
686     isExistSim = false;
687     isExistSim2 = false;
688     uidSimSampleBundleMap_.Iterate([&isExistSim2, &isExistSim](uint32_t uid, const SampleBundleInfo &info) {
689         if (CommonUtils::IsSim(info.bundleName_)) {
690             isExistSim = true;
691         }
692         if (CommonUtils::IsSim2(info.bundleName_)) {
693             isExistSim2 = true;
694         }
695     });
696 }
697 
DeleteUidStats(uint32_t uid)698 void NetStatsCached::DeleteUidStats(uint32_t uid)
699 {
700     auto ret = NetsysController::GetInstance().DeleteStatsInfo(uid);
701     if (ret != NETMANAGER_SUCCESS) {
702         NETMGR_LOG_E("DeleteUidStats statsInfo failed. ret is %{public}d", ret);
703     }
704     std::lock_guard<ffrt::mutex> lock(lock_);
705     stats_.ResetUidStats(uid);
706     lastUidStatsInfo_.erase(std::remove_if(lastUidStatsInfo_.begin(), lastUidStatsInfo_.end(),
707                                            [uid](const auto &item) { return item.uid_ == uid; }),
708                             lastUidStatsInfo_.end());
709     uidPushStatsInfo_.erase(std::remove_if(uidPushStatsInfo_.begin(), uidPushStatsInfo_.end(),
710                                            [uid](const auto &item) { return item.uid_ == uid; }),
711                             uidPushStatsInfo_.end());
712 }
713 
DeleteUidSimStats(uint32_t uid)714 void NetStatsCached::DeleteUidSimStats(uint32_t uid)
715 {
716     std::optional<SampleBundleInfo> sampleBundleInfoOpt = GetUidSimSampleBundle(uid);
717     DeleteUidSimSampleBundle(uid);
718     if (!sampleBundleInfoOpt.has_value()) {
719         auto ret = NetsysController::GetInstance().DeleteSimStatsInfo(uid);
720         if (ret != NETMANAGER_SUCCESS) {
721             NETMGR_LOG_E("DeleteUidSimStats SimStatsInfo Failed. ret is %{public}d", ret);
722         }
723         std::lock_guard<ffrt::mutex> lock(lock_);
724         stats_.ResetUidSimStats(uid);
725         lastUidSimStatsInfo_.erase(std::remove_if(lastUidSimStatsInfo_.begin(), lastUidSimStatsInfo_.end(),
726                                                   [uid](const auto &item) { return item.uid_ == uid; }),
727                                    lastUidSimStatsInfo_.end());
728         return;
729     }
730     auto sampleBundleInfo = sampleBundleInfoOpt.value();
731     if (!sampleBundleInfo.Valid()) {
732         NETMGR_LOG_W("DeleteUidSimStats invalid info[%{public}s]", sampleBundleInfo.ToString().c_str());
733         return;
734     }
735     if (CommonUtils::IsSim(sampleBundleInfo.bundleName_) ||
736         CommonUtils::IsSim2(sampleBundleInfo.bundleName_)) {
737         if (!isDisplayTrafficAncoList) {
738             auto flag = CommonUtils::IsSim(sampleBundleInfo.bundleName_) ? STATS_DATA_FLAG_SIM : STATS_DATA_FLAG_SIM2;
739             DeleteUidSimStatsWithFlag(uid, flag);
740         } else {
741             auto flagBasic = CommonUtils::IsSim(sampleBundleInfo.bundleName_) ?
742                 STATS_DATA_FLAG_SIM_BASIC : STATS_DATA_FLAG_SIM2_BASIC;
743             auto flagHap = (flagBasic == STATS_DATA_FLAG_SIM_BASIC) ? STATS_DATA_FLAG_SIM : STATS_DATA_FLAG_SIM2;
744             DeleteUidSimStatsWithFlag(uid, flagBasic);
745             DeleteUidSimStatsWithFlag(uid, flagHap);
746         }
747     }
748 }
749 
DeleteUidSimStatsWithFlag(uint32_t uid,uint32_t flag)750 void NetStatsCached::DeleteUidSimStatsWithFlag(uint32_t uid, uint32_t flag)
751 {
752     auto handler = std::make_unique<NetStatsDataHandler>();
753     if (handler == nullptr || handler->UpdateSimDataFlag(flag, STATS_DATA_FLAG_UNINSTALLED) != NETMANAGER_SUCCESS) {
754         NETMGR_LOG_E("DeleteUidSimStats updateFlag failed. uid:[%{public}d], flag[%{public}u]", uid, flag);
755     }
756     std::lock_guard<ffrt::mutex> lock(lock_);
757     lastUidSimStatsInfo_.erase(std::remove_if(lastUidSimStatsInfo_.begin(), lastUidSimStatsInfo_.end(),
758                                               [flag](const auto &item) { return item.flag_ == flag; }),
759                                lastUidSimStatsInfo_.end());
760     std::vector<uint32_t> uidList{uid};
761     uidStatsFlagMap_.Iterate([flag, &uidList](const uint32_t &k, const NetStatsDataFlag &v) {
762         if (flag == v) {
763             uidList.push_back(k);
764         }
765     });
766     std::for_each(uidList.begin(), uidList.end(), [this](const uint32_t uid) {
767         uidStatsFlagMap_.EnsureInsert(uid, STATS_DATA_FLAG_DEFAULT);
768         auto ret = NetsysController::GetInstance().DeleteSimStatsInfo(uid);
769         if (ret != NETMANAGER_SUCCESS) {
770             NETMGR_LOG_E("DeleteUidSimStats SimStatsInfo Failed. ret[%{public}d], uid[%{public}u]", ret, uid);
771         }
772     });
773 }
774 
775 #ifdef SUPPORT_NETWORK_SHARE
DeleteIptablesStats()776 void NetStatsCached::DeleteIptablesStats()
777 {
778     std::lock_guard<ffrt::mutex> lock(lock_);
779     stats_.ResetIptablesStats();
780     lastIptablesStatsInfo_.clear();
781 }
782 #endif
783 
GetKernelUidStats(std::vector<NetStatsInfo> & statsInfo)784 void NetStatsCached::GetKernelUidStats(std::vector<NetStatsInfo> &statsInfo)
785 {
786     std::vector<NetStatsInfo> allInfos;
787     NetsysController::GetInstance().GetAllStatsInfo(allInfos);
788     ifaceNameIdentMap_.Iterate([&allInfos](const std::string &k, const std::string &v) {
789         std::for_each(allInfos.begin(), allInfos.end(), [&k, &v](NetStatsInfo &item) {
790             if (item.iface_ == k) {
791                 item.ident_ = v;
792             }
793         });
794     });
795     std::for_each(allInfos.begin(), allInfos.end(), [this, &statsInfo](NetStatsInfo &info) {
796         if (info.iface_ == IFACE_LO) {
797             return;
798         }
799         NetStatsInfo tmp = GetIncreasedStats(info);
800         if (tmp.HasNoData()) {
801             return;
802         }
803         if (tmp.uid_ > 0) {
804             tmp.userId_ = tmp.uid_ / USER_ID_DIVIDOR;
805         }
806         tmp.date_ = CommonUtils::GetCurrentSecond();
807         statsInfo.push_back(std::move(tmp));
808     });
809 }
810 
GetKernelUidSimStats(std::vector<NetStatsInfo> & statsInfo)811 void NetStatsCached::GetKernelUidSimStats(std::vector<NetStatsInfo> &statsInfo)
812 {
813     std::vector<NetStatsInfo> SimInfos;
814     NetsysController::GetInstance().GetAllSimStatsInfo(SimInfos);
815     ifaceNameIdentMap_.Iterate([&SimInfos](const std::string &k, const std::string &v) {
816         std::for_each(SimInfos.begin(), SimInfos.end(), [&k, &v](NetStatsInfo &item) {
817             if (item.iface_ == k) {
818                 item.ident_ = v;
819             }
820         });
821     });
822     uidStatsFlagMap_.Iterate([&SimInfos](const uint32_t &k, const NetStatsDataFlag &v) {
823         std::for_each(SimInfos.begin(), SimInfos.end(), [&k, &v](NetStatsInfo &item) {
824             if (item.uid_ == k) {
825                 item.flag_ = v;
826             }
827         });
828     });
829     std::for_each(SimInfos.begin(), SimInfos.end(), [this, &statsInfo](NetStatsInfo &info) {
830         if (info.iface_ == IFACE_LO) {
831             return;
832         }
833         NetStatsInfo tmp = GetIncreasedSimStats(info);
834         if (tmp.HasNoData()) {
835             return;
836         }
837         tmp.date_ = CommonUtils::GetCurrentSecond();
838         if (tmp.flag_ <= STATS_DATA_FLAG_DEFAULT || tmp.flag_ >= STATS_DATA_FLAG_LIMIT) {
839             tmp.flag_ = GetUidStatsFlag(tmp.uid_);
840         }
841 
842         if (!isDisplayTrafficAncoList) {
843             if (tmp.flag_ == STATS_DATA_FLAG_SIM2) {
844                 tmp.uid_ = SIM2_UID;
845             } else if (tmp.flag_ == STATS_DATA_FLAG_SIM) {
846                 tmp.uid_ = Sim_UID;
847             } else {
848                 return;
849             }
850         } else {
851             if (tmp.flag_ == STATS_DATA_FLAG_SIM_BASIC) {
852                 tmp.uid_ = Sim_UID;
853             } else if (tmp.flag_ == STATS_DATA_FLAG_SIM2_BASIC) {
854                 tmp.uid_ = SIM2_UID;
855             } else if (tmp.flag_ != STATS_DATA_FLAG_SIM && tmp.flag_ != STATS_DATA_FLAG_SIM2) {
856                 return;
857             }
858         }
859         statsInfo.push_back(std::move(tmp));
860     });
861 }
862 
863 #ifdef SUPPORT_NETWORK_SHARE
GetIptablesStatsCached(std::vector<NetStatsInfo> & iptablesStatsInfo)864 void NetStatsCached::GetIptablesStatsCached(std::vector<NetStatsInfo> &iptablesStatsInfo)
865 {
866     std::lock_guard<ffrt::mutex> lock(lock_);
867     iptablesStatsInfo.insert(iptablesStatsInfo.end(),
868         stats_.GetIptablesStatsInfo().begin(), stats_.GetIptablesStatsInfo().end());
869     GetIptablesStatsIncrease(iptablesStatsInfo);
870 }
871 
CacheIptablesStats()872 void NetStatsCached::CacheIptablesStats()
873 {
874     std::string ifaceName;
875     nmd::NetworkSharingTraffic traffic;
876 
877     int32_t ret = NetsysController::GetInstance().GetNetworkCellularSharingTraffic(traffic, ifaceName);
878     if (ret != NETMANAGER_SUCCESS) {
879         NETMGR_LOG_I("GetTrafficBytes err, ret[%{public}d]", ret);
880         return;
881     }
882     CacheIptablesStatsService(traffic, ifaceName);
883 }
884 
CacheIptablesStatsService(nmd::NetworkSharingTraffic & traffic,std::string & ifaceName)885 void NetStatsCached::CacheIptablesStatsService(nmd::NetworkSharingTraffic &traffic, std::string &ifaceName)
886 {
887     NetStatsInfo statsInfos;
888     statsInfos.uid_ = IPTABLES_UID;
889     statsInfos.iface_ = ifaceName;
890     statsInfos.rxBytes_ = static_cast<uint64_t>(traffic.receive);
891     statsInfos.txBytes_ = static_cast<uint64_t>(traffic.send);
892     statsInfos.flag_ = STATS_DATA_FLAG_DEFAULT;
893     statsInfos.rxPackets_ = statsInfos.rxBytes_ > 0 ? 1 : 0;
894     statsInfos.txPackets_ = statsInfos.txBytes_ > 0 ? 1 : 0;
895     std::vector<NetStatsInfo> statsInfosVec;
896     statsInfosVec.push_back(std::move(statsInfos));
897 
898     ifaceNameIdentMap_.Iterate([&statsInfosVec](const std::string &k, const std::string &v) {
899         std::for_each(statsInfosVec.begin(), statsInfosVec.end(), [&k, &v](NetStatsInfo &item) {
900             if (item.iface_ == k) {
901                 item.ident_ = v;
902             }
903         });
904     });
905 
906     std::for_each(statsInfosVec.begin(), statsInfosVec.end(), [this](NetStatsInfo &info) {
907         if (info.iface_ == IFACE_LO) {
908             return;
909         }
910         auto findRet = std::find_if(lastIptablesStatsInfo_.begin(), lastIptablesStatsInfo_.end(),
911             [this, &info](const NetStatsInfo &lastInfo) {return info.Equals(lastInfo); });
912         if (findRet == lastIptablesStatsInfo_.end()) {
913             stats_.PushIptablesStats(info);
914             return;
915         }
916         auto currentStats = info - *findRet;
917         stats_.PushIptablesStats(currentStats);
918     });
919     NETMGR_LOG_D("CacheIptablesStatsService info success");
920     lastIptablesStatsInfo_.swap(statsInfosVec);
921 }
922 
GetIptablesStatsIncrease(std::vector<NetStatsInfo> & infosVec)923 void NetStatsCached::GetIptablesStatsIncrease(std::vector<NetStatsInfo> &infosVec)
924 {
925     std::string ifaceName;
926     nmd::NetworkSharingTraffic traffic;
927     int32_t ret = NetsysController::GetInstance().GetNetworkCellularSharingTraffic(traffic, ifaceName);
928     if (ret != NETMANAGER_SUCCESS) {
929         NETMGR_LOG_E("GetTrafficIncreaseBytes err, ret[%{public}d]", ret);
930         return;
931     }
932     NETMGR_LOG_I("GetIptablesStatsIncrease traffic all=%{public}" PRId64, traffic.all);
933     NetStatsInfo statsInfos;
934     statsInfos.uid_ = IPTABLES_UID;
935     statsInfos.iface_ = ifaceName;
936     statsInfos.rxBytes_ = static_cast<uint64_t>(traffic.receive);
937     statsInfos.txBytes_ = static_cast<uint64_t>(traffic.send);
938     statsInfos.flag_ = STATS_DATA_FLAG_DEFAULT;
939     statsInfos.rxPackets_ = statsInfos.rxBytes_ > 0 ? 1 : 0;
940     statsInfos.txPackets_ = statsInfos.txBytes_ > 0 ? 1 : 0;
941     statsInfos.date_ = CommonUtils::GetCurrentSecond();
942 
943     std::vector<NetStatsInfo> statsInfosVec;
944     statsInfosVec.push_back(std::move(statsInfos));
945 
946     ifaceNameIdentMap_.Iterate([&statsInfosVec](const std::string &k, const std::string &v) {
947         std::for_each(statsInfosVec.begin(), statsInfosVec.end(), [&k, &v](NetStatsInfo &item) {
948             if (item.iface_ == k) {
949                 item.ident_ = v;
950             }
951         });
952     });
953 
954     std::vector<NetStatsInfo> tmpInfosVec;
955     if (!lastIptablesStatsInfo_.empty()) {
956         std::for_each(statsInfosVec.begin(), statsInfosVec.end(),
957             [this, &tmpInfosVec, &statsInfos](NetStatsInfo &info) {
958             if (info.iface_ == IFACE_LO) {
959                 return;
960             }
961             auto findRet = std::find_if(lastIptablesStatsInfo_.begin(), lastIptablesStatsInfo_.end(),
962                 [this, &info](const NetStatsInfo &lastInfo) {return info.Equals(lastInfo); });
963             if (findRet == lastIptablesStatsInfo_.end()) {
964                 tmpInfosVec.push_back(std::move(info));
965             } else {
966                 auto currentStats = info - *findRet;
967                 currentStats.date_ = statsInfos.date_;
968                 tmpInfosVec.push_back(currentStats);
969             }
970         });
971     } else {
972         tmpInfosVec = statsInfosVec;
973     }
974     infosVec.insert(infosVec.end(), tmpInfosVec.begin(), tmpInfosVec.end());
975 }
976 #endif
977 
SaveSharingTraffic(const NetStatsInfo & infos)978 void NetStatsCached::SaveSharingTraffic(const NetStatsInfo &infos)
979 {
980     NETMGR_LOG_I("SaveSharingTraffic enter");
981 #ifdef SUPPORT_NETWORK_SHARE
982     std::lock_guard<ffrt::mutex> lock(lock_);
983     nmd::NetworkSharingTraffic traffic;
984     traffic.receive = infos.rxBytes_;
985     traffic.send = infos.txBytes_;
986     std::string ifaceName = infos.iface_;
987     CacheIptablesStatsService(traffic, ifaceName);
988     WriteIptablesStats();
989     lastIptablesStatsInfo_.clear();
990     NETMGR_LOG_D("SaveSharingTraffic success");
991 #endif
992 }
993 
GetCurPrivateUserId()994 int32_t NetStatsCached::GetCurPrivateUserId()
995 {
996     std::lock_guard<std::mutex> lock(mutex_);
997     return curPrivateUserId_;
998 }
999 
SetCurPrivateUserId(int32_t userId)1000 void NetStatsCached::SetCurPrivateUserId(int32_t userId)
1001 {
1002     std::lock_guard<std::mutex> lock(mutex_);
1003     NETMGR_LOG_I("set privateUserId: %{public}d", userId);
1004     curPrivateUserId_ = userId;
1005 }
1006 
GetCurDefaultUserId()1007 int32_t NetStatsCached::GetCurDefaultUserId()
1008 {
1009     std::lock_guard<std::mutex> lock(mutex_);
1010     return curDefaultUserId_;
1011 }
1012 
SetCurDefaultUserId(int32_t userId)1013 void NetStatsCached::SetCurDefaultUserId(int32_t userId)
1014 {
1015     std::lock_guard<std::mutex> lock(mutex_);
1016     NETMGR_LOG_I("set defaultUserId: %{public}d", userId);
1017     curDefaultUserId_ = userId;
1018 }
1019 } // namespace NetManagerStandard
1020 } // namespace OHOS
1021