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