提交DM框架与服务模块

Signed-off-by: puhui <puhui1@huawei.com>
This commit is contained in:
puhui
2022-01-12 22:00:55 +08:00
parent e75612c55b
commit 931b58ca70
77 changed files with 8863 additions and 1 deletions
+1 -1
View File
@@ -24,4 +24,4 @@ if (defined(ohos_lite)) {
]
}
}
}
}
+476
View File
@@ -0,0 +1,476 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { AsyncCallback, Callback } from './basic';
declare namespace deviceManager {
/**
* DeviceInfo
*/
interface DeviceInfo {
/**
* DeviceId ID.
*/
deviceId: string;
/**
* Device name of the device.
*/
deviceName: string;
/**
* Device type of the device.
*/
deviceType: DeviceType;
}
/**
* Device Type definitions
*/
enum DeviceType {
/**
* Indicates an unknown device type.
*/
UNKNOWN_TYPE = 0,
/**
* Indicates a speaker.
*/
SPEAKER = 0x0A,
/**
* Indicates a smartphone.
*/
PHONE = 0x0E,
/**
* Indicates a tablet.
*/
TABLET = 0x11,
/**
* Indicates a smart watch.
*/
WEARABLE = 0x6D,
/**
* Indicates a car.
*/
CAR = 0x83,
/**
* Indicates a smart TV.
*/
TV = 0x9C
}
/**
* Device state change event definition
*/
enum DeviceStateChangeAction {
/**
* device online action
*/
ONLINE = 0,
/**
* device ready action, the device information synchronization was completed.
*/
READY = 1,
/**
* device offline action
*/
OFFLINE = 2,
/**
* device change action
*/
CHANGE = 3
}
/**
* Service subscribe info for device discover
*
* @systemapi this method can be used only by system applications.
*/
interface SubscribeInfo {
/**
* Service subscribe ID, the value is in scope [0, 65535], should be unique for each discover process
*/
subscribeId: number;
/**
* Discovery mode for service subscription.
*/
mode: DiscoverMode;
/**
* Service subscription medium.
*/
medium: ExchangeMedium;
/**
* Service subscription frequency.
*/
freq: ExchangeFreq;
/**
* only find the device with the same account.
*/
isSameAccount: boolean;
/**
* find the sleeping devices.
*/
isWakeRemote: boolean;
/**
* Subscribe capability.
*/
capability: SubscribeCap;
}
/**
* device discover mode
*
* @systemapi this method can be used only by system applications.
*/
enum DiscoverMode {
/**
* Passive
*/
DISCOVER_MODE_PASSIVE = 0x55,
/**
* Proactive
*/
DISCOVER_MODE_ACTIVE = 0xAA
}
/**
* device discover medium
*
* @systemapi this method can be used only by system applications.
*/
enum ExchangeMedium {
/**
* Automatic medium selection
*/
AUTO = 0,
/**
* Bluetooth
*/
BLE = 1,
/**
* Wi-Fi
*/
COAP = 2,
/**
* USB
*/
USB = 3
}
/**
* device discover freq
*
* @systemapi this method can be used only by system applications.
*/
enum ExchangeFreq {
/**
* Low
*/
LOW = 0,
/**
* Medium
*/
MID = 1,
/**
* High
*/
HIGH = 2,
/**
* Super-high
*/
SUPER_HIGH = 3
}
/**
* device discover capability
*
* @systemapi this method can be used only by system applications.
*/
enum SubscribeCap {
/**
* ddmpCapability
*/
SUBSCRIBE_CAPABILITY_DDMP = 0
}
/**
* Device Authentication param
*
* @systemapi this method can be used only by system applications
*/
interface AuthParam {
/**
* Authentication type, 1 for pin code.
*/
authType: number;
/**
* App application Icon.
*/
appIcon?: Uint8Array;
/**
* App application thumbnail.
*/
appThumbnail?: Uint8Array;
/**
* Authentication extra infos.
*/
extraInfo: {[key:string] : any};
}
/**
* Device auth info.
*
* @systemapi this method can be used only by system applications
*/
interface AuthInfo {
/**
* Authentication type, 1 for pin code.
*/
authType: number;
/**
* the token used for this authentication.
*/
token: number;
/**
* Authentication extra infos.
*/
extraInfo: {[key:string] : any};
}
/**
* User Operation Action from devicemanager Fa.
*
* @systemapi this method can be used only by system applications.
*/
enum UserOperationAction {
/**
* allow authentication
*/
ACTION_ALLOW_AUTH = 0,
/**
* cancel authentication
*/
ACTION_CANCEL_AUTH = 1,
/**
* user operation timeout for authentication confirm
*/
ACTION_AUTH_CONFIRM_TIMEOUT = 2,
/**
* cancel pincode display
*/
ACTION_CANCEL_PINCODE_DISPLAY = 3,
/**
* cancel pincode input
*/
ACTION_CANCEL_PINCODE_INPUT = 4,
}
/**
* Creates a {@code DeviceManager} instance.
*
* <p>To manage devices, you must first call this method to obtain a {@code DeviceManager} instance and then
* use this instance to call other device management methods.
*
* @param bundleName Indicates the bundle name of the application.
* @param callback Indicates the callback to be invoked upon {@code DeviceManager} instance creation.
*/
function createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager>): void;
/**
* Provides methods for managing devices.
*/
interface DeviceManager {
/**
* Releases the {@code DeviceManager} instance after the methods for device management are no longer used.
*/
release(): void;
/**
* Obtains a list of trusted devices.
*
* @param options Indicates the extra parameters to be passed to this method for device filtering or sorting.
* This parameter can be null. For details about available values, see {@link #TARGET_PACKAGE_NAME} and
* {@link #SORT_TYPE}.
* @return Returns a list of trusted devices.
*/
getTrustedDeviceListSync(): Array<DeviceInfo>;
/**
* Start to discover device.
*
* @param bundleName Indicates the bundle name of the application.
* @param subscribeInfo subscribe info to discovery device
* @systemapi this method can be used only by system applications.
*/
startDeviceDiscovery(subscribeInfo: SubscribeInfo): void;
/**
* Stop to discover device.
*
* @param bundleName Indicates the bundle name of the application.
* @param subscribeId Service subscribe ID
* @systemapi this method can be used only by system applications.
*/
stopDeviceDiscovery(subscribeId: number): void;
/**
* Authenticate the specified device.
*
* @param deviceInfo deviceInfo of device to authenticate
* @param authparam authparam of device to authenticate
* @param callback Indicates the callback to be invoked upon authenticateDevice
* @systemapi this method can be used only by system applications.
*/
authenticateDevice(deviceInfo: DeviceInfo, authparam: AuthParam, callback: AsyncCallback<{deviceId: string, pinTone ?: number}>): void;
/**
* verify auth info, such as pin code.
*
* @param authInfo device auth info o verify
* @param callback Indicates the callback to be invoked upon verifyAuthInfo
* @systemapi this method can be used only by system applications.
*/
verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void;
/**
* Get authenticate parameters for peer device, this interface can only used by devicemanager Fa.
*
* @param authParam authparam for peer device
* @systemapi this method can be used only by system applications.
*/
getAuthenticationParam(): AuthParam;
/**
* Set user Operation from devicemanager Fa, this interface can only used by devicemanager Fa.
*
* @param operateAction User Operation Actions.
* @systemapi this method can be used only by system applications.
*/
setUserOperation(operateAction: UserOperationAction): void;
/**
* Register a callback from deviceManager service so that the devicemanager Fa can be notified when some events happen.
* this interface can only used by devicemanager Fa.
*
* @param callback for devicemanager Fa to register.
* @systemapi this method can be used only by system applications.
*/
on(type: 'dmFaCallback', callback: Callback<{ param: string}>): void;
/**
* UnRegister dmFaCallback, this interface can only used by devicemanager Fa.
*
* @param callback for devicemanager Fa to register.
* @systemapi this method can be used only by system applications.
*/
off(type: 'dmFaCallback', callback?: Callback<{ param: string}>): void;
/**
* Register a device state callback so that the application can be notified upon device state changes based on
* the application bundle name.
*
* @param bundleName Indicates the bundle name of the application.
* @param callback Indicates the device state callback to register.
*/
on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void;
/**
* UnRegister device state callback based on the application bundle name.
*
* @param bundleName Indicates the bundle name of the application.
* @param callback Indicates the device state callback to register.
*/
off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void;
/**
* Register a device found callback so that the application can be notified when the device was found
*
* @param callback Indicates the device found callback to register.
* @systemapi this method can be used only by system applications.
*/
on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: DeviceInfo }>): void;
/**
* UnRegister a device found callback so that the application can be notified when the device was found
*
* @param callback Indicates the device found callback to register.
* @systemapi this method can be used only by system applications.
*/
off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: DeviceInfo }>): void;
/**
* Register a device found result callback so that the application can be notified when the device discover was failed
*
* @param callback Indicates the device found result callback to register.
* @systemapi this method can be used only by system applications.
*/
on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: number }>): void;
/**
* UnRegister a device found result callback so that the application can be notified when the device discover was failed
*
* @param callback Indicates the device found result callback to register.
* @systemapi this method can be used only by system applications.
*/
off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: number }>): void;
/**
* Register a serviceError callback so that the application can be notified when devicemanager service died
*
* @param callback Indicates the service error callback to register.
*/
on(type: 'serviceDie', callback: () => void): void;
/**
* UnRegister a serviceError callback so that the application can be notified when devicemanager service died
*
* @param callback Indicates the service error callback to register.
*/
off(type: 'serviceDie', callback?: () => void): void;
}
}
export default deviceManager;
+57
View File
@@ -0,0 +1,57 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'com.huawei.ohos.app'
ohos {
compileSdkVersion 6
defaultConfig {
compatibleSdkVersion 6
}
}
buildscript {
repositories {
maven {
url 'http://repo.ark.tools.huawei.com/artifactory/maven-public/'
}
maven {
url 'https://mirrors.huaweicloud.com/repository/maven/'
}
maven {
url 'https://developer.huawei.com/repo/'
}
jcenter()
}
dependencies {
classpath 'com.huawei.ohos:hap:2.4.4.3-RC'
}
}
allprojects {
repositories {
maven {
url 'http://repo.ark.tools.huawei.com/artifactory/maven-public/'
}
maven {
url 'https://mirrors.huaweicloud.com/repository/maven/'
}
maven {
url 'https://developer.huawei.com/repo/'
}
jcenter()
}
}
+42
View File
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
apply plugin: 'com.huawei.ohos.hap'
apply plugin: 'com.huawei.ohos.decctest'
//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510
ohos {
compileSdkVersion 6
defaultConfig {
compatibleSdkVersion 6
}
buildTypes {
release {
proguardOpt {
proguardEnabled false
rulesFiles 'proguard-rules.pro'
}
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])
testImplementation 'junit:junit:4.13'
ohosTestImplementation 'com.huawei.ohos.testkit:runner:1.0.0.200'
}
decc {
supportType = ['html', 'xml']
}
+61
View File
@@ -0,0 +1,61 @@
{
"app": {
"bundleName": "com.ohos.devicemanagerui",
"vendor": "ohos",
"version": {
"code": 1000000,
"name": "1.0.0"
}
},
"deviceConfig": {},
"module": {
"package": "com.ohos.devicemanagerui",
"name": ".MyApplication",
"mainAbility": "com.ohos.devicemanagerui.MainAbility",
"deviceType": [
"phone",
"tablet",
"tv",
"wearable"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "entry",
"moduleType": "entry",
"installationFree": false
},
"abilities": [
{
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"visible": true,
"name": "com.ohos.devicemanagerui.MainAbility",
"icon": "$media:icon",
"description": "$string:mainability_description",
"label": "$string:entry_MainAbility",
"type": "page",
"launchType": "standard"
}
],
"js": [
{
"pages": [
"pages/index/index"
],
"name": "default",
"window": {
"designWidth": 720,
"autoDesignWidth": true
}
}
]
}
}
+23
View File
@@ -0,0 +1,23 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export default {
onCreate() {
console.info('AceApplication onCreate');
},
onDestroy() {
console.info('AceApplication onDestroy');
}
};
@@ -0,0 +1,4 @@
{
"strings": {
}
}
@@ -0,0 +1,4 @@
{
"strings": {
}
}
@@ -0,0 +1,169 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
.container {
flex-direction: column;
justify-content: center;
align-items: center;
opacity: 0.8;
background-color: azure;
}
.container > div {
flex-direction: column;
justify-content: center;
align-items: center;
}
.main-pin > .pin-numb {
flex-direction: row;
justify-content: space-around;
align-items: center;
padding: 15px 30px 10px 30px;
}
.main-pin > .pin-numb > .pin-numb-item {
font-size: 30px;
line-height: 30px;
height: 40px;
padding-bottom: 5px;
font-weight: 800;
width: 30px;
border-bottom-width: 2px;
border-bottom-color: darkgray;
text-align: center;
}
.main-pin > .input {
flex-direction: row;
justify-content: space-around;
align-items: center;
padding: 5px 30px 5px 30px;
}
.main-pin > .input > .numb {
text-color: black;
padding: 5px;
flex-shrink: 0;
flex-basis: 60px;
background-color: white;
border: 1px;
}
.join-auth {
padding-top: 30px;
}
.join-auth-image > image {
height: 170px;
}
.join-authorize {
padding-top: 10px;
}
.join-pin {
padding: 10px 0;
}
.join-pin > .pin {
font-size: 50px;
line-height: 90px;
font-weight: bolder;
color: #000000;
}
.join-auth > .title,
.join-auth-image > .title,
.join-authorize > .title {
font-size: 18px;
line-height: 80px;
font-weight: 800;
color: #000000;
}
.join-auth > .title {
line-height: 40px;
}
.join-auth-image > .title {
line-height: 26px;
}
.join-pin > .title {
font-size: 28px;
line-height: 60px;
font-weight: 800;
}
.main-pin > .title {
font-size: 30px;
line-height: 40px;
font-weight: bolder;
}
.join-auth > .title-tip,
.join-auth-image > .title-tip,
.main-pin > .title-tip,
.join-authorize > .title-tip {
font-size: 15px;
line-height: 40px;
color: #5A5A5A;
}
.join-auth > .title-tip {
line-height: 40px;
}
.join-auth-image > .title-tip {
line-height: 24px;
}
.join-pin > .title-tip {
font-size: 20px;
line-height: 50px;
font-weight: 600;
}
.main-pin > .title-tip {
font-size: 18px;
line-height: 30px;
font-weight: 800;
}
.join-auth > .dialog-foot,
.join-auth-image > .dialog-foot,
.join-authorize > .dialog-foot {
flex-direction: row;
justify-content: center;
align-items: center;
justify-content: space-around;
margin: 80px 20px 30px 20px;
}
.join-authorize > .dialog-foot {
margin: 100px 20px 30px 20px;
}
.join-auth-image > .dialog-foot {
margin: 10px 20px 10px 20px;
}
.join-pin > .dialog-foot {
margin: 10px 20px 10px 20px;
}
.join-auth .button-cancel,
.join-auth-image .button-cancel,
.join-authorize .button-cancel {
width: 160px;
height: 36px;
}
.join-pin .button-cancel {
width: 100%;
font-size: 26px;
height: 50px;
}
.join-auth .button-ok,
.join-auth-image .button-ok,
.join-authorize .button-ok {
width: 150px;
height: 36px;
}
@@ -0,0 +1,98 @@
<!--
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-->
<div class="container">
<div if="{{status == 'main-pin'}}" class="main-pin">
<text class="title">PIN码连接</text>
<text class="title-tip">请输入平板上显示的PIN码</text>
<div class="pin-numb" >
<text class="pin-numb-item">{{pin[0]}}</text>
<text class="pin-numb-item">{{pin[1]}}</text>
<text class="pin-numb-item">{{pin[2]}}</text>
<text class="pin-numb-item">{{pin[3]}}</text>
<text class="pin-numb-item">{{pin[4]}}</text>
<text class="pin-numb-item">{{pin[5]}}</text>
</div>
<div class="input" >
<button @click="mainInputPin(1)" type="text" class="numb">1</button>
<button @click="mainInputPin(2)" type="text" class="numb">2</button>
<button @click="mainInputPin(3)" type="text" class="numb">3</button>
<button @click="mainInputPin(4)" type="text" class="numb">4</button>
</div>
<div class="input" >
<button @click="mainInputPin(5)" type="text" class="numb">5</button>
<button @click="mainInputPin(6)" type="text" class="numb">6</button>
<button @click="mainInputPin(7)" type="text" class="numb">7</button>
<button @click="mainInputPin(8)" type="text" class="numb">8</button>
</div>
<div class="input" >
<button @click="mainInputPin(9)" type="text" class="numb">9</button>
<button @click="mainInputPin(0)" type="text" class="numb">0</button>
<button @click="mainInputPinBack" type="text" class="numb">删除</button>
<button @click="mainInputPinCancel" type="text" class="numb">取消</button>
</div>
</div>
<div if="{{status == 'join-authorize'}}" class="join-authorize">
<text class="title">是否允许{{statusInfo.deviceName}}连接本机</text>
<text class="title-tip">用于资源访问</text>
<div class="dialog-foot">
<button @click="joinAuthorizeCancel" type="text" class="button-cancel">
取消({{ timeRemaining }}
</button>
<button @click="joinAuthorizeOk" class="button-ok" type="capsule">
允许
</button>
</div>
</div>
<div if="{{status == 'join-auth'}}" class="join-auth">
<text class="title-tip">{{ statusInfo.appName }}</text>
<text class="title">是否允许打开apply auth?</text>
<text class="title-tip">来自{{statusInfo.deviceName}}</text>
<div class="dialog-foot">
<button @click="joinAuthCancel" type="text" class="button-cancel">
取消({{ timeRemaining }}
</button>
<button @click="joinAuthOk" class="button-ok" type="capsule">
允许
</button>
</div>
</div>
<div if="{{status == 'join-auth-image'}}" class="join-auth-image">
<image src="{{ statusInfo.appIcon }}"></image>
<text class="title-tip">{{ statusInfo.appName }}</text>
<text class="title">是否允许打开apply auth?</text>
<text class="title-tip">来自{{statusInfo.deviceName}}</text>
<div class="dialog-foot">
<button @click="joinAuthImageCancel" type="text" class="button-cancel">
取消({{ timeRemaining }}
</button>
<button @click="joinAuthImageOk" class="button-ok" type="capsule">
允许
</button>
</div>
</div>
<div if="{{status == 'join-pin'}}" class="join-pin">
<text class="title">PIN码连接</text>
<text class="title-tip">请在主控端输入连接码进行验证</text>
<text class="pin">{{statusInfo.pinCode.split('').join(' ')}}</text>
<div class="dialog-foot">
<button @click="joinPinCancel" type="text" class="button-cancel">
取消
</button>
</div>
</div>
</div>
@@ -0,0 +1,331 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import router from '@system.router';
import deviceManager from '@ohos.distributedHardware.deviceManager';
function uint8ArrayToBase64(array) {
array = new Uint8Array(array);
let table = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'],
base64Str = '', length = array.byteLength, i = 0;
for(i = 0; length - i >= 3; i += 3) {
let num1 = array[i], num2 = array[i + 1], num3 = array[i + 2];
base64Str += table[num1 >>> 2] + table[((num1 & 0b11) << 4) | (num2 >>> 4)] + table[((num2 & 0b1111) << 2) | (num3 >>> 6)] + table[num3 & 0b111111];
}
const lastByte = length - i;
if (lastByte === 1) {
const lastNum1 = array[i];
base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4)] + '==';
} else if (lastByte === 2) {
const lastNum1 = array[i];
const lastNum2 = array[i + 1];
base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4) | (lastNum2 >>> 4)] + table[(lastNum2 & 0b1111) << 2] + '=';
}
return 'data:image/png;base64,' + base64Str;
}
const TAG = "DeviceManagerUI:";
let dmClass;
export default {
data: {
// showType: ['main-pin','join-authorize','join-auth','join-auth-image','join-pin']
status: "",
// showInfo
statusInfo: {
deviceName: "AppName",
appName: 'PackageName',
appIcon: null,
pinCode: '',
pinToken: ''
},
// join: join-authorize timing
timeRemaining: 0,
// input pinCode
pin: ['','','','','',''],
// input pinCode next number
pinNumb: 0
},
log(m) {
console.info(TAG + m);
},
onDestroy() {
if (dmClass != null) {
dmClass.off('dmFaCallback');
dmClass.off('deviceStateChange');
dmClass.off('serviceDie');
dmClass.release();
dmClass = null
}
},
onShow() {
if (dmClass) {
this.initStatue()
} else {
this.log('createDeviceManager')
deviceManager.createDeviceManager('com.ohos.devicemanagerui', (err, dm) => {
this.log("createDeviceManager err:" + JSON.stringify(err) + ' --success:' + JSON.stringify(dm))
if (err) return;
dmClass = dm;
dmClass.on('dmFaCallback', () => router.back())
this.initStatue()
});
}
},
onHide() {
this.timeRemaining = 0
},
/**
* Get authentication param
*/
initStatue() {
this.log('initStatue')
const data = dmClass.getAuthenticationParam()
this.log('getAuthenticationParam:' + JSON.stringify(data))
// Authentication type, 1 for pin code.
if (data && data.authType == 1) {
this.statusInfo = {
deviceName: data.extraInfo.PackageName,
appName: data.extraInfo.appName,
appIcon: uint8ArrayToBase64(data.appIcon),
pinCode: data.extraInfo.pinCode + '',
pinToken: data.extraInfo.pinToken
}
// direction: 1(main)/0(join)
if (data.extraInfo.direction == 1) {
this.mainPin()
} else if (data.appIcon) {
this.joinAuthImage()
} else if (data.extraInfo.business == 0) {
// business: 0(FA流转)/1(资源访问)
this.joinAuth()
} else {
this.joinAuthorize()
}
}
},
/**
* Set user Operation from devicemanager Fa, this interface can only used by devicemanager Fa.
*
* @param operateAction User Operation Actions.
* ACTION_ALLOW_AUTH = 0, allow authentication
* ACTION_CANCEL_AUTH = 1, cancel authentication
* ACTION_AUTH_CONFIRM_TIMEOUT = 2, user operation timeout for authentication confirm
* ACTION_CANCEL_PINCODE_DISPLAY = 3, cancel pinCode display
* ACTION_CANCEL_PINCODE_INPUT = 4, cancel pinCode input
*/
setUserOperation(operation) {
this.log('setUserOperation: ' + operation)
if (dmClass != null) {
var data = dmClass.setUserOperation(operation);
this.log('setUserOperation result: ' + JSON.stringify(data))
} else {
this.log('deviceManagerObject not exit')
}
},
/**
* verify auth info, such as pin code.
* @param pinCode
* @return
*/
verifyAuthInfo(pinCode) {
this.log('verifyAuthInfo: ' + pinCode)
if (dmClass != null) {
dmClass.verifyAuthInfo({
"authType": 1,
"token": this.statusInfo.pinToken,
"extraInfo": {
"pinCode": +pinCode
}
}, (err, data) => {
if (err) {
this.log("verifyAuthInfo err:" + JSON.stringify(err))
}
this.log("verifyAuthInfo result:" + JSON.stringify(data))
router.back()
});
} else {
this.log('deviceManagerObject not exit')
}
},
/**
* Input pinCode at the main control terminal
*/
mainPin() {
this.status = 'main-pin'
},
/**
* Enter a number with the keyboard
* @param s
* @return
*/
mainInputPin(s) {
this.log('mainInputPin input: ' + s + '-' + this.pin)
if (this.pinNumb == 6) return
if (this.pinNumb < 6) {
this.pin[this.pinNumb] = s
++this.pinNumb
this.pin = [...this.pin]
}
this.log('mainInputPin pin: ' + this.pin + '-' + this.pin.join(''))
if (this.pinNumb == 6) {
// input end
this.log('mainInputPin end: ' + this.pin + '-' + this.pin.join(''))
this.verifyAuthInfo(this.pin.join(''))
}
},
/**
* Keyboard delete number
*/
mainInputPinBack() {
if (this.pinNumb > 0) {
--this.pinNumb
this.pin[this.pinNumb] = ''
this.pin = [...this.pin]
}
},
/**
* Cancel pinCode input
*/
mainInputPinCancel() {
this.setUserOperation(4)
},
/**
* Join end authorization, business(FA流转)/1(资源访问): 0
*/
joinAuthorize() {
this.status = 'join-authorize'
this.timing(60, 'join-authorize', () => {
this.setUserOperation(2)
router.back()
})
},
/**
* Join end authorization, business(FA流转)/1(资源访问): 1
*/
joinAuth() {
this.status = 'join-auth'
this.timing(60, 'join-auth', () => {
this.setUserOperation(2)
router.back()
})
},
/**
* Join end authorization, business(FA流转)/1(资源访问): 1, show application icon
*/
joinAuthImage() {
this.status = 'join-auth-image'
this.timing(60, 'join-auth-image', () => {
this.setUserOperation(2)
router.back()
})
},
/**
* Display pinCode at join end
*/
joinPin() {
this.status = 'join-pin'
},
/**
* Cancel authorization
*/
joinAuthorizeCancel() {
this.setUserOperation(1)
router.back()
},
/**
* Confirm authorization
*/
joinAuthorizeOk() {
this.setUserOperation(0)
this.joinPin()
},
/**
* Cancel authorization
*/
joinAuthCancel() {
this.setUserOperation(1)
router.back()
},
/**
* Confirm authorization
*/
joinAuthOk() {
this.setUserOperation(0)
this.joinPin()
},
/**
* Cancel authorization
*/
joinAuthImageCancel() {
this.setUserOperation(1)
router.back()
},
/**
* Confirm authorization
*/
joinAuthImageOk() {
this.setUserOperation(0)
this.joinPin()
},
/**
* Cancel authorization
*/
joinPinCancel() {
this.setUserOperation(3)
router.back()
},
/**
* Pure function countdown
* @param numb second
* @param status
* @param callback
* @return
*/
timing(numb, status, callback) {
this.timeRemaining = numb
const next = () => {
if (status != this.status) return
--this.timeRemaining
if (this.timeRemaining > 0) {
setTimeout(next, 1000)
} else {
callback()
}
}
next()
}
}
@@ -0,0 +1,12 @@
{
"string": [
{
"name": "entry_MainAbility",
"value": "entry_MainAbility"
},
{
"name": "mainability_description",
"value": "JS_Empty Ability"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

+1
View File
@@ -0,0 +1 @@
include ':entry'
+202
View File
@@ -0,0 +1,202 @@
# Copyright (C) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if (defined(ohos_lite)) {
import("//build/lite/config/component/lite_component.gni")
} else {
import("//build/ohos.gni")
}
import("//foundation/distributedhardware/devicemanager/devicemanager.gni")
if (defined(ohos_lite)) {
executable("devicemanagerservice") {
include_dirs = [
"include",
"include/adapter",
"include/authentication",
"include/ability",
"include/deviceinfo",
"include/devicestate",
"include/discovery",
"include/dependency/hichain",
"include/dependency/softbus",
"include/dependency/timer",
"include/ipc",
"include/ipc/lite",
"${common_path}/include",
"${common_path}/include/ipc",
"${common_path}/include/ipc/model",
"${utils_path}/include",
"${utils_path}/include/ipc/lite",
"${innerkits_path}/native_cpp/include",
"${innerkits_path}/native_cpp/include/ipc",
"${innerkits_path}/native_cpp/include/ipc/lite",
]
include_dirs += [
"//base/security/deviceauth/interfaces/innerkits",
"//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include",
"//utils/native/lite/include",
"//utils/system/safwk/native/include",
"//third_party/json/include",
"//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog",
"//third_party/bounds_checking_function/include",
"//foundation/communication/ipc_lite/interfaces/kits",
"//foundation/communication/dsoftbus/interfaces/kits/bus_center",
"//foundation/communication/dsoftbus/interfaces/kits/common",
"//foundation/communication/dsoftbus/interfaces/kits/discovery",
"//foundation/communication/dsoftbus/interfaces/kits/transport",
"//foundation/communication/dsoftbus/interfaces/inner_kits/transport",
"//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr",
]
sources = [
"src/ability/lite/dm_ability_manager.cpp",
"src/adapter/lite/dm_adapter_manager.cpp",
"src/authentication/auth_message_processor.cpp",
"src/authentication/auth_request_state.cpp",
"src/authentication/auth_response_state.cpp",
"src/authentication/auth_ui.cpp",
"src/authentication/dm_auth_manager.cpp",
"src/dependency/hichain/hichain_connector.cpp",
"src/dependency/softbus/softbus_connector.cpp",
"src/dependency/softbus/softbus_session.cpp",
"src/dependency/timer/dm_timer.cpp",
"src/device_manager_service.cpp",
"src/device_manager_service_listener.cpp",
"src/deviceinfo/dm_device_info_manager.cpp",
"src/devicestate/dm_device_state_manager.cpp",
"src/discovery/dm_discovery_manager.cpp",
"src/ipc/lite/ipc_cmd_parser.cpp",
"src/ipc/lite/ipc_server_listener.cpp",
"src/ipc/lite/ipc_server_listenermgr.cpp",
"src/ipc/lite/ipc_server_main.cpp",
"src/ipc/lite/ipc_server_stub.cpp",
]
defines = [
"LITE_DEVICE",
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"devicemanagerservice\"",
"LOG_DOMAIN=0xD004100",
]
deps = [
"${innerkits_path}/native_cpp:devicemanagersdk",
"${utils_path}:devicemanagerutils",
"//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared",
"//base/security/deviceauth/services:deviceauth_sdk",
"//base/startup/syspara_lite/frameworks/parameter/src:sysparam",
"//foundation/communication/dsoftbus/sdk:softbus_client",
"//foundation/communication/ipc_lite:liteipc_adapter",
"//foundation/distributedschedule/samgr_lite/samgr:samgr",
"//utils/native/lite:utils",
]
}
} else {
ohos_shared_library("devicemanagerservice") {
include_dirs = [
"include",
"include/config",
"include/adapter",
"include/authentication",
"include/ability",
"include/deviceinfo",
"include/devicestate",
"include/discovery",
"include/dependency/commonevent",
"include/dependency/hichain",
"include/dependency/softbus",
"include/dependency/timer",
"include/ipc",
"include/ipc/standard",
"include/eventbus",
"${common_path}/include",
"${common_path}/include/ipc",
"${common_path}/include/ipc/model",
"${utils_path}/include",
"${utils_path}/include/ipc/standard",
"${innerkits_path}/native_cpp/include",
"${innerkits_path}/native_cpp/include/ipc",
"${innerkits_path}/native_cpp/include/ipc/standard",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
"//base/notification/ces_standard/frameworks/core/include",
"//base/notification/ces_standard/interfaces/innerkits/native/include",
"//base/security/deviceauth/interfaces/innerkits",
"//base/startup/syspara_lite/interfaces/kits",
"//base/startup/syspara_lite/adapter/native/syspara/include",
"//third_party/json/include",
]
sources = [
"src/ability/standard/dm_ability_manager.cpp",
"src/adapter/standard/dm_adapter_manager.cpp",
"src/authentication/auth_message_processor.cpp",
"src/authentication/auth_request_state.cpp",
"src/authentication/auth_response_state.cpp",
"src/authentication/auth_ui.cpp",
"src/authentication/dm_auth_manager.cpp",
"src/config/config_manager.cpp",
"src/dependency/commonevent/event_manager_adapt.cpp",
"src/dependency/hichain/hichain_connector.cpp",
"src/dependency/softbus/softbus_connector.cpp",
"src/dependency/softbus/softbus_session.cpp",
"src/dependency/timer/dm_timer.cpp",
"src/device_manager_service.cpp",
"src/device_manager_service_listener.cpp",
"src/deviceinfo/dm_device_info_manager.cpp",
"src/devicestate/dm_device_state_manager.cpp",
"src/discovery/dm_discovery_manager.cpp",
"src/ipc/standard/ipc_cmd_parser.cpp",
"src/ipc/standard/ipc_server_client_proxy.cpp",
"src/ipc/standard/ipc_server_listener.cpp",
"src/ipc/standard/ipc_server_stub.cpp",
]
deps = [
"${innerkits_path}/native_cpp:devicemanagersdk",
"${utils_path}:devicemanagerutils",
"//base/security/deviceauth/services:deviceauth_sdk",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/aafwk/standard/services/abilitymgr:abilityms",
"//utils/native/base:utils",
]
defines = [
"HI_LOG_ENABLE",
"DH_LOG_TAG=\"devicemanagerservice\"",
"LOG_DOMAIN=0xD004100",
]
external_deps = [
"appexecfwk_standard:appexecfwk_base",
"appexecfwk_standard:appexecfwk_core",
"appexecfwk_standard:libeventhandler",
"ces_standard:cesfwk_core",
"ces_standard:cesfwk_innerkits",
"dsoftbus_standard:softbus_client",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"startup_l2:syspara",
]
subsystem_name = "distributedhardware"
part_name = "device_manager_base"
}
}
@@ -0,0 +1,57 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_ABILITY_MANAGER_H
#define OHOS_DM_ABILITY_MANAGER_H
#include <semaphore.h>
#include <mutex>
#include <string>
#include <vector>
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
enum AbilityRole { ABILITY_ROLE_PASSIVE = 0, ABILITY_ROLE_INITIATIVE = 1, ABILITY_ROLE_UNKNOWN = 2 };
enum AbilityStatus { ABILITY_STATUS_FAILED = 0, ABILITY_STATUS_SUCCESS = 1, ABILITY_STATUS_START = 2 };
enum FaAction {
USER_OPERATION_TYPE_ALLOW_AUTH = 0,
USER_OPERATION_TYPE_CANCEL_AUTH = 1,
USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT = 2,
USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY = 3,
USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT = 4
};
class DmAbilityManager {
public:
AbilityRole GetAbilityRole();
AbilityStatus StartAbility(AbilityRole role);
void StartAbilityDone();
private:
void waitForTimeout(uint32_t timeout_s);
private:
sem_t mSem_;
AbilityStatus mStatus_;
AbilityRole mAbilityStatus_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_CRYPTO_ADAPTER_H
#define OHOS_DM_CRYPTO_ADAPTER_H
#include <cstdint>
namespace OHOS {
namespace DistributedHardware {
class ICryptoAdapter {
public:
virtual ~ICryptoAdapter() = default;
virtual std::string GetName() = 0;
virtual std::string GetVersion() = 0;
virtual int32_t MbedTlsEncrypt(const uint8_t *plainText, int32_t plainTextLen, uint8_t *cipherText,
int32_t cipherTextLen, int32_t *outLen) = 0;
virtual int32_t MbedTlsDecrypt(const uint8_t *cipherText, int32_t cipherTextLen, uint8_t *plainText,
int32_t plainTextLen, int32_t *outLen) = 0;
};
using CreateICryptoAdapterFuncPtr = ICryptoAdapter *(*)(void);
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_CRYPTO_ADAPTER_H
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_DECISION_ADAPTER_H
#define OHOS_DM_DECISION_ADAPTER_H
#include <string>
#include <vector>
#include "dm_device_info.h"
namespace OHOS {
namespace DistributedHardware {
class IDecisionAdapter {
public:
virtual ~IDecisionAdapter() = default;
virtual std::string GetName() = 0;
virtual std::string GetVersion() = 0;
virtual int32_t FilterDeviceList(std::vector<DmDeviceInfo> &infoList, const std::string &filterOptions) = 0;
virtual int32_t SortDeviceList(std::vector<DmDeviceInfo> &infoList, const std::string &sortOptions) = 0;
};
using CreateIDecisionAdapterFuncPtr = IDecisionAdapter *(*)(void);
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_DECISION_ADAPTER_H
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_ADAPTER_MANAGER_H
#define OHOS_DM_ADAPTER_MANAGER_H
#include <memory>
#include "crypto_adapter.h"
#include "decision_adapter.h"
#include "profile_adapter.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
class IProfileAdapter;
class DmAdapterManager {
DECLARE_SINGLE_INSTANCE(DmAdapterManager);
public:
std::shared_ptr<IDecisionAdapter> GetDecisionAdapter(const std::string &soName);
std::shared_ptr<IProfileAdapter> GetProfileAdapter(const std::string &soName);
std::shared_ptr<ICryptoAdapter> GetCryptoAdapter(const std::string &soName);
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_ADAPTER_MANAGER_H
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_PROFILE_ADAPTER_H
#define OHOS_DM_PROFILE_ADAPTER_H
#include <cstdint>
#include <string>
namespace OHOS {
namespace DistributedHardware {
class DmDeviceStateManager;
class IProfileAdapter {
public:
virtual ~IProfileAdapter() = default;
virtual int32_t RegisterProfileListener(const std::string &pkgName, const std::string &deviceId,
std::shared_ptr<DmDeviceStateManager> callback) = 0;
virtual int32_t UnRegisterProfileListener(const std::string &pkgName) = 0;
};
using CreateIProfileAdapterFuncPtr = IProfileAdapter *(*)(void);
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_PROFILE_ADAPTER_H
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_AUTH_MESSAGE_PROCESSOR_H
#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_H
#include <memory>
#include <vector>
#include "crypto_adapter.h"
#include "dm_auth_manager.h"
#include "nlohmann/json.hpp"
namespace OHOS {
namespace DistributedHardware {
class DmAuthManager;
struct DmAuthRequestContext;
struct DmAuthResponseContext;
class ICryptoAdapter;
class AuthMessageProcessor {
public:
AuthMessageProcessor(std::shared_ptr<DmAuthManager> authMgr);
~AuthMessageProcessor();
std::vector<std::string> CreateAuthRequestMessage();
std::string CreateSimpleMessage(int32_t msgType);
int32_t ParseMessage(const std::string &message);
void SetRequestContext(std::shared_ptr<DmAuthRequestContext> authRequestContext);
void SetResponseContext(std::shared_ptr<DmAuthResponseContext> authResponseContext);
std::shared_ptr<DmAuthResponseContext> GetResponseContext();
std::shared_ptr<DmAuthRequestContext> GetRequestContext();
private:
std::string CreateRequestAuthMessage(nlohmann::json &json);
void CreateNegotiateMessage(nlohmann::json &json);
void CreateSyncGroupMessage(nlohmann::json &json);
void CreateResponseAuthMessage(nlohmann::json &json);
void ParseAuthResponseMessage(nlohmann::json &json);
void ParseAuthRequestMessage();
void ParseNegotiateMessage(const nlohmann::json &json);
void CreateResponseFinishMessage(nlohmann::json &json);
void ParseResponseFinishMessage(nlohmann::json &json);
private:
std::weak_ptr<DmAuthManager> authMgr_;
std::shared_ptr<ICryptoAdapter> cryptoAdapter_;
std::shared_ptr<DmAuthRequestContext> authRequestContext_;
std::shared_ptr<DmAuthResponseContext> authResponseContext_;
std::vector<nlohmann::json> authSplitJsonList_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_AUTH_MESSAGE_PROCESSOR_H
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_AUTH_REQUEST_STATE_H
#define OHOS_DM_AUTH_REQUEST_STATE_H
#include <cstdint>
#include <memory>
#include <sstream>
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
class DmAuthManager;
struct DmAuthRequestContext;
class AuthRequestState : public std::enable_shared_from_this<AuthRequestState> {
public:
virtual ~AuthRequestState()
{
authManager_.reset();
LOGE("~AuthRequestState");
};
virtual int32_t GetStateType() = 0;
virtual void Enter() = 0;
void Leave();
void TransitionTo(std::shared_ptr<AuthRequestState> state);
void SetAuthManager(std::shared_ptr<DmAuthManager> authManager);
void SetAuthContext(std::shared_ptr<DmAuthRequestContext> context);
std::shared_ptr<DmAuthRequestContext> GetAuthContext();
protected:
std::weak_ptr<DmAuthManager> authManager_;
std::shared_ptr<DmAuthRequestContext> context_;
};
class AuthRequestInitState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthRequestNegotiateState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthRequestNegotiateDoneState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthRequestReplyState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthRequestInputState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthRequestJoinState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthRequestNetworkState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthRequestFinishState : public AuthRequestState {
public:
int32_t GetStateType() override;
void Enter() override;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_AUTH_REQUEST_STATE_H
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_AUTH_RESPONSE_STATE_H
#define OHOS_DM_AUTH_RESPONSE_STATE_H
#include <memory>
namespace OHOS {
namespace DistributedHardware {
class DmAuthManager;
struct DmAuthResponseContext;
class AuthResponseState : public std::enable_shared_from_this<AuthResponseState> {
public:
virtual ~AuthResponseState()
{
authManager_.reset();
};
virtual int32_t GetStateType() = 0;
virtual void Enter() = 0;
void Leave();
void TransitionTo(std::shared_ptr<AuthResponseState> state);
void SetAuthManager(std::shared_ptr<DmAuthManager> authManager);
void SetAuthContext(std::shared_ptr<DmAuthResponseContext> context);
std::shared_ptr<DmAuthResponseContext> GetAuthContext();
protected:
std::weak_ptr<DmAuthManager> authManager_;
std::shared_ptr<DmAuthResponseContext> context_;
};
class AuthResponseInitState : public AuthResponseState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthResponseNegotiateState : public AuthResponseState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthResponseConfirmState : public AuthResponseState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthResponseGroupState : public AuthResponseState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthResponseShowState : public AuthResponseState {
public:
int32_t GetStateType() override;
void Enter() override;
};
class AuthResponseFinishState : public AuthResponseState {
public:
int32_t GetStateType() override;
void Enter() override;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_AUTH_RESPONSE_STATE_H
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_AUTH_UI_H
#define OHOS_DM_AUTH_UI_H
#include <cstdint>
#include "dm_ability_manager.h"
namespace OHOS {
namespace DistributedHardware {
class AuthUi {
public:
AuthUi();
int32_t ShowConfirmDialog(std::shared_ptr<DmAbilityManager> dmAbilityManager);
private:
int32_t StartFaService();
private:
std::shared_ptr<DmAbilityManager> dmAbilityMgr_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_AUTH_UI_H
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_AUTHENTICATION_H
#define OHOS_DM_AUTHENTICATION_H
#include "dm_ability_manager.h"
namespace OHOS {
namespace DistributedHardware {
class IAuthentication {
public:
virtual ~IAuthentication() = default;
virtual int32_t ShowAuthInfo() = 0;
virtual int32_t StartAuth(std::shared_ptr<DmAbilityManager> dmAbilityManager) = 0;
virtual int32_t VerifyAuthentication(std::string pinToken, int32_t code, const std::string &authParam) = 0;
};
using CreateIAuthAdapterFuncPtr = IAuthentication *(*)(void);
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_AUTHENTICATION_H
@@ -0,0 +1,182 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_AUTH_MANAGER_H
#define OHOS_DM_AUTH_MANAGER_H
#include <map>
#include <string>
#include "auth_message_processor.h"
#include "auth_request_state.h"
#include "auth_response_state.h"
#include "auth_ui.h"
#include "authentication.h"
#include "device_manager_service_listener.h"
#include "dm_ability_manager.h"
#include "dm_adapter_manager.h"
#include "dm_constants.h"
#include "dm_device_info.h"
#include "dm_timer.h"
#include "hichain_connector.h"
#include "softbus_connector.h"
#include "softbus_session.h"
namespace OHOS {
namespace DistributedHardware {
typedef enum AuthState {
AUTH_REQUEST_INIT = 1,
AUTH_REQUEST_NEGOTIATE,
AUTH_REQUEST_NEGOTIATE_DONE,
AUTH_REQUEST_REPLY,
AUTH_REQUEST_INPUT,
AUTH_REQUEST_JOIN,
AUTH_REQUEST_NETWORK,
AUTH_REQUEST_FINISH,
AUTH_RESPONSE_INIT = 20,
AUTH_RESPONSE_NEGOTIATE,
AUTH_RESPONSE_CONFIRM,
AUTH_RESPONSE_GROUP,
AUTH_RESPONSE_SHOW,
AUTH_RESPONSE_FINISH,
} AuthState;
enum DmMsgType : int32_t {
MSG_TYPE_UNKNOWN = 0,
MSG_TYPE_NEGOTIATE = 80,
MSG_TYPE_RESP_NEGOTIATE = 90,
MSG_TYPE_REQ_AUTH = 100,
MSG_TYPE_INVITE_AUTH_INFO = 102,
MSG_TYPE_REQ_AUTH_TERMINATE = 104,
MSG_TYPE_RESP_AUTH = 200,
MSG_TYPE_JOIN_AUTH_INFO = 201,
MSG_TYPE_RESP_AUTH_TERMINATE = 205,
MSG_TYPE_CHANNEL_CLOSED = 300,
MSG_TYPE_SYNC_GROUP = 400,
MSG_TYPE_AUTH_BY_PIN = 500,
};
typedef struct DmAuthRequestContext {
int32_t authType;
std::string localDeviceId;
std::string deviceId;
std::string deviceName;
std::string deviceTypeId;
int32_t sessionId;
int32_t groupVisibility;
bool cryptoSupport;
std::string cryptoName;
std::string cryptoVer;
std::string hostPkgName;
std::string targetPkgName;
std::string appName;
std::string appDesc;
std::string appIcon;
std::string appThumbnail;
std::string token;
int32_t reason;
std::vector<std::string> syncGroupList;
} DmAuthRequestContext;
typedef struct DmAuthResponseContext {
int32_t authType;
std::string deviceId;
std::string localDeviceId;
int32_t msgType;
int32_t sessionId;
bool cryptoSupport;
std::string cryptoName;
std::string cryptoVer;
int32_t reply;
std::string networkId;
std::string groupId;
std::string groupName;
std::string hostPkgName;
std::string targetPkgName;
std::string appName;
std::string appDesc;
std::string appIcon;
std::string appThumbnail;
std::string token;
int64_t requestId;
int32_t code;
std::vector<std::string> syncGroupList;
} DmAuthResponseContext;
class AuthMessageProcessor;
class DmAuthManager final : public ISoftbusSessionCallback,
public IHiChainConnectorCallback,
public std::enable_shared_from_this<DmAuthManager> {
public:
DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,
std::shared_ptr<DeviceManagerServiceListener> listener);
~DmAuthManager();
int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId,
const std::string &extra);
int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId);
int32_t VerifyAuthentication(const std::string &authParam);
void OnSessionOpened(const std::string &pkgName, int32_t sessionId, int32_t sessionSide, int32_t result);
void OnSessionClosed(const std::string &pkgName, int32_t sessionId);
void OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message);
void OnGroupCreated(int64_t requestId, const std::string &groupId);
void OnMemberJoin(int64_t requestId, int32_t status);
// auth state machine
void EstablishAuthChannel(const std::string &deviceId);
void StartNegotiate(const int32_t &sessionId);
void RespNegotiate(const int32_t &sessionId);
void SendAuthRequest(const int32_t &sessionId);
void StartAuthProcess(const int32_t &authType);
void StartRespAuthProcess();
void CreateGroup();
void AddMember(const std::string &deviceId);
std::string GetConnectAddr(std::string deviceId);
void JoinNetwork();
void AuthenticateFinish();
void GetIsCryptoSupport(bool &isCryptoSupport);
void SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState);
void SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState);
int32_t GetPinCode();
std::string GenerateGroupName();
void HandleAuthenticateTimeout();
void CancelDisplay();
int32_t GeneratePincode();
void ShowConfigDialog();
void ShowAuthInfoDialog();
void ShowStartAuthDialog();
int32_t GetAuthenticationParam(DmAuthParam &authParam);
int32_t RegisterSessionCallback();
int32_t OnUserOperation(int32_t action);
private:
std::shared_ptr<SoftbusConnector> softbusConnector_;
std::shared_ptr<HiChainConnector> hiChainConnector_;
std::shared_ptr<DeviceManagerServiceListener> listener_;
std::shared_ptr<DmAdapterManager> adapterMgr_;
std::map<int32_t, std::shared_ptr<IAuthentication>> authenticationMap_;
std::shared_ptr<AuthRequestState> authRequestState_ = nullptr;
std::shared_ptr<AuthResponseState> authResponseState_ = nullptr;
std::shared_ptr<DmAuthRequestContext> authRequestContext_;
std::shared_ptr<DmAuthResponseContext> authResponseContext_;
std::shared_ptr<AuthMessageProcessor> authMessageProcessor_;
std::map<std::string, std::shared_ptr<DmTimer>> timerMap_;
std::shared_ptr<DmAbilityManager> dmAbilityMgr_;
bool isCryptoSupport_ = false;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_AUTH_MANAGER_H
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_OHOS_DM_CONFIG_MANAGER_H
#define OHOS_OHOS_DM_CONFIG_MANAGER_H
#include <cstdlib>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include "authentication.h"
#include "crypto_adapter.h"
#include "decision_adapter.h"
#include "profile_adapter.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
typedef struct {
std::string name;
std::string type;
std::string version;
std::string funcName;
std::string soName;
std::string soPath;
} AdapterSoLoadInfo;
typedef struct {
int32_t authType;
std::string name;
std::string type;
std::string version;
std::string funcName;
std::string soName;
std::string soPath;
} AuthSoLoadInfo;
class DmConfigManager final {
DECLARE_SINGLE_INSTANCE_BASE(DmConfigManager);
public:
~DmConfigManager();
void GetAllAuthType(std::vector<std::string> &allAuthType);
std::shared_ptr<IDecisionAdapter> GetDecisionAdapter(const std::string &soName);
std::shared_ptr<IProfileAdapter> GetProfileAdapter(const std::string &soName);
std::shared_ptr<ICryptoAdapter> GetCryptoAdapter(const std::string &soName);
void GetAuthAdapter(std::map<int32_t, std::shared_ptr<IAuthentication>> &authAdapter);
private:
DmConfigManager();
private:
std::mutex authAdapterMutex_;
std::mutex cryptoAdapterMutex_;
std::mutex decisionAdapterMutex_;
std::mutex profileAdapterMutex_;
std::map<int32_t, AuthSoLoadInfo> soAuthLoadInfo_;
std::map<std::string, AdapterSoLoadInfo> soAdapterLoadInfo_;
std::map<std::string, std::shared_ptr<IDecisionAdapter>> decisionAdapterPtr_;
std::map<std::string, std::shared_ptr<IProfileAdapter>> profileAdapterPtr_;
std::map<std::string, std::shared_ptr<ICryptoAdapter>> cryptoAdapterPtr_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_OHOS_DM_CONFIG_MANAGER_H
@@ -0,0 +1,79 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_OHOS_DM_JSON_CONFIG_H
#define OHOS_OHOS_DM_JSON_CONFIG_H
#include <string>
namespace OHOS {
namespace DistributedHardware {
const std::string adapterJsonConfigString =
R"({
"devicemanager_adapter_components": [
{
"name": "crypto_adapter",
"type": "CPYPTO",
"version": "1.0",
"funcName": "CreateCryptoAdapterObject",
"soName": "libdevicemanager_crypto_adapter.z.so",
"soPath": "/system/lib/"
},
{
"name": "device_profile",
"type": "PROFILE",
"version": "1.0",
"funcName": "CreateDeviceProfileObject",
"soName": "libdevicemanagerext_profile.z.so",
"soPath": "/system/lib/"
}
]
})";
const std::string authJsonConfigString =
R"({
"devicemanager_auth_components": [
{
"name": "pin_auth",
"type": "AUTHENTICATE",
"version": "1.0",
"authType": 1,
"funcName": "CreatePinAuthObject",
"soName": "libdevicemanagerext_pin_auth.z.so",
"soPath": "/system/lib/"
},
{
"name": "QRcode_auth",
"type": "AUTHENTICATE",
"version": "1.0",
"authType": 2,
"funcName": "CreateQRcodeAuthObject",
"soName": "libdevicemanager_qrcodeauth.z.so",
"soPath": "/system/lib/"
},
{
"name": "nfc_auth",
"type": "AUTHENTICATE",
"version": "1.0",
"authType": 3,
"funcName": "CreateNfcAuthObject",
"soName": "libdevicemanager_nfcauth.z.so",
"soPath": "/system/lib/"
}
]
})";
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_OHOS_DM_JSON_CONFIG_H
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_EVENT_MANAGER_ADAPT_H
#define OHOS_EVENT_MANAGER_ADAPT_H
#include <map>
#include <mutex>
#include "common_event.h"
#include "common_event_data.h"
#include "common_event_manager.h"
#include "common_event_subscribe_info.h"
#include "common_event_subscriber.h"
#include "dm_log.h"
#include "matching_skills.h"
namespace OHOS {
namespace DistributedHardware {
using CommomEventCallback = void (*)(void);
class DmCommonEventManager {
public:
static DmCommonEventManager &GetInstance();
public:
bool SubscribeServiceEvent(const std::string &event, CommomEventCallback callback);
bool UnsubscribeServiceEvent(const std::string &event);
class EventSubscriber : public EventFwk::CommonEventSubscriber {
public:
explicit EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo)
: EventFwk::CommonEventSubscriber(subscribeInfo)
{
}
void OnReceiveEvent(const EventFwk::CommonEventData &data);
void addEventCallback(const std::string &event, CommomEventCallback callback);
void deleteEventCallback(const std::string &event);
private:
std::mutex callbackLock_;
std::map<std::string, CommomEventCallback> dmEventCallback_;
};
private:
DmCommonEventManager() = default;
virtual ~DmCommonEventManager();
DmCommonEventManager(const DmCommonEventManager &) = delete;
DmCommonEventManager &operator=(const DmCommonEventManager &) = delete;
DmCommonEventManager(DmCommonEventManager &&) = delete;
DmCommonEventManager &operator=(DmCommonEventManager &&) = delete;
private:
static void DealCallback(void);
static void InitCallbackThread(void);
private:
static std::once_flag onceFlag_;
static std::list<CommomEventCallback> callbackQueue_;
static std::mutex callbackQueueMutex_;
static std::condition_variable notEmpty_;
std::map<std::string, std::shared_ptr<EventSubscriber>> dmEventSubscriber_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_EVENT_MANAGER_ADAPT_H
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_HICHAIN_CONNECTOR_H
#define OHOS_HICHAIN_CONNECTOR_H
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "device_auth.h"
#include "hichain_connector_callback.h"
#include "nlohmann/json.hpp"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
struct GroupInfo {
std::string groupName;
std::string groupId;
std::string groupOwner;
int32_t groupType;
int32_t groupVisibility;
GroupInfo() : groupName(""), groupId(""), groupOwner(""), groupType(0), groupVisibility(0)
{
}
};
void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo);
class HiChainConnector {
public:
static bool onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen);
static void onFinish(int64_t requestId, int32_t operationCode, const char *returnData);
static void onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn);
static char *onRequest(int64_t requestId, int32_t operationCode, const char *reqParams);
public:
HiChainConnector();
~HiChainConnector();
int32_t RegisterHiChainCallback(const std::string &pkgName, std::shared_ptr<IHiChainConnectorCallback> callback);
int32_t UnRegisterHiChainCallback(const std::string &pkgName);
int32_t CreateGroup(int64_t requestId, const std::string &groupName);
int32_t AddMember(std::string deviceId, std::string &connectInfo);
int32_t DelMemberFromGroup(std::string groupId, std::string deviceId);
void DeleteGroup(std::string &groupId);
bool IsDevicesInGroup(std::string hostDevice, std::string peerDevice);
void GetRelatedGroups(std::string DeviceId, std::vector<GroupInfo> &groupList);
private:
int64_t GenRequestId();
void SyncGroups(std::string deviceId, std::vector<std::string> &remoteGroupIdList);
void GetSyncGroupList(std::vector<GroupInfo> &groupList, std::vector<std::string> &syncGroupList);
int32_t GetGroupInfo(std::string queryParams, std::vector<GroupInfo> &groupList);
std::string GetConnectPara(std::string deviceId, std::string reqDeviceId);
bool IsGroupCreated(std::string groupName, GroupInfo &groupInfo);
bool IsGroupInfoInvalid(GroupInfo &group);
private:
const DeviceGroupManager *deviceGroupManager_ = nullptr;
DeviceAuthCallback deviceAuthCallback_;
static std::map<std::string, std::shared_ptr<IHiChainConnectorCallback>> hiChainConnectorCallbackMap_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_HICHAIN_CONNECTOR_H
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H
#define OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H
namespace OHOS {
namespace DistributedHardware {
class IHiChainConnectorCallback {
public:
virtual void OnGroupCreated(int64_t requestId, const std::string &groupId) = 0;
virtual void OnMemberJoin(int64_t requestId, int32_t status) = 0;
virtual std::string GetConnectAddr(std::string deviceId) = 0;
virtual int32_t GetPinCode() = 0;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_HICHAIN_CONNECTOR_CALLBACK_H
@@ -0,0 +1,93 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_SOFTBUS_CONNECTOR_H
#define OHOS_DM_SOFTBUS_CONNECTOR_H
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "discovery_service.h"
#include "dm_device_info.h"
#include "dm_subscribe_info.h"
#include "softbus_bus_center.h"
#include "softbus_discovery_callback.h"
#include "softbus_session.h"
#include "softbus_state_callback.h"
namespace OHOS {
namespace DistributedHardware {
class SoftbusConnector {
public:
static void OnPublishSuccess(int32_t publishId);
static void OnPublishFail(int32_t publishId, PublishFailReason reason);
static void OnSoftBusDeviceOnline(NodeBasicInfo *info);
static void OnSoftbusDeviceOffline(NodeBasicInfo *info);
static void OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info);
static void OnSoftbusDeviceFound(const DeviceInfo *device);
static void OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason);
static void OnSoftbusDiscoverySuccess(int32_t subscribeId);
static void OnParameterChgCallback(const char *key, const char *value, void *context);
static int32_t GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress);
static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr);
static bool IsDeviceOnLine(const std::string &deviceId);
static int32_t GetUdidByNetworkId(const char *networkId, std::string &udid);
static int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid);
static int32_t GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info,
int32_t infoLen);
public:
SoftbusConnector();
~SoftbusConnector();
int32_t RegisterSoftbusStateCallback(const std::string &pkgName,
const std::shared_ptr<ISoftbusStateCallback> callback);
int32_t UnRegisterSoftbusStateCallback(const std::string &pkgName);
int32_t RegisterSoftbusDiscoveryCallback(const std::string &pkgName,
const std::shared_ptr<ISoftbusDiscoveryCallback> callback);
int32_t UnRegisterSoftbusDiscoveryCallback(const std::string &pkgName);
int32_t GetTrustedDeviceList(std::vector<DmDeviceInfo> &deviceInfoList);
int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo);
int32_t StartDiscovery(const DmSubscribeInfo &subscribeInfo);
int32_t StopDiscovery(uint16_t subscribeId);
std::shared_ptr<SoftbusSession> GetSoftbusSession();
bool HaveDeviceInMap(std::string deviceId);
private:
int32_t Init();
static void CovertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo);
static void CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo);
static ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type);
private:
enum PulishStatus {
STATUS_UNKNOWN = 0,
ALLOW_BE_DISCOVERY = 1,
NOT_ALLOW_BE_DISCOVERY = 2,
};
static PulishStatus publishStatus;
static INodeStateCb softbusNodeStateCb_;
static IDiscoveryCallback softbusDiscoveryCallback_;
static IPublishCallback softbusPublishCallback_;
std::shared_ptr<SoftbusSession> softbusSession_;
static std::map<std::string, std::shared_ptr<DeviceInfo>> discoveryDeviceInfoMap_;
static std::map<std::string, std::shared_ptr<ISoftbusStateCallback>> stateCallbackMap_;
static std::map<std::string, std::shared_ptr<ISoftbusDiscoveryCallback>> discoveryCallbackMap_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_SOFTBUS_CONNECTOR_H
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H
#define OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H
namespace OHOS {
namespace DistributedHardware {
class ISoftbusDiscoveryCallback {
public:
virtual void OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info) = 0;
virtual void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) = 0;
virtual void OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) = 0;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_SOFTBUS_DISCOVERY_CALLBACK_H
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_SOFTBUS_SESSION_H
#define OHOS_DM_SOFTBUS_SESSION_H
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "inner_session.h"
#include "session.h"
#include "softbus_session_callback.h"
namespace OHOS {
namespace DistributedHardware {
class SoftbusSession {
public:
static int32_t OnSessionOpened(int32_t sessionId, int32_t result);
static void OnSessionClosed(int32_t sessionId);
static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen);
public:
SoftbusSession();
~SoftbusSession();
int32_t RegisterSessionCallback(const std::string &pkgName, std::shared_ptr<ISoftbusSessionCallback> callback);
int32_t UnRegisterSessionCallback(const std::string &pkgName);
int32_t OpenAuthSession(const std::string &deviceId);
void CloseAuthSession(int32_t sessionId);
int32_t SendData(int32_t sessionId, std::string &message);
void GetPeerDeviceId(int32_t sessionId, std::string &peerDevId);
private:
static std::map<std::string, std::shared_ptr<ISoftbusSessionCallback>> sessionCallbackMap_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_SOFTBUS_SESSION_H
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_SOFTBUS_SESSION_CALLBACK_H
#define OHOS_DM_SOFTBUS_SESSION_CALLBACK_H
namespace OHOS {
namespace DistributedHardware {
class ISoftbusSessionCallback {
public:
virtual void OnSessionOpened(const std::string &pkgName, int32_t sessionId, int32_t sessionSide,
int32_t result) = 0;
virtual void OnSessionClosed(const std::string &pkgName, int32_t sessionId) = 0;
virtual void OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message) = 0;
virtual void GetIsCryptoSupport(bool &isCryptoSupport) = 0;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_SOFTBUS_SESSION_CALLBACK_H
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_SOFTBUS_STATE_CALLBACK_H
#define OHOS_DM_SOFTBUS_STATE_CALLBACK_H
namespace OHOS {
namespace DistributedHardware {
class ISoftbusStateCallback {
public:
virtual void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) = 0;
virtual void OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) = 0;
virtual void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) = 0;
virtual void OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info) = 0;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_SOFTBUS_STATE_CALLBACK_H
@@ -0,0 +1,71 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TIMER_H
#define TIMER_H
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <cstdio>
#include <string>
#include <thread>
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
typedef void (*TimeoutHandle)(void *data);
#define MAXEVENTS 255
enum DmTimerStatus : int32_t {
DM_STATUS_INIT = 0,
DM_STATUS_RUNNING = 1,
DM_STATUS_BUSY = 2,
DM_STATUS_CREATE_ERROR = 3,
DM_STATUS_FINISH = 6,
};
class DmTimer {
public:
DmTimer(std::string &name);
~DmTimer();
DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data);
void Stop(int32_t code);
void WaitForTimeout();
private:
int32_t CreateTimeFd();
void Release();
private:
DmTimerStatus mStatus_;
uint32_t mTimeOutSec_;
TimeoutHandle mHandle_;
void *mHandleData_;
int32_t mTimeFd_[2];
struct epoll_event mEv_;
struct epoll_event mEvents_[MAXEVENTS];
int32_t mEpFd_;
std::thread mThread_;
std::string mTimerName_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_SERVICE_H
#define OHOS_DM_SERVICE_H
#include <string>
#include <vector>
#include "dm_ability_manager.h"
#include "dm_auth_manager.h"
#include "dm_device_info.h"
#include "dm_device_info_manager.h"
#include "dm_device_state_manager.h"
#include "dm_discovery_manager.h"
#include "single_instance.h"
#include "softbus_connector.h"
namespace OHOS {
namespace DistributedHardware {
class DeviceManagerService {
DECLARE_SINGLE_INSTANCE(DeviceManagerService);
public:
int32_t Init();
int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra,
std::vector<DmDeviceInfo> &deviceList);
int32_t GetLocalDeviceInfo(DmDeviceInfo &info);
int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid);
int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid);
int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo,
const std::string &extra);
int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId);
int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId,
const std::string &extra);
int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId);
int32_t VerifyAuthentication(const std::string &authParam);
int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam);
int32_t SetUserOperation(std::string &pkgName, int32_t action);
private:
bool intFlag_ = false;
std::shared_ptr<DmAuthManager> authMgr_;
std::shared_ptr<DmDeviceInfoManager> deviceInfoMgr_;
std::shared_ptr<DmDeviceStateManager> deviceStateMgr_;
std::shared_ptr<DmDiscoveryManager> discoveryMgr_;
std::shared_ptr<SoftbusConnector> softbusConnector_;
std::shared_ptr<DeviceManagerServiceListener> listener_;
std::shared_ptr<DmAbilityManager> abilityMgr_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_SERVICE_H
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_SERVICE_LISTENER_H
#define OHOS_DM_SERVICE_LISTENER_H
#include <map>
#include <string>
#include "dm_device_info.h"
#include "ipc_notify_dmfa_result_req.h"
#include "ipc_server_listener.h"
namespace OHOS {
namespace DistributedHardware {
class DeviceManagerServiceListener {
public:
void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info);
void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info);
void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason);
void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId);
void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status,
const std::string &reason);
void OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode,
const std::string &flag);
void OnFaCall(std::string &pkgName, std::string &paramJson);
private:
IpcServerListener ipcServerListener_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_SERVICE_LISTENER_H
@@ -0,0 +1,41 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_DEVICEINFO_MANAGER_H
#define OHOS_DM_DEVICEINFO_MANAGER_H
#include <string>
#include <vector>
#include "dm_adapter_manager.h"
#include "dm_device_info.h"
#include "softbus_connector.h"
namespace OHOS {
namespace DistributedHardware {
class DmDeviceInfoManager {
public:
DmDeviceInfoManager(std::shared_ptr<SoftbusConnector> &softbusConnectorPtr);
int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra,
std::vector<DmDeviceInfo> &deviceList);
int32_t GetLocalDeviceInfo(DmDeviceInfo &info);
private:
std::shared_ptr<SoftbusConnector> softbusConnector_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_DEVICEINFO_MANAGER_H
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_DEVICE_STATE_MANAGER_H
#define OHOS_DM_DEVICE_STATE_MANAGER_H
#include "device_manager_service_listener.h"
#include "dm_adapter_manager.h"
#include "softbus_connector.h"
namespace OHOS {
namespace DistributedHardware {
class DmDeviceStateManager final : public ISoftbusStateCallback,
public std::enable_shared_from_this<DmDeviceStateManager> {
public:
DmDeviceStateManager(std::shared_ptr<SoftbusConnector> softbusConnector,
std::shared_ptr<DeviceManagerServiceListener> listener);
~DmDeviceStateManager();
void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info);
void OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info);
void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info);
void OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info);
void OnProfileReady(const std::string &pkgName, const std::string deviceId);
int32_t RegisterSoftbusStateCallback();
private:
std::shared_ptr<SoftbusConnector> softbusConnector_;
std::shared_ptr<DmAdapterManager> adapterMgr_;
std::shared_ptr<DeviceManagerServiceListener> listener_;
std::map<std::string, DmDeviceState> deviceStateMap_;
std::map<std::string, DmDeviceInfo> remoteDeviceInfos_;
std::string profileSoName_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_DEVICE_STATE_MANAGER_H
@@ -0,0 +1,56 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_DISCOVERY_MANAGER_H
#define OHOS_DM_DISCOVERY_MANAGER_H
#include <queue>
#include "device_manager_service_listener.h"
#include "dm_timer.h"
#include "softbus_connector.h"
namespace OHOS {
namespace DistributedHardware {
typedef struct DmDiscoveryContext {
std::string pkgName;
std::string extra;
uint16_t subscribeId;
} DmDiscoveryContext;
class DmDiscoveryManager final : public ISoftbusDiscoveryCallback,
public std::enable_shared_from_this<DmDiscoveryManager> {
public:
DmDiscoveryManager(std::shared_ptr<SoftbusConnector> softbusConnector,
std::shared_ptr<DeviceManagerServiceListener> listener);
~DmDiscoveryManager();
int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo,
const std::string &extra);
int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId);
void OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info);
void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId);
void OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason);
void HandleDiscoveryTimeout();
private:
std::shared_ptr<SoftbusConnector> softbusConnector_;
std::shared_ptr<DeviceManagerServiceListener> listener_;
std::queue<std::string> discoveryQueue_;
std::map<std::string, DmDiscoveryContext> discoveryContextMap_;
std::shared_ptr<DmTimer> discoveryTimer_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_DISCOVERY_MANAGER_H
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_IPC_SERVER_LISTENER_H
#define OHOS_DM_IPC_SERVER_LISTENER_H
#include <memory>
#include "ipc_req.h"
#include "ipc_rsp.h"
#include "ipc_server_listenermgr.h"
namespace OHOS {
namespace DistributedHardware {
class IpcServerListener {
public:
IpcServerListener() = default;
virtual ~IpcServerListener() = default;
public:
int32_t SendRequest(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp);
int32_t SendAll(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp);
private:
void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity);
int32_t GetIdentityByPkgName(std::string &name, SvcIdentity *svc);
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_IPC_SERVER_LISTENER_H
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_IPC_SERVER_LISTENER_MGR_H
#define OHOS_DM_IPC_SERVER_LISTENER_MGR_H
#include <cstdint>
#include <map>
#include <mutex>
#include <string>
#include "liteipc_adapter.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
typedef struct CommonSvcId {
uint32_t handle;
uint32_t token;
uint32_t cookie;
IpcContext *ipcCtx;
uint32_t cbId;
} CommonSvcId;
class IpcServerListenermgr {
DECLARE_SINGLE_INSTANCE(IpcServerListenermgr);
public:
int32_t RegisterListener(std::string &pkgName, const CommonSvcId *svcId);
int32_t GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId);
int32_t UnregisterListener(std::string &pkgName);
const std::map<std::string, CommonSvcId> &GetAllListeners();
private:
std::map<std::string, CommonSvcId> dmListenerMap_;
std::mutex lock_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_IPC_SERVER_LISTENER_MGR_H
@@ -0,0 +1,26 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_IPC_SERVER_STUB_H
#define OHOS_DM_IPC_SERVER_STUB_H
#include <cstdint>
#include "liteipc_adapter.h"
int32_t IpcServerStubInit(void);
int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply);
int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply);
#endif // OHOS_DM_IPC_SERVER_STUB_H
@@ -0,0 +1,35 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_IPC_SERVER_CLIENT_PROXY_H
#define OHOS_DM_IPC_SERVER_CLIENT_PROXY_H
#include "ipc_remote_broker.h"
#include "iremote_proxy.h"
namespace OHOS {
namespace DistributedHardware {
class IpcServerClientProxy : public IRemoteProxy<IpcRemoteBroker> {
public:
explicit IpcServerClientProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IpcRemoteBroker>(impl){};
~IpcServerClientProxy(){};
int32_t SendCmd(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp) override;
private:
static inline BrokerDelegator<IpcServerClientProxy> delegator_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_IPC_SERVER_CLIENT_PROXY_H
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_IPC_SERVER_LISTENER_H
#define OHOS_DM_IPC_SERVER_LISTENER_H
#include <cstdint>
#include "ipc_req.h"
#include "ipc_rsp.h"
namespace OHOS {
namespace DistributedHardware {
class IpcServerListener {
public:
IpcServerListener() = default;
virtual ~IpcServerListener() = default;
public:
int32_t SendRequest(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp);
int32_t SendAll(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp);
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_IPC_SERVER_LISTENER_H
@@ -0,0 +1,73 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_DM_IPC_SERVER_STUB_H
#define OHOS_DM_IPC_SERVER_STUB_H
#include <map>
#include <memory>
#include <mutex>
#include <tuple>
#include <vector>
#include "hichain_connector.h"
#include "ipc_remote_broker.h"
#include "iremote_stub.h"
#include "nlohmann/json.hpp"
#include "single_instance.h"
#include "system_ability.h"
#include "thread_pool.h"
namespace OHOS {
namespace DistributedHardware {
enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING };
class AppDeathRecipient : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject> &remote) override;
AppDeathRecipient() = default;
~AppDeathRecipient() = default;
};
class IpcServerStub : public SystemAbility, public IRemoteStub<IpcRemoteBroker> {
DECLARE_SYSTEM_ABILITY(IpcServerStub);
DECLARE_SINGLE_INSTANCE_BASE(IpcServerStub);
public:
void OnStart() override;
void OnStop() override;
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
int32_t SendCmd(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp) override;
int32_t RegisterDeviceManagerListener(std::string &pkgName, sptr<IRemoteObject> listener);
int32_t UnRegisterDeviceManagerListener(std::string &pkgName);
ServiceRunningState QueryServiceState() const;
const std::map<std::string, sptr<IRemoteObject>> &GetDmListener();
const sptr<IpcRemoteBroker> GetDmListener(std::string pkgName) const;
private:
IpcServerStub();
~IpcServerStub() = default;
bool Init();
private:
bool registerToService_;
ServiceRunningState state_;
std::mutex listenerLock_;
std::map<std::string, sptr<AppDeathRecipient>> appRecipient_;
std::map<std::string, sptr<IRemoteObject>> dmListener_;
};
} // namespace DistributedHardware
} // namespace OHOS
#endif // OHOS_DM_IPC_SERVER_STUB_H
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_ability_manager.h"
#include "dm_constants.h"
#include "semaphore.h"
namespace OHOS {
namespace DistributedHardware {
AbilityRole DmAbilityManager::GetAbilityRole()
{
return mAbilityStatus_;
}
AbilityStatus DmAbilityManager::StartAbility(AbilityRole role)
{
// not support for L1 yet, do nothing. jsut save status and role
mAbilityStatus_ = role;
mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS;
return mStatus_;
}
void DmAbilityManager::waitForTimeout(uint32_t timeout_s)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_s;
sem_timedwait(&mSem_, &ts);
}
void DmAbilityManager::StartAbilityDone()
{
mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS;
sem_post(&mSem_);
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,75 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_ability_manager.h"
#include "ability_manager_client.h"
#include "ability_manager_service.h"
#include "ability_record.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "parameter.h"
#include "semaphore.h"
#include "single_instance.h"
namespace OHOS {
namespace DistributedHardware {
namespace {
const int32_t ABILITY_START_TIMEOUT = 3; // 3 second
const std::string bundleName = "com.ohos.devicemanagerui";
const std::string abilityName = "com.ohos.devicemanagerui.MainAbility";
} // namespace
AbilityRole DmAbilityManager::GetAbilityRole()
{
return mAbilityStatus_;
}
AbilityStatus DmAbilityManager::StartAbility(AbilityRole role)
{
mAbilityStatus_ = role;
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
std::string deviceId = localDeviceId;
mStatus_ = AbilityStatus::ABILITY_STATUS_START;
AAFwk::Want want;
AppExecFwk::ElementName element(deviceId, bundleName, abilityName);
want.SetElement(element);
AAFwk::AbilityManagerClient::GetInstance()->Connect();
ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want);
if (result != OHOS::ERR_OK) {
LOGE("Start Ability faild");
mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED;
return mStatus_;
}
waitForTimeout(ABILITY_START_TIMEOUT);
return mStatus_;
}
void DmAbilityManager::waitForTimeout(uint32_t timeout_s)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_s;
sem_timedwait(&mSem_, &ts);
}
void DmAbilityManager::StartAbilityDone()
{
mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS;
sem_post(&mSem_);
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,56 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_adapter_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
DmAdapterManager &DmAdapterManager::GetInstance()
{
static DmAdapterManager instance;
return instance;
}
DmAdapterManager::DmAdapterManager()
{
LOGI("DmAdapterManager constructor");
}
DmAdapterManager::~DmAdapterManager()
{
LOGI("DmAdapterManager destructor");
}
std::shared_ptr<IDecisionAdapter> DmAdapterManager::GetDecisionAdapter()
{
return decisionAdapterPtr_;
}
std::shared_ptr<IProfileAdapter> DmAdapterManager::GetProfileAdapter()
{
return profileAdapterPtr_;
}
std::shared_ptr<ICryptoAdapter> DmAdapterManager::GetCryptoAdapter()
{
return cryptoAdapterPtr_;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_adapter_manager.h"
#include <dlfcn.h>
#include "config_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
DmAdapterManager &DmAdapterManager::GetInstance()
{
static DmAdapterManager instance;
return instance;
}
std::shared_ptr<IDecisionAdapter> DmAdapterManager::GetDecisionAdapter(const std::string &soName)
{
DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
return dmConfigManager.GetDecisionAdapter(soName);
}
std::shared_ptr<IProfileAdapter> DmAdapterManager::GetProfileAdapter(const std::string &soName)
{
DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
return dmConfigManager.GetProfileAdapter(soName);
}
std::shared_ptr<ICryptoAdapter> DmAdapterManager::GetCryptoAdapter(const std::string &soName)
{
DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
return dmConfigManager.GetCryptoAdapter(soName);
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,291 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "auth_message_processor.h"
#include "dm_auth_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
AuthMessageProcessor::AuthMessageProcessor(std::shared_ptr<DmAuthManager> authMgr) : authMgr_(authMgr)
{
LOGI("AuthMessageProcessor constructor");
}
AuthMessageProcessor::~AuthMessageProcessor()
{
authMgr_.reset();
}
std::vector<std::string> AuthMessageProcessor::CreateAuthRequestMessage()
{
LOGI("AuthMessageProcessor::CreateAuthRequestMessage start.");
std::vector<std::string> jsonStrVec;
int32_t thumbnailSize = authRequestContext_->appThumbnail.size();
int32_t thumbnailSlice = ((thumbnailSize / MSG_MAX_SIZE) + (thumbnailSize % MSG_MAX_SIZE) == 0 ? 0 : 1);
nlohmann::json jsonObj;
jsonObj[TAG_VER] = DM_ITF_VER;
jsonObj[TAG_TYPE] = MSG_TYPE_REQ_AUTH;
jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1;
jsonObj[TAG_INDEX] = 0;
jsonObj[TAG_REQUESTER] = authRequestContext_->deviceName;
jsonObj[TAG_DEVICE_ID] = authRequestContext_->deviceId;
jsonObj[TAG_DEVICE_TYPE] = authRequestContext_->deviceTypeId;
jsonObj[TAG_AUTH_TYPE] = authRequestContext_->authType;
jsonObj[TAG_TOKEN] = authRequestContext_->token;
jsonObj[TAG_VISIBILITY] = authRequestContext_->groupVisibility;
if (authRequestContext_->groupVisibility == GROUP_VISIBILITY_IS_PRIVATE) {
jsonObj[TAG_TARGET] = authRequestContext_->targetPkgName;
jsonObj[TAG_HOST] = authRequestContext_->hostPkgName;
}
jsonObj[TAG_APP_NAME] = authRequestContext_->appName;
jsonObj[TAG_APP_DESCRIPTION] = authRequestContext_->appDesc;
jsonObj[TAG_APP_ICON] = authRequestContext_->appIcon;
jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize;
jsonStrVec.push_back(jsonObj.dump());
for (int32_t idx = 0; idx < thumbnailSlice; idx++) {
nlohmann::json jsonThumbnailObj;
jsonThumbnailObj[TAG_VER] = DM_ITF_VER;
jsonThumbnailObj[TAG_TYPE] = MSG_TYPE_REQ_AUTH;
jsonThumbnailObj[TAG_SLICE_NUM] = thumbnailSlice + 1;
jsonThumbnailObj[TAG_INDEX] = idx + 1;
jsonThumbnailObj[TAG_DEVICE_ID] = authRequestContext_->deviceId;
jsonThumbnailObj[TAG_THUMBNAIL_SIZE] = thumbnailSize;
int32_t leftLen = thumbnailSize - idx * MSG_MAX_SIZE;
int32_t sliceLen = (leftLen > MSG_MAX_SIZE) ? MSG_MAX_SIZE : leftLen;
LOGD("TAG_APP_THUMBNAIL encode, idx %d, sliceLen %d, thumbnailSize %d", idx, sliceLen, thumbnailSize);
jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen);
jsonStrVec.push_back(jsonThumbnailObj.dump());
}
return jsonStrVec;
}
std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType)
{
LOGI("AuthMessageProcessor::CreateSimpleMessage start. msgType is %d", msgType);
nlohmann::json jsonObj;
jsonObj[TAG_VER] = DM_ITF_VER;
jsonObj[TAG_TYPE] = msgType;
switch (msgType) {
case MSG_TYPE_NEGOTIATE:
case MSG_TYPE_RESP_NEGOTIATE:
CreateNegotiateMessage(jsonObj);
break;
case MSG_TYPE_SYNC_GROUP:
CreateSyncGroupMessage(jsonObj);
break;
case MSG_TYPE_RESP_AUTH:
CreateResponseAuthMessage(jsonObj);
break;
case MSG_TYPE_REQ_AUTH_TERMINATE:
CreateResponseFinishMessage(jsonObj);
break;
default:
break;
}
return jsonObj.dump();
}
void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json)
{
if (cryptoAdapter_ == nullptr) {
json[TAG_CRYPTO_SUPPORT] = false;
} else {
json[TAG_CRYPTO_SUPPORT] = true;
json[TAG_CRYPTO_NAME] = cryptoAdapter_->GetName();
json[TAG_CRYPTO_VERSION] = cryptoAdapter_->GetVersion();
json[TAG_DEVICE_ID] = authRequestContext_->deviceId;
}
json[TAG_REPLY] = authResponseContext_->reply;
json[TAG_LOCAL_DEVICE_ID] = authResponseContext_->localDeviceId;
}
void AuthMessageProcessor::CreateSyncGroupMessage(nlohmann::json &json)
{
json[TAG_DEVICE_ID] = authRequestContext_->deviceId;
json[TAG_GROUPIDS] = authRequestContext_->syncGroupList;
}
void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json)
{
json[TAG_REPLY] = authResponseContext_->reply;
json[TAG_DEVICE_ID] = authResponseContext_->deviceId;
json[TAG_TOKEN] = authResponseContext_->token;
// json[TAG_GROUPIDS] = authResponseContext_->deviceId; //?
LOGI("AuthMessageProcessor::ParseAuthResponseMessage %d,%d", authResponseContext_->reply,
authResponseContext_->code);
LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str());
if (authResponseContext_->reply == 0) {
std::string groupId = authResponseContext_->groupId;
LOGI("AuthMessageProcessor::CreateSimpleMessage groupId %d", groupId.c_str());
nlohmann::json jsonObject = nlohmann::json::parse(groupId, nullptr, false);
if (jsonObject.is_discarded()) {
LOGE("DecodeRequestAuth jsonStr error");
return;
}
groupId = jsonObject[TAG_GROUP_ID];
json[PIN_CODE_KEY] = authResponseContext_->code;
json[TAG_NET_ID] = authResponseContext_->networkId;
json[TAG_REQUEST_ID] = authResponseContext_->requestId;
json[TAG_GROUP_ID] = groupId;
json[TAG_GROUP_NAME] = authResponseContext_->groupName;
LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s", groupId.c_str(),
authResponseContext_->groupName.c_str());
}
}
void AuthMessageProcessor::CreateResponseFinishMessage(nlohmann::json &json)
{
json[TAG_REPLY] = authResponseContext_->reply;
}
int32_t AuthMessageProcessor::ParseMessage(const std::string &message)
{
LOGE(" AuthMessageProcessor ParseMessage");
nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false);
if (jsonObject.is_discarded()) {
LOGE("DecodeRequestAuth jsonStr error");
return DM_FAILED;
}
if (!jsonObject.contains(TAG_TYPE)) {
LOGE("err json string, first time");
return DM_FAILED;
}
int32_t sliceNum = 0;
int32_t msgType = jsonObject[TAG_TYPE];
authResponseContext_->msgType = msgType;
LOGI("AuthMessageProcessor::ParseAuthRequestMessage======== %d", authResponseContext_->msgType);
switch (msgType) {
case MSG_TYPE_NEGOTIATE:
ParseNegotiateMessage(jsonObject);
break;
case MSG_TYPE_REQ_AUTH:
if (!jsonObject.contains(TAG_INDEX) || !jsonObject.contains(TAG_DEVICE_ID) ||
!jsonObject.contains(TAG_SLICE_NUM)) {
LOGE("err json string, first time");
return DM_FAILED;
}
authResponseContext_->deviceId = jsonObject[TAG_DEVICE_ID];
authResponseContext_->authType = jsonObject[TAG_AUTH_TYPE];
authResponseContext_->appDesc = jsonObject[TAG_APP_DESCRIPTION];
authResponseContext_->token = jsonObject[TAG_TOKEN];
authResponseContext_->targetPkgName = jsonObject[TAG_TARGET];
authResponseContext_->appName = jsonObject[TAG_APP_NAME];
LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str());
sliceNum = jsonObject[TAG_SLICE_NUM];
if ((int32_t)authSplitJsonList_.size() < sliceNum) {
authSplitJsonList_.push_back(message);
} else {
ParseAuthRequestMessage();
}
break;
case MSG_TYPE_RESP_AUTH:
ParseAuthResponseMessage(jsonObject);
break;
case MSG_TYPE_REQ_AUTH_TERMINATE:
ParseResponseFinishMessage(jsonObject);
break;
default:
break;
}
return DM_OK;
}
void AuthMessageProcessor::ParseResponseFinishMessage(nlohmann::json &json)
{
authResponseContext_->reply = json[TAG_REPLY];
}
void AuthMessageProcessor::ParseAuthResponseMessage(nlohmann::json &json)
{
LOGI("AuthMessageProcessor::ParseAuthResponseMessage ");
authResponseContext_->reply = json[TAG_REPLY];
authResponseContext_->deviceId = json[TAG_DEVICE_ID];
authResponseContext_->token = json[TAG_TOKEN];
// authResponseContext_->deviceId = json[TAG_GROUPIDS];
if (authResponseContext_->reply == 0) {
authResponseContext_->code = json[PIN_CODE_KEY];
authResponseContext_->networkId = json[TAG_NET_ID];
authResponseContext_->requestId = json[TAG_REQUEST_ID];
authResponseContext_->groupId = json[TAG_GROUP_ID];
authResponseContext_->groupName = json[TAG_GROUP_NAME];
LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s", authResponseContext_->groupId.c_str(),
authResponseContext_->groupName.c_str());
}
LOGI("AuthMessageProcessor::ParseAuthResponseMessage ");
}
void AuthMessageProcessor::ParseAuthRequestMessage()
{
nlohmann::json jsonObject = authSplitJsonList_.front();
authResponseContext_->deviceId = jsonObject[TAG_DEVICE_ID];
authResponseContext_->reply = jsonObject[TAG_REPLY];
// authResponseContext_->syncGroupList = jsonObject[TAG_GROUPIDS];
authResponseContext_->authType = jsonObject[TAG_AUTH_TYPE];
LOGI("AuthMessageProcessor::ParseAuthResponseMessage %d,%d", authResponseContext_->reply);
LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str());
if (authResponseContext_->reply == AUTH_REPLY_ACCEPT) {
authResponseContext_->networkId = jsonObject[TAG_NET_ID];
authResponseContext_->groupId = jsonObject[TAG_GROUP_ID];
authResponseContext_->groupName = jsonObject[TAG_GROUP_NAME];
authResponseContext_->requestId = jsonObject[TAG_REQUEST_ID];
}
authSplitJsonList_.clear();
}
void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json)
{
if (json.contains(TAG_CRYPTO_SUPPORT)) {
authResponseContext_->cryptoSupport = json[TAG_CRYPTO_SUPPORT];
}
if (json.contains(TAG_CRYPTO_NAME)) {
authResponseContext_->cryptoSupport = json[TAG_CRYPTO_NAME];
}
if (json.contains(TAG_CRYPTO_VERSION)) {
authResponseContext_->cryptoSupport = json[TAG_CRYPTO_VERSION];
}
if (json.contains(TAG_DEVICE_ID)) {
authResponseContext_->deviceId = json[TAG_DEVICE_ID];
}
authResponseContext_->localDeviceId = json[TAG_LOCAL_DEVICE_ID];
authResponseContext_->reply = json[TAG_REPLY];
}
void AuthMessageProcessor::SetRequestContext(std::shared_ptr<DmAuthRequestContext> authRequestContext)
{
authRequestContext_ = authRequestContext;
}
void AuthMessageProcessor::SetResponseContext(std::shared_ptr<DmAuthResponseContext> authResponseContext)
{
authResponseContext_ = authResponseContext;
}
std::shared_ptr<DmAuthResponseContext> AuthMessageProcessor::GetResponseContext()
{
return authResponseContext_;
}
std::shared_ptr<DmAuthRequestContext> AuthMessageProcessor::GetRequestContext()
{
return authRequestContext_;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,205 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "auth_request_state.h"
#include <utility>
#include "dm_auth_manager.h"
#include "dm_constants.h"
namespace OHOS {
namespace DistributedHardware {
void AuthRequestState::Leave()
{
}
void AuthRequestState::SetAuthManager(std::shared_ptr<DmAuthManager> authManager)
{
authManager_ = std::move(authManager);
}
// void AuthRequestState::SetLastState(std::shared_ptr<AuthRequestState> state) {
// lastState_ = state;
// }
void AuthRequestState::SetAuthContext(std::shared_ptr<DmAuthRequestContext> context)
{
context_ = std::move(context);
}
std::shared_ptr<DmAuthRequestContext> AuthRequestState::GetAuthContext()
{
return context_;
}
void AuthRequestState::TransitionTo(std::shared_ptr<AuthRequestState> state)
{
LOGE("AuthRequestState::TransitionTo");
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
state->SetAuthManager(stateAuthManager);
stateAuthManager->SetAuthRequestState(state);
state->SetAuthContext(context_);
this->Leave();
state->Enter();
}
int32_t AuthRequestInitState::GetStateType()
{
return AuthState::AUTH_REQUEST_INIT;
}
void AuthRequestInitState::Enter()
{
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->EstablishAuthChannel(context_->deviceId);
}
int32_t AuthRequestNegotiateState::GetStateType()
{
return AuthState::AUTH_REQUEST_NEGOTIATE;
}
void AuthRequestNegotiateState::Enter()
{
// //1. 检查加解密模块是否存在并获取加解密的名称和版本信息
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->StartNegotiate(context_->sessionId);
}
int32_t AuthRequestNegotiateDoneState::GetStateType()
{
return AuthState::AUTH_REQUEST_NEGOTIATE_DONE;
}
void AuthRequestNegotiateDoneState::Enter()
{
// //1. 获取对端加解密信息,并对比两端状态
//
// //2. 保存加解密状态,发送认证请求
// authMessageProcessor_->CreateMessage(MSG_TYPE_REQ_AUTH);
// std::string message;
// softbusSession_->SendData(context_.sessionId, message);
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->SendAuthRequest(context_->sessionId);
}
int32_t AuthRequestReplyState::GetStateType()
{
return AuthState::AUTH_REQUEST_REPLY;
}
void AuthRequestReplyState::Enter()
{
// 1. 收到请求响应,判断用户响应结果
// 2. 用户授权同意
// 3. 回调给认证实现模块,启动认证
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->StartRespAuthProcess();
}
int32_t AuthRequestInputState::GetStateType()
{
return AuthState::AUTH_REQUEST_INPUT;
}
void AuthRequestInputState::Enter()
{
// //1. 获取用户输入
//
// //2. 验证认证信息
LOGE("DmAuthManager::AuthRequestInputState");
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->ShowStartAuthDialog();
}
int32_t AuthRequestJoinState::GetStateType()
{
return AuthState::AUTH_REQUEST_JOIN;
}
void AuthRequestJoinState::Enter()
{
// 1. 加入群组
LOGE("DmAuthManager::AuthRequestJoinState");
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->AddMember(context_->deviceId);
}
int32_t AuthRequestNetworkState::GetStateType()
{
return AuthState::AUTH_REQUEST_NETWORK;
}
void AuthRequestNetworkState::Enter()
{
// 1. 进行组网
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->JoinNetwork();
}
int32_t AuthRequestFinishState::GetStateType()
{
return AuthState::AUTH_REQUEST_FINISH;
}
void AuthRequestFinishState::Enter()
{
// 1. 清理资源
// 2. 通知对端认证结束,并关闭认证通道
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->AuthenticateFinish();
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,159 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "auth_response_state.h"
#include "dm_auth_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
void AuthResponseState::Leave()
{
}
void AuthResponseState::SetAuthContext(std::shared_ptr<DmAuthResponseContext> context)
{
context_ = std::move(context);
}
std::shared_ptr<DmAuthResponseContext> AuthResponseState::GetAuthContext()
{
return context_;
}
void AuthResponseState::SetAuthManager(std::shared_ptr<DmAuthManager> authManager)
{
authManager_ = std::move(authManager);
}
void AuthResponseState::TransitionTo(std::shared_ptr<AuthResponseState> state)
{
LOGI("AuthRequestState:: TransitionTo");
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
state->SetAuthManager(stateAuthManager);
stateAuthManager->SetAuthResponseState(state);
state->SetAuthContext(context_);
this->Leave();
state->Enter();
}
int32_t AuthResponseInitState::GetStateType()
{
return AuthState::AUTH_RESPONSE_INIT;
}
void AuthResponseInitState::Enter()
{
LOGI("AuthResponse:: AuthResponseInitState Enter");
// 1.认证通道建立后,进入该状态
}
int32_t AuthResponseNegotiateState::GetStateType()
{
return AuthState::AUTH_RESPONSE_NEGOTIATE;
}
void AuthResponseNegotiateState::Enter()
{
// 1.收到协商消息后进入
// 2. 获取本地加解密模块信息,并回复消
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->RespNegotiate(context_->sessionId);
}
int32_t AuthResponseConfirmState::GetStateType()
{
return AuthState::AUTH_RESPONSE_CONFIRM;
}
void AuthResponseConfirmState::Enter()
{
//委托授权UI模块进行用户交互
//如果交互成功
// TransitionTo(new AuthResponseGroupState());
LOGI("AuthResponse:: AuthResponseConfirmState Enter");
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->ShowConfigDialog();
}
int32_t AuthResponseGroupState::GetStateType()
{
return AuthState::AUTH_RESPONSE_GROUP;
}
void AuthResponseGroupState::Enter()
{
// //1.创建群组,
// authManagerPtr_->GetHiChainConnector()->CreateGroup();
LOGI("AuthResponse:: AuthResponseGroupState Enter");
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->CreateGroup();
}
int32_t AuthResponseShowState::GetStateType()
{
return AuthState::AUTH_RESPONSE_SHOW;
}
void AuthResponseShowState::Enter()
{
// 1.委托认证实现模块进行用户交互
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->ShowAuthInfoDialog();
}
int32_t AuthResponseFinishState::GetStateType()
{
return AuthState::AUTH_RESPONSE_FINISH;
}
void AuthResponseFinishState::Enter()
{
// 1.结束UI显示
// 2.清理资源,结束状态机
std::shared_ptr<DmAuthManager> stateAuthManager = authManager_.lock();
if (stateAuthManager == nullptr) {
LOGE("AuthRequestState::authManager_ null");
return;
}
stateAuthManager->AuthenticateFinish();
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "auth_ui.h"
#include "dm_ability_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
AuthUi::AuthUi()
{
LOGI("AuthUi constructor");
}
int32_t AuthUi::ShowConfirmDialog(std::shared_ptr<DmAbilityManager> dmAbilityManager)
{
if (dmAbilityManager == nullptr) {
LOGE("AuthUi::dmAbilityManager is null");
return DM_FAILED;
}
dmAbilityMgr_ = dmAbilityManager;
return StartFaService();
}
int32_t AuthUi::StartFaService()
{
AbilityStatus status = dmAbilityMgr_->StartAbility(AbilityRole::ABILITY_ROLE_PASSIVE);
if (status != AbilityStatus::ABILITY_STATUS_SUCCESS) {
LOGE("AuthUi::StartFaService timeout");
return DM_FAILED;
}
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,754 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_auth_manager.h"
#include "auth_message_processor.h"
#include "auth_ui.h"
#include "config_manager.h"
#include "dm_ability_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "dm_random.h"
#include "nlohmann/json.hpp"
#include "parameter.h"
namespace OHOS {
namespace DistributedHardware {
namespace {
std::string AUTHENTICATE_TIMEOUT_TASK = "authenticateTimeoutTask";
std::string NEGOTIATE_TIMEOUT_TASK = "negotiateTimeoutTask";
std::string CONFIRM_TIMEOUT_TASK = "confirmTimeoutTask";
std::string SHOW_TIMEOUT_TASK = "showTimeoutTask";
std::string INPUT_TIMEOUT_TASK = "inputTimeoutTask";
std::string ADD_TIMEOUT_TASK = "addTimeoutTask";
std::string WAIT_NEGOTIATE_TIMEOUT_TASK = "waitNegotiateTimeoutTask";
std::string WAIT_REQUEST_TIMEOUT_TASK = "waitRequestTimeoutTask";
int32_t SESSION_CANCEL_TIMEOUT = 0;
int32_t AUTHENTICATE_TIMEOUT = 120;
int32_t CONFIRM_TIMEOUT = 60;
int32_t NEGOTIATE_TIMEOUT = 10;
int32_t INPUT_TIMEOUT = 60;
int32_t ADD_TIMEOUT = 10;
int32_t WAIT_NEGOTIATE_TIMEOUT = 10;
int32_t WAIT_REQUEST_TIMEOUT = 10;
int32_t CANCEL_PICODE_DISPLAY = 1;
int32_t DEVICE_ID_HALF = 2;
} // namespace
static void TimeOut(void *data)
{
LOGE("time out ");
DmAuthManager *authMgr = (DmAuthManager *)data;
if (authMgr == nullptr) {
LOGE("time out error");
return;
}
authMgr->HandleAuthenticateTimeout();
}
DmAuthManager::DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,
std::shared_ptr<DeviceManagerServiceListener> listener)
: softbusConnector_(softbusConnector), listener_(listener)
{
LOGI("DmAuthManager constructor");
// TODO: load library so for different auth type
hiChainConnector_ = std::make_shared<HiChainConnector>();
DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
dmConfigManager.GetAuthAdapter(authenticationMap_);
}
DmAuthManager::~DmAuthManager()
{
LOGI("DmAuthManager destructor");
}
int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId,
const std::string &extra)
{
// TODO:检查pkgName的权限
// std::shared_ptr<IAuthentication> authentication = authenticationMap_[authType];
// if (authentication == nullptr) {
// LOGE("DmAuthManager::AuthenticateDevice authType %d not support.", authType);
// return DM_AUTH_NOT_SUPPORT;
// }
LOGE("DmAuthManager::AuthenticateDevice is");
if (authRequestState_ != nullptr && authResponseState_ != nullptr) {
LOGE("DmAuthManager::AuthenticateDevice %s is request authentication.",
authRequestState_->GetAuthContext()->hostPkgName.c_str());
listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT,
std::to_string(DM_AUTH_BUSINESS_BUSY));
return DM_AUTH_BUSINESS_BUSY;
}
if (!softbusConnector_->HaveDeviceInMap(deviceId)) {
LOGE("AuthenticateDevice failed, the discoveryDeviceInfoMap_ not have this device");
listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT,
std::to_string(DM_AUTH_INPUT_FAILED));
return DM_AUTH_INPUT_FAILED;
}
if (extra.empty()) {
LOGE("AuthenticateDevice failed, extra is empty");
listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT,
std::to_string(DM_AUTH_BUSINESS_BUSY));
return DM_INPUT_PARA_EMPTY;
}
if (authType != AUTH_TYPE_PIN && authType != AUTH_TYPE_SCAN && authType != AUTH_TYPE_TOUCH) {
LOGE("AuthenticateDevice failed, authType is not support");
listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT,
std::to_string(DM_AUTH_NOT_SUPPORT));
return DM_AUTH_NOT_SUPPORT;
}
softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(pkgName);
softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(pkgName, shared_from_this());
authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
authRequestContext_ = std::make_shared<DmAuthRequestContext>();
authRequestContext_->hostPkgName = pkgName;
authRequestContext_->authType = authType;
authRequestContext_->deviceId = deviceId;
nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false);
if (!jsonObject.is_discarded()) {
if (jsonObject.contains(TARGET_PKG_NAME_KEY)) {
authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY];
}
if (jsonObject.contains(APP_NAME_KEY)) {
authRequestContext_->appName = jsonObject[APP_NAME_KEY];
}
if (jsonObject.contains(APP_DESCRIPTION_KEY)) {
authRequestContext_->appDesc = jsonObject[APP_DESCRIPTION_KEY];
}
if (jsonObject.contains(APP_THUMBNAIL)) {
authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL];
}
if (jsonObject.contains(APP_ICON_KEY)) {
authRequestContext_->appIcon = jsonObject[APP_ICON_KEY];
}
}
authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN));
authRequestState_ = std::shared_ptr<AuthRequestState>(new AuthRequestInitState());
authRequestState_->SetAuthManager(shared_from_this());
authRequestState_->SetAuthContext(authRequestContext_);
authRequestState_->Enter();
std::shared_ptr<DmTimer> authenticateStartTimer = std::make_shared<DmTimer>(AUTHENTICATE_TIMEOUT_TASK);
timerMap_[AUTHENTICATE_TIMEOUT_TASK] = authenticateStartTimer;
authenticateStartTimer->Start(AUTHENTICATE_TIMEOUT, TimeOut, this);
LOGI("DmAuthManager::AuthenticateDevice complete");
return DM_OK;
}
int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId)
{
if (pkgName.empty()) {
LOGI(" DmAuthManager::UnAuthenticateDevice failed pkgName is null");
return DM_FAILED;
}
/* Get UDID by NetworkID */
uint8_t udid[UDID_BUF_LEN] = {0};
int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(deviceId.c_str(), NodeDeivceInfoKey::NODE_KEY_UDID, udid,
sizeof(udid));
if (ret != DM_OK) {
LOGE("UnAuthenticateDevice GetNodeKeyInfo failed");
return DM_FAILED;
}
std::string deviceUdid = (char *)udid;
std::string groupId = "";
std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
hiChainConnector_->GetRelatedGroups(deviceUdid, groupList);
if (groupList.size() > 0) {
groupId = groupList.front().groupId;
LOGI(" DmAuthManager::UnAuthenticateDevice groupId=%s, deviceId=%s, deviceUdid=%s", groupId.c_str(),
deviceId.c_str(), deviceUdid.c_str());
hiChainConnector_->DeleteGroup(groupId);
} else {
LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0");
return DM_FAILED;
}
// groupId = authResponseContext_->groupId;
return DM_OK;
}
int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam)
{
LOGI("DmAuthManager::VerifyAuthentication");
timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT);
std::shared_ptr<IAuthentication> ptr;
if (authenticationMap_.find(1) == authenticationMap_.end()) {
LOGE("DmAuthManager::authenticationMap_ is null");
return DM_FAILED;
}
ptr = authenticationMap_[1];
int32_t ret = ptr->VerifyAuthentication(authRequestContext_->token, authResponseContext_->code, authParam);
switch (ret) {
case DM_OK:
{
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestJoinState()));
}
break;
case DM_AUTH_INPUT_FAILED:
{
std::string flag = "";
listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId,
DM_AUTH_INPUT_FAILED, flag);
}
break;
default:
{
CancelDisplay();
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestFinishState()));
}
}
LOGI("DmAuthManager::VerifyAuthentication complete");
return DM_OK;
}
void DmAuthManager::OnSessionOpened(const std::string &pkgName, int32_t sessionId, int32_t sessionSide, int32_t result)
{
LOGI("DmAuthManager::OnSessionOpened sessionId=%d result=%d", sessionId, result);
if (sessionSide == AUTH_SESSION_SIDE_SERVER) {
if (authResponseState_ == nullptr) {
authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
authResponseState_ = std::shared_ptr<AuthResponseState>(new AuthResponseInitState());
authResponseState_->SetAuthManager(shared_from_this());
authResponseState_->Enter();
hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this());
authResponseContext_ = std::make_shared<DmAuthResponseContext>();
std::shared_ptr<DmTimer> waitStartTimer = std::make_shared<DmTimer>(WAIT_NEGOTIATE_TIMEOUT_TASK);
timerMap_[WAIT_NEGOTIATE_TIMEOUT_TASK] = waitStartTimer;
waitStartTimer->Start(WAIT_NEGOTIATE_TIMEOUT, TimeOut, this);
std::shared_ptr<DmTimer> authenticateStartTimer = std::make_shared<DmTimer>(AUTHENTICATE_TIMEOUT_TASK);
timerMap_[AUTHENTICATE_TIMEOUT_TASK] = authenticateStartTimer;
authenticateStartTimer->Start(AUTHENTICATE_TIMEOUT, TimeOut, this);
} else {
std::shared_ptr<AuthMessageProcessor> authMessageProcessor =
std::make_shared<AuthMessageProcessor>(shared_from_this());
std::shared_ptr<DmAuthResponseContext> authResponseContext = std::make_shared<DmAuthResponseContext>();
authResponseContext->reply = AuthState::AUTH_RESPONSE_INIT;
authMessageProcessor->SetResponseContext(authResponseContext);
std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
}
} else {
if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
hiChainConnector_->RegisterHiChainCallback(pkgName, shared_from_this());
authRequestContext_->sessionId = sessionId;
authRequestState_->SetAuthContext(authRequestContext_);
authMessageProcessor_->SetRequestContext(authRequestContext_);
authResponseContext_ = std::make_shared<DmAuthResponseContext>();
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestNegotiateState()));
} else {
LOGE("DmAuthManager::OnSessionOpened but request state %d is wrong", authRequestState_->GetStateType());
}
}
}
void DmAuthManager::OnSessionClosed(const std::string &pkgName, int32_t sessionId)
{
LOGI("DmAuthManager::OnSessionOpened sessionId=%d", sessionId);
}
void DmAuthManager::OnDataReceived(const std::string &pkgName, int32_t sessionId, std::string message)
{
LOGI("DmAuthManager::OnDataReceived start");
if (authRequestState_ == nullptr && authResponseState_ == nullptr) {
LOGI("DmAuthManager::GetAuthState failed");
return;
}
authResponseContext_->sessionId = sessionId;
authMessageProcessor_->SetResponseContext(authResponseContext_);
int32_t ret = authMessageProcessor_->ParseMessage(message);
if (ret != DM_OK) {
LOGE("OnDataReceived, parse message error");
return;
}
authResponseContext_ = authMessageProcessor_->GetResponseContext();
if (authResponseState_ == nullptr) {
authRequestContext_ = authMessageProcessor_->GetRequestContext();
authRequestState_->SetAuthContext(authRequestContext_);
} else {
authResponseState_->SetAuthContext(authResponseContext_);
}
switch (authResponseContext_->msgType) {
case MSG_TYPE_NEGOTIATE:
if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) {
timerMap_[WAIT_NEGOTIATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT);
authResponseState_->TransitionTo(std::shared_ptr<AuthResponseState>(new AuthResponseNegotiateState()));
} else {
LOGE("Device manager auth state error");
}
break;
case MSG_TYPE_REQ_AUTH:
if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) {
timerMap_[WAIT_REQUEST_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT);
authResponseState_->TransitionTo(std::shared_ptr<AuthResponseState>(new AuthResponseConfirmState()));
} else {
LOGE("Device manager auth state error");
}
break;
case MSG_TYPE_RESP_AUTH:
if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestReplyState()));
} else {
LOGE("Device manager auth state error");
}
break;
case MSG_TYPE_RESP_NEGOTIATE:
if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) {
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestNegotiateDoneState()));
} else {
LOGE("Device manager auth state error");
}
break;
case MSG_TYPE_REQ_AUTH_TERMINATE:
if (authResponseState_ != nullptr &&
authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
authResponseState_->TransitionTo(std::shared_ptr<AuthResponseState>(new AuthResponseFinishState()));
} else if (authRequestState_ != nullptr &&
authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
LOGE("Device manager auth state error");
}
break;
default:
break;
}
}
void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId)
{
//创建群组成功
//发送认证响应消息给请求端
LOGI("DmAuthManager::OnGroupCreated start");
if (authResponseState_ == nullptr) {
LOGI("DmAuthManager::AuthenticateDevice end");
return;
}
if (groupId == "{}") {
authResponseContext_->reply = DM_HICHAIN_GROUP_CREATE_FAILED;
authMessageProcessor_->SetResponseContext(authResponseContext_);
std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
return;
}
authResponseContext_->groupId = groupId;
authMessageProcessor_->SetResponseContext(authResponseContext_);
std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
authResponseState_->TransitionTo(std::shared_ptr<AuthResponseState>(new AuthResponseShowState()));
}
void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status)
{
LOGI("DmAuthManager OnMemberJoin start");
CancelDisplay();
LOGE("DmAuthManager OnMemberJoin start");
if (authRequestState_ != nullptr) {
timerMap_[ADD_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT);
if (status != DM_OK || authResponseContext_->requestId != requestId) {
if (authRequestState_ == nullptr) {
// authResponseState_->TransitionTo(std::shared_ptr<AuthResponseState>(new AuthResponseFinishState()));
} else {
authResponseContext_->reply = AuthState::AUTH_REQUEST_JOIN;
authRequestContext_->reason = DM_AUTH_INPUT_FAILED;
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestFinishState()));
return;
}
}
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestNetworkState()));
}
}
void DmAuthManager::HandleAuthenticateTimeout()
{
// 1. 状态机走到结束状态,并清理资源
LOGI("DmAuthManager::HandleAuthenticateTimeout start");
if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
if (authResponseContext_ == nullptr) {
authResponseContext_ = std::make_shared<DmAuthResponseContext>();
}
authResponseContext_->reply = authRequestState_->GetStateType();
authRequestContext_->reason = DM_TIME_OUT;
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestFinishState()));
}
LOGI("DmAuthManager::HandleAuthenticateTimeout start complete");
}
void DmAuthManager::EstablishAuthChannel(const std::string &deviceId)
{
// TODO:检查crypto模块是否适配
// TODO:兼容性处理,兼容与手机的认证
int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId);
if (sessionId < 0) {
LOGE("OpenAuthSession failed, stop the authentication");
authResponseContext_ = std::make_shared<DmAuthResponseContext>();
authResponseContext_->reply = AuthState::AUTH_REQUEST_NEGOTIATE;
authRequestContext_->reason = DM_AUTH_OPEN_SESSION_FAILED;
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestFinishState()));
}
}
void DmAuthManager::StartNegotiate(const int32_t &sessionId)
{
LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId);
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
authResponseContext_->localDeviceId = localDeviceId;
authResponseContext_->reply = DM_AUTH_NOT_AUTH;
authMessageProcessor_->SetResponseContext(authResponseContext_);
std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE);
softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
std::shared_ptr<DmTimer> negotiateStartTimer = std::make_shared<DmTimer>(NEGOTIATE_TIMEOUT_TASK);
timerMap_[NEGOTIATE_TIMEOUT_TASK] = negotiateStartTimer;
negotiateStartTimer->Start(NEGOTIATE_TIMEOUT, TimeOut, this);
}
void DmAuthManager::RespNegotiate(const int32_t &sessionId)
{
LOGE("DmAuthManager::EstablishAuthChannel session id is %d", sessionId);
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, localDeviceId);
if (ret != true){
LOGE("DmAuthManager::EstablishAuthChannel device is in group");
authResponseContext_->reply = DM_AUTH_PEER_REJECT;
} else {
authResponseContext_->reply = DM_AUTH_NOT_AUTH;
}
std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false);
if (jsonObject.is_discarded()) {
softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
}
authResponseContext_ = authResponseState_->GetAuthContext();
if (jsonObject[TAG_CRYPTO_SUPPORT] == "true" && authResponseContext_->cryptoSupport == true) {
if (jsonObject[TAG_CRYPTO_NAME] == authResponseContext_->cryptoName &&
jsonObject[TAG_CRYPTO_VERSION] == authResponseContext_->cryptoVer) {
isCryptoSupport_ = true;
softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
return;
}
}
jsonObject[TAG_CRYPTO_SUPPORT] = "false";
message = jsonObject.dump();
softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
std::shared_ptr<DmTimer> waitStartTimer = std::make_shared<DmTimer>(WAIT_REQUEST_TIMEOUT_TASK);
timerMap_[WAIT_REQUEST_TIMEOUT_TASK] = waitStartTimer;
waitStartTimer->Start(WAIT_REQUEST_TIMEOUT, TimeOut, this);
}
void DmAuthManager::SendAuthRequest(const int32_t &sessionId)
{
LOGE("DmAuthManager::EstablishAuthChannel session id");
timerMap_[NEGOTIATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT);
if (authResponseContext_->cryptoSupport == true) {
isCryptoSupport_ = true;
}
if (authResponseContext_->reply == DM_AUTH_PEER_REJECT) {
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestFinishState()));
return;
}
std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
for (auto msg : messageList) {
softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
}
std::shared_ptr<DmTimer> confirmStartTimer = std::make_shared<DmTimer>(CONFIRM_TIMEOUT_TASK);
timerMap_[CONFIRM_TIMEOUT_TASK] = confirmStartTimer;
confirmStartTimer->Start(CONFIRM_TIMEOUT, TimeOut, this);
}
void DmAuthManager::StartAuthProcess(const int32_t &action)
{
// 1. 收到请求响应,判断用户响应结果
// 2. 用户授权同意
// 3. 回调给认证实现模块,启动认证
LOGI("DmAuthManager:: StartAuthProcess");
authResponseContext_->reply = action;
if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
authResponseState_->TransitionTo(std::shared_ptr<AuthResponseState>(new AuthResponseGroupState()));
} else {
authMessageProcessor_->SetResponseContext(authResponseContext_);
std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
}
}
void DmAuthManager::StartRespAuthProcess()
{
LOGI("DmAuthManager::StartRespAuthProcess StartRespAuthProcess", authResponseContext_->sessionId);
timerMap_[CONFIRM_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT);
if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) {
std::shared_ptr<DmTimer> inputStartTimer = std::make_shared<DmTimer>(INPUT_TIMEOUT_TASK);
timerMap_[INPUT_TIMEOUT_TASK] = inputStartTimer;
inputStartTimer->Start(INPUT_TIMEOUT, TimeOut, this);
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestInputState()));
} else {
LOGE("do not accept");
authResponseContext_->reply = AuthState::AUTH_REQUEST_REPLY;
authRequestContext_->reason = DM_AUTH_PEER_REJECT;
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestFinishState()));
}
}
void DmAuthManager::CreateGroup()
{
LOGI("DmAuthManager:: CreateGroup");
authResponseContext_->groupName = GenerateGroupName();
authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID);
hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName);
}
void DmAuthManager::AddMember(const std::string &deviceId)
{
LOGI("DmAuthManager::AddMember start");
nlohmann::json jsonObject;
jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId;
jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName;
jsonObject[PIN_CODE_KEY] = authResponseContext_->code;
jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId;
jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId;
std::string connectInfo = jsonObject.dump();
std::shared_ptr<DmTimer> joinStartTimer = std::make_shared<DmTimer>(ADD_TIMEOUT_TASK);
timerMap_[ADD_TIMEOUT_TASK] = joinStartTimer;
joinStartTimer->Start(ADD_TIMEOUT, TimeOut, this);
int32_t ret = hiChainConnector_->AddMember(deviceId, connectInfo);
if (ret != 0) {
return;
}
LOGI("DmAuthManager::authRequestContext CancelDisplay start");
CancelDisplay();
}
std::string DmAuthManager::GetConnectAddr(std::string deviceId)
{
LOGI("DmAuthManager::GetConnectAddr");
std::string connectAddr;
softbusConnector_->GetConnectAddr(deviceId, connectAddr);
return connectAddr;
}
void DmAuthManager::JoinNetwork()
{
// TODO:
LOGE("DmAuthManager JoinNetwork start");
timerMap_[AUTHENTICATE_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT);
authResponseContext_->reply = AuthState::AUTH_REQUEST_FINISH;
authRequestContext_->reason = DM_OK;
authRequestState_->TransitionTo(std::shared_ptr<AuthRequestState>(new AuthRequestFinishState()));
}
void DmAuthManager::AuthenticateFinish()
{
LOGI("DmAuthManager::AuthenticateFinish start");
if (authResponseState_ != nullptr) {
if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) {
CancelDisplay();
}
if (!timerMap_.empty()) {
for (auto &iter : timerMap_) {
iter.second->Stop(SESSION_CANCEL_TIMEOUT);
}
timerMap_.clear();
}
authResponseContext_ = nullptr;
authResponseState_ = nullptr;
authMessageProcessor_ = nullptr;
} else if (authRequestState_ != nullptr) {
std::string flag = "";
if (authResponseContext_->reply < AuthState::AUTH_RESPONSE_INIT) {
authMessageProcessor_->SetResponseContext(authResponseContext_);
std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
}
if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INPUT) {
CancelDisplay();
}
listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId,
authRequestContext_->token, authResponseContext_->reply,
std::to_string(authRequestContext_->reason));
softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(authRequestContext_->hostPkgName);
softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId);
if (!timerMap_.empty()) {
for (auto &iter : timerMap_) {
iter.second->Stop(SESSION_CANCEL_TIMEOUT);
}
timerMap_.clear();
}
authRequestContext_ = nullptr;
authResponseContext_ = nullptr;
authRequestState_ = nullptr;
authMessageProcessor_ = nullptr;
}
LOGI("DmAuthManager::AuthenticateFinish complete");
}
void DmAuthManager::CancelDisplay()
{
LOGI("DmAuthManager::CancelDisplay start");
nlohmann::json jsonObj;
jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PICODE_DISPLAY;
std::string paramJson = jsonObj.dump();
std::string pkgName = "com.ohos.devicemanagerui";
listener_->OnFaCall(pkgName, paramJson);
}
int32_t DmAuthManager::GeneratePincode()
{
return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
}
std::string DmAuthManager::GenerateGroupName()
{
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
std::string sLocalDeviceID = localDeviceId;
std::string groupName = authResponseContext_->targetPkgName + authResponseContext_->hostPkgName +
sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF);
return groupName;
}
void DmAuthManager::GetIsCryptoSupport(bool &isCryptoSupport)
{
LOGI("DmAuthManager::GetIsCryptoSupport start");
if (authResponseState_ == nullptr) {
isCryptoSupport = false;
return;
}
if (authRequestState_ == nullptr) {
if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
isCryptoSupport = false;
return;
}
} else {
if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
isCryptoSupport = false;
return;
}
}
isCryptoSupport = isCryptoSupport_;
}
void DmAuthManager::SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)
{
authRequestState_ = authRequestState;
}
void DmAuthManager::SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)
{
authResponseState_ = authResponseState;
}
int32_t DmAuthManager::GetPinCode()
{
return authResponseContext_->code;
}
void DmAuthManager::ShowConfigDialog()
{
std::shared_ptr<AuthUi> authUi_ = std::make_shared<AuthUi>();
dmAbilityMgr_ = std::make_shared<DmAbilityManager>();
authUi_->ShowConfirmDialog(dmAbilityMgr_);
}
void DmAuthManager::ShowAuthInfoDialog()
{
return;
}
void DmAuthManager::ShowStartAuthDialog()
{
LOGI("DmAuthManager::ShowStartAuthDialog start");
dmAbilityMgr_ = std::make_shared<DmAbilityManager>();
std::shared_ptr<IAuthentication> ptr;
if (authenticationMap_.find(1) == authenticationMap_.end()) {
LOGE("DmAuthManager::authenticationMap_ is null");
return;
}
ptr = authenticationMap_[1];
ptr->StartAuth(dmAbilityMgr_);
}
int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam)
{
dmAbilityMgr_->StartAbilityDone();
AbilityRole role = dmAbilityMgr_->GetAbilityRole();
authParam.direction = (int32_t)role;
// Currently, only Support PinCode, authType not save.
authParam.authType = AUTH_TYPE_PIN;
authParam.authToken = authResponseContext_->token;
if (role == AbilityRole::ABILITY_ROLE_PASSIVE) {
// 生成pincode
authResponseContext_->code = GeneratePincode();
authParam.packageName = authResponseContext_->targetPkgName;
authParam.appName = authResponseContext_->appName;
authParam.appDescription = authResponseContext_->appDesc;
// currently, only support BUSINESS_FA_MIRGRATION
authParam.business = BUSINESS_FA_MIRGRATION;
// 获取生成的pincode
authParam.pincode = authResponseContext_->code;
}
return DM_OK;
}
int32_t DmAuthManager::RegisterSessionCallback()
{
LOGI("DmAuthManager constructor111");
softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(DM_PKG_NAME, shared_from_this());
return DM_OK;
}
int32_t DmAuthManager::OnUserOperation(int32_t action)
{
switch (action)
{
case USER_OPERATION_TYPE_ALLOW_AUTH:
case USER_OPERATION_TYPE_CANCEL_AUTH:
StartAuthProcess(action);
break;
case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT:
AuthenticateFinish();
break;
case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY:
CancelDisplay();
break;
case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT:
AuthenticateFinish();
break;
default:
LOGE("this action id not support");
break;
}
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,299 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config_manager.h"
#include <dlfcn.h>
#include "dm_constants.h"
#include "dm_log.h"
#include "json_config.h"
#include "nlohmann/json.hpp"
namespace OHOS {
namespace DistributedHardware {
void from_json(const nlohmann::json &jsonObject, AdapterSoLoadInfo &soLoadInfo)
{
if (!jsonObject.contains("name") || !jsonObject.contains("type") || !jsonObject.contains("version") ||
!jsonObject.contains("funcName") || !jsonObject.contains("soName") || !jsonObject.contains("soPath")) {
LOGE("AdapterSoLoadInfo json key Not complete");
return;
}
jsonObject["name"].get_to(soLoadInfo.name);
jsonObject["type"].get_to(soLoadInfo.type);
jsonObject["version"].get_to(soLoadInfo.version);
jsonObject["funcName"].get_to(soLoadInfo.funcName);
jsonObject["soName"].get_to(soLoadInfo.soName);
jsonObject["soPath"].get_to(soLoadInfo.soPath);
}
void from_json(const nlohmann::json &jsonObject, AuthSoLoadInfo &soLoadInfo)
{
if (!jsonObject.contains("name") || !jsonObject.contains("type") || !jsonObject.contains("version") ||
!jsonObject.contains("funcName") || !jsonObject.contains("soName") || !jsonObject.contains("soPath") ||
!jsonObject.contains("authType")) {
LOGE("AuthSoLoadInfo json key Not complete");
return;
}
jsonObject["name"].get_to(soLoadInfo.name);
jsonObject["type"].get_to(soLoadInfo.type);
jsonObject["version"].get_to(soLoadInfo.version);
jsonObject["authType"].get_to(soLoadInfo.authType);
jsonObject["funcName"].get_to(soLoadInfo.funcName);
jsonObject["soName"].get_to(soLoadInfo.soName);
jsonObject["soPath"].get_to(soLoadInfo.soPath);
}
DmConfigManager &DmConfigManager::GetInstance()
{
static DmConfigManager instance;
return instance;
}
DmConfigManager::DmConfigManager()
{
LOGI("DmConfigManager constructor");
do {
nlohmann::json adapterJsonObject = nlohmann::json::parse(adapterJsonConfigString, nullptr, false);
if (adapterJsonObject.is_discarded()) {
LOGE("adapter json config string parse error");
break;
}
const char *jsonKey = ADAPTER_LOAD_JSON_KEY.c_str();
if (!adapterJsonObject.contains(jsonKey)) {
LOGE("adapter json config string key not exist");
break;
}
auto soLoadInfo = adapterJsonObject[jsonKey].get<std::vector<AdapterSoLoadInfo>>();
for (uint32_t i = 0; i < soLoadInfo.size(); i++) {
if (soLoadInfo[i].name.size() == 0 || soLoadInfo[i].type.size() == 0 || soLoadInfo[i].version.size() == 0 ||
soLoadInfo[i].funcName.size() == 0 || soLoadInfo[i].soName.size() == 0 ||
soLoadInfo[i].soPath.size() == 0) {
LOGE("adapter json config string exist invalid members");
continue;
}
soAdapterLoadInfo_[soLoadInfo[i].soName] = soLoadInfo[i];
LOGI("soAdapterLoadInfo name is: %s", soLoadInfo[i].name.c_str());
LOGI("soAdapterLoadInfo type is: %s", soLoadInfo[i].type.c_str());
LOGI("soAdapterLoadInfo version is: %s", soLoadInfo[i].version.c_str());
LOGI("soAdapterLoadInfo funcName is: %s", soLoadInfo[i].funcName.c_str());
LOGI("soAdapterLoadInfo soName is: %s", soLoadInfo[i].soName.c_str());
LOGI("soAdapterLoadInfo soPath is: %s", soLoadInfo[i].soPath.c_str());
}
} while (0);
do {
nlohmann::json authJsonObject = nlohmann::json::parse(authJsonConfigString, nullptr, false);
if (authJsonObject.is_discarded()) {
LOGE("auth json config string parse error!\n");
break;
}
const char *jsonKey = AUTH_LOAD_JSON_KEY.c_str();
if (!authJsonObject.contains(jsonKey)) {
LOGE("auth json config string key not exist!\n");
break;
}
auto soLoadInfo = authJsonObject[jsonKey].get<std::vector<AuthSoLoadInfo>>();
for (uint32_t i = 0; i < soLoadInfo.size(); i++) {
if (soLoadInfo[i].name.size() == 0 || soLoadInfo[i].type.size() == 0 || soLoadInfo[i].version.size() == 0 ||
soLoadInfo[i].funcName.size() == 0 || soLoadInfo[i].soName.size() == 0 ||
soLoadInfo[i].soPath.size() == 0) {
LOGE("adapter json config string exist invalid members");
continue;
}
soAuthLoadInfo_[soLoadInfo[i].authType] = soLoadInfo[i];
LOGI("soAuthLoadInfo name is: %s", soLoadInfo[i].name.c_str());
LOGI("soAuthLoadInfo type is: %s", soLoadInfo[i].type.c_str());
LOGI("soAuthLoadInfo version is: %s", soLoadInfo[i].version.c_str());
LOGI("soAuthLoadInfo funcName is: %s", soLoadInfo[i].funcName.c_str());
LOGI("soAuthLoadInfo soName is: %s", soLoadInfo[i].soName.c_str());
LOGI("soAuthLoadInfo soPath is: %s", soLoadInfo[i].soPath.c_str());
LOGI("soAuthLoadInfo authType is: %d", soLoadInfo[i].authType);
}
} while (0);
}
DmConfigManager::~DmConfigManager()
{
void *so_handle = nullptr;
for (auto iter = soAdapterLoadInfo_.begin(); iter != soAdapterLoadInfo_.end(); iter++) {
std::string soPathName = (iter->second).soPath + (iter->second).soName;
so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD);
if (so_handle != nullptr) {
dlclose(so_handle);
}
}
for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) {
std::string soPathName = (iter->second).soPath + (iter->second).soName;
so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD);
if (so_handle != nullptr) {
dlclose(so_handle);
}
}
LOGI("DmAdapterManager destructor");
}
std::shared_ptr<IDecisionAdapter> DmConfigManager::GetDecisionAdapter(const std::string &soName)
{
if (soName.empty()) {
LOGE("soName size is zero");
return nullptr;
}
auto soInfoIter = soAdapterLoadInfo_.find(soName);
if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != DECISION_JSON_TYPE_KEY) {
LOGE("not find so info or type key not match");
return nullptr;
}
std::unique_lock<std::mutex> locker(decisionAdapterMutex_);
auto ptrIter = decisionAdapterPtr_.find(soName);
if (ptrIter != decisionAdapterPtr_.end()) {
return decisionAdapterPtr_[soName];
}
void *so_handle = nullptr;
std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName;
so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD);
if (so_handle == nullptr) {
so_handle = dlopen(soPathName.c_str(), RTLD_NOW);
if (so_handle == nullptr) {
LOGE("load decision so %s failed", soName.c_str());
return nullptr;
}
}
dlerror();
auto func = (CreateIDecisionAdapterFuncPtr)dlsym(so_handle, (soInfoIter->second).funcName.c_str());
if (dlerror() != nullptr || func == nullptr) {
LOGE("Create object function is not exist");
return nullptr;
}
std::shared_ptr<IDecisionAdapter> iDecisionAdapter(func());
decisionAdapterPtr_[soName] = iDecisionAdapter;
return decisionAdapterPtr_[soName];
}
std::shared_ptr<IProfileAdapter> DmConfigManager::GetProfileAdapter(const std::string &soName)
{
if (soName.empty()) {
LOGE("soName size is zero");
return nullptr;
}
auto soInfoIter = soAdapterLoadInfo_.find(soName);
if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != PROFILE_JSON_TYPE_KEY) {
LOGE("not find so info or type key not match");
return nullptr;
}
std::unique_lock<std::mutex> locker(profileAdapterMutex_);
auto ptrIter = profileAdapterPtr_.find(soName);
if (ptrIter != profileAdapterPtr_.end()) {
return profileAdapterPtr_[soName];
}
void *so_handle = nullptr;
std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName;
so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD);
if (so_handle == nullptr) {
so_handle = dlopen(soPathName.c_str(), RTLD_NOW);
if (so_handle == nullptr) {
LOGE("load profile so %s failed", soName.c_str());
return nullptr;
}
}
dlerror();
auto func = (CreateIProfileAdapterFuncPtr)dlsym(so_handle, (soInfoIter->second).funcName.c_str());
if (dlerror() != nullptr || func == nullptr) {
LOGE("Create object function is not exist");
return nullptr;
}
std::shared_ptr<IProfileAdapter> iProfileAdapter(func());
profileAdapterPtr_[soName] = iProfileAdapter;
return profileAdapterPtr_[soName];
}
std::shared_ptr<ICryptoAdapter> DmConfigManager::GetCryptoAdapter(const std::string &soName)
{
if (soName.empty()) {
LOGE("soName size is zero");
return nullptr;
}
auto soInfoIter = soAdapterLoadInfo_.find(soName);
if (soInfoIter == soAdapterLoadInfo_.end() || (soInfoIter->second).type != CPYPTO_JSON_TYPE_KEY) {
LOGE("not find so info or type key not match");
return nullptr;
}
std::unique_lock<std::mutex> locker(cryptoAdapterMutex_);
auto ptrIter = cryptoAdapterPtr_.find(soName);
if (ptrIter != cryptoAdapterPtr_.end()) {
return cryptoAdapterPtr_[soName];
}
void *so_handle = nullptr;
std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName;
so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD);
if (so_handle == nullptr) {
so_handle = dlopen(soPathName.c_str(), RTLD_NOW);
if (so_handle == nullptr) {
LOGE("load crypto so %s failed", soName.c_str());
return nullptr;
}
}
dlerror();
auto func = (CreateICryptoAdapterFuncPtr)dlsym(so_handle, (soInfoIter->second).funcName.c_str());
if (dlerror() != nullptr || func == nullptr) {
LOGE("Create object function is not exist");
return nullptr;
}
std::shared_ptr<ICryptoAdapter> iCryptoAdapter(func());
cryptoAdapterPtr_[soName] = iCryptoAdapter;
return cryptoAdapterPtr_[soName];
}
void DmConfigManager::GetAuthAdapter(std::map<int32_t, std::shared_ptr<IAuthentication>> &authAdapter)
{
authAdapter.clear();
for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) {
if ((iter->second).type != AUTH_JSON_TYPE_KEY) {
LOGE("type key not match");
continue;
}
void *so_handle = nullptr;
std::string soPathName = (iter->second).soPath + (iter->second).soName;
so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD);
if (so_handle == nullptr) {
so_handle = dlopen(soPathName.c_str(), RTLD_NOW);
if (so_handle == nullptr) {
LOGE("load auth so %s failed", (iter->second).soName.c_str());
continue;
}
}
dlerror();
auto func = (CreateIAuthAdapterFuncPtr)dlsym(so_handle, (iter->second).funcName.c_str());
if (dlerror() != nullptr || func == nullptr) {
LOGE("Create object function is not exist");
continue;
}
std::shared_ptr<IAuthentication> iAuthentication(func());
authAdapter[iter->first] = iAuthentication;
LOGI("so name: %s, auth type: %d", (iter->second).soName.c_str(), iter->first);
}
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,151 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "event_manager_adapt.h"
#include <thread>
#include "dm_constants.h"
using namespace OHOS::EventFwk;
namespace OHOS {
namespace DistributedHardware {
std::once_flag DmCommonEventManager::onceFlag_;
std::list<CommomEventCallback> DmCommonEventManager::callbackQueue_;
std::mutex DmCommonEventManager::callbackQueueMutex_;
std::condition_variable DmCommonEventManager::notEmpty_;
DmCommonEventManager &DmCommonEventManager::GetInstance()
{
static DmCommonEventManager instance;
std::call_once(onceFlag_, [] {
std::thread th(DealCallback);
th.detach();
});
return instance;
}
void DmCommonEventManager::DealCallback(void)
{
while (1) {
std::unique_lock<std::mutex> callbackQueueLock(callbackQueueMutex_);
notEmpty_.wait(callbackQueueLock, [] { return !callbackQueue_.empty(); });
CommomEventCallback funcPrt = callbackQueue_.front();
funcPrt();
callbackQueue_.pop_front();
}
}
bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, CommomEventCallback callback)
{
LOGI("Subscribe event: %s", event.c_str());
if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end()) {
LOGE("Subscribe event%s has been added", event.c_str());
return false;
}
MatchingSkills matchingSkills;
matchingSkills.AddEvent(event);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<EventSubscriber> subscriber = std::make_shared<EventSubscriber>(subscriberInfo);
if (subscriber == nullptr) {
LOGE("subscriber is nullptr %s", event.c_str());
return false;
}
subscriber->addEventCallback(event, callback);
bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber);
if (subscribeResult) {
LOGE("Subscribe service event success: %s", event.c_str());
dmEventSubscriber_[event] = subscriber;
return subscribeResult;
} else {
LOGE("Subscribe service event failed: %s", event.c_str());
return false;
}
}
bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event)
{
LOGI("UnSubscribe event: %s", event.c_str());
if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end()) {
LOGE("UnSubscribe event: %s not been exist", event.c_str());
return false;
}
bool unsubscribeResult = CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event]);
if (unsubscribeResult) {
LOGI("Unsubscribe service event success: %s", event.c_str());
dmEventSubscriber_[event]->deleteEventCallback(event);
dmEventSubscriber_.erase(event);
return unsubscribeResult;
} else {
LOGE("Unsubscribe service event failed: %s", event.c_str());
return false;
}
}
DmCommonEventManager::~DmCommonEventManager()
{
for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) {
bool unsubscribeResult = CommonEventManager::UnSubscribeCommonEvent(iter->second);
if (unsubscribeResult) {
LOGI("Unsubscribe service event success: %s", iter->first.c_str());
}
}
}
void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data)
{
std::string event = data.GetWant().GetAction();
LOGI("Received event: %s, value: %d", event.c_str());
std::unique_lock<std::mutex> callbackLock(callbackLock_);
auto iter = dmEventCallback_.find(event);
if (iter != dmEventCallback_.end()) {
CommomEventCallback funcPrt = iter->second;
callbackLock_.unlock();
std::unique_lock<std::mutex> callbackQueueLock(callbackQueueMutex_);
if (callbackQueue_.size() <= COMMON_CALLBACK_MAX_SIZE) {
callbackQueue_.push_back(funcPrt);
notEmpty_.notify_one();
} else {
LOGE("event callback Queue is too long");
}
}
}
void DmCommonEventManager::EventSubscriber::addEventCallback(const std::string &event, CommomEventCallback callback)
{
std::unique_lock<std::mutex> callbackLock(callbackLock_);
if (dmEventCallback_.find(event) == dmEventCallback_.end()) {
dmEventCallback_[event] = callback;
LOGI("add event success: %s", event.c_str());
}
}
void DmCommonEventManager::EventSubscriber::deleteEventCallback(const std::string &event)
{
std::unique_lock<std::mutex> callbackLock(callbackLock_);
if (dmEventCallback_.find(event) != dmEventCallback_.end()) {
dmEventCallback_.erase(event);
LOGI("delete event failed: %s", event.c_str());
}
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,424 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hichain_connector.h"
#include <securec.h>
#include <cstdlib>
#include <ctime>
#include <functional>
#include "dm_anonymous.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "dm_random.h"
#include "hichain_connector_callback.h"
#include "nlohmann/json.hpp"
#include "parameter.h"
namespace OHOS {
namespace DistributedHardware {
void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo)
{
if (jsonObject.find(FIELD_GROUP_NAME) != jsonObject.end()) {
groupInfo.groupName = jsonObject.at(FIELD_GROUP_NAME).get<std::string>();
}
if (jsonObject.find(FIELD_GROUP_ID) != jsonObject.end()) {
groupInfo.groupId = jsonObject.at(FIELD_GROUP_ID).get<std::string>();
}
if (jsonObject.find(FIELD_GROUP_OWNER) != jsonObject.end()) {
groupInfo.groupOwner = jsonObject.at(FIELD_GROUP_OWNER).get<std::string>();
}
if (jsonObject.find(FIELD_GROUP_TYPE) != jsonObject.end()) {
groupInfo.groupType = jsonObject.at(FIELD_GROUP_TYPE).get<int32_t>();
}
if (jsonObject.find(FIELD_GROUP_VISIBILITY) != jsonObject.end()) {
groupInfo.groupVisibility = jsonObject.at(FIELD_GROUP_VISIBILITY).get<int32_t>();
}
}
std::map<std::string, std::shared_ptr<IHiChainConnectorCallback>> HiChainConnector::hiChainConnectorCallbackMap_ = {};
HiChainConnector::HiChainConnector()
{
LOGI("HiChainConnector::constructor");
deviceAuthCallback_ = {.onTransmit = nullptr,
.onFinish = HiChainConnector::onFinish,
.onError = HiChainConnector::onError,
.onRequest = HiChainConnector::onRequest};
InitDeviceAuthService();
deviceGroupManager_ = GetGmInstance();
if (deviceGroupManager_ == nullptr) {
LOGI("HiChainConnector::constructor, failed to init group manager!");
return;
}
deviceGroupManager_->regCallback(DM_PKG_NAME.c_str(), &deviceAuthCallback_);
LOGI("HiChainConnector::constructor success.");
}
HiChainConnector::~HiChainConnector()
{
LOGI("HiChainConnector::destructor.");
}
int32_t HiChainConnector::RegisterHiChainCallback(const std::string &pkgName,
std::shared_ptr<IHiChainConnectorCallback> callback)
{
hiChainConnectorCallbackMap_.emplace(pkgName, callback);
return DM_OK;
}
int32_t HiChainConnector::UnRegisterHiChainCallback(const std::string &pkgName)
{
hiChainConnectorCallbackMap_.erase(pkgName);
return DM_OK;
}
int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &groupName)
{
if (deviceGroupManager_ == nullptr) {
LOGE("HiChainConnector::CreateGroup group manager is null, requestId %lld.", requestId);
return DM_INVALID_VALUE;
}
GroupInfo groupInfo;
if (IsGroupCreated(groupName, groupInfo)) {
DeleteGroup(groupInfo.groupId);
}
LOGI("HiChainConnector::CreateGroup requestId %lld", requestId);
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
std::string sLocalDeviceID = localDeviceId;
nlohmann::json jsonObj;
jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP;
jsonObj[FIELD_DEVICE_ID] = sLocalDeviceID;
jsonObj[FIELD_GROUP_NAME] = groupName;
jsonObj[FIELD_USER_TYPE] = 0;
jsonObj[FIELD_GROUP_VISIBILITY] = GROUP_VISIBILITY_PUBLIC;
jsonObj[FIELD_EXPIRE_TIME] = FIELD_EXPIRE_TIME_VALUE;
int32_t ret = deviceGroupManager_->createGroup(requestId, DM_PKG_NAME.c_str(), jsonObj.dump().c_str());
if (ret != 0) {
LOGE("Failed to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId);
return DM_HICHAIN_GROUP_CREATE_FAILED;
}
return DM_OK;
}
bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInfo)
{
nlohmann::json jsonObj;
jsonObj[FIELD_GROUP_NAME] = groupName.c_str();
std::string queryParams = jsonObj.dump();
std::vector<GroupInfo> groupList;
if (GetGroupInfo(queryParams, groupList)) {
groupInfo = groupList[0];
return true;
}
return false;
}
int32_t HiChainConnector::GetGroupInfo(std::string queryParams, std::vector<GroupInfo> &groupList)
{
char *groupVec = nullptr;
uint32_t num = 0;
int32_t ret = deviceGroupManager_->getGroupInfo(DM_PKG_NAME.c_str(), queryParams.c_str(), &groupVec, &num);
if (ret != 0) {
LOGE("HiChainConnector::GetGroupInfo failed , ret: %d.", ret);
return false;
}
if (groupVec == nullptr) {
LOGE("HiChainConnector::GetGroupInfo failed , returnGroups is nullptr");
return false;
}
if (num == 0) {
LOGE("HiChainConnector::GetGroupInfo group failed, groupNum is 0.");
return false;
}
LOGI("HiChainConnector::GetGroupInfo group(%s), groupNum(%d)", groupVec, num);
std::string relatedGroups = std::string(groupVec);
deviceGroupManager_->destroyInfo(&groupVec);
nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups);
if (jsonObject.is_discarded()) {
LOGE("returnGroups parse error");
return false;
}
std::vector<GroupInfo> groupInfos = jsonObject.get<std::vector<GroupInfo>>();
if (groupInfos.size() == 0) {
LOGE("HiChainConnector::GetGroupInfo group failed, groupInfos is empty.");
return false;
}
groupList = groupInfos;
return true;
}
int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectInfo)
{
LOGI("HiChainConnector::AddMember");
if (deviceGroupManager_ == nullptr) {
LOGI("HiChainConnector::AddMember group manager is null.");
return -1;
}
nlohmann::json jsonObject = nlohmann::json::parse(connectInfo, nullptr, false);
if (jsonObject.is_discarded()) {
LOGE("DecodeRequestAuth jsonStr error");
return DM_FAILED;
}
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
std::string connectInfomation = GetConnectPara(deviceId, jsonObject[TAG_DEVICE_ID]);
int32_t pinCode = jsonObject[PIN_CODE_KEY];
std::string groupId = jsonObject[TAG_GROUP_ID];
nlohmann::json jsonObj;
jsonObj[FIELD_GROUP_ID] = groupId;
jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP;
jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str();
jsonObj[FIELD_IS_ADMIN] = false;
jsonObj[FIELD_DEVICE_ID] = localDeviceId;
jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME];
jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str();
std::string tmpStr = jsonObj.dump();
int64_t requestId = jsonObject[TAG_REQUEST_ID];
// LOGI("HiChainConnector::AddMember completed requestId%d, jsonObject[TAG_GROUP_ID]%s ", requestId,
// groupId.c_str()); LOGI("HiChainConnector::AddMember completed DM_PKG_NAME %s", DM_PKG_NAME.c_str());
// LOGI("HiChainConnector::AddMember completedtmpStr%s", tmpStr.c_str());
int32_t ret = deviceGroupManager_->addMemberToGroup(requestId, DM_PKG_NAME.c_str(), tmpStr.c_str());
LOGI("HiChainConnector::AddMember completed");
return ret;
}
void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData)
{
std::string data = "";
if (returnData != nullptr) {
data = std::string(returnData);
}
LOGI("HiChainConnector::onFinish reqId:%lld, operation:%d", requestId, operationCode);
if (operationCode == GroupOperationCode::MEMBER_JOIN) {
LOGI("Add Member To Group success");
for (auto &iter : hiChainConnectorCallbackMap_) {
iter.second->OnMemberJoin(requestId, DM_OK);
}
}
if (operationCode == GroupOperationCode::GROUP_CREATE) {
LOGI("Create group success");
for (auto &iter : hiChainConnectorCallbackMap_) {
iter.second->OnGroupCreated(requestId, data);
}
}
if (operationCode == GroupOperationCode::MEMBER_DELETE) {
LOGI("Delete Member from group success");
}
if (operationCode == GroupOperationCode::GROUP_DISBAND) {
LOGI("Disband group success");
}
}
void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn)
{
(void)errorReturn;
LOGI("HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", requestId, operationCode, errorCode);
if (operationCode == GroupOperationCode::MEMBER_JOIN) {
LOGE("Add Member To Group failed");
for (auto &iter : hiChainConnectorCallbackMap_) {
iter.second->OnMemberJoin(requestId, DM_FAILED);
}
}
if (operationCode == GroupOperationCode::GROUP_CREATE) {
LOGE("Create group failed");
for (auto &iter : hiChainConnectorCallbackMap_) {
iter.second->OnGroupCreated(requestId, "{}");
}
}
if (operationCode == GroupOperationCode::MEMBER_DELETE) {
LOGE("Delete Member from group failed");
}
if (operationCode == GroupOperationCode::GROUP_DISBAND) {
LOGE("Disband group failed");
}
}
char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams)
{
if (operationCode != GroupOperationCode::MEMBER_JOIN) {
LOGE("HiChainAuthCallBack::onRequest operationCode %d", operationCode);
return nullptr;
}
int32_t pinCode = 0;
for (auto &iter : hiChainConnectorCallbackMap_) {
pinCode = iter.second->GetPinCode();
}
nlohmann::json jsonObj;
if (pinCode == DM_FAILED) {
jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED;
} else {
jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED;
}
jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str();
char localDeviceId[DEVICE_UUID_LENGTH] = {0};
GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
jsonObj[FIELD_DEVICE_ID] = localDeviceId;
std::string jsonStr = jsonObj.dump();
char *buffer = strdup(jsonStr.c_str());
return buffer;
}
int64_t HiChainConnector::GenRequestId()
{
return GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID);
}
std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string reqDeviceId)
{
std::string connectAddr = "";
for (auto &iter : hiChainConnectorCallbackMap_) {
connectAddr = iter.second->GetConnectAddr(deviceId);
}
LOGE("HiChainConnector::GetConnectPara get addrInfo");
nlohmann::json jsonObject = nlohmann::json::parse(connectAddr, nullptr, false);
if (jsonObject.is_discarded()) {
LOGE("DecodeRequestAuth jsonStr error");
return connectAddr;
}
jsonObject[DEVICE_ID] = reqDeviceId;
return jsonObject.dump();
}
void HiChainConnector::GetRelatedGroups(std::string deviceId, std::vector<GroupInfo> &groupList)
{
LOGI("HiChainConnector::GetRelatedGroups Start to get local related groups.");
uint32_t groupNum = 0;
char *returnGroups = nullptr;
int32_t ret =
deviceGroupManager_->getRelatedGroups(DM_PKG_NAME.c_str(), deviceId.c_str(), &returnGroups, &groupNum);
if (ret != 0) {
LOGE("HiChainConnector::GetRelatedGroups faild , ret: %d.", ret);
return;
}
if (returnGroups == nullptr) {
LOGE("HiChainConnector::GetRelatedGroups failed , returnGroups is nullptr");
return;
}
if (groupNum == 0) {
LOGE("HiChainConnector::GetRelatedGroups group failed, groupNum is 0.");
return;
}
std::string relatedGroups = std::string(returnGroups);
nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups);
if (jsonObject.is_discarded()) {
LOGE("returnGroups parse error");
return;
}
std::vector<GroupInfo> groupInfos = jsonObject.get<std::vector<GroupInfo>>();
if (groupInfos.size() == 0) {
LOGE("HiChainConnector::GetRelatedGroups group failed, groupInfos is empty.");
return;
}
groupList = groupInfos;
}
void HiChainConnector::GetSyncGroupList(std::vector<GroupInfo> &groupList, std::vector<std::string> &syncGroupList)
{
if (groupList.empty()) {
LOGE("groupList is empty.");
return;
}
for (auto group : groupList) {
if (IsGroupInfoInvalid(group)) {
continue;
}
syncGroupList.push_back(group.groupId);
}
}
bool HiChainConnector::IsDevicesInGroup(std::string hostDevice, std::string peerDevice)
{
LOGE("HiChainConnector::IsDevicesInGroup");
std::vector<GroupInfo> hostGroupInfoList;
GetRelatedGroups(hostDevice, hostGroupInfoList);
std::vector<GroupInfo> peerGroupInfoList;
GetRelatedGroups(peerDevice, peerGroupInfoList);
for (auto &hostGroupInfo : hostGroupInfoList) {
for (auto &peerGroupInfo : peerGroupInfoList) {
if (hostGroupInfo.groupId == peerGroupInfo.groupId && hostGroupInfo.groupName == peerGroupInfo.groupName) {
LOGE("these are authenticated");
return false;
}
}
}
return true;
}
bool HiChainConnector::IsGroupInfoInvalid(GroupInfo &group)
{
if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC ||
group.groupOwner != DM_PKG_NAME) {
return true;
}
return false;
}
void HiChainConnector::SyncGroups(std::string deviceId, std::vector<std::string> &remoteGroupIdList)
{
std::vector<GroupInfo> groupInfoList;
GetRelatedGroups(deviceId, groupInfoList);
for (auto &groupInfo : groupInfoList) {
if (IsGroupInfoInvalid(groupInfo)) {
continue;
}
auto iter = std::find(remoteGroupIdList.begin(), remoteGroupIdList.end(), groupInfo.groupId);
if (iter == remoteGroupIdList.end()) {
(void)DelMemberFromGroup(groupInfo.groupId, deviceId);
}
}
}
int32_t HiChainConnector::DelMemberFromGroup(std::string groupId, std::string deviceId)
{
int64_t requestId = GenRequestId();
LOGI("Start to delete memeber from group, requestId %lld, deviceId %s, groupId %s", requestId,
GetAnonyString(deviceId).c_str(), GetAnonyString(groupId).c_str());
nlohmann::json jsonObj;
jsonObj[FIELD_GROUP_ID] = groupId;
jsonObj[FIELD_DELETE_ID] = deviceId;
std::string deleteParams = jsonObj.dump();
int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DM_PKG_NAME.c_str(), deleteParams.c_str());
if (ret != 0) {
LOGE("HiChainConnector::DelMemberFromGroup failed , ret: %d.", ret);
return ret;
}
return DM_OK;
}
void HiChainConnector::DeleteGroup(std::string &groupId)
{
int64_t requestId = GenRequestId();
nlohmann::json jsonObj;
jsonObj[FIELD_GROUP_ID] = groupId;
std::string disbandParams = jsonObj.dump();
int32_t ret = deviceGroupManager_->deleteGroup(requestId, DM_PKG_NAME.c_str(), disbandParams.c_str());
if (ret != 0) {
LOGE("HiChainConnector::DeleteGroup failed , ret: %d.", ret);
}
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,561 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "softbus_connector.h"
#include <securec.h>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include "dm_anonymous.h"
#include "dm_constants.h"
#include "dm_device_info.h"
#include "dm_log.h"
#include "nlohmann/json.hpp"
#include "parameter.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace DistributedHardware {
SoftbusConnector::PulishStatus SoftbusConnector::publishStatus = SoftbusConnector::STATUS_UNKNOWN;
std::map<std::string, std::shared_ptr<DeviceInfo>> SoftbusConnector::discoveryDeviceInfoMap_ = {};
std::map<std::string, std::shared_ptr<ISoftbusStateCallback>> SoftbusConnector::stateCallbackMap_ = {};
std::map<std::string, std::shared_ptr<ISoftbusDiscoveryCallback>> SoftbusConnector::discoveryCallbackMap_ = {};
IPublishCallback SoftbusConnector::softbusPublishCallback_ = {.OnPublishSuccess = SoftbusConnector::OnPublishSuccess,
.OnPublishFail = SoftbusConnector::OnPublishFail};
IDiscoveryCallback SoftbusConnector::softbusDiscoveryCallback_ = {
.OnDeviceFound = SoftbusConnector::OnSoftbusDeviceFound,
.OnDiscoverFailed = SoftbusConnector::OnSoftbusDiscoveryFailed,
.OnDiscoverySuccess = SoftbusConnector::OnSoftbusDiscoverySuccess};
INodeStateCb SoftbusConnector::softbusNodeStateCb_ = {
.events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED,
.onNodeOnline = SoftbusConnector::OnSoftBusDeviceOnline,
.onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline,
.onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged};
SoftbusConnector::SoftbusConnector()
{
softbusSession_ = std::make_shared<SoftbusSession>();
Init();
}
SoftbusConnector::~SoftbusConnector()
{
LOGI("SoftbusConnector destructor");
}
int32_t SoftbusConnector::Init()
{
int32_t ret;
int32_t retryTimes = 0;
do {
ret = RegNodeDeviceStateCb(DM_PKG_NAME.c_str(), &softbusNodeStateCb_);
if (ret != DM_OK) {
++retryTimes;
LOGE("RegNodeDeviceStateCb failed with ret %d, retryTimes %d", ret, retryTimes);
usleep(SOFTBUS_CHECK_INTERVAL);
}
} while (ret != DM_OK);
LOGI("RegNodeDeviceStateCb success.");
PublishInfo dmPublishInfo;
dmPublishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID;
dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE;
dmPublishInfo.medium = ExchanageMedium::AUTO;
dmPublishInfo.freq = ExchangeFreq::HIGH;
dmPublishInfo.capability = DM_CAPABILITY_OSD;
dmPublishInfo.capabilityData = nullptr;
dmPublishInfo.dataLen = 0;
char discoverStatus[DISCOVER_STATUS_LEN + 1] = {0};
ret = GetParameter(DISCOVER_STATUS_KEY.c_str(), "not exist", discoverStatus, DISCOVER_STATUS_LEN);
if (strcmp(discoverStatus, "not exist") == 0) {
ret = SetParameter(DISCOVER_STATUS_KEY.c_str(), DISCOVER_STATUS_ON.c_str());
LOGI("service set poatrameter result is : %d", ret);
ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_);
if (ret == DM_OK) {
publishStatus = ALLOW_BE_DISCOVERY;
}
LOGI("service publish result is : %d", ret);
} else if (ret >= 0 && strcmp(discoverStatus, DISCOVER_STATUS_ON.c_str()) == 0) {
ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_);
if (ret == DM_OK) {
publishStatus = ALLOW_BE_DISCOVERY;
}
LOGI("service publish result is : %d", ret);
} else if (ret >= 0 && strcmp(discoverStatus, DISCOVER_STATUS_OFF.c_str()) == 0) {
ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
if (ret == DM_OK) {
publishStatus = NOT_ALLOW_BE_DISCOVERY;
}
LOGI("service unpublish result is : %d", ret);
}
// ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr);
LOGI("register Watch Parameter result is : %d");
return ret;
}
int32_t SoftbusConnector::RegisterSoftbusDiscoveryCallback(const std::string &pkgName,
const std::shared_ptr<ISoftbusDiscoveryCallback> callback)
{
discoveryCallbackMap_.emplace(pkgName, callback);
return DM_OK;
}
int32_t SoftbusConnector::UnRegisterSoftbusDiscoveryCallback(const std::string &pkgName)
{
discoveryCallbackMap_.erase(pkgName);
return DM_OK;
}
int32_t SoftbusConnector::RegisterSoftbusStateCallback(const std::string &pkgName,
const std::shared_ptr<ISoftbusStateCallback> callback)
{
stateCallbackMap_.emplace(pkgName, callback);
return DM_OK;
}
int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgName)
{
stateCallbackMap_.erase(pkgName);
return DM_OK;
}
int32_t SoftbusConnector::GetTrustedDeviceList(std::vector<DmDeviceInfo> &deviceInfoList)
{
LOGD("SoftbusConnector::GetTrustDevices start");
int32_t infoNum = 0;
NodeBasicInfo *nodeInfo = nullptr;
int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeInfo, &infoNum);
if (ret != 0) {
LOGE("GetAllNodeDeviceInfo failed with ret %d", ret);
return DM_FAILED;
}
DmDeviceInfo *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (infoNum));
if (info == nullptr) {
FreeNodeInfo(nodeInfo);
return DM_MALLOC_ERROR;
}
DmDeviceInfo **pInfoList = &info;
for (int32_t i = 0; i < infoNum; ++i) {
NodeBasicInfo *nodeBasicInfo = nodeInfo + i;
DmDeviceInfo *deviceInfo = *pInfoList + i;
CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, *deviceInfo);
deviceInfoList.push_back(*deviceInfo);
}
FreeNodeInfo(nodeInfo);
free(info);
LOGD("SoftbusConnector::GetTrustDevices success, deviceCount %d", infoNum);
return DM_OK;
}
int32_t SoftbusConnector::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo)
{
LOGD("SoftbusConnector::GetLocalDeviceInfo start");
NodeBasicInfo nodeBasicInfo;
int32_t ret = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeBasicInfo);
if (ret != 0) {
LOGE("GetLocalNodeDeviceInfo failed with ret %d", ret);
return DM_FAILED;
}
CovertNodeBasicInfoToDmDevice(nodeBasicInfo, deviceInfo);
LOGD("SoftbusConnector::GetLocalDeviceInfo success");
return DM_OK;
}
int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo)
{
SubscribeInfo subscribeInfo;
subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId;
subscribeInfo.mode = (DiscoverMode)dmSubscribeInfo.mode;
subscribeInfo.medium = (ExchanageMedium)dmSubscribeInfo.medium;
subscribeInfo.freq = (ExchangeFreq)dmSubscribeInfo.freq;
subscribeInfo.isSameAccount = dmSubscribeInfo.isSameAccount;
subscribeInfo.isWakeRemote = dmSubscribeInfo.isWakeRemote;
subscribeInfo.capability = dmSubscribeInfo.capability;
subscribeInfo.capabilityData = nullptr;
subscribeInfo.dataLen = 0;
int32_t ret = ::StartDiscovery(DM_PKG_NAME.c_str(), &subscribeInfo, &softbusDiscoveryCallback_);
if (ret != 0) {
LOGE("StartDiscovery failed with ret %d.", ret);
return DM_DISCOVERY_FAILED;
}
return DM_OK;
}
int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId)
{
LOGI("StopDiscovery begin, subscribeId:%d", (int32_t)subscribeId);
int32_t ret = ::StopDiscovery(DM_PKG_NAME.c_str(), subscribeId);
if (ret != 0) {
LOGE("StopDiscovery failed with ret %d", ret);
return ret;
}
LOGI("SoftbusConnector::StopDiscovery completed");
return DM_OK;
}
int32_t SoftbusConnector::GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeivceInfoKey key, uint8_t *info,
int32_t infoLen)
{
LOGI("GetNodeKeyInfoByNetworkId begin");
int32_t ret = GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId, key, info, infoLen);
if (ret != DM_OK) {
LOGE("GetNodeKeyInfoByNetworkId GetNodeKeyInfo failed");
return DM_FAILED;
}
LOGI("SoftbusConnector::GetNodeKeyInfoByNetworkId completed");
return DM_OK;
}
int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string &udid)
{
LOGI("GetUdidByNetworkId begin");
uint8_t mUdid[UDID_BUF_LEN] = {0};
int32_t ret =
GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId, NodeDeivceInfoKey::NODE_KEY_UDID, mUdid, sizeof(mUdid));
if (ret != DM_OK) {
LOGE("GetUdidByNetworkId GetNodeKeyInfo failed");
return DM_FAILED;
}
udid = (char *)mUdid;
LOGI("SoftbusConnector::GetUdidByNetworkId completed");
return DM_OK;
}
int32_t SoftbusConnector::GetUuidByNetworkId(const char *networkId, std::string &uuid)
{
LOGI("GetUuidByNetworkId begin");
uint8_t mUuid[UUID_BUF_LEN] = {0};
int32_t ret =
GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId, NodeDeivceInfoKey::NODE_KEY_UUID, mUuid, sizeof(mUuid));
if (ret != DM_OK) {
LOGE("GetUuidByNetworkId GetNodeKeyInfo failed");
return DM_FAILED;
}
uuid = (char *)mUuid;
LOGI("SoftbusConnector::GetUuidByNetworkId completed");
return DM_OK;
}
bool SoftbusConnector::IsDeviceOnLine(const std::string &deviceId)
{
NodeBasicInfo *info = nullptr;
int32_t infoNum = 0;
if (GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &info, &infoNum) != DM_OK) {
LOGE("GetAllNodeDeviceInfo failed");
return false;
}
bool bDeviceOnline = false;
for (int32_t i = 0; i < infoNum; ++i) {
NodeBasicInfo *nodeBasicInfo = info + i;
if (nodeBasicInfo == nullptr) {
LOGE("nodeBasicInfo is empty for index %d, infoNum %d.", i, infoNum);
continue;
}
std::string networkId = nodeBasicInfo->networkId;
if (networkId == deviceId) {
LOGI("DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str());
bDeviceOnline = true;
break;
}
uint8_t udid[UDID_BUF_LEN] = {0};
int32_t ret = GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId.c_str(), NodeDeivceInfoKey::NODE_KEY_UDID, udid,
sizeof(udid));
if (ret != DM_OK) {
LOGE("DM_IsDeviceOnLine GetNodeKeyInfo failed");
break;
}
if (strcmp((char *)udid, deviceId.c_str()) == 0) {
LOGI("DM_IsDeviceOnLine device %s online", GetAnonyString(deviceId).c_str());
bDeviceOnline = true;
break;
}
}
FreeNodeInfo(info);
return bDeviceOnline;
}
std::shared_ptr<SoftbusSession> SoftbusConnector::GetSoftbusSession()
{
return softbusSession_;
}
bool SoftbusConnector::HaveDeviceInMap(std::string deviceId)
{
auto iter = discoveryDeviceInfoMap_.find(deviceId);
if (iter == discoveryDeviceInfoMap_.end()) {
LOGE("deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str());
return false;
}
return true;
}
int32_t SoftbusConnector::GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress)
{
auto iter = discoveryDeviceInfoMap_.find(deviceId);
if (iter == discoveryDeviceInfoMap_.end()) {
LOGE("deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str());
return DM_FAILED;
}
DeviceInfo *deviceInfo = iter->second.get();
if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) {
LOGE("deviceInfo address num not valid, addrNum %d", deviceInfo->addrNum);
return DM_FAILED;
}
for (uint32_t i = 0; i < deviceInfo->addrNum; ++i) {
// currently, only support CONNECT_ADDR_WLAN
if (deviceInfo->addr[i].type != ConnectionAddrType::CONNECTION_ADDR_WLAN &&
deviceInfo->addr[i].type != ConnectionAddrType::CONNECTION_ADDR_ETH) {
continue;
}
ipAddress = deviceInfo->addr[i].info.ip.ip;
LOGI("DM_GetConnectionIpAddr get ip ok.");
return DM_OK;
}
LOGE("failed to get ipAddress for deviceId %s", GetAnonyString(deviceId).c_str());
return DM_FAILED;
}
ConnectionAddr *SoftbusConnector::GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type)
{
if (deviceInfo == nullptr) {
return nullptr;
}
for (uint32_t i = 0; i < deviceInfo->addrNum; ++i) {
if (deviceInfo->addr[i].type == type) {
return &deviceInfo->addr[i];
}
}
return nullptr;
}
ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr)
{
auto iter = discoveryDeviceInfoMap_.find(deviceId);
if (iter == discoveryDeviceInfoMap_.end()) {
LOGE("deviceInfo not found by deviceId %s", GetAnonyString(deviceId).c_str());
return nullptr;
}
DeviceInfo *deviceInfo = iter->second.get();
if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) {
LOGE("deviceInfo addrNum not valid, addrNum %d", deviceInfo->addrNum);
return nullptr;
}
nlohmann::json jsonPara;
ConnectionAddr *addr = nullptr;
addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH);
if (addr != nullptr) {
LOGI("get ETH ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str());
jsonPara[ETH_IP] = addr->info.ip.ip;
jsonPara[ETH_PORT] = addr->info.ip.port;
connectAddr = jsonPara.dump();
return addr;
}
addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN);
if (addr != nullptr) {
jsonPara[WIFI_IP] = addr->info.ip.ip;
jsonPara[WIFI_PORT] = addr->info.ip.port;
LOGI("get WLAN ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str());
connectAddr = jsonPara.dump();
return addr;
}
addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE);
if (addr != nullptr) {
jsonPara[BR_MAC] = addr->info.br.brMac;
LOGI("get BLE ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str());
connectAddr = jsonPara.dump();
return addr;
}
addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR);
if (addr != nullptr) {
jsonPara[BLE_MAC] = addr->info.ble.bleMac;
LOGI("get BR ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str());
connectAddr = jsonPara.dump();
return addr;
}
LOGE("failed to get ConnectionAddr for deviceId %s", GetAnonyString(deviceId).c_str());
return nullptr;
}
void SoftbusConnector::CovertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo)
{
(void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo));
if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), nodeBasicInfo.networkId,
std::min(sizeof(dmDeviceInfo.deviceId), sizeof(nodeBasicInfo.networkId))) != DM_OK) {
LOGE("copy data failed");
}
if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName,
std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DM_OK) {
LOGE("copy data failed");
}
dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId;
}
void SoftbusConnector::CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo)
{
(void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo));
if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId,
std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != DM_OK) {
LOGE("copy data failed");
}
if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName,
std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) {
LOGE("copy data failed");
}
dmDeviceInfo.deviceTypeId = deviceInfo.devType;
}
void SoftbusConnector::OnPublishSuccess(int32_t publishId)
{
LOGI("SoftbusConnector::OnPublishSuccess, publishId: %d", publishId);
}
void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason)
{
LOGI("SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason);
}
void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info)
{
LOGI("device online");
if (info == nullptr) {
LOGE("SoftbusConnector::OnSoftbusDeviceOffline NodeBasicInfo is nullptr");
return;
}
if (discoveryDeviceInfoMap_.empty()) {
return;
}
DmDeviceInfo dmDeviceInfo;
CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
for (auto &iter : stateCallbackMap_) {
iter.second->OnDeviceOnline(iter.first, dmDeviceInfo);
}
// remove the discovery node map
uint8_t udid[UDID_BUF_LEN] = {0};
int32_t ret =
GetNodeKeyInfo(DM_PKG_NAME.c_str(), info->networkId, NodeDeivceInfoKey::NODE_KEY_UDID, udid, sizeof(udid));
if (ret != DM_OK) {
LOGE("GetNodeKeyInfo failed");
return;
}
std::string deviceId = (char *)udid;
LOGI("device online, deviceId: %s", GetAnonyString(deviceId).c_str());
discoveryDeviceInfoMap_.erase(deviceId);
}
void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info)
{
if (info == nullptr) {
LOGE("OnSoftbusDeviceOffline NodeBasicInfo is nullptr");
return;
}
DmDeviceInfo dmDeviceInfo;
CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo);
for (auto &iter : stateCallbackMap_) {
iter.second->OnDeviceOffline(iter.first, dmDeviceInfo);
}
}
void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info)
{
LOGI("SoftbusConnector::OnSoftbusDeviceInfoChanged.");
}
void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device)
{
if (device == nullptr) {
LOGE("device is null");
return;
}
std::string deviceId = device->devId;
LOGI("SoftbusConnector::OnSoftbusDeviceFound device %s found.", GetAnonyString(deviceId).c_str());
if (IsDeviceOnLine(deviceId)) {
return;
}
std::shared_ptr<DeviceInfo> infoPtr = std::make_shared<DeviceInfo>();
DeviceInfo *srcInfo = infoPtr.get();
if (memcpy_s(srcInfo, sizeof(DeviceInfo), device, sizeof(DeviceInfo)) != 0) {
LOGE("save discovery device info failed");
return;
}
discoveryDeviceInfoMap_[deviceId] = infoPtr;
// Remove the earliest element when reached the max size
if (discoveryDeviceInfoMap_.size() == SOFTBUS_DISCOVER_DEVICE_INFO_MAX_SIZE) {
auto iter = discoveryDeviceInfoMap_.begin();
discoveryDeviceInfoMap_.erase(iter->second->devId);
}
DmDeviceInfo dmDeviceInfo;
CovertDeviceInfoToDmDevice(*device, dmDeviceInfo);
for (auto &iter : discoveryCallbackMap_) {
iter.second->OnDeviceFound(iter.first, dmDeviceInfo);
}
}
void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason)
{
LOGI("In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason);
uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK);
for (auto &iter : discoveryCallbackMap_) {
iter.second->OnDiscoveryFailed(iter.first, originId, (int32_t)failReason);
}
}
void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId)
{
LOGI("In, subscribeId %d", subscribeId);
uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK);
for (auto &iter : discoveryCallbackMap_) {
iter.second->OnDiscoverySuccess(iter.first, originId);
}
}
void SoftbusConnector::OnParameterChgCallback(const char *key, const char *value, void *context)
{
if (strcmp(value, DISCOVER_STATUS_ON.c_str()) == 0 && publishStatus != ALLOW_BE_DISCOVERY) {
PublishInfo dmPublishInfo;
dmPublishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID;
dmPublishInfo.mode = DiscoverMode::DISCOVER_MODE_ACTIVE;
dmPublishInfo.medium = ExchanageMedium::AUTO;
dmPublishInfo.freq = ExchangeFreq::HIGH;
dmPublishInfo.capability = DM_CAPABILITY_OSD;
dmPublishInfo.capabilityData = nullptr;
dmPublishInfo.dataLen = 0;
int32_t ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_);
if (ret == DM_OK) {
publishStatus = ALLOW_BE_DISCOVERY;
}
LOGI("service publish result is : %d", ret);
} else if (strcmp(value, DISCOVER_STATUS_OFF.c_str()) == 0 && publishStatus != NOT_ALLOW_BE_DISCOVERY) {
int32_t ret = UnPublishService(DM_PKG_NAME.c_str(), DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
if (ret == DM_OK) {
publishStatus = NOT_ALLOW_BE_DISCOVERY;
}
LOGI("service unpublish result is : %d", ret);
}
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,163 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "softbus_session.h"
#include "dm_anonymous.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "nlohmann/json.hpp"
#include "softbus_connector.h"
namespace OHOS {
namespace DistributedHardware {
std::map<std::string, std::shared_ptr<ISoftbusSessionCallback>> SoftbusSession::sessionCallbackMap_ = {};
SoftbusSession::SoftbusSession()
{
ISessionListener sessionListener = {.OnSessionOpened = SoftbusSession::OnSessionOpened,
.OnSessionClosed = SoftbusSession::OnSessionClosed,
.OnBytesReceived = SoftbusSession::OnBytesReceived,
.OnMessageReceived = nullptr,
.OnStreamReceived = nullptr};
int32_t ret = CreateSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str(), &sessionListener);
if (ret != DM_OK) {
LOGD("CreateSessionServer failed");
} else {
LOGI("CreateSessionServer ok");
}
}
SoftbusSession::~SoftbusSession()
{
RemoveSessionServer(DM_PKG_NAME.c_str(), DM_SESSION_NAME.c_str());
}
int32_t SoftbusSession::RegisterSessionCallback(const std::string &pkgName,
std::shared_ptr<ISoftbusSessionCallback> callback)
{
sessionCallbackMap_[pkgName] = callback;
return DM_OK;
}
int32_t SoftbusSession::UnRegisterSessionCallback(const std::string &pkgName)
{
sessionCallbackMap_.erase(pkgName);
return DM_OK;
}
int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId)
{
LOGE("SoftbusSession::OpenAuthSession");
int32_t sessionId = -1;
std::string connectAddr;
ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr);
if (addrInfo == nullptr) {
LOGE("GetConnectAddr error");
return sessionId;
}
sessionId = ::OpenAuthSession(DM_SESSION_NAME.c_str(), addrInfo, 1, nullptr);
if (sessionId < 0) {
LOGE("open session error, ret:%d", sessionId);
return sessionId;
}
LOGI("SoftbusSession::OpenAuthSession success. sessionId is:%d", sessionId);
return sessionId;
}
void SoftbusSession::CloseAuthSession(int32_t sessionId)
{
LOGI("SoftbusSession::CloseAuthSession");
::CloseSession(sessionId);
}
void SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId)
{
char peerDeviceId[DEVICE_UUID_LENGTH] = {0};
int32_t ret = ::GetPeerDeviceId(sessionId, &peerDeviceId[0], DEVICE_UUID_LENGTH);
if (ret == 0) {
peerDevId = peerDeviceId;
LOGI("GetPeerDeviceId success for session:%d, peerDeviceId:%s", sessionId, GetAnonyString(peerDevId).c_str());
return;
}
LOGE("GetPeerDeviceId failed for session:%d", sessionId);
peerDevId = "";
}
int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message)
{
LOGE("SendData Start");
nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false);
if (jsonObject.is_discarded()) {
LOGE("extrasJson error");
return DM_FAILED;
}
int32_t msgType = jsonObject[TAG_TYPE];
LOGI("AuthMessageProcessor::ParseAuthRequestMessage msgType = %d", msgType);
bool isCryptoSupport = false;
for (auto &iter : sessionCallbackMap_) {
iter.second->GetIsCryptoSupport(isCryptoSupport);
}
if (isCryptoSupport) {
LOGI("SoftbusSession::SendData Start encryption");
}
int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str()));
if (ret != DM_OK) {
LOGE("SendData Start failed");
return DM_FAILED;
}
LOGE("SendData Start success");
return DM_OK;
}
int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result)
{
int32_t sessionSide = GetSessionSide(sessionId);
for (auto &iter : sessionCallbackMap_) {
iter.second->OnSessionOpened(iter.first, sessionId, sessionSide, result);
}
LOGI("OnSessionOpened, success:");
return DM_OK;
}
void SoftbusSession::OnSessionClosed(int32_t sessionId)
{
LOGI("OnSessionClosed, sessionId:%d", sessionId);
}
void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen)
{
LOGI("OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen);
if (sessionId < 0 || data == nullptr || dataLen <= 0) {
LOGI("OnBytesReceived param check failed");
return;
}
bool isCryptoSupport = false;
for (auto &iter : sessionCallbackMap_) {
iter.second->GetIsCryptoSupport(isCryptoSupport);
}
if (isCryptoSupport) {
LOGI("SoftbusSession::OnBytesReceived Start decryption");
}
std::string message = std::string((const char *)data, dataLen);
for (auto &iter : sessionCallbackMap_) {
iter.second->OnDataReceived(iter.first, sessionId, message);
}
LOGI("OnBytesReceived completed");
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,153 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_timer.h"
#include <thread>
#include "securec.h"
namespace OHOS {
namespace DistributedHardware {
namespace {
const int32_t MILL_SECONDS_PER_SECOND = 1000;
}
DmTimer::DmTimer(std::string &name)
{
mStatus_ = DmTimerStatus::DM_STATUS_INIT;
mTimeOutSec_ = 0;
mHandle_ = nullptr;
mHandleData_ = nullptr;
(void)memset_s(mTimeFd_, sizeof(mTimeFd_), 0, sizeof(mTimeFd_));
(void)memset_s(&mEv_, sizeof(mEv_), 0, sizeof(mEv_));
(void)memset_s(mEvents_, sizeof(mEvents_), 0, sizeof(mEvents_));
mEpFd_ = 0;
mTimerName_ = name;
}
DmTimer::~DmTimer()
{
LOGI("DmTimer %s Destory in", mTimerName_.c_str());
Release();
}
DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data)
{
LOGI("DmTimer %s start timeout(%d)", mTimerName_.c_str(), timeOut);
if (mStatus_ != DmTimerStatus::DM_STATUS_INIT) {
return DmTimerStatus::DM_STATUS_BUSY;
}
mTimeOutSec_ = timeOut;
mHandle_ = handle;
mHandleData_ = data;
if (CreateTimeFd()) {
return DmTimerStatus::DM_STATUS_CREATE_ERROR;
}
mStatus_ = DmTimerStatus::DM_STATUS_RUNNING;
mThread_ = std::thread(&DmTimer::WaitForTimeout, this);
mThread_.detach();
return mStatus_;
}
void DmTimer::Stop(int32_t code)
{
LOGI("DmTimer %s Stop code (%d)", mTimerName_.c_str(), code);
if (mTimeFd_[1]) {
char event = 'S';
if (write(mTimeFd_[1], &event, 1) < 0) {
LOGE("DmTimer %s Stop timer failed, errno %d", mTimerName_.c_str(), errno);
return;
}
LOGI("DmTimer %s Stop success", mTimerName_.c_str());
}
return;
}
void DmTimer::WaitForTimeout()
{
LOGI("DmTimer %s start timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_);
int32_t nfds = epoll_wait(mEpFd_, mEvents_, MAXEVENTS, mTimeOutSec_ * MILL_SECONDS_PER_SECOND);
if (nfds < 0) {
LOGE("DmTimer %s epoll_wait returned n=%d, error: %d", mTimerName_.c_str(), nfds, errno);
}
char event = 0;
if (nfds > 0) {
if (mEvents_[0].events & EPOLLIN) {
int num = read(mTimeFd_[0], &event, 1);
if (num > 0) {
LOGI("DmTimer %s exit with event %d", mTimerName_.c_str(), event);
} else {
LOGE("DmTimer %s exit with errno %d", mTimerName_.c_str(), errno);
}
}
Release();
return;
}
mHandle_(mHandleData_);
Release();
LOGE("DmTimer %s end timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_);
return;
}
int32_t DmTimer::CreateTimeFd()
{
LOGI("DmTimer %s creatTimeFd", mTimerName_.c_str());
int ret = 0;
ret = pipe(mTimeFd_);
if (ret < 0) {
LOGE("DmTimer %s CreateTimeFd fail:(%d) errno(%d)", mTimerName_.c_str(), ret, errno);
return ret;
}
mEv_.data.fd = mTimeFd_[0];
mEv_.events = EPOLLIN | EPOLLET;
mEpFd_ = epoll_create(MAXEVENTS);
ret = epoll_ctl(mEpFd_, EPOLL_CTL_ADD, mTimeFd_[0], &mEv_);
if (ret != 0) {
Release();
}
return ret;
}
void DmTimer::Release()
{
LOGI("DmTimer %s Release in", mTimerName_.c_str());
if (mStatus_ == DmTimerStatus::DM_STATUS_INIT) {
LOGI("DmTimer %s already Release", mTimerName_.c_str());
return;
}
mStatus_ = DmTimerStatus::DM_STATUS_INIT;
close(mTimeFd_[0]);
close(mTimeFd_[1]);
if (mEpFd_ >= 0) {
close(mEpFd_);
}
mTimeFd_[0] = 0;
mTimeFd_[1] = 0;
mEpFd_ = 0;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,229 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "device_manager_service.h"
#include "device_manager_service_listener.h"
#include "dm_constants.h"
#include "dm_device_info_manager.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService);
int32_t DeviceManagerService::Init()
{
if (intFlag_) {
LOGE("Init failed, singleton cannot be initialized multiple times");
return DM_INT_MULTIPLE;
}
if (softbusConnector_ == nullptr) {
softbusConnector_ = std::make_shared<SoftbusConnector>();
if (softbusConnector_ == nullptr) {
LOGE("Init failed, softbusConnector_ apply for failure");
return DM_MAKE_SHARED_FAIL;
}
}
if (listener_ == nullptr) {
listener_ = std::make_shared<DeviceManagerServiceListener>();
if (softbusConnector_ == nullptr) {
LOGE("Init failed, listener_ apply for failure");
return DM_MAKE_SHARED_FAIL;
}
}
if (deviceInfoMgr_ == nullptr) {
deviceInfoMgr_ = std::make_shared<DmDeviceInfoManager>(softbusConnector_);
if (deviceInfoMgr_ == nullptr) {
LOGE("Init failed, deviceInfoMgr_ apply for failure");
return DM_MAKE_SHARED_FAIL;
}
}
if (deviceStateMgr_ == nullptr) {
deviceStateMgr_ = std::make_shared<DmDeviceStateManager>(softbusConnector_, listener_);
if (deviceStateMgr_ == nullptr) {
LOGE("Init failed, deviceStateMgr_ apply for failure");
return DM_MAKE_SHARED_FAIL;
}
deviceStateMgr_->RegisterSoftbusStateCallback();
}
if (discoveryMgr_ == nullptr) {
discoveryMgr_ = std::make_shared<DmDiscoveryManager>(softbusConnector_, listener_);
if (discoveryMgr_ == nullptr) {
LOGE("Init failed, discoveryMgr_ apply for failure");
return DM_MAKE_SHARED_FAIL;
}
}
if (authMgr_ == nullptr) {
authMgr_ = std::make_shared<DmAuthManager>(softbusConnector_, listener_);
if (authMgr_ == nullptr) {
LOGE("Init failed, authMgr_ apply for failure");
return DM_MAKE_SHARED_FAIL;
}
authMgr_->RegisterSessionCallback();
}
LOGI("Init success, singleton initialized");
intFlag_ = true;
return DM_OK;
}
int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra,
std::vector<DmDeviceInfo> &deviceList)
{
if (!intFlag_) {
LOGE("GetTrustedDeviceList failed, singleton not init or init fail");
return DM_NOT_INIT;
}
if (pkgName.empty()) {
LOGE("GetTrustedDeviceList failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList);
}
int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info)
{
if (!intFlag_) {
LOGE("GetLocalDeviceInfo failed, singleton not init or init fail");
return DM_NOT_INIT;
}
return deviceInfoMgr_->GetLocalDeviceInfo(info);
}
int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId,
std::string &udid)
{
if (!intFlag_) {
LOGE("GetLocalDeviceInfo failed, singleton not init or init fail");
return DM_NOT_INIT;
}
if (pkgName.empty()) {
LOGE("StartDeviceDiscovery failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid);
return DM_OK;
}
int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId,
std::string &uuid)
{
if (!intFlag_) {
LOGE("GetLocalDeviceInfo failed, singleton not init or init fail");
return DM_NOT_INIT;
}
if (pkgName.empty()) {
LOGE("StartDeviceDiscovery failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid);
return DM_OK;
}
int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo,
const std::string &extra)
{
if (!intFlag_) {
LOGE("StartDeviceDiscovery failed, singleton not init or init fail");
return DM_NOT_INIT;
}
if (pkgName.empty()) {
LOGE("StartDeviceDiscovery failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra);
}
int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId)
{
if (!intFlag_) {
LOGE("StopDeviceDiscovery failed, singleton not init or init fail");
return DM_NOT_INIT;
}
if (pkgName.empty()) {
LOGE("StopDeviceDiscovery failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId);
}
int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType,
const std::string &deviceId, const std::string &extra)
{
if (!intFlag_) {
LOGE("AuthenticateDevice failed, singleton not init or init fail");
return DM_NOT_INIT;
}
if (pkgName.empty()) {
LOGE("AuthenticateDevice failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
if (deviceId.empty()) {
LOGE("AuthenticateDevice failed, deviceId is empty");
return DM_INPUT_PARA_EMPTY;
}
return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra);
}
int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId)
{
if (!intFlag_) {
LOGE("UnAuthenticateDevice failed, singleton not init or init fail");
return DM_NOT_INIT;
}
if (pkgName.empty()) {
LOGE("UnAuthenticateDevice failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
if (deviceId.empty()) {
LOGE("UnAuthenticateDevice failed, deviceId is empty");
return DM_INPUT_PARA_EMPTY;
}
return authMgr_->UnAuthenticateDevice(pkgName, deviceId);
}
int32_t DeviceManagerService::VerifyAuthentication(const std::string &authParam)
{
if (!intFlag_) {
LOGE("VerifyAuthentication failed, singleton not init or init fail");
return DM_NOT_INIT;
}
return authMgr_->VerifyAuthentication(authParam);
}
int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam)
{
if (pkgName.empty()) {
LOGE("GetFaParam failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
authMgr_->GetAuthenticationParam(authParam);
return DM_OK;
}
int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action)
{
if (pkgName.empty()) {
LOGE("SetUserOperation failed, pkgName is empty");
return DM_INPUT_PARA_EMPTY;
}
authMgr_->OnUserOperation(action);
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,120 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "device_manager_service_listener.h"
#include <memory>
#include "dm_anonymous.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "ipc_notify_auth_result_req.h"
#include "ipc_notify_device_found_req.h"
#include "ipc_notify_device_state_req.h"
#include "ipc_notify_discover_result_req.h"
#include "ipc_notify_verify_auth_result_req.h"
namespace OHOS {
namespace DistributedHardware {
void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state,
const DmDeviceInfo &info)
{
LOGI("OnDeviceStateChange, state=%d", state);
std::shared_ptr<IpcNotifyDeviceStateReq> pReq = std::make_shared<IpcNotifyDeviceStateReq>();
std::shared_ptr<IpcRsp> pRsp = std::make_shared<IpcRsp>();
pReq->SetDeviceState(state);
pReq->SetDeviceInfo(info);
ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp);
}
void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId,
const DmDeviceInfo &info)
{
LOGI("call OnDeviceFound for %s, originId %d, deviceId %s", pkgName.c_str(), subscribeId,
GetAnonyString(std::string(info.deviceId)).c_str());
std::shared_ptr<IpcNotifyDeviceFoundReq> pReq = std::make_shared<IpcNotifyDeviceFoundReq>();
std::shared_ptr<IpcRsp> pRsp = std::make_shared<IpcRsp>();
pReq->SetPkgName(pkgName);
pReq->SetSubscribeId(subscribeId);
pReq->SetDeviceInfo(info);
ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp);
}
void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId,
int32_t failedReason)
{
LOGI("OnDiscoveryFailed");
std::shared_ptr<IpcNotifyDiscoverResultReq> pReq = std::make_shared<IpcNotifyDiscoverResultReq>();
std::shared_ptr<IpcRsp> pRsp = std::make_shared<IpcRsp>();
pReq->SetPkgName(pkgName);
pReq->SetSubscribeId(subscribeId);
pReq->SetResult(failedReason);
ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp);
}
void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId)
{
LOGI("OnDiscoverySuccess");
std::shared_ptr<IpcNotifyDiscoverResultReq> pReq = std::make_shared<IpcNotifyDiscoverResultReq>();
std::shared_ptr<IpcRsp> pRsp = std::make_shared<IpcRsp>();
pReq->SetPkgName(pkgName);
pReq->SetSubscribeId(subscribeId);
pReq->SetResult(DM_OK);
ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp);
}
void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId,
const std::string &token, int32_t status, const std::string &reason)
{
LOGI("%s, package: %s, deviceId: %s", __FUNCTION__, pkgName.c_str(), GetAnonyString(deviceId).c_str());
std::shared_ptr<IpcNotifyAuthResultReq> pReq = std::make_shared<IpcNotifyAuthResultReq>();
std::shared_ptr<IpcRsp> pRsp = std::make_shared<IpcRsp>();
pReq->SetPkgName(pkgName);
pReq->SetDeviceId(deviceId);
pReq->SetToken(token);
pReq->SetStatus(status);
// pReq->SetReason(reason);
ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp);
}
void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId,
int32_t resultCode, const std::string &flag)
{
std::shared_ptr<IpcNotifyVerifyAuthResultReq> pReq = std::make_shared<IpcNotifyVerifyAuthResultReq>();
std::shared_ptr<IpcRsp> pRsp = std::make_shared<IpcRsp>();
pReq->SetDeviceId(deviceId);
pReq->SetResult(resultCode);
ipcServerListener_.SendAll(SERVER_VERIFY_AUTH_RESULT, pReq, pRsp);
}
void DeviceManagerServiceListener::OnFaCall(std::string &pkgName, std::string &paramJson)
{
LOGI("OnFaCall in");
std::shared_ptr<IpcNotifyDMFAResultReq> pReq = std::make_shared<IpcNotifyDMFAResultReq>();
std::shared_ptr<IpcRsp> pRsp = std::make_shared<IpcRsp>();
pReq->SetPkgName(pkgName);
pReq->SetJsonParam(paramJson);
ipcServerListener_.SendRequest(SERVER_DEVICE_FA_NOTIFY, pReq, pRsp);
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_device_info_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr<SoftbusConnector> &softbusConnectorPtr)
: softbusConnector_(softbusConnectorPtr)
{
LOGI("DmDeviceInfoManager constructor");
}
int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra,
std::vector<DmDeviceInfo> &deviceList)
{
int32_t ret = softbusConnector_->GetTrustedDeviceList(deviceList);
if (ret != DM_OK) {
LOGE("GetTrustedDeviceList failed");
return ret;
}
if (!extra.empty() && !deviceList.empty()) {
std::string soName;
DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance();
std::shared_ptr<IDecisionAdapter> decisionAdapter = adapterMgrPtr.GetDecisionAdapter(soName);
if (decisionAdapter != nullptr) {
decisionAdapter->FilterDeviceList(deviceList, extra);
} else {
LOGE("GetTrustedDeviceList decisionAdapter is nullptr");
}
}
return DM_OK;
}
int32_t DmDeviceInfoManager::GetLocalDeviceInfo(DmDeviceInfo &info)
{
int32_t ret = softbusConnector_->GetLocalDeviceInfo(info);
if (ret != DM_OK) {
LOGE("GetLocalDeviceInfo failed");
return ret;
}
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,122 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_device_state_manager.h"
#include "dm_adapter_manager.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr<SoftbusConnector> softbusConnector,
std::shared_ptr<DeviceManagerServiceListener> listener)
: softbusConnector_(softbusConnector), listener_(listener)
{
LOGI("DmDeviceStateManager constructor");
profileSoName_ = "libdevicemanagerext_profile.z.so";
}
DmDeviceStateManager::~DmDeviceStateManager()
{
LOGI("DmDeviceStateManager destructor");
softbusConnector_->UnRegisterSoftbusStateCallback("");
}
void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info)
{
LOGI("DmDeviceStateManager::OnDeviceOnline in");
DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance();
std::shared_ptr<IProfileAdapter> profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_);
if (profileAdapter == nullptr) {
LOGE("OnDeviceOnline profile adapter is null");
} else {
uint8_t udid[UDID_BUF_LEN] = {0};
int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(info.deviceId, NodeDeivceInfoKey::NODE_KEY_UDID, udid,
sizeof(udid));
if (ret != DM_OK) {
LOGE("DmDeviceStateManager::OnDeviceOnline GetNodeKeyInfo failed");
} else {
std::string deviceUdid = (char *)udid;
DmDeviceInfo saveInfo = info;
std::string uuid;
SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid);
remoteDeviceInfos_[uuid] = saveInfo;
LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s, uuid = %s",
info.deviceId, deviceUdid.c_str(), uuid.c_str());
//set networkId or udid;
profileAdapter->RegisterProfileListener(pkgName, deviceUdid, shared_from_this());
LOGI("RegisterProfileListener out");
}
}
DmDeviceState state = DEVICE_STATE_ONLINE;
deviceStateMap_[info.deviceId] = DEVICE_STATE_ONLINE;
listener_->OnDeviceStateChange(pkgName, state, info);
LOGI("DmDeviceStateManager::OnDeviceOnline out");
}
void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info)
{
DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance();
std::shared_ptr<IProfileAdapter> profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_);
if (profileAdapter == nullptr) {
LOGE("OnDeviceOffline profile adapter is null");
} else {
profileAdapter->UnRegisterProfileListener(pkgName);
std::string uuid;
SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid);
auto iter = remoteDeviceInfos_.find(std::string(info.deviceId));
if (iter == remoteDeviceInfos_.end()) {
} else {
remoteDeviceInfos_.erase(std::string(info.deviceId));
}
}
DmDeviceState state = DEVICE_STATE_OFFLINE;
deviceStateMap_[info.deviceId] = DEVICE_STATE_OFFLINE;
listener_->OnDeviceStateChange(pkgName, state, info);
}
void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info)
{
deviceStateMap_[info.deviceId] = DEVICE_INFO_CHANGED;
}
void DmDeviceStateManager::OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &info)
{
deviceStateMap_[info.deviceId] = DEVICE_INFO_READY;
}
void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std::string deviceId)
{
//deviceId is uuid;
DmDeviceInfo saveInfo;
auto iter = remoteDeviceInfos_.find(deviceId);
if (iter == remoteDeviceInfos_.end()) {
LOGE("DmDeviceStateManager::OnProfileReady complete not find deviceID = %s", deviceId.c_str());
} else {
saveInfo = iter->second;
}
DmDeviceState state = DEVICE_INFO_READY;
listener_->OnDeviceStateChange(pkgName, state, saveInfo);
}
int32_t DmDeviceStateManager::RegisterSoftbusStateCallback()
{
softbusConnector_->RegisterSoftbusStateCallback(DM_PKG_NAME,
std::shared_ptr<DmDeviceStateManager>(shared_from_this()));
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,119 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dm_discovery_manager.h"
#include "dm_anonymous.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
namespace {
std::string DISCOVERY_TIMEOUT_TASK = "discoveryTimeout";
int32_t DISCOVERY_TIMEOUT = 120;
int32_t SESSION_CANCEL_TIMEOUT = 0;
} // namespace
static void TimeOut(void *data)
{
LOGE("time out ");
DmDiscoveryManager *discoveryMgr = (DmDiscoveryManager *)data;
if (discoveryMgr == nullptr) {
LOGE("time out error");
return;
}
discoveryMgr->HandleDiscoveryTimeout();
}
DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr<SoftbusConnector> softbusConnector,
std::shared_ptr<DeviceManagerServiceListener> listener)
: softbusConnector_(softbusConnector), listener_(listener)
{
LOGI("DmDiscoveryManager constructor");
}
DmDiscoveryManager::~DmDiscoveryManager()
{
LOGI("DmDiscoveryManager destructor");
}
int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo,
const std::string &extra)
{
if (!discoveryQueue_.empty()) {
if (pkgName == discoveryQueue_.front()) {
LOGE("DmDiscoveryManager::StartDeviceDiscovery repeated, pkgName:%s", pkgName.c_str());
return DM_DISCOVERY_REPEATED;
} else {
LOGD("DmDiscoveryManager::StartDeviceDiscovery stop preview discovery first, the preview pkgName is %s",
discoveryQueue_.front().c_str());
StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId);
}
}
discoveryQueue_.push(pkgName);
DmDiscoveryContext context = {pkgName, extra, subscribeInfo.subscribeId};
discoveryContextMap_.emplace(pkgName, context);
softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName,
std::shared_ptr<ISoftbusDiscoveryCallback>(shared_from_this()));
discoveryTimer_ = std::make_shared<DmTimer>(DISCOVERY_TIMEOUT_TASK);
discoveryTimer_->Start(DISCOVERY_TIMEOUT, TimeOut, this);
return softbusConnector_->StartDiscovery(subscribeInfo);
}
int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId)
{
if (!discoveryQueue_.empty()) {
discoveryQueue_.pop();
}
if (!discoveryContextMap_.empty()) {
discoveryContextMap_.erase(pkgName);
softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName);
discoveryTimer_->Stop(SESSION_CANCEL_TIMEOUT);
}
return softbusConnector_->StopDiscovery(subscribeId);
}
void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info)
{
LOGI("DmDiscoveryManager::OnDeviceFound deviceId=%s", GetAnonyString(info.deviceId).c_str());
auto iter = discoveryContextMap_.find(pkgName);
if (iter == discoveryContextMap_.end()) {
LOGE("subscribeId not found by pkgName %s", GetAnonyString(pkgName).c_str());
return;
}
listener_->OnDeviceFound(pkgName, iter->second.subscribeId, info);
}
void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason)
{
LOGI("DmDiscoveryManager::OnDiscoveryFailed subscribeId=%d reason=%d", subscribeId, failedReason);
StopDeviceDiscovery(pkgName, subscribeId);
listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason);
}
void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId)
{
LOGI("DmDiscoveryManager::OnDiscoverySuccess subscribeId=%d", subscribeId);
discoveryContextMap_[pkgName].subscribeId = subscribeId;
listener_->OnDiscoverySuccess(pkgName, subscribeId);
}
void DmDiscoveryManager::HandleDiscoveryTimeout()
{
LOGI("DmDiscoveryManager::HandleDiscoveryTimeout");
StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId);
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,256 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "device_manager_service.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "ipc_cmd_register.h"
#include "ipc_def.h"
#include "ipc_notify_auth_result_req.h"
#include "ipc_notify_device_found_req.h"
#include "ipc_notify_device_state_req.h"
#include "ipc_notify_discover_result_req.h"
#include "ipc_notify_verify_auth_result_req.h"
#include "ipc_server_stub.h"
namespace OHOS {
namespace DistributedHardware {
ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr<IpcReq> pBaseReq, IpcIo &request, uint8_t *buffer,
size_t buffLen)
{
std::shared_ptr<IpcNotifyDeviceStateReq> pReq = std::static_pointer_cast<IpcNotifyDeviceStateReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
int32_t deviceState = pReq->GetDeviceState();
DmDeviceInfo deviceInfo = pReq->GetDeviceInfo();
IpcIoInit(&request, buffer, buffLen, 0);
IpcIoPushString(&request, pkgName.c_str());
IpcIoPushInt32(&request, deviceState);
IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo));
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(IpcIoPopInt32(&reply));
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr<IpcReq> pBaseReq, IpcIo &request, uint8_t *buffer,
size_t buffLen)
{
std::shared_ptr<IpcNotifyDeviceFoundReq> pReq = std::static_pointer_cast<IpcNotifyDeviceFoundReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
uint16_t subscribeId = pReq->GetSubscribeId();
DmDeviceInfo deviceInfo = pReq->GetDeviceInfo();
IpcIoInit(&request, buffer, buffLen, 0);
IpcIoPushString(&request, pkgName.c_str());
IpcIoPushUint16(&request, subscribeId);
IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo));
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, IpcIo &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(IpcIoPopInt32(&reply));
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr<IpcReq> pBaseReq, IpcIo &request, uint8_t *buffer,
size_t buffLen)
{
std::shared_ptr<IpcNotifyDiscoverResultReq> pReq = std::static_pointer_cast<IpcNotifyDiscoverResultReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
uint16_t subscribeId = pReq->GetSubscribeId();
int32_t result = pReq->GetResult();
IpcIoInit(&request, buffer, buffLen, 0);
IpcIoPushString(&request, pkgName.c_str());
IpcIoPushUint16(&request, subscribeId);
IpcIoPushInt32(&request, result);
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, IpcIo &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(IpcIoPopInt32(&reply));
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr<IpcReq> pBaseReq, IpcIo &request, uint8_t *buffer,
size_t buffLen)
{
std::shared_ptr<IpcNotifyAuthResultReq> pReq = std::static_pointer_cast<IpcNotifyAuthResultReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
std::string deviceId = pReq->GetDeviceId();
std::string token = pReq->GetPinToken();
int32_t status = pReq->GetStatus();
int32_t reason = pReq->GetReason();
IpcIoInit(&request, buffer, buffLen, 0);
IpcIoPushString(&request, pkgName.c_str());
IpcIoPushString(&request, deviceId.c_str());
IpcIoPushString(&request, token.c_str());
IpcIoPushInt32(&request, status);
IpcIoPushInt32(&request, reason);
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(IpcIoPopInt32(&reply));
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_VERIFY_AUTH_RESULT, std::shared_ptr<IpcReq> pBaseReq, IpcIo &request, uint8_t *buffer,
size_t buffLen)
{
std::shared_ptr<IpcNotifyVerifyAuthResultReq> pReq =
std::static_pointer_cast<IpcNotifyVerifyAuthResultReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
std::string deviceId = pReq->GetDeviceId();
int32_t result = pReq->GetResult();
int32_t flag = pReq->GetFlag();
IpcIoInit(&request, buffer, buffLen, 0);
IpcIoPushString(&request, pkgName.c_str());
IpcIoPushString(&request, deviceId.c_str());
IpcIoPushInt32(&request, result);
IpcIoPushInt32(&request, flag);
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, IpcIo &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(IpcIoPopInt32(&reply));
return DM_OK;
}
ON_IPC_SERVER_CMD(REGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply)
{
int32_t errCode = RegisterDeviceManagerListener(&req, &reply);
IpcIoPushInt32(&reply, errCode);
}
ON_IPC_SERVER_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply)
{
int32_t errCode = UnRegisterDeviceManagerListener(&req, &reply);
IpcIoPushInt32(&reply, errCode);
}
ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply)
{
LOGI("enter GetTrustedDeviceList.");
std::string pkgName = (const char *)IpcIoPopString(&req, nullptr);
std::string extra = (const char *)IpcIoPopString(&req, nullptr);
std::vector<DmDeviceInfo> deviceList;
int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList);
IpcIoPushInt32(&reply, deviceList.size());
if (deviceList.size() > 0) {
IpcIoPushFlatObj(&reply, deviceList.data(), sizeof(DmDeviceInfo) * deviceList.size());
}
IpcIoPushInt32(&reply, ret);
}
ON_IPC_SERVER_CMD(GET_LOCAL_DEVICE_INFO, IpcIo &req, IpcIo &reply)
{
LOGI("enter GetLocalDeviceInfo.");
DmDeviceInfo dmDeviceInfo;
int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo);
IpcIoPushFlatObj(&reply, &dmDeviceInfo, sizeof(DmDeviceInfo));
IpcIoPushInt32(&reply, ret);
}
ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply)
{
LOGI("StartDeviceDiscovery service listener.");
std::string pkgName = (const char *)IpcIoPopString(&req, nullptr);
std::string extra = (const char *)IpcIoPopString(&req, nullptr);
uint32_t size = 0;
DmSubscribeInfo *pDmSubscribeInfo = (DmSubscribeInfo *)IpcIoPopFlatObj(&req, &size);
int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo, extra);
IpcIoPushInt32(&reply, ret);
}
ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply)
{
LOGI("StopDeviceDiscovery service listener.");
std::string pkgName = (const char *)IpcIoPopString(&req, nullptr);
uint16_t subscribeId = IpcIoPopUint16(&req);
int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId);
IpcIoPushInt32(&reply, ret);
}
ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply)
{
LOGI("AuthenticateDevice service listener.");
std::string pkgName = (const char *)IpcIoPopString(&req, nullptr);
std::string extra = (const char *)IpcIoPopString(&req, nullptr);
std::string deviceId = (const char *)IpcIoPopString(&req, nullptr);
int32_t authType = IpcIoPopInt32(&req);
int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra);
IpcIoPushInt32(&reply, ret);
}
ON_IPC_SERVER_CMD(UNAUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply)
{
LOGI("UnAuthenticateDevice service listener.");
std::string pkgName = (const char *)IpcIoPopString(&req, nullptr);
std::string deviceId = (const char *)IpcIoPopString(&req, nullptr);
int32_t ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId);
IpcIoPushInt32(&reply, ret);
}
ON_IPC_SERVER_CMD(VERIFY_AUTHENTICATION, IpcIo &req, IpcIo &reply)
{
LOGI("VerifyAuthentication service listener.");
std::string pkgName = (const char *)IpcIoPopString(&req, nullptr);
std::string authParam = (const char *)IpcIoPopString(&req, nullptr);
int32_t ret = DeviceManagerService::GetInstance().VerifyAuthentication(pkgName, authParam);
IpcIoPushInt32(&reply, ret);
}
ON_IPC_SERVER_CMD(SERVER_USER_AUTH_OPERATION, IpcIo &req, IpcIo &reply)
{
size_t len = 0;
std::string packName = (const char *)IpcIoPopString(&req, &len);
int32_t action = IpcIoPopInt32(&reply);
DeviceManagerService::GetInstance().SetUserOperation(packName, action);
IpcIoPushInt32(&reply, action);
}
ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr<IpcReq> pBaseReq, IpcIo &request, uint8_t *buffer,
size_t buffLen)
{
std::shared_ptr<IpcNotifyDMFAResultReq> pReq = std::static_pointer_cast<IpcNotifyDMFAResultReq>(pBaseReq);
std::string packagname = pReq->GetPkgName();
std::string paramJson = pReq->GetJsonParam();
IpcIoPushString(&request, packagname.c_str());
IpcIoPushString(&request, paramJson.c_str());
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, IpcIo &request, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(reply.ReadInt32());
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,92 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_server_listener.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "ipc_cmd_register.h"
#include "ipc_def.h"
#include "ipc_server_listenermgr.h"
namespace OHOS {
namespace DistributedHardware {
void IpcServerListener::CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity)
{
identity->handle = svcId->handle;
identity->token = svcId->token;
identity->cookie = svcId->cookie;
#ifdef __LINUX__
identity->ipcContext = svcId->ipcCtx;
#endif
}
int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity *svc)
{
CommonSvcId svcId;
if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DM_OK) {
LOGE("get identity failed.");
return DM_FAILED;
}
CommonSvcToIdentity(&svcId, svc);
return DM_OK;
}
int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp)
{
std::string pkgName = req->GetPkgName();
SvcIdentity svc;
if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) {
LOGE("OnDeviceFound callback get listener failed.");
return DM_FAILED;
}
IpcIo io;
uint8_t data[MAX_DM_IPC_LEN] = {0};
if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) {
LOGD("SetRequest failed cmdCode:%d", cmdCode);
return DM_FAILED;
}
if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) {
LOGD("SendRequest failed cmdCode:%d", cmdCode);
}
return DM_OK;
}
int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp)
{
const std::map<std::string, CommonSvcId> &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners();
for (auto &kv : listenerMap) {
SvcIdentity svc;
IpcIo io;
uint8_t data[MAX_DM_IPC_LEN] = {0};
std::string pkgName = kv.first;
req->SetPkgName(pkgName);
if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) {
LOGD("SetRequest failed cmdCode:%d", cmdCode);
continue;
}
CommonSvcId svcId = kv.second;
CommonSvcToIdentity(&svcId, &svc);
if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DM_OK) {
LOGD("SendRequest failed cmdCode:%d", cmdCode);
}
}
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_server_listenermgr.h"
#include "dm_constants.h"
#include "dm_log.h"
namespace OHOS {
namespace DistributedHardware {
IMPLEMENT_SINGLE_INSTANCE(IpcServerListenermgr);
int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const CommonSvcId *svcId)
{
if (pkgName == "" || svcId == nullptr) {
LOGE("invalid param");
return DM_FAILED;
}
LOGI("new listener register:%s", pkgName.c_str());
std::lock_guard<std::mutex> autoLock(lock_);
dmListenerMap_[pkgName] = *svcId;
return DM_OK;
}
int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId)
{
if (pkgName == "" || svcId == nullptr) {
LOGE("invalid param");
return DM_FAILED;
}
std::lock_guard<std::mutex> autoLock(lock_);
std::map<std::string, CommonSvcId>::iterator iter = dmListenerMap_.find(pkgName);
if (iter == dmListenerMap_.end()) {
LOGE("listener not found for pkg:%s", pkgName.c_str());
return DM_FAILED;
}
*svcId = iter->second;
return DM_OK;
}
int32_t IpcServerListenermgr::UnregisterListener(std::string &pkgName)
{
std::lock_guard<std::mutex> autoLock(lock_);
dmListenerMap_.erase(pkgName);
return DM_OK;
}
const std::map<std::string, CommonSvcId> &IpcServerListenermgr::GetAllListeners()
{
return dmListenerMap_;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <unistd.h>
#include <cstdint>
#include "device_manager_service.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "ipc_server_stub.h"
using namespace OHOS::DistributedHardware;
static void InitAll()
{
const int32_t DM_SERVICE_INIT_DELAY = 2;
sleep(DM_SERVICE_INIT_DELAY);
if (IpcServerStubInit() != DM_OK) {
LOGE("IpcServerStubInit failed");
return;
}
if (DeviceManagerService::GetInstance().Init() != DM_OK) {
LOGE("module init failed");
return;
}
LOGI("DM ipc server Init success");
}
int32_t main(int32_t argc, char *argv[])
{
(void)argc;
(void)argv;
InitAll();
while (1) {
pause();
}
return 0;
}
@@ -0,0 +1,223 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_server_stub.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "dm_subscribe_info.h"
#include "ipc_cmd_register.h"
#include "ipc_def.h"
#include "ipc_server_listenermgr.h"
#include "iproxy_server.h"
#include "liteipc_adapter.h"
#include "ohos_init.h"
#include "samgr_lite.h"
#include "securec.h"
namespace {
const int32_t WAIT_FOR_SERVER = 2;
const int32_t STACK_SIZE = 0x1000;
const int32_t QUEUE_SIZE = 32;
} // namespace
using namespace OHOS::DistributedHardware;
struct DefaultFeatureApi {
INHERIT_SERVER_IPROXY;
};
struct DeviceManagerSamgrService {
INHERIT_SERVICE;
INHERIT_IUNKNOWNENTRY(DefaultFeatureApi);
Identity identity;
};
static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, void *arg)
{
(void)context;
(void)ipcMsg;
(void)data;
if (arg == NULL) {
LOGE("package name is NULL.");
return DM_INVALID_VALUE;
}
CommonSvcId svcId = {0};
std::string pkgName = (const char *)arg;
if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_OK) {
LOGE("not found client by package name.");
free(arg);
arg = NULL;
return DM_FAILED;
}
IpcServerListenermgr::GetInstance().UnregisterListener(pkgName);
free(arg);
arg = NULL;
#ifdef __LINUX__
BinderRelease(svcId.ipcCtx, svcId.handle);
#endif
SvcIdentity sid = {0};
sid.handle = svcId.handle;
sid.token = svcId.token;
sid.cookie = svcId.cookie;
UnregisterDeathCallback(sid, svcId.cbId);
return DM_OK;
}
int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply)
{
LOGI("register service listener.");
size_t len = 0;
uint8_t *name = IpcIoPopString(req, &len);
SvcIdentity *svc = IpcIoPopSvc(req);
if (name == NULL || svc == NULL || len == 0) {
LOGE("get para failed");
return DM_INVALID_VALUE;
}
CommonSvcId svcId = {0};
svcId.handle = svc->handle;
svcId.token = svc->token;
svcId.cookie = svc->cookie;
SvcIdentity sid = *svc;
#ifdef __LINUX__
svcId.ipcCtx = svc->ipcContext;
BinderAcquire(svcId.ipcCtx, svcId.handle);
free(svc);
svc = NULL;
#endif
char *pkgName = (char *)malloc(len + 1);
if (pkgName == NULL) {
LOGE("malloc failed!");
return DM_MALLOC_ERROR;
}
if (strcpy_s(pkgName, len + 1, (const char *)name) != DM_OK) {
LOGE("strcpy_s failed!");
free(pkgName);
return DM_COPY_FAILED;
}
uint32_t cbId = 0;
RegisterDeathCallback(NULL, sid, DeathCb, pkgName, &cbId);
svcId.cbId = cbId;
std::string strPkgName = (const char *)name;
return IpcServerListenermgr::GetInstance().RegisterListener(strPkgName, &svcId);
}
int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply)
{
LOGI("unregister service listener.");
size_t len = 0;
std::string pkgName = (const char *)IpcIoPopString(req, &len);
if (pkgName == "" || len == 0) {
LOGE("get para failed");
return DM_FAILED;
}
CommonSvcId svcId;
if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DM_OK) {
LOGE("not found listener by package name.");
return DM_FAILED;
}
int32_t ret = IpcServerListenermgr::GetInstance().UnregisterListener(pkgName);
if (ret == DM_OK) {
#ifdef __LINUX__
BinderRelease(svcId.ipcCtx, svcId.handle);
#endif
SvcIdentity sid;
sid.handle = svcId.handle;
sid.token = svcId.token;
sid.cookie = svcId.cookie;
ret = UnregisterDeathCallback(sid, svcId.cbId);
}
return ret;
}
static const char *GetName(Service *service)
{
(void)service;
return DEVICE_MANAGER_SERVICE_NAME;
}
static BOOL Initialize(Service *service, Identity identity)
{
if (service == NULL) {
LOGW("invalid param");
return FALSE;
}
DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service;
mgrService->identity = identity;
return TRUE;
}
static BOOL MessageHandle(Service *service, Request *request)
{
if ((service == NULL) || (request == NULL)) {
LOGW("invalid param");
return FALSE;
}
return TRUE;
}
static TaskConfig GetTaskConfig(Service *service)
{
(void)service;
TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL, STACK_SIZE, QUEUE_SIZE, SHARED_TASK};
return config;
}
static int32_t OnRemoteRequest(IServerProxy *iProxy, int32_t funcId, void *origin, IpcIo *req, IpcIo *reply)
{
LOGI("Receive funcId:%d", funcId);
(void)origin;
return IpcCmdRegister::GetInstance().OnIpcServerCmd(funcId, *req, *reply);
}
static void HOS_SystemInit(void)
{
SAMGR_Bootstrap();
return;
}
int32_t IpcServerStubInit(void)
{
HOS_SystemInit();
return DM_OK;
}
static void DevMgrSvcInit(void)
{
sleep(WAIT_FOR_SERVER);
static DeviceManagerSamgrService service = {
.GetName = GetName,
.Initialize = Initialize,
.MessageHandle = MessageHandle,
.GetTaskConfig = GetTaskConfig,
SERVER_IPROXY_IMPL_BEGIN,
.Invoke = OnRemoteRequest,
IPROXY_END,
};
if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) {
LOGE("%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME);
return;
}
if (!SAMGR_GetInstance()->RegisterDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME, GET_IUNKNOWN(service))) {
LOGE("%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME);
return;
}
LOGI("%s, init success", DEVICE_MANAGER_SERVICE_NAME);
}
SYSEX_SERVICE_INIT(DevMgrSvcInit);
@@ -0,0 +1,435 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <memory>
#include "device_manager_service.h"
#include "dm_constants.h"
#include "dm_device_info.h"
#include "dm_log.h"
#include "dm_subscribe_info.h"
#include "ipc_cmd_register.h"
#include "ipc_def.h"
#include "ipc_notify_auth_result_req.h"
#include "ipc_notify_device_found_req.h"
#include "ipc_notify_device_state_req.h"
#include "ipc_notify_discover_result_req.h"
#include "ipc_notify_verify_auth_result_req.h"
#include "ipc_server_stub.h"
namespace OHOS {
namespace DistributedHardware {
ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr<IpcReq> pBaseReq, MessageParcel &data)
{
std::shared_ptr<IpcNotifyDeviceStateReq> pReq = std::static_pointer_cast<IpcNotifyDeviceStateReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
int32_t deviceState = pReq->GetDeviceState();
DmDeviceInfo deviceInfo = pReq->GetDeviceInfo();
if (!data.WriteString(pkgName)) {
LOGE("write pkgName failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt32(deviceState)) {
LOGE("write state failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) {
LOGE("write deviceInfo failed");
return DM_FLATTEN_OBJECT;
}
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(reply.ReadInt32());
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr<IpcReq> pBaseReq, MessageParcel &data)
{
std::shared_ptr<IpcNotifyDeviceFoundReq> pReq = std::static_pointer_cast<IpcNotifyDeviceFoundReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
uint16_t subscribeId = pReq->GetSubscribeId();
DmDeviceInfo deviceInfo = pReq->GetDeviceInfo();
if (!data.WriteString(pkgName)) {
LOGE("write pkgName failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt16(subscribeId)) {
LOGE("write subscribeId failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) {
LOGE("write deviceInfo failed");
return DM_FLATTEN_OBJECT;
}
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, MessageParcel &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(reply.ReadInt32());
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr<IpcReq> pBaseReq, MessageParcel &data)
{
std::shared_ptr<IpcNotifyDiscoverResultReq> pReq = std::static_pointer_cast<IpcNotifyDiscoverResultReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
uint16_t subscribeId = pReq->GetSubscribeId();
int32_t result = pReq->GetResult();
if (!data.WriteString(pkgName)) {
LOGE("write pkgName failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt16(subscribeId)) {
LOGE("write subscribeId failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt32(result)) {
LOGE("write result failed");
return DM_FLATTEN_OBJECT;
}
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, MessageParcel &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(reply.ReadInt32());
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr<IpcReq> pBaseReq, MessageParcel &data)
{
std::shared_ptr<IpcNotifyAuthResultReq> pReq = std::static_pointer_cast<IpcNotifyAuthResultReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
std::string deviceId = pReq->GetDeviceId();
std::string token = pReq->GetPinToken();
int32_t status = pReq->GetStatus();
int32_t reason = pReq->GetReason();
if (!data.WriteString(pkgName)) {
LOGE("write pkgName failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteString(deviceId)) {
LOGE("write deviceId failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteString(token)) {
LOGE("write token failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt32(status)) {
LOGE("write status failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt32(reason)) {
LOGE("write reason failed");
return DM_FLATTEN_OBJECT;
}
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, MessageParcel &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(reply.ReadInt32());
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_VERIFY_AUTH_RESULT, std::shared_ptr<IpcReq> pBaseReq, MessageParcel &data)
{
std::shared_ptr<IpcNotifyVerifyAuthResultReq> pReq =
std::static_pointer_cast<IpcNotifyVerifyAuthResultReq>(pBaseReq);
std::string pkgName = pReq->GetPkgName();
std::string deviceId = pReq->GetDeviceId();
int32_t result = pReq->GetResult();
int32_t flag = pReq->GetFlag();
if (!data.WriteString(pkgName)) {
LOGE("write pkgName failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteString(deviceId)) {
LOGE("write deviceId failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt32(result)) {
LOGE("write result failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteInt32(flag)) {
LOGE("write flag failed");
return DM_FLATTEN_OBJECT;
}
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_VERIFY_AUTH_RESULT, MessageParcel &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(reply.ReadInt32());
return DM_OK;
}
ON_IPC_SET_REQUEST(SERVER_DEVICE_FA_NOTIFY, std::shared_ptr<IpcReq> pBaseReq, MessageParcel &data)
{
std::shared_ptr<IpcNotifyDMFAResultReq> pReq = std::static_pointer_cast<IpcNotifyDMFAResultReq>(pBaseReq);
std::string packagname = pReq->GetPkgName();
std::string paramJson = pReq->GetJsonParam();
if (!data.WriteString(packagname)) {
LOGE("write pkgName failed");
return DM_FLATTEN_OBJECT;
}
if (!data.WriteString(paramJson)) {
LOGE("write paramJson failed");
return DM_FLATTEN_OBJECT;
}
return DM_OK;
}
ON_IPC_READ_RESPONSE(SERVER_DEVICE_FA_NOTIFY, MessageParcel &reply, std::shared_ptr<IpcRsp> pBaseRsp)
{
pBaseRsp->SetErrCode(reply.ReadInt32());
return DM_OK;
}
ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
std::string extra = data.ReadString();
LOGI("pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str());
std::vector<DmDeviceInfo> deviceList;
int32_t result = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList);
int32_t infoNum = deviceList.size();
DmDeviceInfo deviceInfo;
if (!reply.WriteInt32(infoNum)) {
LOGE("write infoNum failed");
return DM_WRITE_FAILED;
}
if (!deviceList.empty()) {
for (; !deviceList.empty();) {
deviceInfo = deviceList.back();
deviceList.pop_back();
if (!reply.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) {
LOGE("write subscribeInfo failed");
return DM_WRITE_FAILED;
}
}
}
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
LOGI("GET_TRUST_DEVICE_LIST ok pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str());
return DM_OK;
}
ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
sptr<IRemoteObject> listener = data.ReadRemoteObject();
int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener);
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName);
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
std::string extra = data.ReadString();
DmSubscribeInfo *subscribeInfo = (DmSubscribeInfo *)data.ReadRawData(sizeof(DmSubscribeInfo));
int32_t result = DM_POINT_NULL;
if (subscribeInfo != nullptr) {
LOGI("pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId);
result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo, extra);
}
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
uint16_t subscribeId = data.ReadInt32();
LOGI("pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeId);
int32_t result = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId);
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
std::string extra = data.ReadString();
std::string deviceId = data.ReadString();
int32_t authType = data.ReadInt32();
int32_t result = DM_OK;
result = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra);
LOGE("AuthenticateDevice");
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
LOGE("AuthenticateDevice %d", result);
return DM_OK;
}
ON_IPC_CMD(UNAUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
std::string deviceId = data.ReadString();
int32_t result = DM_OK;
LOGI("pkgName:%s, trustedDeviceInfo: %d", pkgName.c_str(), deviceId.c_str());
result = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId);
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(VERIFY_AUTHENTICATION, MessageParcel &data, MessageParcel &reply)
{
LOGI("ON_IPC_CMD VERIFY_AUTHENTICATION start");
std::string authPara = data.ReadString();
int32_t result = DeviceManagerService::GetInstance().VerifyAuthentication(authPara);
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(GET_LOCAL_DEVICE_INFO, MessageParcel &data, MessageParcel &reply)
{
DmDeviceInfo localDeviceInfo;
int32_t result = 0;
result = DeviceManagerService::GetInstance().GetLocalDeviceInfo(localDeviceInfo);
if (!reply.WriteRawData(&localDeviceInfo, sizeof(DmDeviceInfo))) {
LOGE("write subscribeInfo failed");
}
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
LOGI("localDeviceInfo: %s", localDeviceInfo.deviceId);
return DM_OK;
}
ON_IPC_CMD(GET_UDID_BY_NETWORK, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
std::string netWorkId = data.ReadString();
std::string udid;
int32_t result = DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, netWorkId, udid);
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
if (!reply.WriteString(udid)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(GET_UUID_BY_NETWORK, MessageParcel &data, MessageParcel &reply)
{
std::string pkgName = data.ReadString();
std::string netWorkId = data.ReadString();
std::string uuid;
int32_t result = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid);
if (!reply.WriteInt32(result)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
if (!reply.WriteString(uuid)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return DM_OK;
}
ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply)
{
std::string packName = data.ReadString();
DmAuthParam authParam;
int32_t ret = DM_OK;
ret = DeviceManagerService::GetInstance().GetFaParam(packName, authParam);
int32_t appIconLen = authParam.imageinfo.GetAppIconLen();
int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen();
if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) ||
!reply.WriteString(authParam.authToken) || !reply.WriteString(authParam.packageName) ||
!reply.WriteString(authParam.appName) || !reply.WriteString(authParam.appDescription) ||
!reply.WriteInt32(authParam.business) || !reply.WriteInt32(authParam.pincode) ||
!reply.WriteInt32(appIconLen) || !reply.WriteInt32(appThumbnailLen)) {
LOGE("write reply failed");
return DM_IPC_FLATTEN_OBJECT;
}
if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) {
if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) {
LOGE("write appIcon failed");
return DM_IPC_FLATTEN_OBJECT;
}
}
if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) {
if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) {
LOGE("write appThumbnail failed");
return DM_IPC_FLATTEN_OBJECT;
}
}
return DM_OK;
}
ON_IPC_CMD(SERVER_USER_AUTH_OPERATION, MessageParcel &data, MessageParcel &reply)
{
std::string packageName = data.ReadString();
int32_t action = data.ReadInt32();
int result = DeviceManagerService::GetInstance().SetUserOperation(packageName, action);
if (!reply.WriteInt32(action)) {
LOGE("write result failed");
return DM_WRITE_FAILED;
}
return result;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_server_client_proxy.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "ipc_cmd_register.h"
#include "ipc_def.h"
#include "ipc_types.h"
namespace OHOS {
namespace DistributedHardware {
int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp)
{
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
LOGE("remote service null");
return DM_POINT_NULL;
}
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) {
return DM_IPC_FAILED;
}
if (remote->SendRequest(cmdCode, data, reply, option) != DM_OK) {
LOGE("SendRequest fail, cmd:%d", cmdCode);
return DM_IPC_FAILED;
}
return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp);
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_server_listener.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "ipc_server_stub.h"
namespace OHOS {
namespace DistributedHardware {
int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp)
{
std::string pkgName = req->GetPkgName();
sptr<IpcRemoteBroker> listener = IpcServerStub::GetInstance().GetDmListener(pkgName);
if (listener == nullptr) {
LOGI("cannot get listener for package:%s.", pkgName.c_str());
return DM_POINT_NULL;
}
return listener->SendCmd(cmdCode, req, rsp);
}
int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp)
{
std::map<std::string, sptr<IRemoteObject>> listeners = IpcServerStub::GetInstance().GetDmListener();
for (auto iter : listeners) {
auto pkgName = iter.first;
auto remote = iter.second;
req->SetPkgName(pkgName);
sptr<IpcRemoteBroker> listener = iface_cast<IpcRemoteBroker>(remote);
listener->SendCmd(cmdCode, req, rsp);
}
return DM_OK;
}
} // namespace DistributedHardware
} // namespace OHOS
@@ -0,0 +1,187 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_server_stub.h"
#include <algorithm>
#include <thread>
#include "device_manager_impl.h"
#include "device_manager_service.h"
#include "dm_constants.h"
#include "dm_log.h"
#include "if_system_ability_manager.h"
#include "ipc_cmd_register.h"
#include "ipc_skeleton.h"
#include "ipc_types.h"
#include "iservice_registry.h"
#include "string_ex.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace DistributedHardware {
IMPLEMENT_SINGLE_INSTANCE(IpcServerStub);
const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&IpcServerStub::GetInstance());
IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true)
{
registerToService_ = false;
state_ = ServiceRunningState::STATE_NOT_START;
}
void IpcServerStub::OnStart()
{
LOGI("IpcServerStub::OnStart start");
if (state_ == ServiceRunningState::STATE_RUNNING) {
LOGD("IpcServerStub has already started.");
return;
}
if (!Init()) {
LOGE("failed to init IpcServerStub");
return;
}
state_ = ServiceRunningState::STATE_RUNNING;
}
bool IpcServerStub::Init()
{
LOGI("IpcServerStub::Init ready to init.");
if (!registerToService_) {
bool ret = Publish(this);
if (!ret) {
LOGE("IpcServerStub::Init Publish failed!");
return false;
}
registerToService_ = true;
}
std::thread{[] { DeviceManagerService::GetInstance().Init(); }}.detach();
return true;
}
void IpcServerStub::OnStop()
{
LOGI("IpcServerStub::OnStop ready to stop service.");
state_ = ServiceRunningState::STATE_NOT_START;
registerToService_ = false;
}
int32_t IpcServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
LOGI("code = %d, flags= %d.", code, option.GetFlags());
int32_t ret = DM_OK;
ret = IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply);
if (ret == DM_IPC_NOT_REGISTER_FUNC) {
LOGW("unsupport code: %d", code);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
return ret;
}
int32_t IpcServerStub::SendCmd(int32_t cmdCode, std::shared_ptr<IpcReq> req, std::shared_ptr<IpcRsp> rsp)
{
return DM_OK;
}
ServiceRunningState IpcServerStub::QueryServiceState() const
{
return state_;
}
int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr<IRemoteObject> listener)
{
if (pkgName.empty() || listener == nullptr) {
LOGE("Error: parameter invalid");
return DM_POINT_NULL;
}
LOGI("In, pkgName: %s", pkgName.c_str());
std::lock_guard<std::mutex> autoLock(listenerLock_);
auto iter = dmListener_.find(pkgName);
if (iter != dmListener_.end()) {
LOGI("RegisterDeviceManagerListener: listener already exists");
return DM_OK;
}
sptr<AppDeathRecipient> appRecipient = sptr<AppDeathRecipient>(new AppDeathRecipient());
if (!listener->AddDeathRecipient(appRecipient)) {
LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed");
}
dmListener_[pkgName] = listener;
appRecipient_[pkgName] = appRecipient;
return DM_OK;
}
int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName)
{
if (pkgName.empty()) {
LOGE("Error: parameter invalid");
return DM_POINT_NULL;
}
LOGI("In, pkgName: %s", pkgName.c_str());
std::lock_guard<std::mutex> autoLock(listenerLock_);
auto listenerIter = dmListener_.find(pkgName);
if (listenerIter == dmListener_.end()) {
LOGI("UnRegisterDeviceManagerListener: listener not exists");
return DM_OK;
}
auto recipientIter = appRecipient_.find(pkgName);
if (recipientIter == appRecipient_.end()) {
LOGI("UnRegisterDeviceManagerListener: appRecipient not exists");
dmListener_.erase(pkgName);
return DM_OK;
}
auto listener = listenerIter->second;
auto appRecipient = recipientIter->second;
listener->RemoveDeathRecipient(appRecipient);
appRecipient_.erase(pkgName);
dmListener_.erase(pkgName);
return DM_OK;
}
const std::map<std::string, sptr<IRemoteObject>> &IpcServerStub::GetDmListener()
{
return dmListener_;
}
const sptr<IpcRemoteBroker> IpcServerStub::GetDmListener(std::string pkgName) const
{
auto iter = dmListener_.find(pkgName);
if (iter == dmListener_.end()) {
return nullptr;
}
auto remote = iter->second;
sptr<IpcRemoteBroker> dmListener = iface_cast<IpcRemoteBroker>(remote);
return dmListener;
}
void AppDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
LOGW("AppDeathRecipient: OnRemoteDied");
std::map<std::string, sptr<IRemoteObject>> listeners = IpcServerStub::GetInstance().GetDmListener();
std::string pkgName;
for (auto iter : listeners) {
if (iter.second == remote.promote()) {
pkgName = iter.first;
break;
}
}
if (pkgName.empty()) {
LOGE("AppDeathRecipient: OnRemoteDied, no pkgName matched");
return;
}
LOGI("AppDeathRecipient: OnRemoteDied for %s", pkgName.c_str());
IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName);
}
} // namespace DistributedHardware
} // namespace OHOS