• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# VPN Extension Ability Development
2
3## Introduction
4
5A virtual private network (VPN) is a dedicated network established on a public network. Unlike a traditional private network, a VPN does not require an end-to-end physical link between any two nodes. It is built over a network platform (for example, Internet) provided by a public network service provider. User data is transmitted over the logical link.
6
7OpenHarmony provides the VPN Extension solution for enhanced VPN management. The following guides you through on how to develop your own VPN client.
8
9> **NOTE**
10>
11> To maximize the application running efficiency, all APIs are called asynchronously in callback or promise mode. The following code examples use the promise mode. For details about the APIs, see [API Reference](../reference/apis-network-kit/js-apis-net-vpnExtension.md).
12
13## VPN Extension Ability UI
14
15With the VPN Extension APIs provided by OpenHarmony, you can build VPN services that support different protocols. OpenHarmony provides a UI for users to learn about VPN startup and connection.
16
17- When the VPN application sets up a connection for the first time, the VPN connection authorization dialog box is displayed. The dialog box prompts users whether to trust the VPN application and accept the VPN connection request.
18- If the VPN connection is successful, a VPN icon (a key) is displayed in the status bar to remind the user that the VPN is connected.
19
20To facilitate the query and configuration, your VPN application needs to provide the following UIs:
21
22- UI for manually starting and stopping the VPN connection.
23- UI for displaying the connection status of the VPN application in the notification bar  or providing network statistics (such as the connection duration and traffic) of the VPN connection. Touching the notification in notification bar should bring your VPN application to the foreground.
24
25## Available APIs
26
27For details about the complete JavaScript APIs and sample code, see [API Reference](../reference/apis-network-kit/js-apis-net-vpnExtension.md).
28
29## Creating a VPN Extension Ability
30
31To enable your application to support the VPN functionality, you need to create an **ExtensionAbilities** instance inherited from **VpnExtensionAbility**.
32
33```ts
34// Assume that the VNP application is named MyVpnExtAbility. Define it in module.json5.
35"extensionAbilities": [
36  {
37    "name": "MyVpnExtAbility",
38    "description": "vpnservice",
39    "type": "vpn",
40    "srcEntry": "./ets/serviceextability/MyVpnExtAbility.ts"
41  }
42]
43```
44
45> **NOTE**
46>
47> If the DevEco Studio tool displays a message indicating unrecognizable **"type": "vpn"**, you need to manually add **vpn** to the **type** enums corresponding to **extensionAbilities** in the **toolchains\modulecheck\module.json** file of the SDK and clear the build cache.
48
49Next, you need to configure, start, and stop the VPN in the created **VpnExtensionAbility**.
50
51- Create a VPN tunnel. The TCP tunnel is used as an example. For details, see **TcpConnect()** in [vpn_client](https://gitee.com/openharmony/applications_app_samples/blob/master/code/BasicFeature/Connectivity/VPN/entry/src/main/cpp/vpn_client.cpp) demo project.
52- Use [VpnConnection.protect](../reference/apis-network-kit/js-apis-net-vpnExtension.md#protect) to enable protection for the TCP tunnel.
53- Construct VPN Config parameters. For details, see [VPN Config Parameters](#description-of-vpn-config-parameters).
54- Use [VpnConnection.create](../reference/apis-network-kit/js-apis-net-vpnExtension.md#create) to establish a VPN connection.
55- Process data of the virtual network interface card (vNIC), such as reading or writing data.
56
57
58## Starting the VPN Extension Ability
59
60To start a connection from the VPN application, you need to call **startVpnExtensionAbility** with the **VpnExtensionAbility** information specified. Make sure that **bundleName** is the same as that of the VPN application, and **abilityName** is the name of the **VpnExtensionAbility** you created. The sample code is as follows:
61
62```ts
63import { common, Want } from '@kit.AbilityKit';
64import { vpnExtension } from '@kit.NetworkKit';
65
66let context = getContext(this) as common.VpnExtensionContext;
67let want: Want = {
68  deviceId: "",
69  bundleName: "com.example.myvpndemo",
70  abilityName: "MyVpnExtAbility",
71};
72
73@Entry
74@Component
75struct Index {
76  @State message: string = 'Hello World';
77
78  build() {
79    Row() {
80      Column() {
81        Text(this.message)
82          .fontSize(50)
83          .fontWeight(FontWeight.Bold).onClick(() => {
84          console.info("btn click") })
85        Button('Start Extension').onClick(() => {
86          vpnExtension.startVpnExtensionAbility(want);
87        }).width('70%').fontSize(45).margin(16)
88        }.width('100%')
89    }.height('100%')
90  }
91}
92```
93
94If your VPN app is not trusted by the user, the system displays a dialog box asking the user to authorize the VPN connection. After obtaining the authorization, the system automatically calls [onCreate](../reference/apis-network-kit/js-apis-VpnExtensionAbility.md#vpnextensionabilityoncreate) of the **VpnExtensionAbility**.
95
96Currently, only one active VPN connection is supported. If the application calls **startVpnExtensionAbility** when a VPN connection is active, it will receive a system rejection error. In this case, you are advised to remind the user to disconnect the active VPN connection first.
97
98
99
100## Stopping the VPN Extension Ability
101
102To stop a VPN connection, the VPN application needs to call **stopVpnExtensionAbility** with the target **VpnExtensionAbility** specified. The system verifies the permission of the caller. The caller of **stopVpnExtensionAbility** must have obtained the VPN connection authorization of the user and can only stop the **VpnExtensionAbility** it started. Therefore, make sure that the value of **bundleName** passed by the API is the same as that of the VPN application, and the value of **abilityName** is the same as that of the target **VpnExtensionAbility**.
103
104The sample code is as follows:
105
106```ts
107import { common, Want } from '@kit.AbilityKit';
108import { vpnExtension } from '@kit.NetworkKit';
109
110let context = getContext(this) as common.VpnExtensionContext;
111let want: Want = {
112  deviceId: "",
113  bundleName: "com.example.myvpndemo",
114  abilityName: "MyVpnExtAbility",
115};
116
117@Entry
118@Component
119struct Index {
120  @State message: string = 'Hello World';
121
122  build() {
123    Row() {
124      Column() {
125        Text(this.message)
126          .fontSize(50)
127          .fontWeight(FontWeight.Bold).onClick(() => {
128          console.info("btn click") })
129        Button('Start Extension').onClick(() => {
130          vpnExtension.startVpnExtensionAbility(want);
131        }).width('70%').fontSize(45).margin(16)
132        Button('Stop Extension').onClick(() => {
133          console.info("btn end")
134          vpnExtension.stopVpnExtensionAbility(want);
135        }).width('70%').fontSize(45).margin(16)
136
137        }.width('100%')
138    }.height('100%')
139  }
140}
141```
142
143After the **VPNExtensionAbility** is stopped, call [onDestroy](../reference/apis-network-kit/js-apis-VpnExtensionAbility.md#vpnextensionabilityondestroy) to destroy the VPN connection and release related resources.
144
145```ts
146import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit';
147import { common, Want } from '@kit.AbilityKit';
148import { BusinessError } from '@kit.BasicServicesKit';
149
150let context: vpnExtension.VpnExtensionContext;
151export default class MyVpnExtAbility extends VpnExtensionAbility {
152  onDestroy() {
153    let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
154    console.info("vpn createVpnConnection: " + JSON.stringify(VpnConnection));
155    VpnConnection.destroy().then(() => {
156      console.info("destroy success.");
157    }).catch((error : BusinessError) => {
158      console.error("destroy fail" + JSON.stringify(error));
159    });
160  }
161}
162```
163
164## Service Lifecycle Management
165
166To ensure network connectivity, the system automatically stops the VPN connection when detecting that the VPN application is abnormal:
167
168- The application process that calls **startVpnExtensionAbility** exits.
169- The VPN service process is destroyed.
170
171## Description of VPN Config parameters
172
173| Name               | Type                                                        | Mandatory| Description                                                        |
174| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
175| addresses           | Array\<[LinkAddress](../reference/apis-network-kit/js-apis-net-connection.md#linkaddress)\> | Yes  | IP addresses of virtual network interface cards (vNICs).                                       |
176| routes              | Array\<[RouteInfo](../reference/apis-network-kit/js-apis-net-connection.md#routeinfo)\> | No  | Routes of vNICs. Currently, a maximum of 1024 routes can be configured.           |
177| dnsAddresses        | Array\<string\>                                              | No  | IP addresses of DNS servers. Trusted VPN applications can access the network through these IP addresses. If this parameter is not configured, IP address allocated by the system will be used.|
178| searchDomains       | Array\<string\>                                              | No  | List of DNS search domains.                                           |
179| mtu                 | number                                                       | No  | Maximum transmission unit (MTU), in bytes.                              |
180| isIPv4Accepted      | boolean                                                      | No  | Whether IPv4 is supported. The default value is **true**.                                |
181| isIPv6Accepted      | boolean                                                      | No  | Whether IPv6 is supported. The default value is **false**.                               |
182| isInternal          | boolean                                                      | No  | Whether the built-in VPN is supported. The default value is **false**.                            |
183| isBlocking          | boolean                                                      | No  | Whether the blocking mode is used. The default value is **false**.                               |
184| trustedApplications | Array\<string\>                                              | No  | Trusted VPN applications, which are represented by bundle names of the string type             |
185| blockedApplications | Array\<string\>                                              | No  | Blocked VPN applications, which are represented by bundle names of the string type           |
186
187**Example**
188
189```ts
190import { vpnExtension} from '@kit.NetworkKit';
191
192let vpnConfig: vpnExtension.VpnConfig = {
193  // Configure the IP address of the vNIC.
194  addresses: [{
195    address: {
196      address:'192.x.x.5',
197      family:1
198    },
199    prefixLength:24
200  }],
201  // Configure route information.
202  routes: [{
203    // Set the name of the vNIC, which has a fixed value of vpn-tun.
204    interface: 'vpn-tun',
205    destination: {
206      address: {
207        address:'10.x.x.8',
208        family:1,
209        port:8080
210      },
211      prefixLength:24
212    },
213    gateway: {
214      address:'10.x.x.5',
215      family:1,
216      port:8080
217    },
218    hasGateway: false,
219    isDefaultRoute: false,
220  }],
221  // Configure the MTU.
222  mtu: 1400,
223  // Configure IP addresses of DNS serves.
224  dnsAddresses: ['223.x.x.5', '223.x.x.6'],
225  // Configure trusted VPN applications.
226  trustedApplications: ['com.test.browser'],
227  // Configure blocked VPN applications.
228  blockedApplications: ['com.test.games'],
229}
230let context: vpnExtension.VpnExtensionContext;
231
232function vpnCreate(){
233  let VpnConnection: vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
234  VpnConnection.create(vpnConfig).then((data) => {
235    console.info("vpn create " + JSON.stringify(data));
236  })
237}
238```
239
240
241
242## VPN Demo
243
244The OpenHarmony project provides a sample application named [VPN](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/VPN), which showcases how to implement the VPN service.
245