1# @ohos.net.vpnExtension (Enhanced VPN Management)
2
3This module implements virtual private network (VPN) management, such as starting and stopping a third-party VPN.
4Third-party VPNs refer to VPN services provided by third parties. They usually support more security and privacy functions and more comprehensive customization options.
5
6> **NOTE**
7> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9## Modules to Import
10
11```js
12import { vpnExtension } from '@kit.NetworkKit';
13```
14
15## LinkAddress<sup>11+</sup>
16type LinkAddress = connection.LinkAddress
17
18Defines the network link address information.
19
20**System capability**: SystemCapability.Communication.NetManager.Core
21
22| Type  | Description                                                        |
23| ------ | ------------------------------------------------------------ |
24| [connection.LinkAddress](./js-apis-net-connection.md#linkaddress) | network link address information.|
25
26## RouteInfo<sup>11+</sup>
27type RouteInfo = connection.RouteInfo
28
29Defines the network route information.
30
31**System capability**: SystemCapability.Communication.NetManager.Core
32
33| Type  | Description                                                        |
34| ------ | ------------------------------------------------------------ |
35| [connection.RouteInfo](./js-apis-net-connection.md#routeinfo) | Network route information.|
36
37## VpnExtensionContext<sup>11+</sup>
38type VpnExtensionContext = _VpnExtensionContext
39
40Defines the VPN extension context. It allows access to serviceExtension-specific resources.
41
42**System capability**: SystemCapability.Ability.AbilityRuntime.Core.
43
44| Type  | Description                                                        |
45| ------ | ------------------------------------------------------------ |
46| [_VpnExtensionContext](./js-apis-inner-application-VpnExtensionContext.md) | VPN extension context.|
47
48## vpnExtension.startVpnExtensionAbility
49
50startVpnExtensionAbility(want: Want): Promise\<void>
51
52Enables the VPN extension ability.
53
54**System capability**: SystemCapability.Ability.AbilityRuntime.Core.
55
56**Model restriction**: This API can be used only in the stage model.
57
58**Parameters**
59
60| Name| Type                               | Mandatory| Description              |
61| ------ | ----------------------------------- | ---- | ------------------ |
62| want   | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes  | Want information.|
63
64**Return value**
65
66| Type          | Description                   |
67| -------------- | ----------------------- |
68| Promise\<void> | Promise that returns no value.|
69
70**Error codes**
71
72| ID| Error Message                              |
73| --------- | -------------------------------------- |
74| 401       | If the input parameter is not valid parameter.|
75| 16000001  | The specified ability does not exist.  |
76| 16000002  | Incorrect ability type.                |
77| 16000006  | Cross-user operations are not allowed. |
78| 16000008  | The crowdtesting application expires.  |
79| 16000011  | The context does not exist.            |
80| 16000050  | Internal error.                        |
81| 16200001  | The caller has been released.          |
82
83**Example**
84Stage model:
85
86```ts
87import { common, Want } from '@kit.AbilityKit';
88import { vpnExtension } from '@kit.NetworkKit';
89
90let context = getContext(this) as common.VpnExtensionContext;
91let want: Want = {
92  deviceId: "",
93  bundleName: "com.example.myvpndemo",
94  abilityName: "MyVpnExtAbility",
95};
96
97@Entry
98@Component
99struct Index {
100  @State message: string = 'Hello World'
101
102  build() {
103    Row() {
104      Column() {
105        Text(this.message)
106          .fontSize(50)
107          .fontWeight(FontWeight.Bold).onClick(() => {
108          console.info("btn click") })
109        Button('Start Extension').onClick(() => {
110          vpnExtension.startVpnExtensionAbility(want);
111        }).width('70%').fontSize(45).margin(16)
112        }.width('100%')
113    }.height('100%')
114  }
115}
116```
117
118## vpnExtension.stopVpnExtensionAbility
119
120stopVpnExtensionAbility(want: Want): Promise\<void>
121
122Stops the VPN extension ability.
123
124**System capability**: SystemCapability.Ability.AbilityRuntime.Core.
125
126**Model restriction**: This API can be used only in the stage model.
127
128**Parameters**
129
130| Name| Type                               | Mandatory| Description            |
131| ------ | ----------------------------------- | ---- | ---------------- |
132| want   | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes  | Want information.|
133
134**Return value**
135
136| Type          | Description                   |
137| -------------- | ----------------------- |
138| Promise\<void> | Promise that returns no value.|
139
140**Error codes**
141
142| ID| Error Message                              |
143| --------- | -------------------------------------- |
144| 401       | If the input parameter is not valid parameter.|
145| 16000001  | The specified ability does not exist.  |
146| 16000002  | Incorrect ability type.                |
147| 16000006  | Cross-user operations are not allowed. |
148| 16000011  | The context does not exist.            |
149| 16000050  | Internal error.                        |
150| 16200001  | The caller has been released.          |
151
152**Example**
153Stage model:
154
155```ts
156import { common, Want } from '@kit.AbilityKit';
157import { vpnExtension } from '@kit.NetworkKit';
158
159let context = getContext(this) as common.VpnExtensionContext;
160let want: Want = {
161  deviceId: "",
162  bundleName: "com.example.myvpndemo",
163  abilityName: "MyVpnExtAbility",
164};
165
166@Entry
167@Component
168struct Index {
169  @State message: string = 'Hello World'
170
171  build() {
172    Row() {
173      Column() {
174        Text(this.message)
175          .fontSize(50)
176          .fontWeight(FontWeight.Bold).onClick(() => {
177          console.info("btn click") })
178        Button('Start Extension').onClick(() => {
179          vpnExtension.startVpnExtensionAbility(want);
180        }).width('70%').fontSize(45).margin(16)
181        Button('Stop Extension').onClick(() => {
182          console.info("btn end")
183          vpnExtension.stopVpnExtensionAbility(want);
184        }).width('70%').fontSize(45).margin(16)
185
186        }.width('100%')
187    }.height('100%')
188  }
189}
190```
191
192## vpnExtension.createVpnConnection
193
194createVpnConnection(context: VpnExtensionContext): VpnConnection
195
196Creates a **VpnConnection** object.
197
198> **NOTE**
199>
200> Before calling **createVpnConnection**, call **startVpnExtensionAbility** to enable the VPN function.
201
202**System capability**: SystemCapability.Communication.NetManager.Vpn
203
204**Model restriction**: This API can be used only in the stage model.
205
206**Parameters**
207
208| Name | Type                                                        | Mandatory| Description          |
209| ------- | ------------------------------------------------------------ | ---- | -------------- |
210| context | [VpnExtensionContext](js-apis-inner-application-VpnExtensionContext.md) | Yes  | Specified context.|
211
212**Return value**
213
214| Type                           | Description                   |
215| :------------------------------ | :---------------------- |
216| [VpnConnection](#vpnconnection) | **VpnConnection** object.|
217
218**Error codes**
219
220| ID| Error Message        |
221| --------- | ---------------- |
222| 401       | Parameter error. |
223
224**Example**
225Stage model:
226
227```ts
228import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit';
229import { common, Want } from '@kit.AbilityKit';
230
231let context: vpnExtension.VpnExtensionContext;
232export default class MyVpnExtAbility extends VpnExtensionAbility {
233  onCreate(want: Want) {
234    let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
235    console.info("vpn createVpnConnection: " + JSON.stringify(VpnConnection));
236  }
237}
238```
239
240## VpnConnection
241
242Defines a **VpnConnection** object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling **vpnExt.createVpnConnection**.
243
244### create
245
246create(config: VpnConfig): Promise\<number\>
247
248Creates a VPN based on the specified configuration. This API uses a promise to return the result.
249
250**System capability**: SystemCapability.Communication.NetManager.Vpn
251
252**Parameters**
253
254| Name| Type                   | Mandatory| Description                     |
255| ------ | ----------------------- | ---- | ------------------------- |
256| config | [VpnConfig](#vpnconfig) | Yes  | VPN configuration.|
257
258**Return value**
259
260| Type             | Description                                                          |
261| ----------------- | -------------------------------------------------------------- |
262| Promise\<number\> | Promise used to return the result, which is the file descriptor of the vNIC.|
263
264**Error codes**
265
266| ID| Error Message                                        |
267| --------- | ------------------------------------------------ |
268| 401       | Parameter error.                                 |
269| 2200001   | Invalid parameter value.                         |
270| 2200002   | Operation failed. Cannot connect to service.     |
271| 2200003   | System internal error.                           |
272| 2203001   | VPN creation denied, please check the user type. |
273| 2203002   | VPN exist already, please execute destroy first. |
274
275**Example**
276
277```js
278import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit';
279import { common, Want } from '@kit.AbilityKit';
280import { hilog } from '@kit.PerformanceAnalysisKit';
281
282let context: vpnExtension.VpnExtensionContext;
283export default class MyVpnExtAbility extends VpnExtensionAbility {
284  private tunIp: string = '10.0.0.5';
285  private blockedAppName: string = 'com.example.myvpndemo';
286  onCreate(want: Want) {
287    let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
288    console.info("vpn createVpnConnection: " + JSON.stringify(VpnConnection));
289    this.SetupVpn();
290  }
291  SetupVpn() {
292        class Address {
293            address: string;
294            family: number;
295
296            constructor(address: string, family: number) {
297                this.address = address;
298                this.family = family;
299            }
300        }
301
302        class AddressWithPrefix {
303            address: Address;
304            prefixLength: number;
305
306            constructor(address: Address, prefixLength: number) {
307                this.address = address;
308                this.prefixLength = prefixLength;
309            }
310        }
311
312        class Config {
313            addresses: AddressWithPrefix[];
314            mtu: number;
315            dnsAddresses: string[];
316            trustedApplications: string[];
317            blockedApplications: string[];
318
319            constructor(
320                tunIp: string,
321                blockedAppName: string
322            ) {
323                this.addresses = [
324                    new AddressWithPrefix(new Address(tunIp, 1), 24)
325                ];
326                this.mtu = 1400;
327                this.dnsAddresses = ["114.114.114.114"];
328                this.trustedApplications = [];
329                this.blockedApplications = [blockedAppName];
330            }
331        }
332
333        let config = new Config(this.tunIp, this.blockedAppName);
334
335        try {
336            let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
337            VpnConnection.create(config).then((data) => {
338                hilog.error(0x0000, 'developTag', 'tunfd: %{public}s', JSON.stringify(data) ?? '');
339            })
340        } catch (error) {
341            hilog.error(0x0000, 'developTag', 'vpn setUp fail: %{public}s', JSON.stringify(error) ?? '');
342        }
343    }
344}
345```
346
347### protect
348
349protect(socketFd: number): Promise\<void\>
350
351Protects sockets against a VPN connection. The data sent through sockets is directly transmitted over the physical network and therefore the traffic does not traverse through the VPN. This API uses a promise to return the result.
352
353**System capability**: SystemCapability.Communication.NetManager.Vpn
354
355**Parameters**
356
357| Name  | Type  | Mandatory| Description                                                                                       |
358| -------- | ------ | ---- | ------------------------------------------------------------------------------------------- |
359| socketFd | number | Yes  | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1).|
360
361**Return value**
362
363| Type           | Description                                                 |
364| --------------- | ----------------------------------------------------- |
365| Promise\<void\> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
366
367**Error codes**
368
369| ID| Error Message                                    |
370| --------- | -------------------------------------------- |
371| 401       | Parameter error.                             |
372| 2200001   | Invalid parameter value.                     |
373| 2200002   | Operation failed. Cannot connect to service. |
374| 2200003   | System internal error.                       |
375| 2203004   | Invalid socket file descriptor.              |
376
377**Example**
378
379```js
380import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit';
381import { common, Want } from '@kit.AbilityKit';
382import { hilog } from '@kit.PerformanceAnalysisKit';
383
384let g_tunnelFd = -1;
385let context: vpnExtension.VpnExtensionContext;
386export default class MyVpnExtAbility extends VpnExtensionAbility {
387  private vpnServerIp: string = '192.168.31.13';
388  onCreate(want: Want) {
389    let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
390    console.info("vpn createVpnConnection: " + JSON.stringify(VpnConnection));
391    this.CreateTunnel();
392    this.Protect();
393  }
394  CreateTunnel() {
395      g_tunnelFd = 8888;
396  }
397  Protect() {
398        hilog.info(0x0000, 'developTag', '%{public}s', 'vpn Protect');
399        let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
400        VpnConnection.protect(g_tunnelFd).then(() => {
401            hilog.info(0x0000, 'developTag', '%{public}s', 'vpn Protect Success');
402        }).catch((err : Error) => {
403            hilog.error(0x0000, 'developTag', 'vpn Protect Failed %{public}s', JSON.stringify(err) ?? '');
404        })
405  }
406}
407```
408
409### destroy
410
411destroy(): Promise\<void\>
412
413Destroys a VPN. This API uses a promise to return the result.
414
415**System capability**: SystemCapability.Communication.NetManager.Vpn
416
417**Return value**
418
419| Type           | Description                                                 |
420| --------------- | ----------------------------------------------------- |
421| Promise\<void\> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
422
423**Error codes**
424
425| ID| Error Message                                    |
426| --------- | -------------------------------------------- |
427| 401       | Parameter error.                             |
428| 2200002   | Operation failed. Cannot connect to service. |
429| 2200003   | System internal error.                       |
430
431**Example**
432
433```js
434import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit';
435import { common, Want } from '@kit.AbilityKit';
436import { BusinessError } from '@kit.BasicServicesKit';
437
438let context: vpnExtension.VpnExtensionContext;
439export default class MyVpnExtAbility extends VpnExtensionAbility {
440  onCreate(want: Want) {
441    let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
442    console.info("vpn createVpnConnection: " + JSON.stringify(VpnConnection));
443    VpnConnection.destroy().then(() => {
444      console.info("destroy success.");
445    }).catch((error : BusinessError) => {
446      console.error("destroy fail" + JSON.stringify(error));
447    });
448  }
449}
450```
451
452## VpnConfig
453
454Defines the VPN configuration.
455
456**System capability**: SystemCapability.Communication.NetManager.Vpn
457
458| Name               | Type                                                          | Mandatory| Description                               |
459| ------------------- | -------------------------------------------------------------- | ---- | ----------------------------------- |
460| addresses           | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress)\> | Yes  | IP address of the vNIC.           |
461| routes              | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo)\>     | No  | Route information of the vNIC. Currently, a maximum of 1024 routes can be configured.           |
462| dnsAddresses        | Array\<string\>                                                | No  | IP address of the DNS server.               |
463| searchDomains       | Array\<string\>                                                | No  | List of DNS search domains.                 |
464| mtu                 | number                                                         | No  | Maximum transmission unit (MTU), in bytes.    |
465| isIPv4Accepted      | boolean                                                        | No  | Whether IPv4 is supported. The default value is **true**.     |
466| isIPv6Accepted      | boolean                                                        | No  | Whether IPv6 is supported. The default value is **false**.    |
467| isInternal          | boolean                                                        | No  | Whether the built-in VPN is supported. The default value is **false**.  |
468| isBlocking          | boolean                                                        | No  | Whether the blocking mode is used. The default value is **false**.      |
469| trustedApplications | Array\<string\>                                                | No  | List of trusted applications, which are represented by bundle names of the string type. |
470| blockedApplications | Array\<string\>                                                | No  | List of blocked applications, which are represented by bundle names of the string type. |
471
472**Example**
473
474```js
475import { vpnExtension} from '@kit.NetworkKit';
476
477let vpnConfig: vpnExtension.VpnConfig = {
478  addresses: [],
479  routes: [{
480    interface: "eth0",
481    destination: {
482      address: {
483        address:'',
484        family:1,
485        port:8080
486      },
487      prefixLength:1
488    },
489    gateway: {
490      address:'',
491      family:1,
492      port:8080
493    },
494    hasGateway: true,
495    isDefaultRoute: true,
496  }],
497  mtu: 1400,
498  dnsAddresses: ["223.5.5.5", "223.6.6.6"],
499  trustedApplications: [],
500  blockedApplications: [],
501}
502let context: vpnExtension.VpnExtensionContext;
503
504function vpnCreate(){
505  let VpnConnection: vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context);
506  VpnConnection.create(vpnConfig).then((data) => {
507    console.info("vpn create " + JSON.stringify(data));
508  })
509}
510```
511