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