1 /*
2  * Copyright (c) 2023-2024 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 "networkvpn_service.h"
17 
18 #include <cerrno>
19 #include <ctime>
20 #include <fcntl.h>
21 #include <sys/socket.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <sys/un.h>
25 #include <unistd.h>
26 #include <string>
27 #include <fstream>
28 #include <thread>
29 
30 #include "ipc_skeleton.h"
31 #include "securec.h"
32 #include "system_ability_definition.h"
33 #include "iservice_registry.h"
34 
35 #include "ability_manager_client.h"
36 #include "extended_vpn_ctl.h"
37 #include "net_event_report.h"
38 #include "net_manager_center.h"
39 #include "net_manager_constants.h"
40 #include "net_manager_ext_constants.h"
41 #include "netmanager_base_permission.h"
42 #include "netmgr_ext_log_wrapper.h"
43 #include "netsys_controller.h"
44 #include "networkvpn_hisysevent.h"
45 #include "net_datashare_utils_iface.h"
46 #ifdef SUPPORT_SYSVPN
47 #include "vpn_data_bean.h"
48 #endif // SUPPORT_SYSVPN
49 
50 namespace OHOS {
51 namespace NetManagerStandard {
52 constexpr int32_t USER_ID_DIVIDOR  = 200000;
53 constexpr int32_t MAX_CALLBACK_COUNT = 128;
54 constexpr const char *NET_ACTIVATE_WORK_THREAD = "VPN_CALLBACK_WORK_THREAD";
55 constexpr const char* VPN_CONFIG_FILE = "/data/service/el1/public/netmanager/vpn_config.json";
56 constexpr const char* VPN_EXTENSION_LABEL = ":vpn";
57 constexpr uint32_t MAX_GET_SERVICE_COUNT = 30;
58 constexpr uint32_t WAIT_FOR_SERVICE_TIME_S = 1;
59 constexpr uint32_t AGAIN_REGISTER_CALLBACK_INTERVAL = 500;
60 constexpr uint32_t MAX_RETRY_TIMES = 10;
61 constexpr const char *VPNEXT_MODE_URI =
62     "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true&key=vpnext_mode";
63 
64 const bool REGISTER_LOCAL_RESULT_NETVPN =
65     SystemAbility::MakeAndRegisterAbility(&NetworkVpnService::GetInstance());
66 
NetworkVpnService()67 NetworkVpnService::NetworkVpnService() : SystemAbility(COMM_VPN_MANAGER_SYS_ABILITY_ID, true) {}
~NetworkVpnService()68 NetworkVpnService::~NetworkVpnService()
69 {
70     RemoveALLClientDeathRecipient();
71 }
72 
OnStart()73 void NetworkVpnService::OnStart()
74 {
75     if (state_ == STATE_RUNNING) {
76         NETMGR_EXT_LOG_D("OnStart Vpn Service state is already running");
77         return;
78     }
79     if (!Init()) {
80         NETMGR_EXT_LOG_E("OnStart Vpn init failed");
81         VpnHisysEvent::SendFaultEvent(VpnEventType::TYPE_UNKNOWN, VpnEventOperator::OPERATION_START_SA,
82                                       VpnEventErrorType::ERROR_INTERNAL_ERROR, "Start Vpn Service failed");
83         return;
84     }
85     state_ = STATE_RUNNING;
86     NETMGR_EXT_LOG_I("OnStart vpn successful");
87 }
88 
OnStop()89 void NetworkVpnService::OnStop()
90 {
91     state_ = STATE_STOPPED;
92     isServicePublished_ = false;
93 
94     NETMGR_EXT_LOG_I("OnStop vpn successful");
95 }
96 
Dump(int32_t fd,const std::vector<std::u16string> & args)97 int32_t NetworkVpnService::Dump(int32_t fd, const std::vector<std::u16string> &args)
98 {
99     std::string result;
100     GetDumpMessage(result);
101     NETMGR_EXT_LOG_I("Vpn dump fd: %{public}d, content: %{public}s", fd, result.c_str());
102     int32_t ret = dprintf(fd, "%s\n", result.c_str());
103     if (ret < 0) {
104         NETMGR_EXT_LOG_E("dprintf failed, errno[%{public}d]", errno);
105         return NETMANAGER_EXT_ERR_INTERNAL;
106     }
107     return NETMANAGER_EXT_SUCCESS;
108 }
109 
Init()110 bool NetworkVpnService::Init()
111 {
112     if (!REGISTER_LOCAL_RESULT_NETVPN) {
113         NETMGR_EXT_LOG_E("Register to local sa manager failed");
114         return false;
115     }
116     networkVpnServiceFfrtQueue_ = std::make_shared<ffrt::queue>("NetworkVpnService");
117     if (!networkVpnServiceFfrtQueue_) {
118         NETMGR_EXT_LOG_E("FFRT Create Fail");
119         return false;
120     }
121     if (!isServicePublished_) {
122         if (!Publish(&NetworkVpnService::GetInstance())) {
123             NETMGR_EXT_LOG_E("Register to sa manager failed");
124             return false;
125         }
126         isServicePublished_ = true;
127     }
128 
129     AddSystemAbilityListener(COMM_NETSYS_NATIVE_SYS_ABILITY_ID);
130 
131     SubscribeCommonEvent();
132     if (!vpnConnCallback_) {
133         vpnConnCallback_ = std::make_shared<VpnConnStateCb>(*this);
134     }
135 
136     vpnHapObserver_ = new VpnHapObserver(*this);
137     RegisterFactoryResetCallback();
138 #ifdef SUPPORT_SYSVPN
139     vpnDbHelper_ = std::make_shared<VpnDatabaseHelper>();
140     if (vpnDbHelper_ == nullptr) {
141         NETMGR_EXT_LOG_E("vpnDbHelper_ make_shared failed.");
142     }
143 #endif // SUPPORT_SYSVPN
144     return true;
145 }
146 
GetDumpMessage(std::string & message)147 void NetworkVpnService::GetDumpMessage(std::string &message)
148 {
149     std::unique_lock<std::mutex> locker(netVpnMutex_);
150     message.append("Net Vpn Info:\n");
151     if (vpnObj_ != nullptr) {
152         const auto &config = vpnObj_->GetVpnConfig();
153         std::string isLegacy = (config->isLegacy_) ? "true" : "false";
154         message.append("\tisLegacy: " + isLegacy + "\n");
155         message.append("\tPackageName: " + vpnObj_->GetVpnPkg() + "\n");
156         message.append("\tinterface: " + vpnObj_->GetInterfaceName() + "\n");
157         message.append("\tstate: connected\n");
158     } else {
159         message.append("\tstate: disconnected\n");
160     }
161     message.append("\tend.\n");
162 }
163 
OnVpnConnStateChanged(const VpnConnectState & state)164 void NetworkVpnService::VpnConnStateCb::OnVpnConnStateChanged(const VpnConnectState &state)
165 {
166     NETMGR_EXT_LOG_I("receive new vpn connect state[%{public}d].", static_cast<uint32_t>(state));
167     if (!vpnService_.networkVpnServiceFfrtQueue_) {
168         NETMGR_EXT_LOG_E("FFRT Create Fail");
169         return;
170     }
171     std::function<void()> OnVpnConnStateChangedFunction = [this, &state]() {
172         std::for_each(vpnService_.vpnEventCallbacks_.begin(), vpnService_.vpnEventCallbacks_.end(),
173                       [&state](const auto &callback) {
174                           callback->OnVpnStateChanged((VpnConnectState::VPN_CONNECTED == state) ? true : false);
175                       });
176     };
177     ffrt::task_handle OnVpnConnStateTask =
178         vpnService_.networkVpnServiceFfrtQueue_->submit_h(OnVpnConnStateChangedFunction,
179             ffrt::task_attr().name("OnVpnConnStateChanged"));
180     vpnService_.networkVpnServiceFfrtQueue_->wait(OnVpnConnStateTask);
181 }
182 
OnVpnMultiUserSetUp()183 void NetworkVpnService::OnVpnMultiUserSetUp()
184 {
185     NETMGR_EXT_LOG_I("user multiple execute set up.");
186     if (!networkVpnServiceFfrtQueue_) {
187         NETMGR_EXT_LOG_E("FFRT Create Fail");
188         return;
189     }
190     std::function<void()> OnVpnMultiUserSetUpFunction = [this]() {
191         std::for_each(vpnEventCallbacks_.begin(), vpnEventCallbacks_.end(),
192                       [](const auto &callback) { callback->OnVpnMultiUserSetUp(); });
193     };
194     ffrt::task_handle OnVpnMultiUserSetUpTask =
195         networkVpnServiceFfrtQueue_->submit_h(OnVpnMultiUserSetUpFunction,
196             ffrt::task_attr().name("OnVpnMultiUserSetUp"));
197     networkVpnServiceFfrtQueue_->wait(OnVpnMultiUserSetUpTask);
198 }
199 
Prepare(bool & isExistVpn,bool & isRun,std::string & pkg)200 int32_t NetworkVpnService::Prepare(bool &isExistVpn, bool &isRun, std::string &pkg)
201 {
202     std::unique_lock<std::mutex> locker(netVpnMutex_);
203     isRun = false;
204     isExistVpn = false;
205     if (vpnObj_ != nullptr) {
206         isExistVpn = true;
207         isRun = vpnObj_->IsVpnConnecting();
208         pkg = vpnObj_->GetVpnPkg();
209     }
210     NETMGR_EXT_LOG_I("NetworkVpnService Prepare successfully");
211     return NETMANAGER_EXT_SUCCESS;
212 }
213 
ConvertStringToConfig(sptr<VpnConfig> & vpnCfg,const cJSON * const doc)214 void NetworkVpnService::ConvertStringToConfig(sptr<VpnConfig> &vpnCfg, const cJSON* const doc)
215 {
216     cJSON *dnsAddr = cJSON_GetObjectItem(doc, "dnsAddresses");
217     if (dnsAddr != nullptr && cJSON_IsArray(dnsAddr)) {
218         for (int32_t i = 0; i < cJSON_GetArraySize(dnsAddr); i++) {
219             cJSON *item = cJSON_GetArrayItem(dnsAddr, i);
220             if (cJSON_IsString(item)) {
221                 std::string mem = cJSON_GetStringValue(item);
222                 vpnCfg->dnsAddresses_.push_back(mem);
223             }
224         }
225     }
226     cJSON *sDomain = cJSON_GetObjectItem(doc, "searchDomains");
227     if (sDomain != nullptr && cJSON_IsArray(sDomain)) {
228         for (int32_t i = 0; i < cJSON_GetArraySize(sDomain); i++) {
229             cJSON *item = cJSON_GetArrayItem(sDomain, i);
230             if (cJSON_IsString(item)) {
231                 std::string mem = cJSON_GetStringValue(item);
232                 vpnCfg->searchDomains_.push_back(mem);
233             }
234         }
235     }
236     cJSON *acceptApp = cJSON_GetObjectItem(doc, "acceptedApplications");
237     if (acceptApp != nullptr && cJSON_IsArray(acceptApp)) {
238         for (int32_t i = 0; i < cJSON_GetArraySize(acceptApp); i++) {
239             cJSON *item = cJSON_GetArrayItem(acceptApp, i);
240             if (cJSON_IsString(item)) {
241                 std::string mem = cJSON_GetStringValue(item);
242                 NETMGR_EXT_LOG_D("acceptApp = %{public}s", mem.c_str());
243                 vpnCfg->acceptedApplications_.push_back(mem);
244             }
245         }
246     }
247     cJSON *refusedApp = cJSON_GetObjectItem(doc, "refusedApplications");
248     if (refusedApp != nullptr && cJSON_IsArray(refusedApp)) {
249         for (int32_t i = 0; i < cJSON_GetArraySize(refusedApp); i++) {
250             cJSON *item = cJSON_GetArrayItem(refusedApp, i);
251             if (cJSON_IsString(item)) {
252                 std::string mem = cJSON_GetStringValue(item);
253                 NETMGR_EXT_LOG_D("refusedApp = %{public}s", mem.c_str());
254                 vpnCfg->refusedApplications_.push_back(mem);
255             }
256         }
257     }
258 }
259 
ConvertNetAddrToConfig(INetAddr & tmp,const cJSON * const mem)260 void NetworkVpnService::ConvertNetAddrToConfig(INetAddr& tmp, const cJSON* const mem)
261 {
262     cJSON *type = cJSON_GetObjectItem(mem, "type");
263     if (type != nullptr && cJSON_IsNumber(type)) {
264         tmp.type_ = static_cast<int32_t>(cJSON_GetNumberValue(type));
265         NETMGR_EXT_LOG_D("type = %{public}d", tmp.type_);
266     }
267     cJSON *family = cJSON_GetObjectItem(mem, "family");
268     if (family != nullptr && cJSON_IsNumber(family)) {
269         tmp.family_ = static_cast<int32_t>(cJSON_GetNumberValue(family));
270         NETMGR_EXT_LOG_D("family = %{public}d", tmp.family_);
271     }
272     cJSON *prefixlen = cJSON_GetObjectItem(mem, "prefixlen");
273     if (prefixlen != nullptr && cJSON_IsNumber(prefixlen)) {
274         tmp.prefixlen_ = static_cast<int32_t>(cJSON_GetNumberValue(prefixlen));
275         NETMGR_EXT_LOG_D("prefixlen = %{public}d", tmp.prefixlen_);
276     }
277     cJSON *address = cJSON_GetObjectItem(mem, "address");
278     if (address != nullptr && cJSON_IsString(address)) {
279         tmp.address_ = cJSON_GetStringValue(address);
280     }
281     cJSON *netMask = cJSON_GetObjectItem(mem, "netMask");
282     if (netMask != nullptr && cJSON_IsString(netMask)) {
283         tmp.netMask_ = cJSON_GetStringValue(netMask);
284         NETMGR_EXT_LOG_D("netMask = %{public}s", tmp.netMask_.c_str());
285     }
286     cJSON *hostName = cJSON_GetObjectItem(mem, "hostName");
287     if (hostName != nullptr && cJSON_IsString(hostName)) {
288         tmp.hostName_ = cJSON_GetStringValue(hostName);
289     }
290     cJSON *port = cJSON_GetObjectItem(mem, "port");
291     if (port != nullptr && cJSON_IsNumber(port)) {
292         tmp.port_ = static_cast<int32_t>(cJSON_GetNumberValue(port));
293         NETMGR_EXT_LOG_D("port = %{public}d", tmp.port_);
294     }
295 }
296 
ConvertVecAddrToConfig(sptr<VpnConfig> & vpnCfg,const cJSON * const doc)297 void NetworkVpnService::ConvertVecAddrToConfig(sptr<VpnConfig> &vpnCfg, const cJSON* const doc)
298 {
299     cJSON *addresses = cJSON_GetObjectItem(doc, "addresses");
300     if (addresses != nullptr && cJSON_IsArray(addresses)) {
301         uint32_t itemSize = cJSON_GetArraySize(addresses);
302         for (uint32_t i = 0; i < itemSize; i++) {
303             cJSON *item = cJSON_GetArrayItem(addresses, i);
304             if (cJSON_IsObject(item)) {
305                 INetAddr tmp;
306                 ConvertNetAddrToConfig(tmp, item);
307                 vpnCfg->addresses_.push_back(tmp);
308             }
309         }
310     }
311 }
312 
ConvertRouteToConfig(Route & tmp,const cJSON * const mem)313 void NetworkVpnService::ConvertRouteToConfig(Route& tmp, const cJSON* const mem)
314 {
315     cJSON *iface = cJSON_GetObjectItem(mem, "iface");
316     if (iface != nullptr && cJSON_IsString(iface)) {
317         tmp.iface_ = cJSON_GetStringValue(iface);
318         NETMGR_EXT_LOG_D("iface = %{public}s", tmp.iface_.c_str());
319     }
320     cJSON *rtnType = cJSON_GetObjectItem(mem, "rtnType");
321     if (rtnType != nullptr && cJSON_IsNumber(rtnType)) {
322         tmp.rtnType_ = cJSON_GetNumberValue(rtnType);
323         NETMGR_EXT_LOG_D("rtnType = %{public}d", tmp.rtnType_);
324     }
325     cJSON *mtu = cJSON_GetObjectItem(mem, "mtu");
326     if (mtu != nullptr && cJSON_IsNumber(mtu)) {
327         tmp.mtu_ = cJSON_GetNumberValue(mtu);
328         NETMGR_EXT_LOG_D("mtu = %{public}d", tmp.mtu_);
329     }
330     cJSON *isHost = cJSON_GetObjectItem(mem, "isHost");
331     if (isHost != nullptr && cJSON_IsBool(isHost)) {
332         tmp.isHost_ = cJSON_IsTrue(isHost) ? true : false;
333         NETMGR_EXT_LOG_D("isHost = %{public}d", tmp.isHost_);
334     }
335     cJSON *hasGateway = cJSON_GetObjectItem(mem, "hasGateway");
336     if (hasGateway != nullptr && cJSON_IsBool(hasGateway)) {
337         tmp.hasGateway_ = cJSON_IsTrue(hasGateway) ? true : false;
338         NETMGR_EXT_LOG_D("hasGateway_ = %{public}d", tmp.hasGateway_);
339     }
340     cJSON *isDefaultRoute = cJSON_GetObjectItem(mem, "isDefaultRoute");
341     if (isDefaultRoute != nullptr && cJSON_IsBool(isDefaultRoute)) {
342         tmp.isDefaultRoute_ = cJSON_IsTrue(isDefaultRoute) ? true : false;
343         NETMGR_EXT_LOG_D("isDefaultRoute_ = %{public}d", tmp.isDefaultRoute_);
344     }
345     cJSON *destination = cJSON_GetObjectItem(mem, "destination");
346     if (destination != nullptr && cJSON_IsObject(destination)) {
347         INetAddr tmpINet;
348         ConvertNetAddrToConfig(tmpINet, destination);
349         tmp.destination_ = tmpINet;
350     }
351     cJSON *gateway = cJSON_GetObjectItem(mem, "gateway");
352     if (gateway != nullptr && cJSON_IsObject(gateway)) {
353         INetAddr tmpINet;
354         ConvertNetAddrToConfig(tmpINet, gateway);
355         tmp.gateway_ = tmpINet;
356     }
357 }
358 
ConvertVecRouteToConfig(sptr<VpnConfig> & vpnCfg,const cJSON * const doc)359 void NetworkVpnService::ConvertVecRouteToConfig(sptr<VpnConfig> &vpnCfg, const cJSON* const doc)
360 {
361     cJSON *routes = cJSON_GetObjectItem(doc, "routes");
362     if (routes != nullptr && cJSON_IsArray(routes)) {
363         uint32_t itemSize = cJSON_GetArraySize(routes);
364         for (uint32_t i = 0; i < itemSize; i++) {
365             cJSON *item = cJSON_GetArrayItem(routes, i);
366             if (cJSON_IsObject(item)) {
367                 Route tmp;
368                 ConvertRouteToConfig(tmp, item);
369                 vpnCfg->routes_.push_back(tmp);
370             }
371         }
372     }
373 }
374 
ParseJsonToConfig(sptr<VpnConfig> & vpnCfg,const std::string & jsonString)375 void NetworkVpnService::ParseJsonToConfig(sptr<VpnConfig> &vpnCfg, const std::string& jsonString)
376 {
377     cJSON *doc = cJSON_Parse(jsonString.c_str());
378     if (doc == nullptr) {
379         NETMGR_EXT_LOG_E("jsonString parse failed!");
380         return;
381     }
382     cJSON *mtu = cJSON_GetObjectItem(doc, "mtu");
383     if (mtu != nullptr && cJSON_IsNumber(mtu)) {
384         vpnCfg->mtu_ = cJSON_GetNumberValue(mtu);
385         NETMGR_EXT_LOG_D("mtu = %{public}d", vpnCfg->mtu_);
386     }
387     cJSON *isAcceptIPv4 = cJSON_GetObjectItem(doc, "isAcceptIPv4");
388     if (isAcceptIPv4 != nullptr && cJSON_IsBool(isAcceptIPv4)) {
389         vpnCfg->isAcceptIPv4_ = cJSON_IsTrue(isAcceptIPv4);
390         NETMGR_EXT_LOG_D("isAcceptIPv4 = %{public}d", vpnCfg->isAcceptIPv4_);
391     }
392     cJSON *isAcceptIPv6 = cJSON_GetObjectItem(doc, "isAcceptIPv6");
393     if (isAcceptIPv6 != nullptr && cJSON_IsBool(isAcceptIPv6)) {
394         vpnCfg->isAcceptIPv6_ = cJSON_IsTrue(isAcceptIPv6);
395         NETMGR_EXT_LOG_D("isAcceptIPv6 = %{public}d", vpnCfg->isAcceptIPv6_);
396     }
397     cJSON *isLegacy = cJSON_GetObjectItem(doc, "isLegacy");
398     if (isLegacy != nullptr && cJSON_IsBool(isLegacy)) {
399         vpnCfg->isLegacy_ = cJSON_IsTrue(isLegacy);
400         NETMGR_EXT_LOG_D("isLegacy = %{public}d", vpnCfg->isLegacy_);
401     }
402     cJSON *isMetered = cJSON_GetObjectItem(doc, "isMetered");
403     if (isMetered != nullptr && cJSON_IsBool(isMetered)) {
404         vpnCfg->isMetered_ = cJSON_IsTrue(isMetered);
405         NETMGR_EXT_LOG_D("isMetered = %{public}d", vpnCfg->isMetered_);
406     }
407     cJSON *isBlocking = cJSON_GetObjectItem(doc, "isBlocking");
408     if (isBlocking != nullptr && cJSON_IsBool(isBlocking)) {
409         vpnCfg->isBlocking_ = cJSON_IsTrue(isBlocking);
410         NETMGR_EXT_LOG_D("isBlocking = %{public}d", vpnCfg->isBlocking_);
411     }
412 
413     ConvertStringToConfig(vpnCfg, doc);
414 
415     ConvertVecAddrToConfig(vpnCfg, doc);
416 
417     ConvertVecRouteToConfig(vpnCfg, doc);
418 
419     cJSON_Delete(doc);
420 }
421 
RecoverVpnConfig()422 void NetworkVpnService::RecoverVpnConfig()
423 {
424     sptr<VpnConfig> vpnCfg = new VpnConfig();
425     std::ifstream ifs(VPN_CONFIG_FILE);
426     if (!ifs) {
427         NETMGR_EXT_LOG_D("file don't exist, don't need recover");
428         return;
429     }
430     std::string jsonString;
431     std::getline(ifs, jsonString);
432     ParseJsonToConfig(vpnCfg, jsonString);
433     SetUpVpn(vpnCfg);
434 }
435 
ConvertNetAddrToJson(const INetAddr & netAddr,cJSON * jInetAddr)436 void NetworkVpnService::ConvertNetAddrToJson(const INetAddr& netAddr, cJSON* jInetAddr)
437 {
438     cJSON_AddItemToObject(jInetAddr, "type", cJSON_CreateNumber(netAddr.type_));
439     cJSON_AddItemToObject(jInetAddr, "family", cJSON_CreateNumber(netAddr.family_));
440     cJSON_AddItemToObject(jInetAddr, "prefixlen", cJSON_CreateNumber(netAddr.prefixlen_));
441     cJSON_AddItemToObject(jInetAddr, "address", cJSON_CreateString(netAddr.address_.c_str()));
442     cJSON_AddItemToObject(jInetAddr, "netMask", cJSON_CreateString(netAddr.netMask_.c_str()));
443     cJSON_AddItemToObject(jInetAddr, "hostName", cJSON_CreateString(netAddr.hostName_.c_str()));
444     cJSON_AddItemToObject(jInetAddr, "port", cJSON_CreateNumber(netAddr.port_));
445 }
446 
ConvertVecRouteToJson(const std::vector<Route> & routes,cJSON * jVecRoutes)447 void NetworkVpnService::ConvertVecRouteToJson(const std::vector<Route>& routes, cJSON* jVecRoutes)
448 {
449     for (const auto& mem : routes) {
450         cJSON *jRoute = cJSON_CreateObject();
451         cJSON_AddItemToObject(jRoute, "iface", cJSON_CreateString(mem.iface_.c_str()));
452         cJSON *jDestination = cJSON_CreateObject();
453         ConvertNetAddrToJson(mem.destination_, jDestination);
454         cJSON_AddItemToObject(jRoute, "destination", jDestination);
455         cJSON *jGateway = cJSON_CreateObject();
456         ConvertNetAddrToJson(mem.gateway_, jGateway);
457         cJSON_AddItemToObject(jRoute, "gateway", jGateway);
458         cJSON_AddItemToObject(jRoute, "rtnType", cJSON_CreateNumber(mem.rtnType_));
459         cJSON_AddItemToObject(jRoute, "mtu", cJSON_CreateNumber(mem.mtu_));
460         cJSON_AddItemToObject(jRoute, "isHost", cJSON_CreateBool(mem.isHost_));
461         cJSON_AddItemToObject(jRoute, "hasGateway", cJSON_CreateBool(mem.hasGateway_));
462         cJSON_AddItemToObject(jRoute, "isDefaultRoute", cJSON_CreateBool(mem.isDefaultRoute_));
463         cJSON_AddItemToArray(jVecRoutes, jRoute);
464     }
465 }
466 
ParseConfigToJson(const sptr<VpnConfig> & vpnCfg,std::string & jsonString)467 void NetworkVpnService::ParseConfigToJson(const sptr<VpnConfig> &vpnCfg, std::string& jsonString)
468 {
469     cJSON *root = cJSON_CreateObject();
470     cJSON *jVecAddrs = cJSON_CreateArray();
471     for (const auto& mem : vpnCfg->addresses_) {
472         cJSON *jInetAddr = cJSON_CreateObject();
473         ConvertNetAddrToJson(mem, jInetAddr);
474         cJSON_AddItemToArray(jVecAddrs, jInetAddr);
475     }
476     cJSON_AddItemToObject(root, "addresses", jVecAddrs);
477 
478     cJSON *jVecRoutes = cJSON_CreateArray();
479     ConvertVecRouteToJson(vpnCfg->routes_, jVecRoutes);
480     cJSON_AddItemToObject(root, "routes", jVecRoutes);
481 
482     cJSON_AddItemToObject(root, "mtu", cJSON_CreateNumber(vpnCfg->mtu_));
483     cJSON_AddItemToObject(root, "isAcceptIPv4", cJSON_CreateBool(vpnCfg->isAcceptIPv4_));
484     cJSON_AddItemToObject(root, "isAcceptIPv6", cJSON_CreateBool(vpnCfg->isAcceptIPv6_));
485     cJSON_AddItemToObject(root, "isLegacy", cJSON_CreateBool(vpnCfg->isLegacy_));
486     cJSON_AddItemToObject(root, "isMetered", cJSON_CreateBool(vpnCfg->isMetered_));
487     cJSON_AddItemToObject(root, "isBlocking", cJSON_CreateBool(vpnCfg->isBlocking_));
488 
489     cJSON *jVecDnsAddrs = cJSON_CreateArray();
490     for (const auto& mem : vpnCfg->dnsAddresses_) {
491         cJSON_AddItemToArray(jVecDnsAddrs, cJSON_CreateString(mem.c_str()));
492     }
493     cJSON_AddItemToObject(root, "dnsAddresses", jVecDnsAddrs);
494 
495     cJSON *jVecDomains = cJSON_CreateArray();
496     for (const auto& mem : vpnCfg->searchDomains_) {
497         cJSON_AddItemToArray(jVecDomains, cJSON_CreateString(mem.c_str()));
498     }
499     cJSON_AddItemToObject(root, "searchDomains", jVecDomains);
500 
501     cJSON *jVecAcceptApp = cJSON_CreateArray();
502     for (const auto& mem : vpnCfg->acceptedApplications_) {
503         cJSON_AddItemToArray(jVecAcceptApp, cJSON_CreateString(mem.c_str()));
504     }
505     cJSON_AddItemToObject(root, "acceptedApplications", jVecAcceptApp);
506 
507     cJSON *jVecRefuseApp = cJSON_CreateArray();
508     for (const auto& mem : vpnCfg->refusedApplications_) {
509         cJSON_AddItemToArray(jVecRefuseApp, cJSON_CreateString(mem.c_str()));
510     }
511     cJSON_AddItemToObject(root, "refusedApplications", jVecRefuseApp);
512     char *str = cJSON_Print(root);
513     if (str == nullptr) {
514         cJSON_Delete(root);
515         return;
516     }
517     jsonString = str;
518     cJSON_Delete(root);
519     free(str);
520 }
521 
SaveVpnConfig(const sptr<VpnConfig> & vpnCfg)522 void NetworkVpnService::SaveVpnConfig(const sptr<VpnConfig> &vpnCfg)
523 {
524     std::string jsonString;
525     ParseConfigToJson(vpnCfg, jsonString);
526     std::ofstream ofs(VPN_CONFIG_FILE);
527     ofs << jsonString;
528 }
529 
SetUpVpn(const sptr<VpnConfig> & config,bool isVpnExtCall)530 int32_t NetworkVpnService::SetUpVpn(const sptr<VpnConfig> &config, bool isVpnExtCall)
531 {
532     std::unique_lock<std::mutex> locker(netVpnMutex_);
533     std::string vpnBundleName = GetBundleName();
534     if (!NetManagerPermission::CheckPermission(Permission::MANAGE_VPN)) {
535         std::string vpnExtMode;
536         int32_t ret = NetDataShareHelperUtilsIface::Query(VPNEXT_MODE_URI, vpnBundleName, vpnExtMode);
537         NETMGR_EXT_LOG_D("SetUpVpn ret = [%{public}d], bundleName = [%{public}s]", ret, vpnBundleName.c_str());
538         if (ret != 0 || vpnExtMode != "1") {
539             NETMGR_EXT_LOG_E("query datebase fail.");
540             return NETMANAGER_EXT_ERR_PERMISSION_DENIED;
541         }
542     }
543 
544     int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
545     std::vector<int32_t> activeUserIds;
546     auto ret = CheckCurrentAccountType(userId, activeUserIds);
547     if (NETMANAGER_EXT_SUCCESS != ret) {
548         return ret;
549     }
550 
551     if (vpnObj_ != nullptr) {
552         if (vpnObj_->GetUserId() == userId) {
553             NETMGR_EXT_LOG_W("vpn exist already, please execute destory first");
554             return NETWORKVPN_ERROR_VPN_EXIST;
555         } else {
556             NETMGR_EXT_LOG_W("vpn using by other user");
557             return NETWORKVPN_ERROR_VPN_EXIST;
558         }
559     }
560 
561     vpnObj_ = std::make_shared<ExtendedVpnCtl>(config, "", userId, activeUserIds);
562     if (vpnObj_->RegisterConnectStateChangedCb(vpnConnCallback_) != NETMANAGER_EXT_SUCCESS) {
563         NETMGR_EXT_LOG_E("SetUpVpn register internal callback fail.");
564         return NETMANAGER_EXT_ERR_INTERNAL;
565     }
566     ret = vpnObj_->SetUp();
567     if (ret == NETMANAGER_EXT_SUCCESS && !vpnBundleName.empty()) {
568         std::vector<std::string> list = {vpnBundleName, vpnBundleName + VPN_EXTENSION_LABEL};
569         auto regRet =
570             Singleton<AppExecFwk::AppMgrClient>::GetInstance().RegisterApplicationStateObserver(vpnHapObserver_, list);
571         NETMGR_EXT_LOG_I("vpnHapOberver RegisterApplicationStateObserver ret = %{public}d", regRet);
572     }
573     NETMGR_EXT_LOG_I("NetworkVpnService SetUp");
574     if (ret == NETMANAGER_EXT_SUCCESS) {
575         currentVpnBundleName_ = vpnBundleName;
576     }
577     return ret;
578 }
579 
Protect(bool isVpnExtCall)580 int32_t NetworkVpnService::Protect(bool isVpnExtCall)
581 {
582     /*
583      * Only permission verification is performed and
584      * the protected socket implements fwmark_service in the netsys process.
585      */
586     NETMGR_EXT_LOG_I("Protect vpn tunnel successfully.");
587     return NETMANAGER_EXT_SUCCESS;
588 }
589 
DestroyVpn(bool isVpnExtCall)590 int32_t NetworkVpnService::DestroyVpn(bool isVpnExtCall)
591 {
592     std::unique_lock<std::mutex> locker(netVpnMutex_);
593     std::string vpnBundleName = GetBundleName();
594     if (!NetManagerPermission::CheckPermission(Permission::MANAGE_VPN)) {
595         std::string vpnExtMode;
596         int32_t ret = NetDataShareHelperUtilsIface::Query(VPNEXT_MODE_URI, vpnBundleName, vpnExtMode);
597         NETMGR_EXT_LOG_D("DestroyVpn ret = [%{public}d], bundleName = [%{public}s]", ret, vpnBundleName.c_str());
598         if (ret != 0 || vpnExtMode != "1") {
599             NETMGR_EXT_LOG_E("query datebase fail.");
600             return NETMANAGER_EXT_ERR_PERMISSION_DENIED;
601         }
602     }
603 
604     int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
605     std::vector<int32_t> activeUserIds;
606     auto ret = CheckCurrentAccountType(userId, activeUserIds);
607     if (NETMANAGER_EXT_SUCCESS != ret) {
608         return ret;
609     }
610 
611     if ((vpnObj_ != nullptr) && (vpnObj_->Destroy() != NETMANAGER_EXT_SUCCESS)) {
612         NETMGR_EXT_LOG_E("destroy vpn is failed");
613         return NETMANAGER_EXT_ERR_INTERNAL;
614     }
615     vpnObj_ = nullptr;
616     // remove vpn config
617     remove(VPN_CONFIG_FILE);
618 
619     NETMGR_EXT_LOG_I("Destroy vpn successfully.");
620     currentVpnBundleName_.clear();
621     return NETMANAGER_EXT_SUCCESS;
622 }
623 
624 #ifdef SUPPORT_SYSVPN
AddSysVpnConfig(sptr<SysVpnConfig> & config)625 int32_t NetworkVpnService::AddSysVpnConfig(sptr<SysVpnConfig> &config)
626 {
627     if (config == nullptr) {
628         NETMGR_EXT_LOG_E("config is null");
629         return NETMANAGER_EXT_ERR_PARAMETER_ERROR;
630     }
631     std::unique_lock<std::mutex> locker(netVpnMutex_);
632     int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
633     std::vector<int32_t> activeUserIds;
634     int32_t ret = CheckCurrentAccountType(userId, activeUserIds);
635     if (NETMANAGER_EXT_SUCCESS != ret) {
636         NETMGR_EXT_LOG_E("sysvpn service AddSysVpnConfig failed!");
637         return ret;
638     }
639     if (!NetManagerPermission::IsSystemCaller()) {
640         NETMGR_EXT_LOG_E("sysvpn api Caller not have sys permission");
641         return NETMANAGER_EXT_ERR_NOT_SYSTEM_CALL;
642     }
643 
644     NETMGR_EXT_LOG_I("sysvpn service AddSysVpnConfig id=%{public}s name=%{public}s type=%{public}d",
645         config->vpnId_.c_str(), config->vpnName_.c_str(), config->vpnType_);
646 
647     config->userId_ = userId;
648     sptr<VpnDataBean> vpnBean = VpnDataBean::ConvertSysVpnConfigToVpnBean(config);
649     if (vpnDbHelper_ == nullptr || vpnBean == nullptr) {
650         NETMGR_EXT_LOG_E("AddSysVpnConfig failed, vpnDbHelper_ or vpnBean is nullptr");
651         return NETMANAGER_EXT_ERR_OPERATION_FAILED;
652     }
653     return vpnDbHelper_->InsertOrUpdateData(vpnBean);
654 }
655 
DeleteSysVpnConfig(std::string & vpnId)656 int32_t NetworkVpnService::DeleteSysVpnConfig(std::string &vpnId)
657 {
658     if (vpnId.empty()) {
659         NETMGR_EXT_LOG_E("DeleteSysVpnConfig vpnId is null");
660         return NETMANAGER_EXT_ERR_PARAMETER_ERROR;
661     }
662     std::unique_lock<std::mutex> locker(netVpnMutex_);
663     int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
664     std::vector<int32_t> activeUserIds;
665     int32_t ret = CheckCurrentAccountType(userId, activeUserIds);
666     if (NETMANAGER_EXT_SUCCESS != ret) {
667         NETMGR_EXT_LOG_E("sysvpn service DeleteSysVpnConfig failed!");
668         return ret;
669     }
670     if (!NetManagerPermission::IsSystemCaller()) {
671         NETMGR_EXT_LOG_E("sysvpn api Caller not have sys permission");
672         return NETMANAGER_EXT_ERR_NOT_SYSTEM_CALL;
673     }
674 
675     NETMGR_EXT_LOG_I("sysvpn service DeleteSysVpnConfig %{public}s", vpnId.c_str());
676     if (vpnDbHelper_ == nullptr) {
677         NETMGR_EXT_LOG_E("AddSysVpnConfig vpnDbHelper is nullptr");
678         return NETMANAGER_EXT_ERR_OPERATION_FAILED;
679     }
680     int32_t result = vpnDbHelper_->DeleteVpnData(vpnId);
681     if (NETMANAGER_EXT_SUCCESS != result) {
682         NETMGR_EXT_LOG_I("DeleteSystemVpn failed, code = %{public}d", result);
683     }
684     return result;
685 }
686 
GetSysVpnConfigList(std::vector<SysVpnConfig> & vpnList)687 int32_t NetworkVpnService::GetSysVpnConfigList(std::vector<SysVpnConfig> &vpnList)
688 {
689     std::unique_lock<std::mutex> locker(netVpnMutex_);
690     int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
691     std::vector<int32_t> activeUserIds;
692     int32_t ret = CheckCurrentAccountType(userId, activeUserIds);
693     if (NETMANAGER_EXT_SUCCESS != ret) {
694         NETMGR_EXT_LOG_E("sysvpn service GetSysVpnConfigList failed!");
695         return ret;
696     }
697     if (!NetManagerPermission::IsSystemCaller()) {
698         NETMGR_EXT_LOG_E("sysvpn api Caller not have sys permission");
699         return NETMANAGER_EXT_ERR_NOT_SYSTEM_CALL;
700     }
701 
702     NETMGR_EXT_LOG_I("sysvpn service GetSysVpnConfigList");
703     if (vpnDbHelper_ == nullptr) {
704         NETMGR_EXT_LOG_E("GetSysVpnConfigList vpnDbHelper is nullptr");
705         return NETMANAGER_EXT_ERR_OPERATION_FAILED;
706     }
707     int32_t result = vpnDbHelper_->QueryAllData(vpnList, userId);
708     if (NETMANAGER_EXT_SUCCESS != result) {
709         NETMGR_EXT_LOG_I("GetSystemVpnList QueryAllData failed, code = %{public}d", result);
710     }
711     return result;
712 }
713 
GetSysVpnConfig(sptr<SysVpnConfig> & config,std::string & vpnId)714 int32_t NetworkVpnService::GetSysVpnConfig(sptr<SysVpnConfig> &config, std::string &vpnId)
715 {
716     if (vpnId.empty()) {
717         NETMGR_EXT_LOG_E("vpnId is null");
718         return NETMANAGER_EXT_ERR_PARAMETER_ERROR;
719     }
720     std::unique_lock<std::mutex> locker(netVpnMutex_);
721     int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
722     std::vector<int32_t> activeUserIds;
723     int32_t ret = CheckCurrentAccountType(userId, activeUserIds);
724     if (NETMANAGER_EXT_SUCCESS != ret) {
725         NETMGR_EXT_LOG_E("sysvpn service GetSysVpnConfig failed!");
726         return ret;
727     }
728     if (!NetManagerPermission::IsSystemCaller()) {
729         NETMGR_EXT_LOG_E("sysvpn api Caller not have sys permission");
730         return NETMANAGER_EXT_ERR_NOT_SYSTEM_CALL;
731     }
732 
733     NETMGR_EXT_LOG_I("sysvpn service GetSysVpnConfig id=%{public}s", vpnId.c_str());
734     sptr<VpnDataBean> vpnBean = new (std::nothrow) VpnDataBean();
735     if (vpnDbHelper_ == nullptr || vpnBean == nullptr) {
736         NETMGR_EXT_LOG_E("GetSysVpnConfig failed, vpnDbHelper or vpnBean is nullptr");
737         return NETMANAGER_EXT_ERR_OPERATION_FAILED;
738     }
739     int32_t result = vpnDbHelper_->QueryVpnData(vpnBean, vpnId);
740     if (NETMANAGER_EXT_SUCCESS != result) {
741         NETMGR_EXT_LOG_I("GetSysVpnConfig failed, code = %{public}d", result);
742     }
743     config = VpnDataBean::ConvertVpnBeanToSysVpnConfig(vpnBean);
744     return result;
745 }
746 
GetConnectedSysVpnConfig(sptr<SysVpnConfig> & config)747 int32_t NetworkVpnService::GetConnectedSysVpnConfig(sptr<SysVpnConfig> &config)
748 {
749     std::unique_lock<std::mutex> locker(netVpnMutex_);
750     int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
751     std::vector<int32_t> activeUserIds;
752     int32_t ret = CheckCurrentAccountType(userId, activeUserIds);
753     if (NETMANAGER_EXT_SUCCESS != ret) {
754         NETMGR_EXT_LOG_E("sysvpn service GetConnectedSysVpnConfig failed!");
755         return ret;
756     }
757     if (!NetManagerPermission::IsSystemCaller()) {
758         NETMGR_EXT_LOG_E("sysvpn api Caller not have sys permission");
759         return NETMANAGER_EXT_ERR_NOT_SYSTEM_CALL;
760     }
761 
762     if (vpnObj_ == nullptr) {
763         NETMGR_EXT_LOG_I("GetConnectedSysVpnConfig is null. maybe not setup yet");
764         return NETMANAGER_EXT_SUCCESS;
765     }
766     return NETMANAGER_EXT_SUCCESS;
767 }
768 #endif // SUPPORT_SYSVPN
769 
RegisterVpnEvent(const sptr<IVpnEventCallback> callback)770 int32_t NetworkVpnService::RegisterVpnEvent(const sptr<IVpnEventCallback> callback)
771 {
772     int32_t ret = NETMANAGER_EXT_ERR_OPERATION_FAILED;
773     if (!networkVpnServiceFfrtQueue_) {
774         NETMGR_EXT_LOG_E("FFRT Create Fail");
775         return ret;
776     }
777     ffrt::task_handle RegisterVpnEventTask = networkVpnServiceFfrtQueue_->submit_h([this, &callback, &ret]() {
778         ret = SyncRegisterVpnEvent(callback);
779     }, ffrt::task_attr().name("RegisterVpnEvent"));
780     networkVpnServiceFfrtQueue_->wait(RegisterVpnEventTask);
781     return ret;
782 }
783 
UnregisterVpnEvent(const sptr<IVpnEventCallback> callback)784 int32_t NetworkVpnService::UnregisterVpnEvent(const sptr<IVpnEventCallback> callback)
785 {
786     int32_t ret = NETMANAGER_EXT_ERR_OPERATION_FAILED;
787     if (!networkVpnServiceFfrtQueue_) {
788         NETMGR_EXT_LOG_E("FFRT Create Fail");
789         return ret;
790     }
791     ffrt::task_handle UnregisterVpnEventTask = networkVpnServiceFfrtQueue_->submit_h([this, &callback, &ret]() {
792         ret = SyncUnregisterVpnEvent(callback);
793     }, ffrt::task_attr().name("RegisterVpnEvent"));
794     networkVpnServiceFfrtQueue_->wait(UnregisterVpnEventTask);
795     return ret;
796 }
797 
CreateVpnConnection(bool isVpnExtCall)798 int32_t NetworkVpnService::CreateVpnConnection(bool isVpnExtCall)
799 {
800     /*
801      * Only permission verification is performed
802      */
803     NETMGR_EXT_LOG_I("CreateVpnConnection successfully.");
804     return NETMANAGER_EXT_SUCCESS;
805 }
806 
CheckCurrentAccountType(int32_t & userId,std::vector<int32_t> & activeUserIds)807 int32_t NetworkVpnService::CheckCurrentAccountType(int32_t &userId, std::vector<int32_t> &activeUserIds)
808 {
809     int32_t uid = IPCSkeleton::GetCallingUid();
810     int32_t userId_Max = 99;
811     if (AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId) != ERR_OK) {
812         NETMGR_EXT_LOG_E("GetOsAccountLocalIdFromUid error, uid: %{public}d.", uid);
813         return NETMANAGER_EXT_ERR_INTERNAL;
814     }
815 
816     if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserIds) != ERR_OK) {
817         NETMGR_EXT_LOG_E("QueryActiveOsAccountIds error.");
818     }
819 
820     if (userId >= 0 && userId <= userId_Max) {
821        return NETMANAGER_EXT_SUCCESS;
822     }
823 
824     auto itr = std::find_if(activeUserIds.begin(), activeUserIds.end(),
825                             [userId](const int32_t &elem) { return (elem == userId) ? true : false; });
826     if (itr == activeUserIds.end()) {
827         NETMGR_EXT_LOG_E("userId: %{public}d is not active user. activeUserIds.size: %{public}zd", userId,
828                          activeUserIds.size());
829         return NETWORKVPN_ERROR_REFUSE_CREATE_VPN;
830     }
831 
832     activeUserIds.clear();
833 
834     AccountSA::OsAccountInfo accountInfo;
835     if (AccountSA::OsAccountManager::QueryOsAccountById(userId, accountInfo) != ERR_OK) {
836         NETMGR_EXT_LOG_E("QueryOsAccountById error, userId: %{public}d.", userId);
837         return NETMANAGER_EXT_ERR_INTERNAL;
838     }
839 
840     if (accountInfo.GetType() == AccountSA::OsAccountType::GUEST) {
841         NETMGR_EXT_LOG_E("The guest user cannot execute the VPN interface.");
842         return NETWORKVPN_ERROR_REFUSE_CREATE_VPN;
843     }
844     return NETMANAGER_EXT_SUCCESS;
845 }
846 
SyncRegisterVpnEvent(const sptr<IVpnEventCallback> callback)847 int32_t NetworkVpnService::SyncRegisterVpnEvent(const sptr<IVpnEventCallback> callback)
848 {
849     for (auto iterCb = vpnEventCallbacks_.begin(); iterCb != vpnEventCallbacks_.end(); iterCb++) {
850         if ((*iterCb)->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
851             NETMGR_EXT_LOG_E("Register vpn event callback failed, callback already exists");
852             return NETMANAGER_EXT_ERR_OPERATION_FAILED;
853         }
854     }
855 
856     if (vpnEventCallbacks_.size() >= MAX_CALLBACK_COUNT) {
857         NETMGR_EXT_LOG_E("callback above max count, return error.");
858         return NETMANAGER_EXT_ERR_PARAMETER_ERROR;
859     }
860 
861     vpnEventCallbacks_.push_back(callback);
862     AddClientDeathRecipient(callback);
863     NETMGR_EXT_LOG_I("Register vpn event callback successfully");
864     return NETMANAGER_EXT_SUCCESS;
865 }
866 
SyncUnregisterVpnEvent(const sptr<IVpnEventCallback> callback)867 int32_t NetworkVpnService::SyncUnregisterVpnEvent(const sptr<IVpnEventCallback> callback)
868 {
869     for (auto iter = vpnEventCallbacks_.begin(); iter != vpnEventCallbacks_.end(); ++iter) {
870         if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
871             vpnEventCallbacks_.erase(iter);
872             RemoveClientDeathRecipient(callback);
873             NETMGR_EXT_LOG_I("Unregister vpn event successfully.");
874             return NETMANAGER_EXT_SUCCESS;
875         }
876     }
877     NETMGR_EXT_LOG_E("Unregister vpn event callback is does not exist.");
878     return NETMANAGER_EXT_ERR_OPERATION_FAILED;
879 }
880 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)881 void NetworkVpnService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
882 {
883     NETMGR_EXT_LOG_D("NetworkVpnService::OnAddSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
884     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
885         if (hasSARemoved_) {
886             OnNetSysRestart();
887             hasSARemoved_ = false;
888         }
889     }
890 }
891 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)892 void NetworkVpnService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
893 {
894     NETMGR_EXT_LOG_D("NetworkVpnService::OnRemoveSystemAbility systemAbilityId[%{public}d]", systemAbilityId);
895     if (systemAbilityId == COMM_NETSYS_NATIVE_SYS_ABILITY_ID) {
896         hasSARemoved_ = true;
897     }
898 }
899 
OnNetSysRestart()900 void NetworkVpnService::OnNetSysRestart()
901 {
902     std::lock_guard<std::mutex> locker(netVpnMutex_);
903     NETMGR_EXT_LOG_I("NetworkVpnService::OnNetSysRestart");
904     if (vpnObj_ != nullptr) {
905         vpnObj_->ResumeUids();
906     }
907 }
908 
FactoryResetVpn()909 int32_t NetworkVpnService::FactoryResetVpn()
910 {
911     NETMGR_EXT_LOG_I("factory reset Vpn enter.");
912 
913     return NETMANAGER_EXT_SUCCESS;
914 }
915 
RegisterFactoryResetCallback()916 void NetworkVpnService::RegisterFactoryResetCallback()
917 {
918     std::thread t([this]() {
919         uint32_t count = 0;
920         while (NetConnClient::GetInstance().SystemReady() != NETMANAGER_SUCCESS && count < MAX_GET_SERVICE_COUNT) {
921             std::this_thread::sleep_for(std::chrono::seconds(WAIT_FOR_SERVICE_TIME_S));
922             count++;
923         }
924         NETMGR_EXT_LOG_W("NetConnClient Get SystemReady count: %{public}u", count);
925         if (count > MAX_GET_SERVICE_COUNT) {
926             NETMGR_EXT_LOG_E("Connect netconn service fail.");
927         } else {
928             netFactoryResetCallback_ = (std::make_unique<FactoryResetCallBack>(*this)).release();
929             if (netFactoryResetCallback_ != nullptr) {
930                 int ret = NetConnClient::GetInstance().RegisterNetFactoryResetCallback(netFactoryResetCallback_);
931                 if (ret != NETMANAGER_SUCCESS) {
932                     NETMGR_EXT_LOG_E("RegisterNetFactoryResetCallback ret: %{public}d.", ret);
933                 }
934             } else {
935                 NETMGR_EXT_LOG_E("netFactoryResetCallback_ is null.");
936             }
937         }
938     });
939     std::string threadName = "vpnRegisterFactoryResetCallback";
940     pthread_setname_np(t.native_handle(), threadName.c_str());
941     t.detach();
942 }
943 
SetAlwaysOnVpn(std::string & pkg,bool & enable)944 int32_t NetworkVpnService::SetAlwaysOnVpn(std::string &pkg, bool &enable)
945 {
946     int32_t ret = NetDataShareHelperUtilsIface::Update(ALWAYS_ON_VPN_URI, KEY_ALWAYS_ON_VPN, (enable ? pkg:""));
947     if (ret != NETMANAGER_EXT_SUCCESS) {
948         NETMGR_EXT_LOG_E("SetAlwaysOnVpn fail: %{public}d", ret);
949         return NETMANAGER_ERR_INTERNAL;
950     }
951     NETMGR_EXT_LOG_I("SetAlwaysOnVpn success: %{public}s", pkg.c_str());
952 
953     StartAlwaysOnVpn();
954 
955     return NETMANAGER_EXT_SUCCESS;
956 }
957 
GetAlwaysOnVpn(std::string & pkg)958 int32_t NetworkVpnService::GetAlwaysOnVpn(std::string &pkg)
959 {
960     std::string value = "";
961     int32_t ret = NetDataShareHelperUtilsIface::Query(ALWAYS_ON_VPN_URI, KEY_ALWAYS_ON_VPN, value);
962     if (ret != NETMANAGER_EXT_SUCCESS) {
963         NETMGR_EXT_LOG_E("GetAlwaysOnVpn fail: %{public}d", ret);
964         return NETMANAGER_ERR_INTERNAL;
965     }
966     pkg = value;
967     NETMGR_EXT_LOG_I("GetAlwaysOnVpn success: %{public}s", pkg.c_str());
968     return NETMANAGER_EXT_SUCCESS;
969 }
970 
StartAlwaysOnVpn()971 void NetworkVpnService::StartAlwaysOnVpn()
972 {
973     //first, according the uerId, query local vpn config, if exist apply
974     //the config as VPN, if the local VPN is null, query the local kept
975     //package if exist will call up the target app to provide the VPN
976     std::string alwaysOnBundleName = "";
977     int32_t ret = GetAlwaysOnVpn(alwaysOnBundleName);
978     if (ret != NETMANAGER_EXT_SUCCESS) {
979         NETMGR_EXT_LOG_E("StartAlwaysOnVpn fail: %{public}d", ret);
980         return;
981     }
982 
983     if (alwaysOnBundleName != "") {
984         if (vpnObj_ != nullptr) {
985             std::string pkg = vpnObj_->GetVpnPkg();
986             if (pkg != alwaysOnBundleName) {
987                 NETMGR_EXT_LOG_W("vpn [ %{public}s] exist, destroy vpn first", pkg.c_str());
988                 DestroyVpn();
989             }
990         }
991         // recover vpn config
992         RecoverVpnConfig();
993     }
994 }
995 
SubscribeCommonEvent()996 void NetworkVpnService::SubscribeCommonEvent()
997 {
998     EventFwk::MatchingSkills matchingSkills;
999     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
1000     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_SAVE_MODE_CHANGED);
1001     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
1002     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
1003     // 1 means CORE_EVENT_PRIORITY
1004     subscribeInfo.SetPriority(1);
1005     subscriber_ = std::make_shared<ReceiveMessage>(subscribeInfo, *this);
1006     uint32_t tryCount = 0;
1007     bool subscribeResult = false;
1008     while (!subscribeResult && tryCount <= MAX_RETRY_TIMES) {
1009         std::this_thread::sleep_for(std::chrono::milliseconds(AGAIN_REGISTER_CALLBACK_INTERVAL));
1010         subscribeResult = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_);
1011         tryCount++;
1012         NETMGR_EXT_LOG_E("SubscribeCommonEvent try  %{public}d", tryCount);
1013     }
1014 
1015     if (!subscribeResult) {
1016         NETMGR_EXT_LOG_E("SubscribeCommonEvent fail: %{public}d", subscribeResult);
1017     }
1018 }
1019 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)1020 void NetworkVpnService::ReceiveMessage::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
1021 {
1022     const auto &action = eventData.GetWant().GetAction();
1023     const auto &data = eventData.GetData();
1024     const auto &code = eventData.GetCode();
1025     NETMGR_EXT_LOG_I("NetVReceiveMessage::OnReceiveEvent(), event:[%{public}s], data:[%{public}s], code:[%{public}d]",
1026         action.c_str(), data.c_str(), code);
1027     if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_SAVE_MODE_CHANGED) {
1028         bool isPowerSave = (code == SAVE_MODE || code == LOWPOWER_MODE);
1029         if (isPowerSave) {
1030             vpnService_.StartAlwaysOnVpn();
1031         }
1032         return;
1033     }
1034 
1035     if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) {
1036         vpnService_.StartAlwaysOnVpn();
1037     }
1038 
1039     if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) {
1040         std::unique_lock<std::mutex> locker(vpnService_.netVpnMutex_);
1041         std::string vpnBundleName = vpnService_.GetBundleName();
1042         NETMGR_EXT_LOG_D("COMMON_EVENT_PACKAGE_REMOVED, BundleName %{public}s", vpnBundleName.c_str());
1043         NetDataShareHelperUtilsIface::Delete(VPNEXT_MODE_URI, vpnBundleName);
1044     }
1045 }
1046 
RegisterBundleName(const std::string & bundleName)1047 int32_t NetworkVpnService::RegisterBundleName(const std::string &bundleName)
1048 {
1049     return 0;
1050 }
1051 
GetSelfAppName(std::string & selfAppName)1052 int32_t NetworkVpnService::GetSelfAppName(std::string &selfAppName)
1053 {
1054     std::string bundleName;
1055     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1056     if (samgr == nullptr) {
1057         NETMGR_EXT_LOG_E("Get ability manager failed");
1058         return NETMANAGER_EXT_ERR_INTERNAL;
1059     }
1060     auto object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1061     if (object == nullptr) {
1062         NETMGR_EXT_LOG_E("object is NULL.");
1063         return NETMANAGER_EXT_ERR_INTERNAL;
1064     }
1065     auto bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
1066     if (bms == nullptr) {
1067         NETMGR_EXT_LOG_E("bundle manager service is NULL.");
1068         return NETMANAGER_EXT_ERR_INTERNAL;
1069     }
1070     int32_t uid = IPCSkeleton::GetCallingUid();
1071     auto result = bms->GetNameForUid(uid, bundleName);
1072     if (result != NETMANAGER_EXT_SUCCESS) {
1073         NETMGR_EXT_LOG_E("Error GetBundleNameForUid fail");
1074         return NETMANAGER_EXT_ERR_INTERNAL;
1075     }
1076 
1077     auto bundleResourceProxy = bms->GetBundleResourceProxy();
1078     if (bundleResourceProxy == nullptr) {
1079         NETMGR_EXT_LOG_E("Error get bundleResourceProxy fail");
1080         return NETMANAGER_EXT_ERR_INTERNAL;
1081     }
1082     AppExecFwk::BundleResourceInfo bundleResourceInfo;
1083     auto errCode = bundleResourceProxy->GetBundleResourceInfo(
1084         bundleName, static_cast<uint32_t>(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), bundleResourceInfo);
1085     if (errCode != ERR_OK) {
1086         NETMGR_EXT_LOG_E("Error call GetBundleResourceInfo fail %{public}d", static_cast<int>(errCode));
1087         return NETMANAGER_EXT_ERR_INTERNAL;
1088     }
1089     NETMGR_EXT_LOG_I("StartVpnExtensionAbility bundleResourceInfo.label %{public}s", bundleResourceInfo.label.c_str());
1090     selfAppName = bundleResourceInfo.label;
1091     return NETMANAGER_EXT_SUCCESS;
1092 }
1093 
GetBundleName()1094 std::string NetworkVpnService::GetBundleName()
1095 {
1096     std::string bundleName;
1097     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1098     if (samgr == nullptr) {
1099         NETMGR_EXT_LOG_E("Get ability manager failed");
1100         return bundleName;
1101     }
1102 
1103     sptr<IRemoteObject> object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1104     if (object == nullptr) {
1105         NETMGR_EXT_LOG_E("object is NULL.");
1106         return bundleName;
1107     }
1108     sptr<OHOS::AppExecFwk::IBundleMgr> bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
1109     if (bms == nullptr) {
1110         NETMGR_EXT_LOG_E("bundle manager service is NULL.");
1111         return bundleName;
1112     }
1113 
1114     int32_t uid = IPCSkeleton::GetCallingUid();
1115     auto result = bms->GetNameForUid(uid, bundleName);
1116     if (result != NETMANAGER_EXT_SUCCESS) {
1117         NETMGR_EXT_LOG_E("Error GetBundleNameForUid fail");
1118         return bundleName;
1119     }
1120     NETMGR_EXT_LOG_I("bundle name is [%{public}s], uid = [%{public}d]", bundleName.c_str(), uid);
1121 
1122     AppExecFwk::BundleInfo bundleInfo;
1123     auto res = bms->GetBundleInfoV9(
1124         bundleName,
1125         static_cast<int32_t>(
1126             static_cast<uint32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) |
1127             static_cast<uint32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY)),
1128         bundleInfo, uid / USER_ID_DIVIDOR);
1129     if (res != 0) {
1130         NETMGR_EXT_LOG_E("Error GetBundleInfoV9 %{public}d", res);
1131     }
1132     for (const auto &hap : bundleInfo.hapModuleInfos) {
1133         for (const auto &ext : hap.extensionInfos) {
1134             if (ext.type == AppExecFwk::ExtensionAbilityType::VPN) {
1135                 currentVpnAbilityName_.emplace_back(ext.name);
1136             }
1137         }
1138     }
1139 
1140     return bundleName;
1141 }
1142 
OnExtensionStateChanged(const AppExecFwk::AbilityStateData & abilityStateData)1143 void NetworkVpnService::VpnHapObserver::OnExtensionStateChanged(const AppExecFwk::AbilityStateData &abilityStateData)
1144 {
1145     NETMGR_EXT_LOG_I("VPN HAP is OnExtensionStateChanged");
1146 }
1147 
OnProcessCreated(const AppExecFwk::ProcessData & processData)1148 void NetworkVpnService::VpnHapObserver::OnProcessCreated(const AppExecFwk::ProcessData &processData)
1149 {
1150     NETMGR_EXT_LOG_I("VPN HAP is OnProcessCreated");
1151 }
1152 
OnProcessStateChanged(const AppExecFwk::ProcessData & processData)1153 void NetworkVpnService::VpnHapObserver::OnProcessStateChanged(const AppExecFwk::ProcessData &processData)
1154 {
1155     NETMGR_EXT_LOG_I("VPN HAP is OnProcessStateChanged");
1156 }
1157 
GetCurrentVpnBundleName()1158 std::string NetworkVpnService::GetCurrentVpnBundleName()
1159 {
1160     return currentVpnBundleName_;
1161 }
1162 
GetCurrentVpnAbilityName()1163 std::vector<std::string> NetworkVpnService::GetCurrentVpnAbilityName()
1164 {
1165     return currentVpnAbilityName_;
1166 }
1167 
OnProcessDied(const AppExecFwk::ProcessData & processData)1168 void NetworkVpnService::VpnHapObserver::OnProcessDied(const AppExecFwk::ProcessData &processData)
1169 {
1170     std::unique_lock<std::mutex> locker(vpnService_.netVpnMutex_);
1171     auto extensionBundleName = vpnService_.GetCurrentVpnBundleName();
1172     auto extensionAbilityName = vpnService_.GetCurrentVpnAbilityName();
1173     if ((vpnService_.vpnObj_ != nullptr) && (vpnService_.vpnObj_->Destroy() != NETMANAGER_EXT_SUCCESS)) {
1174         NETMGR_EXT_LOG_E("destroy vpn failed");
1175     }
1176     vpnService_.vpnObj_ = nullptr;
1177     for (const auto &name : extensionAbilityName) {
1178         AAFwk::Want want;
1179         AppExecFwk::ElementName elem;
1180         elem.SetBundleName(extensionBundleName);
1181         elem.SetAbilityName(name);
1182         want.SetElement(elem);
1183         auto res = AAFwk::AbilityManagerClient::GetInstance()->StopExtensionAbility(
1184             want, nullptr, AAFwk::DEFAULT_INVAL_VALUE, AppExecFwk::ExtensionAbilityType::VPN);
1185         NETMGR_EXT_LOG_I("VPN HAP is OnProcessDied StopExtensionAbility res= %{public}d", res);
1186     }
1187 }
1188 
OnRemoteDied(const wptr<IRemoteObject> & remoteObject)1189 void NetworkVpnService::OnRemoteDied(const wptr<IRemoteObject> &remoteObject)
1190 {
1191     NETMGR_EXT_LOG_I("vpn OnRemoteDied");
1192     sptr<IRemoteObject> diedRemoted = remoteObject.promote();
1193     if (diedRemoted == nullptr) {
1194         NETMGR_EXT_LOG_E("diedRemoted is null");
1195         return;
1196     }
1197     sptr<IVpnEventCallback> callback = iface_cast<IVpnEventCallback>(diedRemoted);
1198     UnregisterVpnEvent(callback);
1199     DestroyVpn();
1200 }
1201 
AddClientDeathRecipient(const sptr<IVpnEventCallback> & callback)1202 void NetworkVpnService::AddClientDeathRecipient(const sptr<IVpnEventCallback> &callback)
1203 {
1204     NETMGR_EXT_LOG_I("vpn AddClientDeathRecipient");
1205     std::lock_guard<std::mutex> autoLock(remoteMutex_);
1206     if (deathRecipient_ == nullptr) {
1207         deathRecipient_ = new (std::nothrow) VpnAppDeathRecipient(*this);
1208     }
1209     if (deathRecipient_ == nullptr) {
1210         NETMGR_EXT_LOG_E("deathRecipient is null");
1211         return;
1212     }
1213     if (!callback->AsObject()->AddDeathRecipient(deathRecipient_)) {
1214         NETMGR_EXT_LOG_E("AddClientDeathRecipient failed");
1215         return;
1216     }
1217     auto iter =
1218         std::find_if(vpnEventCallbacks_.cbegin(), vpnEventCallbacks_.cend(),
1219                      [&callback](const sptr<IVpnEventCallback> &item) {
1220                         return item->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr();
1221         });
1222     if (iter == vpnEventCallbacks_.cend()) {
1223         vpnEventCallbacks_.emplace_back(callback);
1224     }
1225 }
1226 
RemoveClientDeathRecipient(const sptr<IVpnEventCallback> & callback)1227 void NetworkVpnService::RemoveClientDeathRecipient(const sptr<IVpnEventCallback> &callback)
1228 {
1229     NETMGR_EXT_LOG_I("vpn RemoveClientDeathRecipient");
1230     std::lock_guard<std::mutex> autoLock(remoteMutex_);
1231     auto iter =
1232         std::find_if(vpnEventCallbacks_.cbegin(), vpnEventCallbacks_.cend(),
1233                      [&callback](const sptr<IVpnEventCallback> &item) {
1234                          return item->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr();
1235         });
1236     if (iter == vpnEventCallbacks_.cend()) {
1237         return;
1238     }
1239     callback->AsObject()->RemoveDeathRecipient(deathRecipient_);
1240     vpnEventCallbacks_.erase(iter);
1241 }
1242 
RemoveALLClientDeathRecipient()1243 void NetworkVpnService::RemoveALLClientDeathRecipient()
1244 {
1245     std::lock_guard<std::mutex> autoLock(remoteMutex_);
1246     for (auto &item : vpnEventCallbacks_) {
1247         item->AsObject()->RemoveDeathRecipient(deathRecipient_);
1248     }
1249     vpnEventCallbacks_.clear();
1250     deathRecipient_ = nullptr;
1251 }
1252 } // namespace NetManagerStandard
1253 } // namespace OHOS
1254