1# @ohos.net.vpnExtension (VPN 增强管理)
2
3三方VPN管理模块,支持三方VPN的启动和停止功能。
4三方VPN是指由第三方提供的VPN服务,它们通常提供更多的功能和更广泛的网络连接选项,包括更多的安全和隐私功能,以及更全面的定制选项。
5
6> **说明:**
7> 本模块首批接口从 API version 11 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8
9## 导入模块
10
11```js
12import { vpnExtension } from '@kit.NetworkKit';
13```
14
15## LinkAddress<sup>11+</sup>
16type LinkAddress = connection.LinkAddress
17
18获取网络链接信息。
19
20**系统能力**:SystemCapability.Communication.NetManager.Core
21
22| 类型   | 说明                                                         |
23| ------ | ------------------------------------------------------------ |
24| [connection.LinkAddress](./js-apis-net-connection.md#linkaddress) | 网络链路信息 |
25
26## RouteInfo<sup>11+</sup>
27type RouteInfo = connection.RouteInfo
28
29获取网络路由信息。
30
31**系统能力**:SystemCapability.Communication.NetManager.Core
32
33| 类型   | 说明                                                         |
34| ------ | ------------------------------------------------------------ |
35| [connection.RouteInfo](./js-apis-net-connection.md#routeinfo) | 网络路由信息 |
36
37## VpnExtensionContext<sup>11+</sup>
38type VpnExtensionContext = _VpnExtensionContext
39
40vpn扩展的上下文。它允许访问serviceExtension特定资源。
41
42**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
43
44| 类型   | 说明                                                         |
45| ------ | ------------------------------------------------------------ |
46| [_VpnExtensionContext](./js-apis-inner-application-VpnExtensionContext.md) | vpn扩展的上下文 |
47
48## vpnExtension.startVpnExtensionAbility
49
50startVpnExtensionAbility(want: Want): Promise\<void>
51
52启动新的三方vpn功能。
53
54**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
55
56**模型约束**:此接口仅可在Stage模型下使用。
57
58**参数:**
59
60| 参数名 | 类型                                | 必填 | 说明               |
61| ------ | ----------------------------------- | ---- | ------------------ |
62| want   | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | 是   | 指示要启动的信息。 |
63
64**返回值:**
65
66| 类型           | 说明                    |
67| -------------- | ----------------------- |
68| Promise\<void> | 无返回值的Promise对象。 |
69
70**错误码:**
71
72| 错误码 ID | 错误信息                               |
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**示例:**
84Stage 模型示例:
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
122停止同一应用程序中的服务。
123
124**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
125
126**模型约束**:此接口仅可在Stage模型下使用。
127
128**参数:**
129
130| 参数名 | 类型                                | 必填 | 说明             |
131| ------ | ----------------------------------- | ---- | ---------------- |
132| want   | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | 是   | 指示要启动的信息 |
133
134**返回值:**
135
136| 类型           | 说明                    |
137| -------------- | ----------------------- |
138| Promise\<void> | 无返回值的Promise对象。 |
139
140**错误码:**
141
142| 错误码 ID | 错误信息                               |
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**示例:**
153Stage 模型示例:
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
196创建一个 三方VPN 连接对象。
197
198> **说明:**
199>
200> 调用createVpnConnection接口前,需要先调用startVpnExtensionAbility接口启用vpn功能。
201
202**系统能力**:SystemCapability.Communication.NetManager.Vpn
203
204**模型约束**:此接口仅可在Stage模型下使用。
205
206**参数:**
207
208| 参数名  | 类型                                                         | 必填 | 说明           |
209| ------- | ------------------------------------------------------------ | ---- | -------------- |
210| context | [VpnExtensionContext](js-apis-inner-application-VpnExtensionContext.md) | 是   | 指定 context。 |
211
212**返回值:**
213
214| 类型                            | 说明                    |
215| :------------------------------ | :---------------------- |
216| [VpnConnection](#vpnconnection) | 返回一个 VPN 连接对象。 |
217
218**错误码:**
219
220| 错误码 ID | 错误信息         |
221| --------- | ---------------- |
222| 401       | Parameter error. |
223
224**示例:**
225Stage 模型示例:
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
242VPN 连接对象。在调用 VpnConnection 的方法前,需要先通过vpnExt.createVpnConnection创建 VPN 连接对象。
243
244### create
245
246create(config: VpnConfig): Promise\<number\>
247
248使用 config 创建一个 vpn 网络,使用 Promise 方式作为异步方法。
249
250**系统能力**:SystemCapability.Communication.NetManager.Vpn
251
252**参数:**
253
254| 参数名 | 类型                    | 必填 | 说明                      |
255| ------ | ----------------------- | ---- | ------------------------- |
256| config | [VpnConfig](#vpnconfig) | 是   | 指定 VPN 网络的配置信息。 |
257
258**返回值:**
259
260| 类型              | 说明                                                           |
261| ----------------- | -------------------------------------------------------------- |
262| Promise\<number\> | 以 Promise 形式返回获取结果,返回指定虚拟网卡的文件描述符 fd。 |
263
264**错误码:**
265
266| 错误码 ID | 错误信息                                         |
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**示例:**
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
351保护套接字不受 VPN 连接影响,通过该套接字发送的数据将直接基于物理网络收发,因此其流量不会通过 VPN 转发, 使用 Promise 方式作为异步方法。
352
353**系统能力**:SystemCapability.Communication.NetManager.Vpn
354
355**参数:**
356
357| 参数名   | 类型   | 必填 | 说明                                                                                        |
358| -------- | ------ | ---- | ------------------------------------------------------------------------------------------- |
359| socketFd | number | 是   | 指定保护的 socketfd, 该文件描述符通过[getSocketFd](js-apis-socket.md#getsocketfd10-1)获取。 |
360
361**返回值:**
362
363| 类型            | 说明                                                  |
364| --------------- | ----------------------------------------------------- |
365| Promise\<void\> | 以 Promise 形式返回设定结果,失败返回错误码错误信息。 |
366
367**错误码:**
368
369| 错误码 ID | 错误信息                                     |
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**示例:**
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
413销毁启动的 VPN 网络,使用 Promise 方式作为异步方法。
414
415**系统能力**:SystemCapability.Communication.NetManager.Vpn
416
417**返回值:**
418
419| 类型            | 说明                                                  |
420| --------------- | ----------------------------------------------------- |
421| Promise\<void\> | 以 Promise 形式返回设定结果,失败返回错误码错误信息。 |
422
423**错误码:**
424
425| 错误码 ID | 错误信息                                     |
426| --------- | -------------------------------------------- |
427| 401       | Parameter error.                             |
428| 2200002   | Operation failed. Cannot connect to service. |
429| 2200003   | System internal error.                       |
430
431**示例:**
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
454三方VPN配置参数。
455
456**系统能力**:SystemCapability.Communication.NetManager.Vpn
457
458| 名称                | 类型                                                           | 必填 | 说明                                |
459| ------------------- | -------------------------------------------------------------- | ---- | ----------------------------------- |
460| addresses           | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress)\> | 是   | VPN 虚拟网卡的 IP 地址。            |
461| routes              | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo)\>     | 否   | VPN 虚拟网卡的路由信息(目前最多可配置1024条路由)。            |
462| dnsAddresses        | Array\<string\>                                                | 否   | DNS 服务器地址信息。                |
463| searchDomains       | Array\<string\>                                                | 否   | DNS 的搜索域列表。                  |
464| mtu                 | number                                                         | 否   | 最大传输单元 MTU 值(单位:字节)。     |
465| isIPv4Accepted      | boolean                                                        | 否   | 是否支持 IPV4, 默认值为 true。      |
466| isIPv6Accepted      | boolean                                                        | 否   | 是否支持 IPV6, 默认值为 false。     |
467| isInternal          | boolean                                                        | 否   | 是否支持内置 VPN, 默认值为 false。   |
468| isBlocking          | boolean                                                        | 否   | 是否阻塞模式, 默认值为 false。       |
469| trustedApplications | Array\<string\>                                                | 否   | 白名单信息, string 类型表示的包名。  |
470| blockedApplications | Array\<string\>                                                | 否   | 黑名单信息, string 类型表示的包名。  |
471
472**示例:**
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```