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 #ifndef NETWORK_VPN_SERVICE_H
17 #define NETWORK_VPN_SERVICE_H
18 
19 #include <memory>
20 #include <string>
21 #include "event_handler.h"
22 #include "i_vpn_conn_state_cb.h"
23 #include "net_vpn_impl.h"
24 #include "networkvpn_service_stub.h"
25 #include "os_account_manager.h"
26 #include "singleton.h"
27 #include "system_ability.h"
28 #include "common_event_manager.h"
29 #include "common_event_subscriber.h"
30 #include "common_event_support.h"
31 #include "application_state_observer_stub.h"
32 #include "app_mgr_client.h"
33 #include "cJSON.h"
34 #include "ffrt.h"
35 #ifdef SUPPORT_SYSVPN
36 #include "ipsec_vpn_ctl.h"
37 #include "vpn_database_helper.h"
38 #endif // SUPPORT_SYSVPN
39 
40 namespace OHOS {
41 namespace NetManagerStandard {
42 namespace {
43 constexpr const char *ALWAYS_ON_VPN_URI =
44     "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true&key=sharing_always_on_vpn";
45 constexpr const char *KEY_ALWAYS_ON_VPN = "settings.netmanager.always_on_vpn";
46 
47 } // namespace
48 using namespace OHOS::EventFwk;
49 class NetworkVpnService : public SystemAbility, public NetworkVpnServiceStub, protected NoCopyable {
50     DECLARE_SYSTEM_ABILITY(NetworkVpnService)
51 
52     NetworkVpnService();
53     virtual ~NetworkVpnService();
54 
55     enum ServiceRunningState {
56         STATE_STOPPED = 0,
57         STATE_RUNNING,
58     };
59 
60     enum {
61         POWER_MODE_MIN = 600,
62         NORMAL_MODE = POWER_MODE_MIN,
63         SAVE_MODE,
64         EXTREME_MODE,
65         LOWPOWER_MODE,
66         POWER_MODE_MAX = LOWPOWER_MODE
67     };
68     class VpnConnStateCb : public IVpnConnStateCb {
69     public:
VpnConnStateCb(const NetworkVpnService &vpnService)70         explicit VpnConnStateCb(const NetworkVpnService &vpnService) : vpnService_(vpnService){};
71         virtual ~VpnConnStateCb() = default;
72         void OnVpnConnStateChanged(const VpnConnectState &state) override;
73 
74     private:
75         const NetworkVpnService &vpnService_;
76     };
77 
78     class ReceiveMessage : public OHOS::EventFwk::CommonEventSubscriber {
79     public:
ReceiveMessage(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, NetworkVpnService &vpnService)80         explicit ReceiveMessage(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, NetworkVpnService &vpnService)
81             : EventFwk::CommonEventSubscriber(subscriberInfo), vpnService_(vpnService){};
82 
83         virtual void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override;
84 
85     private:
86         NetworkVpnService &vpnService_;
87     };
88 
89 public:
GetInstance()90     static NetworkVpnService &GetInstance()
91     {
92         static NetworkVpnService instance;
93         return instance;
94     }
95     /**
96      * service start
97      */
98     void OnStart() override;
99 
100     /**
101      * service stop
102      */
103     void OnStop() override;
104 
105     /**
106      * check current whether has vpn is running
107      */
108     int32_t Prepare(bool &isExistVpn, bool &isRun, std::string &pkg) override;
109 
110     /**
111      * This function is called when the three-party vpn application negotiation ends
112      */
113     int32_t SetUpVpn(const sptr<VpnConfig> &config, bool isVpnExtCall = false) override;
114 
115     /**
116      * protect vpn tunnel
117      */
118     int32_t Protect(bool isVpnExtCall = false) override;
119 
120     /**
121      * stop the vpn connection
122      */
123     int32_t DestroyVpn(bool isVpnExtCall = false) override;
124 
125 #ifdef SUPPORT_SYSVPN
126     /**
127      * This function is called when the system vpn application negotiation ends
128      */
129     int32_t SetUpVpn(const sptr<SysVpnConfig> &config) override;
130 
131     /**
132      * save the vpn config
133      */
134     int32_t AddSysVpnConfig(sptr<SysVpnConfig> &config) override;
135 
136     /**
137      * get the vpn config list
138      */
139     int32_t DeleteSysVpnConfig(const std::string &vpnId) override;
140 
141     /**
142      * get the vpn config listGetConnectedSysVpnConfig
143      */
144     int32_t GetSysVpnConfigList(std::vector<SysVpnConfig> &vpnList) override;
145 
146     /**
147      * get the vpn config
148      */
149     int32_t GetSysVpnConfig(sptr<SysVpnConfig> &config, const std::string &vpnId) override;
150 
151     /**
152      * get the vpn connection state
153      */
154     int32_t GetConnectedSysVpnConfig(sptr<SysVpnConfig> &config) override;
155 
156     /**
157      * notify the vpn connection stage and result
158      */
159     int32_t NotifyConnectStage(const std::string &stage, const int32_t &result) override;
160 
161     int32_t GetSysVpnCertUri(const int32_t certType, std::string &certUri) override;
162 #endif // SUPPORT_SYSVPN
163 
164     /**
165      * register callback
166      */
167     int32_t RegisterVpnEvent(const sptr<IVpnEventCallback> callback) override;
168 
169     /**
170      * unregister callback
171      */
172     int32_t UnregisterVpnEvent(const sptr<IVpnEventCallback> callback) override;
173 
174     /**
175      * create the vpn connection
176      */
177     int32_t CreateVpnConnection(bool isVpnExtCall = false) override;
178 
179     /**
180      * dump function
181      */
182     int32_t Dump(int32_t fd, const std::vector<std::u16string> &args) override;
183 
184 	 /**
185      * factory reset vpn , such as always on vpn
186      *
187      * @return Returns 0 success. Otherwise fail
188      */
189     int32_t FactoryResetVpn() override;
190 
191     /**
192      * persist the always on vpn's package
193      * pass empty will disable always on VPN
194     */
195     int32_t SetAlwaysOnVpn(std::string &pkg, bool &enable);
196 
197     /**
198      * read the persisted always on vpn's package
199     */
200     int32_t GetAlwaysOnVpn(std::string &pkg);
201 
202     int32_t GetSelfAppName(std::string &selfAppName) override;
203 
204 protected:
205     void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
206     void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override;
207 
208 private:
209     bool Init();
210     void GetDumpMessage(std::string &message);
211     int32_t CheckCurrentAccountType(int32_t &userId, std::vector<int32_t> &activeUserIds);
212 
213     void OnVpnMultiUserSetUp();
214     int32_t SyncRegisterVpnEvent(const sptr<IVpnEventCallback> callback);
215     int32_t SyncUnregisterVpnEvent(const sptr<IVpnEventCallback> callback);
216 
217     void OnNetSysRestart();
218     void ConvertVecRouteToJson(const std::vector<Route>& routes, cJSON* jVecRoutes);
219     void ConvertNetAddrToJson(const INetAddr& netAddr, cJSON* jInetAddr);
220     void ParseConfigToJson(const sptr<VpnConfig> &vpnCfg, std::string& jsonString);
221     void SaveVpnConfig(const sptr<VpnConfig> &vpnCfg);
222 
223     void ConvertRouteToConfig(Route& tmp, const cJSON* const mem);
224     void ConvertVecRouteToConfig(sptr<VpnConfig> &vpnCfg, const cJSON* const doc);
225     void ConvertNetAddrToConfig(INetAddr& tmp, const cJSON* const mem);
226     void ConvertVecAddrToConfig(sptr<VpnConfig> &vpnCfg, const cJSON* const doc);
227     void ConvertStringToConfig(sptr<VpnConfig> &vpnCfg, const cJSON* const doc);
228     void ParseJsonToConfig(sptr<VpnConfig> &vpnCfg, const std::string& jsonString);
229     void RecoverVpnConfig();
230 
231     void StartAlwaysOnVpn();
232     void SubscribeCommonEvent();
233     bool PublishEvent(const OHOS::AAFwk::Want &want, int eventCode,
234          bool isOrdered, bool isSticky, const std::vector<std::string> &permissions) const;
235     void PublishVpnConnectionStateEvent(const VpnConnectState &state) const;
236 #ifdef SUPPORT_SYSVPN
237     std::shared_ptr<NetVpnImpl> CreateSysVpnCtl(const sptr<SysVpnConfig> &config, int32_t userId,
238         std::vector<int32_t> &activeUserIds);
239     std::shared_ptr<NetVpnImpl> CreateOpenvpnCtl(sptr<VpnDataBean> vpnBean, int32_t userId,
240         std::vector<int32_t> &activeUserIds);
241     std::shared_ptr<IpsecVpnCtl> CreateIpsecVpnCtl(sptr<VpnDataBean> vpnBean, int32_t userId,
242         std::vector<int32_t> &activeUserIds);
243     int32_t QueryVpnData(const sptr<SysVpnConfig> config, sptr<VpnDataBean> &vpnBean);
244     std::shared_ptr<IpsecVpnCtl> CreateL2tpCtl(sptr<VpnDataBean> vpnBean, int32_t userId,
245         std::vector<int32_t> &activeUserIds);
246 #endif // SUPPORT_SYSVPN
247     std::string GetBundleName();
248     std::string GetCurrentVpnBundleName();
249     std::vector<std::string> GetCurrentVpnAbilityName();
250 
251 private:
252     ServiceRunningState state_ = ServiceRunningState::STATE_STOPPED;
253     bool isServicePublished_ = false;
254     std::shared_ptr<IVpnConnStateCb> vpnConnCallback_;
255     std::shared_ptr<NetVpnImpl> vpnObj_;
256     std::vector<sptr<IVpnEventCallback>> vpnEventCallbacks_;
257     std::shared_ptr<ffrt::queue> networkVpnServiceFfrtQueue_ = nullptr;
258     std::mutex netVpnMutex_;
259     bool hasSARemoved_ = false;
260 
261     std::shared_ptr<ReceiveMessage> subscriber_ = nullptr;
262 
263 private:
264     void RegisterFactoryResetCallback();
265     class FactoryResetCallBack : public IRemoteStub<INetFactoryResetCallback> {
266     public:
FactoryResetCallBack(NetworkVpnService& vpnService)267         explicit FactoryResetCallBack(NetworkVpnService& vpnService):vpnService_(vpnService){};
268 
OnNetFactoryReset()269         int32_t OnNetFactoryReset()
270         {
271             return vpnService_.FactoryResetVpn();
272         }
273     private:
274         NetworkVpnService& vpnService_;
275     };
276 
277     sptr<INetFactoryResetCallback> netFactoryResetCallback_ = nullptr;
278 
279 public:
280     int32_t RegisterBundleName(const std::string &bundleName) override;
281     class VpnHapObserver : public AppExecFwk::ApplicationStateObserverStub {
282     public:
VpnHapObserver(NetworkVpnService &vpnService)283         explicit VpnHapObserver(NetworkVpnService &vpnService) : vpnService_(vpnService){};
284         virtual ~VpnHapObserver() = default;
285         void OnExtensionStateChanged(const AppExecFwk::AbilityStateData &abilityStateData) override ;
286         void OnProcessCreated(const AppExecFwk::ProcessData &processData) override ;
287         void OnProcessStateChanged(const AppExecFwk::ProcessData &processData) override ;
288         void OnProcessDied(const AppExecFwk::ProcessData &processData) override ;
289     private:
290         NetworkVpnService& vpnService_;
291     };
292 private:
293     class VpnAppDeathRecipient : public IRemoteObject::DeathRecipient {
294     public:
VpnAppDeathRecipient(NetworkVpnService &client)295         explicit VpnAppDeathRecipient(NetworkVpnService &client) : client_(client) {}
296         ~VpnAppDeathRecipient() override = default;
297         void OnRemoteDied(const wptr<IRemoteObject> &remote) override
298         {
299             client_.OnRemoteDied(remote);
300         }
301 
302     private:
303         NetworkVpnService &client_;
304     };
305     void OnRemoteDied(const wptr<IRemoteObject> &remoteObject);
306     void AddClientDeathRecipient(const sptr<IVpnEventCallback> &callback);
307     void RemoveClientDeathRecipient(const sptr<IVpnEventCallback> &callback);
308     void RemoveALLClientDeathRecipient();
309 
310     std::mutex remoteMutex_;
311     sptr<IRemoteObject::DeathRecipient> deathRecipient_ = nullptr;
312     sptr<VpnHapObserver> vpnHapObserver_ = nullptr;
313     int32_t hasOpenedVpnUid_ = 0;
314     std::string currentVpnBundleName_;
315     std::vector<std::string> currentVpnAbilityName_;
316 };
317 } // namespace NetManagerStandard
318 } // namespace OHOS
319 #endif // NETWORK_VPN_SERVICE_H
320