提交 1fba7ee1 编写于 作者: G Gloria

Update docs against 22141+21634

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 a59cf942
......@@ -61,7 +61,7 @@
- [Component Startup Rules (Stage Model)](component-startup-rules.md)
- Inter-Device Application Component Interaction (Continuation)
- [Continuation Overview](inter-device-interaction-hop-overview.md)
- [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md)
- [Cross-Device Migration](hop-cross-device-migration.md)
- [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md)
- [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md)
- Process Model
......
......@@ -9,6 +9,8 @@
- [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md)
- [mDNS Management](net-mdns.md)
- [Traffic Management](net-statistics.md)
- [VPN Management](net-vpn.md)
- IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md)
......
# VPN Management
## Overview
A virtual private network (VPN) is a dedicated network established on a public network. On a VPN, the connection between any two nodes does not have an end-to-end physical link required by the traditional private network. Instead, user data is transmitted over a logical link because a VPN is a logical network deployed over the network platform (such as the Internet) provided by the public network service provider.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-vpn.md).
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [VPN Management](../reference/apis/js-apis-net-vpn.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.vpn | setUp(config: VpnConfig, callback: AsyncCallback\<number\>): void | Establishes a VPN. This API uses an asynchronous callback to return the result.|
| ohos.net.vpn | protect(socketFd: number, callback: AsyncCallback\<void\>): void | Enables VPN tunnel protection. This API uses an asynchronous callback to return the result.|
| ohos.net.vpn | destroy(callback: AsyncCallback\<void\>): void | Destroys a VPN. This API uses an asynchronous callback to return the result.|
## Starting a VPN
1. Establish a VPN tunnel. The following uses the UDP tunnel as an example.
2. Enable protection for the UDP tunnel.
3. Establish a VPN.
4. Process data of the virtual network interface card (vNIC), such as reading or writing data.
5. Destroy the VPN.
This example shows how to develop an application using native C++ code. For details, see [Simple Native C++ Example (ArkTS) (API9)] (https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo).
The sample application consists of two parts: JS code and C++ code.
## JS Code
The JS code is used to implement the service logic, such as creating a tunnel, establishing a VPN, enabling VPN protection, and destroying a VPN.
```js
import hilog from '@ohos.hilog';
import vpn from '@ohos.net.vpn';
import UIAbility from '@ohos.app.ability.UIAbility';
import vpn_client from "libvpn_client.so"
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
globalThis.context = this.context;
}
}
let TunnelFd = -1
let VpnConnection = vpn.createVpnConnection(globalThis.context)
@Entry
@Component
struct Index {
@State message: string = 'Test VPN'
//1. Establish a VPN tunnel. The following uses the UDP tunnel as an example.
CreateTunnel() {
TunnelFd = vpn_client.udpConnect("192.168.43.208", 8888)
}
// 2. Enable protection for the UDP tunnel.
Protect() {
VpnConnection.protect(TunnelFd).then(function () {
console.info("vpn Protect Success.")
}).catch(function (err) {
console.info("vpn Protect Failed " + JSON.stringify(err))
})
}
SetupVpn() {
let config = {
addresses: [{
address: {
address: "10.0.0.5",
family: 1
},
prefixLength: 24,
}],
routes: [],
mtu: 1400,
dnsAddresses: [
"114.114.114.114"
],
acceptedApplications: [],
refusedApplications: []
}
try {
// 3. Create a VPN.
VpnConnection.setUp(config, (error, data) => {
console.info("tunfd: " + JSON.stringify(data));
// 4. Process data of the virtual vNIC, such as reading or writing data.
vpn_client.startVpn(data, TunnelFd)
})
} catch (error) {
console.info("vpn setUp fail " + JSON.stringify(error));
}
}
// 5. Destroy the VPN.
Destroy() {
vpn_client.stopVpn(TunnelFd)
VpnConnection.destroy().then(function () {
console.info("vpn Destroy Success.")
}).catch(function (err) {
console.info("vpn Destroy Failed " + JSON.stringify(err))
})
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
console.info("vpn Client")
})
Button('CreateTunnel').onClick(() => {
this.CreateTunnel()
}).fontSize(50)
Button('Protect').onClick(() => {
this.Protect()
}).fontSize(50)
Button('SetupVpn').onClick(() => {
this.SetupVpn()
}).fontSize(50)
Button('Destroy').onClick(() => {
this.Destroy()
}).fontSize(50)
}
.width('100%')
}
.height('100%')
}
}
```
## C++ Code
The C++ code is used for underlying service implementation, such as UDP tunnel client implementation and vNIC data read and write.
```c++
#include "napi/native_api.h"
#include "hilog/log.h"
#include <cstring>
#include <thread>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <thread>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFER_SIZE 2048
#define VPN_LOG_TAG "NetMgrVpn"
#define VPN_LOG_DOMAIN 0x15b0
#define MAKE_FILE_NAME (strrchr(__FILE__, '/') + 1)
#define NETMANAGER_VPN_LOGE(fmt, ...) \
OH_LOG_Print(LOG_APP, LOG_ERROR, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
__LINE__, ##__VA_ARGS__)
#define NETMANAGER_VPN_LOGI(fmt, ...) \
OH_LOG_Print(LOG_APP, LOG_INFO, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
__LINE__, ##__VA_ARGS__)
#define NETMANAGER_VPN_LOGD(fmt, ...) \
OH_LOG_Print(LOG_APP, LOG_DEBUG, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
__LINE__, ##__VA_ARGS__)
struct FdInfo {
int32_t tunFd = 0;
int32_t tunnelFd = 0;
struct sockaddr_in serverAddr;
};
static FdInfo fdInfo;
static bool threadRunF = false;
static std::thread threadt1;
static std::thread threadt2;
// Obtain the IP address of the UDP server.
static constexpr const int MAX_STRING_LENGTH = 1024;
std::string GetStringFromValueUtf8(napi_env env, napi_value value) {
std::string result;
char str[MAX_STRING_LENGTH] = {0};
size_t length = 0;
napi_get_value_string_utf8(env, value, str, MAX_STRING_LENGTH, &length);
if (length > 0) {
return result.append(str, length);
}
return result;
}
void HandleReadTunfd(FdInfo fdInfo) {
uint8_t buffer[BUFFER_SIZE] = {0};
while (threadRunF) {
int ret = read(fdInfo.tunFd, buffer, sizeof(buffer));
if (ret <= 0) {
if (errno != 11) {
NETMANAGER_VPN_LOGE("read tun device error: %{public}d, tunfd: %{public}d", errno, fdInfo.tunFd);
}
continue;
}
// Read data from the vNIC and send the data to the UDP server through the UDP tunnel.
NETMANAGER_VPN_LOGD("buffer: %{public}s, len: %{public}d", buffer, ret);
ret = sendto(fdInfo.tunnelFd, buffer, ret, 0, (struct sockaddr *)&fdInfo.serverAddr, sizeof(fdInfo.serverAddr));
if (ret <= 0) {
NETMANAGER_VPN_LOGE("send to server[%{public}s:%{public}d] failed, ret: %{public}d, error: %{public}s",
inet_ntoa(fdInfo.serverAddr.sin_addr), ntohs(fdInfo.serverAddr.sin_port), ret,
strerror(errno));
continue;
}
}
}
void HandleTcpReceived(FdInfo fdInfo) {
int addrlen = sizeof(struct sockaddr_in);
uint8_t buffer[BUFFER_SIZE] = {0};
while (threadRunF) {
int length = recvfrom(fdInfo.tunnelFd, buffer, sizeof(buffer), 0, (struct sockaddr *)&fdInfo.serverAddr,
(socklen_t *)&addrlen);
if (length < 0) {
if (errno != 11) {
NETMANAGER_VPN_LOGE("read tun device error: %{public}d, tunnelfd: %{public}d", errno, fdInfo.tunnelFd);
}
continue;
}
// Receive data from the UDP server and write the data to the vNIC.
NETMANAGER_VPN_LOGD("from [%{public}s:%{public}d] data: %{public}s, len: %{public}d",
inet_ntoa(fdInfo.serverAddr.sin_addr), ntohs(fdInfo.serverAddr.sin_port), buffer, length);
int ret = write(fdInfo.tunFd, buffer, length);
if (ret <= 0) {
NETMANAGER_VPN_LOGE("error Write To Tunfd, errno: %{public}d", errno);
}
}
}
static napi_value UdpConnect(napi_env env, napi_callback_info info) {
size_t argc = 2;
napi_value args[2] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
int32_t port = 0;
napi_get_value_int32(env, args[1], &port);
std::string ipAddr = GetStringFromValueUtf8(env, args[0]);
NETMANAGER_VPN_LOGI("ip: %{public}s port: %{public}d", ipAddr.c_str(), port);
// Establish a UDP tunnel.
int32_t sockFd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockFd == -1) {
NETMANAGER_VPN_LOGE("socket() error");
return 0;
}
struct timeval timeout = {1, 0};
setsockopt(sockFd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval));
memset(&fdInfo.serverAddr, 0, sizeof(fdInfo.serverAddr));
fdInfo.serverAddr.sin_family = AF_INET;
fdInfo.serverAddr.sin_addr.s_addr = inet_addr(ipAddr.c_str()); // server's IP addr
fdInfo.serverAddr.sin_port = htons(port); // port
NETMANAGER_VPN_LOGI("Connection successful");
napi_value tunnelFd;
napi_create_int32(env, sockFd, &tunnelFd);
return tunnelFd;
}
static napi_value StartVpn(napi_env env, napi_callback_info info) {
size_t argc = 2;
napi_value args[2] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
napi_get_value_int32(env, args[0], &fdInfo.tunFd);
napi_get_value_int32(env, args[1], &fdInfo.tunnelFd);
if (threadRunF) {
threadRunF = false;
threadt1.join();
threadt2.join();
}
// Start two threads. One is used to read data from the vNIC, and the other is used to receive data from the server.
threadRunF = true;
std::thread tt1(HandleReadTunfd, fdInfo);
std::thread tt2(HandleTcpReceived, fdInfo);
threadt1 = std::move(tt1);
threadt2 = std::move(tt2);
NETMANAGER_VPN_LOGI("StartVpn successful");
napi_value retValue;
napi_create_int32(env, 0, &retValue);
return retValue;
}
static napi_value StopVpn(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
int32_t tunnelFd;
napi_get_value_int32(env, args[0], &tunnelFd);
if (tunnelFd) {
close(tunnelFd);
tunnelFd = 0;
}
// Stop the two threads.
if (threadRunF) {
threadRunF = false;
threadt1.join();
threadt2.join();
}
NETMANAGER_VPN_LOGI("StopVpn successful");
napi_value retValue;
napi_create_int32(env, 0, &retValue);
return retValue;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor desc[] = {
{"udpConnect", nullptr, UdpConnect, nullptr, nullptr, nullptr, napi_default, nullptr},
{"startVpn", nullptr, StartVpn, nullptr, nullptr, nullptr, napi_default, nullptr},
{"stopVpn", nullptr, StopVpn, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "entry",
.nm_priv = ((void *)0),
.reserved = {0},
};
extern "C" __attribute__((constructor)) void RegisterEntryModule(void) {
napi_module_register(&demoModule);
}
```
......@@ -201,6 +201,7 @@
- UI Page
- [@ohos.animator (Animator)](js-apis-animator.md)
- [@ohos.arkui.componentSnapshot (Component Snapshot)](js-apis-arkui-componentSnapshot.md)
- [@ohos.arkui.componentUtils (componentUtils)](js-apis-arkui-componentUtils.md)
- [@ohos.arkui.dragController (DragController)](js-apis-arkui-dragController.md)
- [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md)
- [@ohos.arkui.inspector (Layout Callback)](js-apis-arkui-inspector.md)
......@@ -320,6 +321,7 @@
- [@ohos.net.sharing (Network Sharing)](js-apis-net-sharing.md)
- [@ohos.net.socket (Socket Connection)](js-apis-socket.md)
- [@ohos.net.statistics (Traffic Management)](js-apis-net-statistics.md)
- [@ohos.net.vpn (VPN Management)](js-apis-net-vpn.md)
- [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md)
- [@ohos.request (Upload and Download)](js-apis-request.md)
......@@ -382,6 +384,7 @@
- [@ohos.charger (Charging Type)](js-apis-charger.md)
- [@ohos.cooperate (Screen Hopping)](js-apis-devicestatus-cooperate.md)
- [@ohos.deviceAttest (Device Attestation)](js-apis-deviceAttest.md)
- [@ohos.deviceStatus.dragInteraction (Drag)](js-apis-devicestatus-draginteraction.md)
- [@ohos.deviceInfo (Device Information)](js-apis-device-info.md)
- [@ohos.distributedDeviceManager (Device Management)](js-apis-distributedDeviceManager.md)
- [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md)
......
# @ohos.arkui.componentUtils (componentUtils)
The **componentUtils** module provides API for obtaining the coordinates and size of the drawing area of a component.
> **NOTE**
>
> The APIs of this module are supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version.
>
> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
>
> Since API version 10, you can use the [getComponentUtils](./js-apis-arkui-UIContext.md#getcomponentutils) API in **UIContext** to obtain the **ComponentUtils** object associated with the current UI context. For this API to work correctly, call it after the notification indicating completion of component layout is received through [@ohos.arkui.inspector (layout callback)](js-apis-arkui-inspector.md).
## Modules to Import
```js
import componentUtils from '@ohos.arkui.componentUtils'
```
## componentUtils.getRectangleById
getRectangleById(id: string): ComponentInfo
Obtains a **ComponentInfo** object based on the component ID.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------- |
| id | string | Yes | Component ID.|
**Return value**
| Type | Description |
| ------ | ---------- |
| [ComponentInfo](#componentinfo) | **ComponentInfo** object, which provides the size, position, translation, scaling, rotation, and affine matrix information of the component.|
**Example**
```js
let modePosition = componentUtils.getRectangleById("onClick");
```
## ComponentInfo
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ---------------|------------ | -----------------------------| -----------------------------|
| size | [Size](#size) | Yes| Component size. |
| localOffset | [Offset](#offset) | Yes| Offset of the component relative to the parent component. |
| windowOffset | [Offset](#offset) | Yes| Offset of the component relative to the window. |
| screenOffset | [Offset](#offset) | Yes| Offset of the component relative to the screen. |
| translate | [TranslateResult](#translateresult) | Yes| Translation of the component. |
| scale | [ScaleResult](#scaleresult) | Yes| Scaling of the component. |
| rotate | [RotateResult](#rotateresult) | Yes| Rotation of the component. |
| transform | [Matrix4Result](#matrix4result) | Yes| Affine matrix of the component, which is a 4x4 matrix object created based on the input parameter. |
### Size
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type| Mandatory| Description |
| -------- | ---- | ----------------------------------| ----------------------------------|
| width | number | Yes| Component width. |
| height | number | Yes| Component height. |
### Offset
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type| Mandatory| Description |
| --------| ---- | -----------------------------------| -----------------------------------|
| x | number | Yes| X coordinate. |
| y | number | Yes| Y coordinate. |
### TranslateResult
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type| Mandatory| Description |
| --------| ---- | -----------------------------------| -----------------------------------|
| x | number | Yes| Translation distance along the x-axis. |
| y | number | Yes| Translation distance along the y-axis. |
| z | number | Yes| Translation distance along the z-axis. |
### ScaleResult
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type| Mandatory| Description |
| --------| ---- | -----------------------------------| -----------------------------------|
| x | number | Yes| Scale factor along the x-axis. |
| y | number | Yes| Scale factor along the y-axis. |
| z | number | Yes| Scale factor along the z-axis. |
| centerX | number | Yes| X coordinate of the center point. |
| centerY | number | Yes| Y coordinate of the center point. |
### RotateResult
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type| Mandatory| Description |
| --------| ---- | -----------------------------------| -----------------------------------|
| x | number | Yes| X coordinate of the rotation vector. |
| y | number | Yes| Y coordinate of the rotation vector. |
| z | number | Yes| Z coordinate of the rotation vector. |
| angle | number | Yes| Rotation angle. |
| centerX | number | Yes| X coordinate of the center point. |
| centerY | number | Yes| Y coordinate of the center point. |
### Matrix4Result
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Value Range | Description |
| --------| -----------------------------------|
| [number,number,number,number,<br>number,number,number,number,<br>number,number,number,number,<br>number,number,number,number] | A number array whose length is 16 (4 x 4). For details, see **4 x 4 matrix description**.|
**4 x 4 matrix description**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------ |
| m00 | number | Yes | Scale factor along the x-axis. Defaults to **1** for the identity matrix. |
| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. |
| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. |
| m03 | number | Yes | Meaningless value. |
| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. |
| m11 | number | Yes | Scale factor along the y-axis. Defaults to **1** for the identity matrix. |
| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. |
| m13 | number | Yes | Meaningless value. |
| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. |
| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. |
| m22 | number | Yes | Scale factor along the z-axis. Defaults to **1** for the identity matrix. |
| m23 | number | Yes | Meaningless value. |
| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the unit matrix.|
| m31 | number | Yes | Translation value of the y-axis, in px. The default value is **0** for the identity matrix.|
| m32 | number | Yes | Translation value of the z-axis, in px. The default value is **0** for the identity matrix.|
| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. |
**Example**
```js
import matrix4 from '@ohos.matrix4';
import componentUtils from '@ohos.arkui.componentUtils';
@Entry
@Component
struct Utils{
private getComponentRect(key) {
console.info("Mode Key: " + key);
let modePosition = componentUtils.getRectangleById(key);
let localOffsetWidth = modePosition.size.width;
let localOffsetHeight = modePosition.size.height;
let localOffsetX = modePosition.localOffset.x;
let localOffsetY = modePosition.localOffset.y;
let windowOffsetX = modePosition.windowOffset.x;
let windowOffsetY = modePosition.windowOffset.y;
let screenOffsetX = modePosition.screenOffset.x;
let screenOffsetY = modePosition.screenOffset.y;
let translateX = modePosition.translate.x;
let translateY = modePosition.translate.y;
let translateZ = modePosition.translate.z;
let scaleX = modePosition.scale.x;
let scaleY = modePosition.scale.y;
let scaleZ = modePosition.scale.z;
let scaleCenterX = modePosition.scale.centerX;
let scaleCenterY = modePosition.scale.centerY;
let rotateX = modePosition.rotate.x;
let rotateY = modePosition.rotate.y;
let rotateZ = modePosition.rotate.z;
let rotateCenterX = modePosition.rotate.centerX;
let rotateCenterY = modePosition.rotate.centerY;
let rotateAngle = modePosition.rotate.angle;
let Matrix4_1 = modePosition.transform[0];
let Matrix4_2 = modePosition.transform[1];
let Matrix4_3 = modePosition.transform[2];
let Matrix4_4 = modePosition.transform[3];
let Matrix4_5 = modePosition.transform[4];
let Matrix4_6 = modePosition.transform[5];
let Matrix4_7 = modePosition.transform[6];
let Matrix4_8 = modePosition.transform[7];
let Matrix4_9 = modePosition.transform[8];
let Matrix4_10 = modePosition.transform[9];
let Matrix4_11 = modePosition.transform[10];
let Matrix4_12 = modePosition.transform[11];
let Matrix4_13 = modePosition.transform[12];
let Matrix4_14 = modePosition.transform[13];
let Matrix4_15 = modePosition.transform[14];
let Matrix4_16 = modePosition.transform[15];
console.info("[getRectangleById] current component obj is: " + modePosition );
}
@State x: number = 120;
@State y: number = 10;
@State z: number = 100;
private matrix1 = matrix4.identity().translate({ x: this.x, y: this.y, z: this.z });
build() {
Column() {
Image($r("app.media.icon"))
.transform(this.matrix1)
.translate({ x: 100, y: 10, z: 50})
.scale({ x: 2, y: 0.5, z: 1 })
.rotate({
x: 1,
y: 1,
z: 1,
centerX: '50%',
centerY: '50%',
angle: 300
})
.width("40%")
.height(100)
.key("image_01")
Button() {
Text('getRectangleById').fontSize(40).fontWeight(FontWeight.Bold);
}.margin({ top: 20 })
.onClick(() => {
this.getComponentRect("image_01");
}).id('onClick');
}
}
}
```
# @ohos. deviceStatus.dragInteraction (Drag)
The **dragInteraction** module provides the APIs to enable and disable listening for dragging status changes.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs provided by this module are system APIs.
## Modules to Import
```js
import dragInteraction from '@ohos.deviceStatus.dragInteraction'
```
## dragInteraction.on
on(type: 'drag', callback: Callback&lt;DragState&gt;): void;
Enables listening for dragging status changes.
**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **drag**.|
| callback | Callback&lt;[DragState](#dragstate)&gt; | Yes | Callback used to return the dragging status.|
**Example**
```js
try {
dragInteraction.on('drag', (data) => {
console.log(`Drag interaction event: ${JSON.stringify(data)}`);
});
} catch (error) {
console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## dragInteraction.off
off(type: 'drag', callback?: Callback&lt;DragState&gt;): void;
Disables listening for dragging status changes.
**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **drag**.|
| callback | Callback&lt;[DragState](#dragstate)> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.|
**Example**
```js
// Unregister a single callback.
function callback(event) {
console.log(`Drag interaction event: ${JSON.stringify(event)}`);
return false;
}
try {
dragInteraction.on('drag', callback);
dragInteraction.off("drag", callback);
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
```js
// Unregister all callbacks.
function callback(event) {
console.log(`Drag interaction event: ${JSON.stringify(event)}`);
return false;
}
try {
dragInteraction.on('drag', callback);
dragInteraction.off("drag");
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## DragState
Enumerates dragging states.
**System capability**: SystemCapability.Msdp.DeviceStatus.Drag
| Name | Value | Description |
| -------- | ----------------- | ----------------- |
| MSG_DRAG_STATE_START | 1 | Dragging starts.|
| MSG_DRAG_STATE_STOP | 2 | Dragging is ended. |
| MSG_DRAG_STATE_CANCEL | 3 | Dragging is canceled. |
# @ohos.net.vpn (VPN Management)
The **vpn** module implements virtual private network (VPN) management, such as starting and stopping a VPN.
> **NOTE**
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import vpn from '@ohos.net.vpn';
```
## vpn.createVpnConnection
createVpnConnection(context: AbilityContext): VpnConnection
Creates a VPN connection.
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| context | [AbilityContext](js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) | Yes | Specified context. |
**Return value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| [VpnConnection](#vpnconnection) | VPN connection object.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
**Example**
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
globalThis.context = this.context;
}
}
let context = globalThis.context;
VpnConnection = vpn.createVpnConnection(context);
console.info("vpn onInit: " + JSON.stringify(VpnConnection));
```
## VpnConnection
Defines a VPN connection object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling [vpn.createVpnConnection](#vpncreatevpnconnection).
### setUp
setUp(config: VpnConfig, callback: AsyncCallback\<number\>): void
Creates a VPN based on the specified configuration. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_VPN
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. |
| callback | AsyncCallback\<number\> | Yes | Callback used to return the result. If a VPN is created successfully, **error** is **undefined** and **data** is the file descriptor of the vNIC. Otherwise, **error** is an error object.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203001 | VPN creation denied, please check the user type. |
| 2203002 | VPN exist already, please execute destroy first. |
**Example**
```js
let config = {
addresses: [{
address: {
address: "10.0.0.5",
family: 1
},
prefixLength: 24,
}],
routes: [],
mtu: 1400,
dnsAddresses:[
"114.114.114.114"
],
trustedApplications:[],
blockedApplications:[]
}
VpnConnection.setUp(config, (error, data) => {
console.info(JSON.stringify(error));
console.info("tunfd: " + JSON.stringify(data));
})
```
### setUp
setUp(config: VpnConfig): Promise\<number\>
Creates a VPN based on the specified configuration. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_VPN
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<number\> | The obtaining result is returned in Promise format. The file descriptor fd of the specified virtual network adapter is returned.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203001 | VPN creation denied, please check the user type. |
| 2203002 | VPN exist already, please execute destroy first. |
**Example**
```js
let config = {
addresses: [{
address: {
address: "10.0.0.5",
family: 1
},
prefixLength: 24,
}],
routes: [],
mtu: 1400,
dnsAddresses:[
"114.114.114.114"
],
trustedApplications:[],
blockedApplications:[]
}
VpnConnection.setUp(config).then((data) => {
console.info(TAG + "setUp success, tunfd: " + JSON.stringify(data))
}).catch(err => {
console.info(TAG + "setUp fail" + JSON.stringify(err))
})
```
### protect
protect(socketFd: number, callback: AsyncCallback\<void\>): void
Protects 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 an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_VPN
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10). |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined**. If the operation fails, an error message is returned.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203004 | Invalid socket file descriptor. |
**Example**
```js
import socket from "@ohos.net.socket";
var tcp = socket.constructTCPSocketInstance();
tcp.bind({
address: "0.0.0.0",
family: 1
})
let connectAddress = {
address: "192.168.1.11",
port: 8888,
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
})
tcp.getSocketFd().then((tunnelfd) => {
console.info("tunenlfd: " + tunnelfd);
VpnConnection.protect(tunnelfd, (error) => {
console.info(JSON.stringify(error));
})
})
```
### protect
protect(socketFd: number): Promise\<void\>
Protects sockets against a VPN connection. The data sent through sockets is directly transmitted over the physical network and therefore traffic does not traverse through the VPN. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_VPN
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1). |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| 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.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203004 | Invalid socket file descriptor. |
**Example**
```js
import socket from "@ohos.net.socket";
var tcp = socket.constructTCPSocketInstance();
tcp.bind({
address: "0.0.0.0",
family: 1
})
let connectAddress = {
address: "192.168.1.11",
port: 8888,
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
})
tcp.getSocketFd().then((tunnelfd) => {
console.info("tunenlfd: " + tunnelfd);
VpnConnection.protect(tunnelfd).then(() => {
console.info("protect success.")
}).catch(err => {
console.info("protect fail" + JSON.stringify(err))
})
})
```
### destroy
destroy(callback: AsyncCallback\<void\>): void
Destroys a VPN. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_VPN
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined**. If the operation fails, an error message is returned.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example**
```js
VpnConnection.destroy((error) => {
console.info(JSON.stringify(error));
})
```
### destroy
destroy(): Promise\<void\>
Destroys a VPN. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.MANAGE_VPN
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| 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.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example**
```js
VpnConnection.destroy().then(() => {
console.info("destroy success.")
}).catch(err => {
console.info("destroy fail" + JSON.stringify(err))
});
```
## VpnConfig
Defines the VPN configuration.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Vpn
| Name| Type| Mandatory| Description|
| ------- | ------ | -- |------------------------------ |
| addresses | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress8)\> | Yes| IP address of the vNIC.|
| routes | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo8)\> | No| Route information of the vNIC.|
| dnsAddresses | Array\<string\> | No| IP address of the DNS server.|
| searchDomains | Array\<string\> | No| List of DNS search domains.|
| mtu | number | No| Maximum transmission unit (MTU), in bytes.|
| isIPv4Accepted | boolean | No| Whether IPv4 is supported. The default value is **true**.|
| isIPv6Accepted | boolean | No| Whether IPv6 is supported. The default value is **false**.|
| isLegacy | boolean | No| Whether the built-in VPN is supported. The default value is **false**.|
| isBlocking | boolean | No| Whether the blocking mode is used. The default value is **false**.|
| trustedApplications | Array\<string\> | No| List of trusted applications, which are represented by bundle names of the string type.|
| blockedApplications | Array\<string\> | No| List of blocked applications, which are represented by bundle names of the string type.|
......@@ -59,6 +59,7 @@
- [Policy Management Error Codes](errorcode-net-policy.md)
- [mDNS Error Codes](errorcode-net-mdns.md)
- [Traffic Management Error Codes](errorcode-net-statistics.md)
- [VPN Error Codes](errorcode-net-vpn.md)
- Connectivity
- [Bluetooth Error Codes](errorcode-bluetoothManager.md)
- [Wi-Fi Error Codes](errorcode-wifi.md)
......
# VPN Error Codes
> **NOTE**
>
> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md).
## 2203001 Failed to Create a VPN
**Error Information**
VPN creation denied, please check the user type.
**Description**
This error code is reported if a VPN fails to be created.
**Possible Causes**
The login user does not have the operation permission. Specifically, the GUEST user does not have the permission to call the **setUp** API.
**Solution**
Check the type of the login user.
## 2203002 VPN Already Exists
**Error Information**
VPN exist already, please execute destroy first.
**Description**
This error code is reported if a VPN already exists.
**Possible Causes**
The VPN has been created.
**Solution**
Call the **destroy** API to destroy the existing VPN, and then call the **setUp** API.
## 2203004 Invalid Descriptor
**Error Information**
Invalid socket file descriptor.
**Description**
This error code is reported if the socket file descriptor is invalid.
**Possible Causes**
A TCP socket connection fails to be established.
**Solution**
Check whether a TCP socket connection is set up successfully.
......@@ -25,9 +25,6 @@
- HSP
- [In-Application HSP Development](quick-start/in-app-hsp.md)
- [Inter-Application HSP Development](quick-start/cross-app-hsp.md)
- Atomic Service
- [Atomic Service Development](quick-start/atomicService.md)
- [Atomic Service Space Management (for System Applications Only)](quick-start/atomicService-aging.md)
- Quick Fix
- [Quick Fix Overview](quick-start/quickfix-principles.md)
- [CLI-based Quick Fix Development](quick-start/quickfix-debug.md)
......@@ -147,7 +144,6 @@
- [Cross-Device Migration](application-models/hop-cross-device-migration.md)
- [Multi-device Collaboration (for System Applications Only)](application-models/hop-multi-device-collaboration.md)
- [Subscribing to System Environment Variable Changes](application-models/subscribe-system-environment-variable-changes.md)
- [Setting Atomic Services to Support Sharing](application-models/atomic-services-support-sharing.md)
- Process Model
- [Process Model Overview](application-models/process-model-stage.md)
- Common Events
......@@ -560,6 +556,7 @@
- [Network Connection Management](connectivity/net-connection-manager.md)
- [MDNS Management](connectivity/net-mdns.md)
- [Traffic Management](connectivity/net-statistics.md)
- [VPN Management](connectivity/net-vpn.md)
- IPC & RPC
- [IPC & RPC Overview](connectivity/ipc-rpc-overview.md)
- [IPC & RPC Development](connectivity/ipc-rpc-development-guideline.md)
......@@ -915,6 +912,7 @@
- UI Page
- [@ohos.animator (Animator)](reference/apis/js-apis-animator.md)
- [@ohos.arkui.componentSnapshot (Component Snapshot)](reference/apis/js-apis-arkui-componentSnapshot.md)
- [@ohos.arkui.componentUtils (componentUtils)](reference/apis/js-apis-arkui-componentUtils.md)
- [@ohos.arkui.dragController (DragController)](reference/apis/js-apis-arkui-dragController.md)
- [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](reference/apis/js-apis-arkui-drawableDescriptor.md)
- [@ohos.arkui.inspector (Layout Callback)](reference/apis/js-apis-arkui-inspector.md)
......@@ -1024,11 +1022,12 @@
- [@ohos.net.sharing (Network Sharing)](reference/apis/js-apis-net-sharing.md)
- [@ohos.net.socket (Socket Connection)](reference/apis/js-apis-socket.md)
- [@ohos.net.statistics (Traffic Management)](reference/apis/js-apis-net-statistics.md)
- [@ohos.net.vpn (VPN Management)](reference/apis/js-apis-net-vpn.md)
- [@ohos.net.webSocket (WebSocket Connection)](reference/apis/js-apis-webSocket.md)
- [@ohos.request (Upload and Download)](reference/apis/js-apis-request.md)
- Connectivity
- [@ohos.bluetooth (Bluetooth) (To Be Deprecated Soon)](reference/apis/js-apis-bluetooth.md)
- [@ohos.bluetoothManager (Bluetooth) (Recommended)](reference/apis/js-apis-bluetoothManager.md)
- [@ohos.bluetoothManager (Bluetooth) (To Be Deprecated Soon)](reference/apis/js-apis-bluetoothManager.md)
- [@ohos.connectedTag (Active Tags)](reference/apis/js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](reference/apis/js-apis-cardEmulation.md)
- [@ohos.nfc.controller (Standard NFC)](reference/apis/js-apis-nfcController.md)
......@@ -1083,6 +1082,7 @@
- [@ohos.charger (Charging Type)](reference/apis/js-apis-charger.md)
- [@ohos.cooperate (Screen Hopping)](reference/apis/js-apis-devicestatus-cooperate.md)
- [@ohos.deviceAttest (Device Attestation)](reference/apis/js-apis-deviceAttest.md)
- [@ohos.deviceStatus.dragInteraction (Drag)](reference/apis/js-apis-devicestatus-draginteraction.md)
- [@ohos.deviceInfo (Device Information)](reference/apis/js-apis-device-info.md)
- [@ohos.distributedDeviceManager (Device Management)](reference/apis/js-apis-distributedDeviceManager.md)
- [@ohos.distributedHardware.deviceManager (Device Management)](reference/apis/js-apis-device-manager.md)
......@@ -1649,6 +1649,7 @@
- [Policy Management Error Codes](reference/errorcodes/errorcode-net-policy.md)
- [mDNS Error Codes](reference/errorcodes/errorcode-net-mdns.md)
- [Traffic Management Error Codes](reference/errorcodes/errorcode-net-statistics.md)
- [VPN Error Codes](reference/errorcodes/errorcode-net-vpn.md)
- Connectivity
- [Bluetooth Error Codes](reference/errorcodes/errorcode-bluetoothManager.md)
- [Wi-Fi Error Codes](reference/errorcodes/errorcode-wifi.md)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册