• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "softbus_proxychannel_message.h"
17 
18 #include <securec.h>
19 #include <stdatomic.h>
20 
21 #include "auth_interface.h"
22 #include "bus_center_manager.h"
23 #include "lnn_ohos_account_adapter.h"
24 #include "softbus_access_token_adapter.h"
25 #include "softbus_adapter_crypto.h"
26 #include "softbus_adapter_mem.h"
27 #include "softbus_adapter_socket.h"
28 #include "softbus_def.h"
29 #include "softbus_datahead_transform.h"
30 #include "softbus_error_code.h"
31 #include "softbus_json_utils.h"
32 #include "softbus_message_open_channel.h"
33 #include "softbus_proxychannel_manager.h"
34 #include "softbus_utils.h"
35 #include "trans_log.h"
36 #include "trans_session_account_adapter.h"
37 
38 
39 static _Atomic int32_t g_proxyPktHeadSeq = 2048;
40 
TransProxyParseMessageHead(char * data,int32_t len,ProxyMessage * msg)41 static int32_t TransProxyParseMessageHead(char *data, int32_t len, ProxyMessage *msg)
42 {
43     char *ptr = data;
44     uint8_t firstByte = *ptr;
45     ptr += sizeof(int8_t);
46     int8_t version = (firstByte >> VERSION_SHIFT) & FOUR_BIT_MASK;
47     msg->msgHead.type = firstByte & FOUR_BIT_MASK;
48     if (version != VERSION || msg->msgHead.type >= PROXYCHANNEL_MSG_TYPE_MAX) {
49         TRANS_LOGE(TRANS_CTRL, "parseMessage: unsupported message, version=%{public}d, type=%{public}d",
50             version, msg->msgHead.type);
51         return SOFTBUS_TRANS_INVALID_MESSAGE_TYPE;
52     }
53 
54     msg->msgHead.cipher = *ptr;
55     ptr += sizeof(int8_t);
56     msg->msgHead.peerId = (int16_t)SoftBusBEtoLEs(*(uint16_t *)ptr);
57     ptr += sizeof(uint16_t);
58     msg->msgHead.myId = (int16_t)SoftBusBEtoLEs(*(uint16_t *)ptr);
59     ptr += sizeof(uint16_t);
60     msg->msgHead.reserved = (int16_t)SoftBusBEtoLEs(*(uint16_t *)ptr);
61     msg->data = data + sizeof(ProxyMessageHead);
62     msg->dateLen = len - sizeof(ProxyMessageHead);
63 
64     return SOFTBUS_OK;
65 }
66 
TransProxyPackMessageHead(ProxyMessageHead * msgHead,uint8_t * buf,uint32_t size)67 static void TransProxyPackMessageHead(ProxyMessageHead *msgHead, uint8_t *buf, uint32_t size)
68 {
69     if (size < PROXY_CHANNEL_HEAD_LEN) {
70         TRANS_LOGE(TRANS_CTRL, "proxy head not enough");
71         return;
72     }
73     uint32_t offset = 0;
74     *buf = msgHead->type;
75     offset += sizeof(uint8_t);
76     *(buf + offset) = msgHead->cipher;
77     offset += sizeof(uint8_t);
78     *(uint16_t *)(buf + offset) = SoftBusLEtoBEs((uint16_t)msgHead->myId);
79     offset += sizeof(uint16_t);
80     *(uint16_t *)(buf + offset) = SoftBusLEtoBEs((uint16_t)msgHead->peerId);
81     offset += sizeof(uint16_t);
82     *(uint16_t *)(buf + offset) = SoftBusLEtoBEs((uint16_t)msgHead->reserved);
83 }
84 
GetRemoteUdidByBtMac(const char * peerMac,char * udid,int32_t len)85 static int32_t GetRemoteUdidByBtMac(const char *peerMac, char *udid, int32_t len)
86 {
87     char networkId[NETWORK_ID_BUF_LEN] = {0};
88     char *tmpMac = NULL;
89     Anonymize(peerMac, &tmpMac);
90     int32_t ret = LnnGetNetworkIdByBtMac(peerMac, networkId, sizeof(networkId));
91     if (ret != SOFTBUS_OK) {
92         TRANS_LOGE(TRANS_CTRL, "LnnGetNetworkIdByBtMac fail, peerMac=%{public}s", AnonymizeWrapper(tmpMac));
93         AnonymizeFree(tmpMac);
94         return ret;
95     }
96     ret = LnnGetRemoteStrInfo(networkId, STRING_KEY_DEV_UDID, udid, len);
97     if (ret != SOFTBUS_OK) {
98         TRANS_LOGE(TRANS_CTRL, "LnnGetRemoteStrInfo UDID fail, peerMac=%{public}s", tmpMac);
99     }
100     AnonymizeFree(tmpMac);
101     return ret;
102 }
103 
GetRemoteBtMacByUdidHash(const uint8_t * udidHash,uint32_t udidHashLen,char * brMac,int32_t len)104 static int32_t GetRemoteBtMacByUdidHash(const uint8_t *udidHash, uint32_t udidHashLen, char *brMac, int32_t len)
105 {
106     char networkId[NETWORK_ID_BUF_LEN] = {0};
107     int32_t ret = LnnGetNetworkIdByUdidHash(udidHash, udidHashLen, networkId, sizeof(networkId), true);
108     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "LnnGetNetworkIdByUdidHash fail");
109 
110     ret = LnnGetRemoteStrInfo(networkId, STRING_KEY_BT_MAC, brMac, len);
111     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "GetRemoteBtMac fail");
112 
113     return SOFTBUS_OK;
114 }
115 
TransProxyGetAuthConnInfo(uint32_t connId,AuthConnInfo * connInfo)116 static int32_t TransProxyGetAuthConnInfo(uint32_t connId, AuthConnInfo *connInfo)
117 {
118     ConnectionInfo info = { 0 };
119     int32_t ret = ConnGetConnectionInfo(connId, &info);
120     TRANS_CHECK_AND_RETURN_RET_LOGE(
121         ret == SOFTBUS_OK, ret, TRANS_CTRL, "ConnGetConnectionInfo fail, connId=%{public}u", connId);
122     switch (info.type) {
123         case CONNECT_TCP:
124             connInfo->type = AUTH_LINK_TYPE_WIFI;
125             if (strcpy_s(connInfo->info.ipInfo.ip, IP_LEN, info.socketInfo.addr) != EOK) {
126                 TRANS_LOGE(TRANS_CTRL, "strcpy_s ip fail.");
127                 return SOFTBUS_STRCPY_ERR;
128             }
129             break;
130         case CONNECT_BR:
131             connInfo->type = AUTH_LINK_TYPE_BR;
132             if (strcpy_s(connInfo->info.brInfo.brMac, BT_MAC_LEN, info.brInfo.brMac) != EOK) {
133                 TRANS_LOGE(TRANS_CTRL, "strcpy_s brMac fail.");
134                 return SOFTBUS_STRCPY_ERR;
135             }
136             break;
137         case CONNECT_BLE:
138             connInfo->type = AUTH_LINK_TYPE_BLE;
139             if (strcpy_s(connInfo->info.bleInfo.bleMac, BT_MAC_LEN, info.bleInfo.bleMac) != EOK) {
140                 TRANS_LOGE(TRANS_CTRL, "strcpy_s brMac fail.");
141                 return SOFTBUS_STRCPY_ERR;
142             }
143             if (memcpy_s(connInfo->info.bleInfo.deviceIdHash, UDID_HASH_LEN,
144                 info.bleInfo.deviceIdHash, UDID_HASH_LEN) != EOK) {
145                 TRANS_LOGE(TRANS_CTRL, "memcpy_s brMac fail.");
146                 return SOFTBUS_MEM_ERR;
147             }
148             connInfo->info.bleInfo.protocol = info.bleInfo.protocol;
149             connInfo->info.bleInfo.psm = (int32_t)info.bleInfo.psm;
150             break;
151         default:
152             TRANS_LOGE(TRANS_CTRL, "unexpected conn type=%{public}d.", info.type);
153             return SOFTBUS_TRANS_UNEXPECTED_CONN_TYPE;
154     }
155     return SOFTBUS_OK;
156 }
157 
ConvertBrConnInfo2BleConnInfo(AuthConnInfo * connInfo)158 static int32_t ConvertBrConnInfo2BleConnInfo(AuthConnInfo *connInfo)
159 {
160     char udid[UDID_BUF_LEN] = {0};
161     int32_t ret = GetRemoteUdidByBtMac(connInfo->info.brInfo.brMac, udid, UDID_BUF_LEN);
162     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get udid by btmac fail");
163 
164     ret = SoftBusGenerateStrHash((unsigned char *)udid, strlen(udid), connInfo->info.bleInfo.deviceIdHash);
165     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "generate udid hash fail");
166 
167     connInfo->type = AUTH_LINK_TYPE_BLE;
168     return SOFTBUS_OK;
169 }
170 
ConvertBleConnInfo2BrConnInfo(AuthConnInfo * connInfo)171 static int32_t ConvertBleConnInfo2BrConnInfo(AuthConnInfo *connInfo)
172 {
173     char brMac[BT_MAC_LEN] = {0};
174     int32_t ret = GetRemoteBtMacByUdidHash(connInfo->info.bleInfo.deviceIdHash, UDID_HASH_LEN, brMac, BT_MAC_LEN);
175     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "get btmac by udid fail");
176 
177     if (strcpy_s(connInfo->info.brInfo.brMac, BT_MAC_LEN, brMac) != EOK) {
178         TRANS_LOGE(TRANS_CTRL, "copy br mac fail");
179         return SOFTBUS_STRCPY_ERR;
180     }
181     connInfo->type = AUTH_LINK_TYPE_BR;
182     return SOFTBUS_OK;
183 }
184 
GetAuthIdByHandshakeMsg(uint32_t connId,uint8_t cipher,AuthHandle * authHandle,int32_t index)185 static int32_t GetAuthIdByHandshakeMsg(uint32_t connId, uint8_t cipher, AuthHandle *authHandle, int32_t index)
186 {
187     AuthConnInfo connInfo;
188     int32_t ret = TransProxyGetAuthConnInfo(connId, &connInfo);
189     TRANS_CHECK_AND_RETURN_RET_LOGE(
190         ret == SOFTBUS_OK, ret, TRANS_CTRL, "get connInfo fail connId=%{public}d", connId);
191     bool isBle = ((cipher & USE_BLE_CIPHER) != 0);
192     if (isBle && connInfo.type == AUTH_LINK_TYPE_BR) {
193         ret = ConvertBrConnInfo2BleConnInfo(&connInfo);
194         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret,
195             TRANS_CTRL, "ConvertBrConnInfo2BleConnInfo fail, connInfoType=%{public}d", connInfo.type);
196     } else if (!isBle && connInfo.type == AUTH_LINK_TYPE_BLE) {
197         ret = ConvertBleConnInfo2BrConnInfo(&connInfo);
198         TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret,
199             TRANS_CTRL, "ConvertBleConnInfo2BrConnInfo fail, connInfoType=%{public}d", connInfo.type);
200     }
201     bool isAuthServer = !((cipher & AUTH_SERVER_SIDE) != 0);
202     authHandle->type = connInfo.type;
203     authHandle->authId = AuthGetIdByConnInfo(&connInfo, isAuthServer, false);
204     if (authHandle->authId == AUTH_INVALID_ID) {
205         if (AuthGetAuthHandleByIndex(&connInfo, isAuthServer, index, authHandle) != SOFTBUS_OK &&
206             AuthGetAuthHandleByIndex(&connInfo, !isAuthServer, index, authHandle) != SOFTBUS_OK) {
207             TRANS_LOGE(TRANS_CTRL, "get auth handle fail");
208             return SOFTBUS_NOT_FIND;
209         }
210     }
211     return SOFTBUS_OK;
212 }
213 
GetAuthIdReDecrypt(AuthHandle * authHandle,ProxyMessage * msg,uint8_t * decData,uint32_t * decDataLen)214 static int32_t GetAuthIdReDecrypt(AuthHandle *authHandle, ProxyMessage *msg, uint8_t *decData, uint32_t *decDataLen)
215 {
216     AuthConnInfo connInfo;
217     (void)memset_s(&connInfo, sizeof(AuthConnInfo), 0, sizeof(AuthConnInfo));
218     int32_t ret = TransProxyGetAuthConnInfo(msg->connId, &connInfo);
219     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret,
220         TRANS_CTRL, "get connInfo fail connId=%{public}d", msg->connId);
221     int32_t index = (int32_t)SoftBusLtoHl(*(uint32_t *)msg->data);
222     if (AuthGetAuthHandleByIndex(&connInfo, false, index, authHandle) != SOFTBUS_OK &&
223         AuthGetAuthHandleByIndex(&connInfo, true, index, authHandle) != SOFTBUS_OK) {
224         TRANS_LOGE(TRANS_CTRL, "get auth handle fail");
225         return SOFTBUS_NOT_FIND;
226     }
227     return AuthDecrypt(authHandle, (uint8_t *)msg->data, (uint32_t)msg->dateLen, decData, decDataLen);
228 }
229 
GetBrMacFromConnInfo(uint32_t connId,char * peerBrMac,uint32_t len)230 int32_t GetBrMacFromConnInfo(uint32_t connId, char *peerBrMac, uint32_t len)
231 {
232     AuthConnInfo connInfo;
233 
234     if (peerBrMac == NULL || len <= 0 || len > BT_MAC_LEN) {
235         return SOFTBUS_INVALID_PARAM;
236     }
237     int32_t ret = TransProxyGetAuthConnInfo(connId, &connInfo);
238     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret,
239         TRANS_CTRL, "get connInfo fail connId=%{public}d", connId);
240 
241     if (strcpy_s(peerBrMac, len, connInfo.info.brInfo.brMac) != EOK) {
242         TRANS_LOGE(TRANS_CTRL, "copy brMac fail.");
243         return SOFTBUS_STRCPY_ERR;
244     }
245     return SOFTBUS_OK;
246 }
247 
TransProxyParseMessageNoDecrypt(ProxyMessage * msg)248 static int32_t TransProxyParseMessageNoDecrypt(ProxyMessage *msg)
249 {
250     if (msg->dateLen > (PROXY_BYTES_LENGTH_MAX + OVERHEAD_LEN)) {
251         TRANS_LOGE(TRANS_CTRL, "The data length of the ProxyMessage is abnormal!");
252         return SOFTBUS_TRANS_INVALID_DATA_LENGTH;
253     }
254     uint8_t *allocData = (uint8_t *)SoftBusCalloc((uint32_t)msg->dateLen);
255     if (allocData == NULL) {
256         TRANS_LOGE(TRANS_CTRL, "malloc data fail");
257         return SOFTBUS_MALLOC_ERR;
258     }
259     if (memcpy_s(allocData, msg->dateLen, msg->data, msg->dateLen) != EOK) {
260         TRANS_LOGE(TRANS_CTRL, "memcpy data fail");
261         SoftBusFree(allocData);
262         return SOFTBUS_MEM_ERR;
263     }
264     msg->data = (char *)allocData;
265     return SOFTBUS_OK;
266 }
267 
TransProxyParseMessage(char * data,int32_t len,ProxyMessage * msg,AuthHandle * auth)268 int32_t TransProxyParseMessage(char *data, int32_t len, ProxyMessage *msg, AuthHandle *auth)
269 {
270     TRANS_CHECK_AND_RETURN_RET_LOGE(len > PROXY_CHANNEL_HEAD_LEN,
271         SOFTBUS_INVALID_PARAM, TRANS_CTRL, "parseMessage: invalid message len, len=%{public}d", len);
272     int32_t ret = TransProxyParseMessageHead(data, len, msg);
273     TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_CTRL, "TransProxyParseMessageHead fail!");
274     if ((msg->msgHead.cipher & ENCRYPTED) != 0) {
275         if ((uint32_t)msg->dateLen < (sizeof(uint32_t) + OVERHEAD_LEN) ||
276             (uint32_t)msg->dateLen > (PROXY_BYTES_LENGTH_MAX + OVERHEAD_LEN + sizeof(uint32_t))) {
277             TRANS_LOGE(TRANS_CTRL, "The data length of the ProxyMessage is abnormal!");
278             return SOFTBUS_TRANS_INVALID_DATA_LENGTH;
279         }
280         if (msg->msgHead.type == PROXYCHANNEL_MSG_TYPE_HANDSHAKE) {
281             TRANS_LOGD(TRANS_CTRL, "prxoy recv handshake cipher=0x%{public}02x", msg->msgHead.cipher);
282             ret = GetAuthIdByHandshakeMsg(msg->connId, msg->msgHead.cipher, auth,
283                 (int32_t)SoftBusLtoHl(*(uint32_t *)msg->data));
284         } else {
285             ret = TransProxyGetAuthId(msg->msgHead.myId, auth);
286         }
287         if (ret != SOFTBUS_OK || auth->authId == AUTH_INVALID_ID) {
288             TRANS_LOGE(TRANS_CTRL, "get authId fail, connId=%{public}d, myChannelId=%{public}d, type=%{public}d",
289                 msg->connId, msg->msgHead.myId, msg->msgHead.type);
290             return SOFTBUS_AUTH_NOT_FOUND;
291         }
292         msg->authHandle = (*auth);
293         uint32_t decDataLen = AuthGetDecryptSize((uint32_t)msg->dateLen);
294         uint8_t *decData = (uint8_t *)SoftBusCalloc(decDataLen);
295         if (decData == NULL) {
296             return SOFTBUS_MALLOC_ERR;
297         }
298         msg->keyIndex = (int32_t)SoftBusLtoHl(*(uint32_t *)msg->data);
299         if (AuthDecrypt(auth, (uint8_t *)msg->data, (uint32_t)msg->dateLen, decData, &decDataLen) != SOFTBUS_OK &&
300             GetAuthIdReDecrypt(auth, msg, decData, &decDataLen) != SOFTBUS_OK) {
301             SoftBusFree(decData);
302             TRANS_LOGE(TRANS_CTRL, "parse msg decrypt fail");
303             return SOFTBUS_DECRYPT_ERR;
304         }
305         msg->data = (char *)decData;
306         msg->dateLen = (int32_t)decDataLen;
307     } else {
308         ret = TransProxyParseMessageNoDecrypt(msg);
309         if (ret != SOFTBUS_OK) {
310             TRANS_LOGE(TRANS_CTRL, "trans not need decrypt msg fail, ret=%{public}d", ret);
311             return ret;
312         }
313     }
314     return SOFTBUS_OK;
315 }
316 
PackPlaintextMessage(ProxyMessageHead * msg,ProxyDataInfo * dataInfo)317 int32_t PackPlaintextMessage(ProxyMessageHead *msg, ProxyDataInfo *dataInfo)
318 {
319     if (msg == NULL || dataInfo == NULL) {
320         TRANS_LOGE(TRANS_CTRL, "invalid param.");
321         return SOFTBUS_INVALID_PARAM;
322     }
323     uint32_t connHeadLen = ConnGetHeadSize();
324     uint32_t size = PROXY_CHANNEL_HEAD_LEN + connHeadLen + dataInfo->inLen;
325     uint8_t *buf = (uint8_t *)SoftBusCalloc(size);
326     if (buf == NULL) {
327         TRANS_LOGE(TRANS_CTRL, "malloc proxy buf fail, myChannelId=%{public}d", msg->myId);
328         return SOFTBUS_MALLOC_ERR;
329     }
330     TransProxyPackMessageHead(msg, buf + connHeadLen, PROXY_CHANNEL_HEAD_LEN);
331     if (memcpy_s(buf + connHeadLen + PROXY_CHANNEL_HEAD_LEN, size - connHeadLen - PROXY_CHANNEL_HEAD_LEN,
332         dataInfo->inData, dataInfo->inLen) != EOK) {
333         TRANS_LOGE(TRANS_CTRL, "plaint ext message memcpy fail.");
334         SoftBusFree(buf);
335         return SOFTBUS_MEM_ERR;
336     }
337     dataInfo->outData = buf;
338     dataInfo->outLen = size;
339     return SOFTBUS_OK;
340 }
341 
PackEncryptedMessage(ProxyMessageHead * msg,AuthHandle authHandle,ProxyDataInfo * dataInfo)342 static int32_t PackEncryptedMessage(ProxyMessageHead *msg, AuthHandle authHandle, ProxyDataInfo *dataInfo)
343 {
344     if (authHandle.authId == AUTH_INVALID_ID) {
345         TRANS_LOGE(TRANS_CTRL, "invalid authId, myChannelId=%{public}d", msg->myId);
346         return SOFTBUS_INVALID_PARAM;
347     }
348     uint32_t size = ConnGetHeadSize() + PROXY_CHANNEL_HEAD_LEN +
349         AuthGetEncryptSize(authHandle.authId, dataInfo->inLen);
350     uint8_t *buf = (uint8_t *)SoftBusCalloc(size);
351     if (buf == NULL) {
352         TRANS_LOGE(TRANS_CTRL, "malloc enc buf fail, myChannelId=%{public}d", msg->myId);
353         return SOFTBUS_MALLOC_ERR;
354     }
355     TransProxyPackMessageHead(msg, buf + ConnGetHeadSize(), PROXY_CHANNEL_HEAD_LEN);
356     uint8_t *encData = buf + ConnGetHeadSize() + PROXY_CHANNEL_HEAD_LEN;
357     uint32_t encDataLen = size - ConnGetHeadSize() - PROXY_CHANNEL_HEAD_LEN;
358     if (AuthEncrypt(&authHandle, dataInfo->inData, dataInfo->inLen, encData, &encDataLen) != SOFTBUS_OK) {
359         SoftBusFree(buf);
360         TRANS_LOGE(TRANS_CTRL, "pack msg encrypt fail, myChannelId=%{public}d", msg->myId);
361         return SOFTBUS_ENCRYPT_ERR;
362     }
363     dataInfo->outData = buf;
364     dataInfo->outLen = size;
365     return SOFTBUS_OK;
366 }
367 
TransProxyPackMessage(ProxyMessageHead * msg,AuthHandle authHandle,ProxyDataInfo * dataInfo)368 int32_t TransProxyPackMessage(ProxyMessageHead *msg, AuthHandle authHandle, ProxyDataInfo *dataInfo)
369 {
370     if (msg == NULL || dataInfo == NULL || dataInfo->inData == NULL || dataInfo->inLen == 0) {
371         return SOFTBUS_INVALID_PARAM;
372     }
373 
374     int32_t ret;
375     if ((msg->cipher & ENCRYPTED) == 0) {
376         ret = PackPlaintextMessage(msg, dataInfo);
377     } else {
378         ret = PackEncryptedMessage(msg, authHandle, dataInfo);
379     }
380     if (ret != SOFTBUS_OK) {
381         TRANS_LOGE(TRANS_CTRL, "pack proxy msg fail, myChannelId=%{public}d", msg->myId);
382         return ret;
383     }
384     return SOFTBUS_OK;
385 }
386 
PackHandshakeMsgForFastData(AppInfo * appInfo,cJSON * root)387 static int32_t PackHandshakeMsgForFastData(AppInfo *appInfo, cJSON *root)
388 {
389     if (appInfo->fastTransDataSize > 0) {
390         TRANS_LOGI(TRANS_CTRL, "have fast data need transport");
391         if (!AddNumberToJsonObject(root, JSON_KEY_ROUTE_TYPE, appInfo->routeType)) {
392             TRANS_LOGE(TRANS_CTRL, "add route type fail.");
393             return SOFTBUS_PARSE_JSON_ERR;
394         }
395         uint8_t *encodeFastData = (uint8_t *)SoftBusMalloc(BASE64_FAST_DATA_LEN);
396         if (encodeFastData == NULL) {
397             TRANS_LOGE(TRANS_CTRL, "malloc encode fast data fail.");
398             return SOFTBUS_MALLOC_ERR;
399         }
400         size_t fastDataSize = 0;
401         uint32_t outLen;
402         char *buf = TransProxyPackFastData(appInfo, &outLen);
403         if (buf == NULL) {
404             TRANS_LOGE(TRANS_CTRL, "failed to pack bytes.");
405             SoftBusFree(encodeFastData);
406             return SOFTBUS_TRANS_PACK_FAST_DATA_FAILED;
407         }
408         int32_t ret = SoftBusBase64Encode(encodeFastData, BASE64_FAST_DATA_LEN, &fastDataSize,
409             (const unsigned char *)buf, outLen);
410         if (ret != SOFTBUS_OK) {
411             TRANS_LOGE(TRANS_CTRL, "mbedtls base64 encode failed.");
412             SoftBusFree(encodeFastData);
413             SoftBusFree(buf);
414             return SOFTBUS_DECRYPT_ERR;
415         }
416         if (!AddStringToJsonObject(root, JSON_KEY_FIRST_DATA, (const char *)encodeFastData)) {
417             TRANS_LOGE(TRANS_CTRL, "add first data failed.");
418             SoftBusFree(encodeFastData);
419             SoftBusFree(buf);
420             return SOFTBUS_PARSE_JSON_ERR;
421         }
422         SoftBusFree(encodeFastData);
423         SoftBusFree(buf);
424     }
425     if (!AddNumber16ToJsonObject(root, JSON_KEY_FIRST_DATA_SIZE, appInfo->fastTransDataSize)) {
426         TRANS_LOGE(TRANS_CTRL, "add first data size failed.");
427         return SOFTBUS_PARSE_JSON_ERR;
428     }
429     return SOFTBUS_OK;
430 }
431 
TransProxyCheckIsApp(AppInfo * appInfo,cJSON * root)432 static void TransProxyCheckIsApp(AppInfo *appInfo, cJSON *root)
433 {
434     if (!SoftBusCheckIsCollabApp(appInfo->callingTokenId, appInfo->myData.sessionName)) {
435         return;
436     }
437 
438     appInfo->myData.userId = TransGetForegroundUserId();
439     uint32_t size = 0;
440     if (GetOsAccountUidByUserId(appInfo->myData.accountId, ACCOUNT_UID_LEN_MAX - 1, &size,
441         appInfo->myData.userId) != SOFTBUS_OK) {
442         TRANS_LOGE(TRANS_CTRL, "get current account failed.");
443     }
444     (void)AddStringToJsonObject(root, JSON_KEY_ACCOUNT_ID, appInfo->myData.accountId);
445     (void)AddNumberToJsonObject(root, JSON_KEY_USER_ID, appInfo->myData.userId);
446 }
447 
PackHandshakeMsgForNormal(SessionKeyBase64 * sessionBase64,AppInfo * appInfo,cJSON * root)448 static int32_t PackHandshakeMsgForNormal(SessionKeyBase64 *sessionBase64, AppInfo *appInfo, cJSON *root)
449 {
450     int32_t ret = SoftBusBase64Encode((unsigned char *)sessionBase64->sessionKeyBase64,
451         sizeof(sessionBase64->sessionKeyBase64), &(sessionBase64->len),
452         (unsigned char *)appInfo->sessionKey, sizeof(appInfo->sessionKey));
453     if (ret != SOFTBUS_OK) {
454         TRANS_LOGE(TRANS_CTRL, "mbedtls_base64_encode FAIL ret=%{public}d", ret);
455         return ret;
456     }
457     TRANS_LOGI(TRANS_CTRL, "mbedtls_base64_encode len=%{public}zu", sessionBase64->len);
458     if (!AddNumberToJsonObject(root, JSON_KEY_UID, appInfo->myData.uid) ||
459         !AddNumberToJsonObject(root, JSON_KEY_PID, appInfo->myData.pid) ||
460         !AddStringToJsonObject(root, JSON_KEY_GROUP_ID, appInfo->groupId) ||
461         !AddStringToJsonObject(root, JSON_KEY_PKG_NAME, appInfo->myData.pkgName) ||
462         !AddStringToJsonObject(root, JSON_KEY_SESSION_KEY, sessionBase64->sessionKeyBase64)) {
463         return SOFTBUS_PARSE_JSON_ERR;
464     }
465     if (!AddNumberToJsonObject(root, JSON_KEY_ENCRYPT, appInfo->encrypt) ||
466         !AddNumberToJsonObject(root, JSON_KEY_ALGORITHM, appInfo->algorithm) ||
467         !AddNumberToJsonObject(root, JSON_KEY_CRC, appInfo->crc)) {
468         return SOFTBUS_PARSE_JSON_ERR;
469     }
470     if (PackHandshakeMsgForFastData(appInfo, root) != SOFTBUS_OK) {
471         TRANS_LOGE(TRANS_CTRL, "proxy channel pack fast data failed");
472         return SOFTBUS_PARSE_JSON_ERR;
473     }
474     TransProxyCheckIsApp(appInfo, root);
475     (void)AddNumberToJsonObject(root, JSON_KEY_BUSINESS_TYPE, appInfo->businessType);
476     (void)AddNumberToJsonObject(root, JSON_KEY_TRANS_FLAGS, TRANS_FLAG_HAS_CHANNEL_AUTH);
477     (void)AddNumberToJsonObject(root, JSON_KEY_MY_HANDLE_ID, appInfo->myHandleId);
478     (void)AddNumberToJsonObject(root, JSON_KEY_PEER_HANDLE_ID, appInfo->peerHandleId);
479     (void)AddNumber64ToJsonObject(root, JSON_KEY_CALLING_TOKEN_ID, (int64_t)appInfo->callingTokenId);
480     return SOFTBUS_OK;
481 }
482 
TransProxyPackHandshakeErrMsg(int32_t errCode)483 char *TransProxyPackHandshakeErrMsg(int32_t errCode)
484 {
485     cJSON *root = NULL;
486     char *buf = NULL;
487 
488     root = cJSON_CreateObject();
489     if (root == NULL) {
490         TRANS_LOGE(TRANS_CTRL, "create json object failed.");
491         return NULL;
492     }
493 
494     if (!AddNumberToJsonObject(root, ERR_CODE, errCode)) {
495         cJSON_Delete(root);
496         return NULL;
497     }
498 
499     buf = cJSON_PrintUnformatted(root);
500     cJSON_Delete(root);
501     return buf;
502 }
503 
TransProxyAddJsonObject(cJSON * root,ProxyChannelInfo * info)504 static bool TransProxyAddJsonObject(cJSON *root, ProxyChannelInfo *info)
505 {
506     if (!AddNumberToJsonObject(root, JSON_KEY_TYPE, info->appInfo.appType) ||
507         !AddStringToJsonObject(root, JSON_KEY_IDENTITY, info->identity) ||
508         !AddStringToJsonObject(root, JSON_KEY_DEVICE_ID, info->appInfo.myData.deviceId) ||
509         !AddStringToJsonObject(root, JSON_KEY_SRC_BUS_NAME, info->appInfo.myData.sessionName) ||
510         !AddStringToJsonObject(root, JSON_KEY_DST_BUS_NAME, info->appInfo.peerData.sessionName) ||
511         !AddNumberToJsonObject(root, API_VERSION, info->appInfo.myData.apiVersion) ||
512         !AddNumberToJsonObject(root, JSON_KEY_MTU_SIZE, info->appInfo.myData.dataConfig)) {
513         return false;
514     }
515     if (!AddNumberToJsonObject(root, TRANS_CAPABILITY, info->appInfo.channelCapability)) {
516         return false;
517     }
518     return true;
519 }
520 
TransProxyPackHandshakeMsg(ProxyChannelInfo * info)521 char *TransProxyPackHandshakeMsg(ProxyChannelInfo *info)
522 {
523     if (info == NULL) {
524         TRANS_LOGE(TRANS_CTRL, "invalid param.");
525         return NULL;
526     }
527 
528     cJSON *root = cJSON_CreateObject();
529     if (root == NULL) {
530         TRANS_LOGE(TRANS_CTRL, "create json object failed.");
531         return NULL;
532     }
533     char *buf = NULL;
534     AppInfo *appInfo = &(info->appInfo);
535     SessionKeyBase64 sessionBase64;
536     (void)memset_s(&sessionBase64, sizeof(SessionKeyBase64), 0, sizeof(SessionKeyBase64));
537     if (!TransProxyAddJsonObject(root, info)) {
538         goto EXIT;
539     }
540     (void)cJSON_AddTrueToObject(root, JSON_KEY_HAS_PRIORITY);
541     if (appInfo->appType == APP_TYPE_NORMAL) {
542         if (PackHandshakeMsgForNormal(&sessionBase64, appInfo, root) != SOFTBUS_OK) {
543             goto EXIT;
544         }
545     } else if (appInfo->appType == APP_TYPE_AUTH) {
546         if (strlen(appInfo->reqId) == 0 && GenerateRandomStr(appInfo->reqId, REQ_ID_SIZE_MAX) != SOFTBUS_OK) {
547             goto EXIT;
548         }
549         if (!AddStringToJsonObject(root, JSON_KEY_REQUEST_ID, appInfo->reqId)) {
550             goto EXIT;
551         }
552         if (!AddStringToJsonObject(root, JSON_KEY_PKG_NAME, appInfo->myData.pkgName)) {
553             goto EXIT;
554         }
555     } else {
556         int32_t ret = SoftBusBase64Encode((uint8_t *)sessionBase64.sessionKeyBase64,
557             sizeof(sessionBase64.sessionKeyBase64), &(sessionBase64.len),
558             (uint8_t *)appInfo->sessionKey, sizeof(appInfo->sessionKey));
559         if (ret != SOFTBUS_OK) {
560             TRANS_LOGE(TRANS_CTRL, "mbedtls_base64_encode FAIL ret=%{public}d", ret);
561             goto EXIT;
562         }
563         if (!AddStringToJsonObject(root, JSON_KEY_SESSION_KEY, sessionBase64.sessionKeyBase64)) {
564             goto EXIT;
565         }
566     }
567     buf = cJSON_PrintUnformatted(root);
568 EXIT:
569     cJSON_Delete(root);
570     return buf;
571 }
572 
TransProxyPackHandshakeAckMsg(ProxyChannelInfo * chan)573 char *TransProxyPackHandshakeAckMsg(ProxyChannelInfo *chan)
574 {
575     TRANS_CHECK_AND_RETURN_RET_LOGE(chan != NULL, NULL, TRANS_CTRL, "invalid param.");
576     AppInfo *appInfo = &(chan->appInfo);
577     TRANS_CHECK_AND_RETURN_RET_LOGE(appInfo != NULL, NULL, TRANS_CTRL, "invalid param.");
578     if (appInfo->appType == APP_TYPE_NOT_CARE) {
579         TRANS_LOGE(TRANS_CTRL, "invalid appType.");
580         return NULL;
581     }
582 
583     cJSON *root = cJSON_CreateObject();
584     TRANS_CHECK_AND_RETURN_RET_LOGE(root != NULL, NULL, TRANS_CTRL, "create json object failed.");
585     if (!AddStringToJsonObject(root, JSON_KEY_IDENTITY, chan->identity) ||
586         !AddStringToJsonObject(root, JSON_KEY_DEVICE_ID, appInfo->myData.deviceId) ||
587         !AddNumberToJsonObject(root, TRANS_CAPABILITY, appInfo->channelCapability)) {
588         cJSON_Delete(root);
589         return NULL;
590     }
591     if (appInfo->peerData.dataConfig != 0) {
592         if (!AddNumberToJsonObject(root, JSON_KEY_MTU_SIZE, appInfo->myData.dataConfig)) {
593             cJSON_Delete(root);
594             return NULL;
595         }
596     }
597     (void)cJSON_AddTrueToObject(root, JSON_KEY_HAS_PRIORITY);
598     if (appInfo->appType == APP_TYPE_NORMAL) {
599         if (!AddNumberToJsonObject(root, JSON_KEY_UID, appInfo->myData.uid) ||
600             !AddNumberToJsonObject(root, JSON_KEY_PID, appInfo->myData.pid) ||
601             !AddStringToJsonObject(root, JSON_KEY_PKG_NAME, appInfo->myData.pkgName) ||
602             !AddNumberToJsonObject(root, JSON_KEY_ENCRYPT, appInfo->encrypt) ||
603             !AddNumberToJsonObject(root, JSON_KEY_ALGORITHM, appInfo->algorithm) ||
604             !AddNumberToJsonObject(root, JSON_KEY_CRC, appInfo->crc) ||
605             !AddNumber16ToJsonObject(root, JSON_KEY_FIRST_DATA_SIZE, appInfo->fastTransDataSize) ||
606             !AddStringToJsonObject(root, JSON_KEY_SRC_BUS_NAME, appInfo->myData.sessionName) ||
607             !AddStringToJsonObject(root, JSON_KEY_DST_BUS_NAME, appInfo->peerData.sessionName)) {
608             cJSON_Delete(root);
609             return NULL;
610         }
611         (void)AddNumberToJsonObject(root, JSON_KEY_MY_HANDLE_ID, appInfo->myHandleId);
612     } else if (appInfo->appType == APP_TYPE_AUTH) {
613         if (!AddStringToJsonObject(root, JSON_KEY_PKG_NAME, appInfo->myData.pkgName)) {
614             cJSON_Delete(root);
615             return NULL;
616         }
617     }
618 
619     char *buf = cJSON_PrintUnformatted(root);
620     cJSON_Delete(root);
621     return buf;
622 }
623 
TransProxyUnPackHandshakeErrMsg(const char * msg,int32_t * errCode,int32_t len)624 int32_t TransProxyUnPackHandshakeErrMsg(const char *msg, int32_t *errCode, int32_t len)
625 {
626     if (errCode == NULL) {
627         TRANS_LOGE(TRANS_CTRL, "invalid param errCode.");
628         return SOFTBUS_INVALID_PARAM;
629     }
630 
631     cJSON *root = cJSON_ParseWithLength(msg, len);
632     if (root == NULL) {
633         TRANS_LOGE(TRANS_CTRL, "parse json failed.");
634         return SOFTBUS_CREATE_JSON_ERR;
635     }
636 
637     if (!GetJsonObjectInt32Item(root, ERR_CODE, errCode)) {
638         cJSON_Delete(root);
639         return SOFTBUS_PARSE_JSON_ERR;
640     }
641     TRANS_LOGE(TRANS_CTRL, "remote device is faulty, errCode=%{public}d", *errCode);
642 
643     cJSON_Delete(root);
644     return SOFTBUS_OK;
645 }
646 
TransProxyUnPackRestErrMsg(const char * msg,int32_t * errCode,int32_t len)647 int32_t TransProxyUnPackRestErrMsg(const char *msg, int32_t *errCode, int32_t len)
648 {
649     if (errCode == NULL) {
650         TRANS_LOGE(TRANS_CTRL, "invalid param errCode.");
651         return SOFTBUS_INVALID_PARAM;
652     }
653 
654     cJSON *root = cJSON_ParseWithLength(msg, len);
655     if (root == NULL) {
656         TRANS_LOGE(TRANS_CTRL, "parse json failed.");
657         return SOFTBUS_CREATE_JSON_ERR;
658     }
659 
660     if (!GetJsonObjectInt32Item(root, ERR_CODE, errCode) && !GetJsonObjectInt32Item(root, "ERROR_CODE", errCode)) {
661         TRANS_LOGE(TRANS_CTRL, "get errCode failed.");
662         cJSON_Delete(root);
663         return SOFTBUS_PARSE_JSON_ERR;
664     }
665 
666     cJSON_Delete(root);
667     return SOFTBUS_OK;
668 }
669 
TransProxyUnpackHandshakeAckMsg(const char * msg,ProxyChannelInfo * chanInfo,int32_t len,uint16_t * fastDataSize)670 int32_t TransProxyUnpackHandshakeAckMsg(const char *msg, ProxyChannelInfo *chanInfo,
671     int32_t len, uint16_t *fastDataSize)
672 {
673     TRANS_CHECK_AND_RETURN_RET_LOGE(msg != NULL && chanInfo != NULL && fastDataSize != NULL,
674         SOFTBUS_INVALID_PARAM, TRANS_CTRL, "msg or chanInfo or fastDataSize is empty.");
675 
676     TRANS_CHECK_AND_RETURN_RET_LOGE(&chanInfo->appInfo != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "appInfo is null");
677 
678     cJSON *root = cJSON_ParseWithLength(msg, len);
679     TRANS_CHECK_AND_RETURN_RET_LOGE(root != NULL, SOFTBUS_PARSE_JSON_ERR, TRANS_CTRL, "parse json failed.");
680 
681     if (!GetJsonObjectStringItem(root, JSON_KEY_IDENTITY, chanInfo->identity, sizeof(chanInfo->identity)) ||
682         !GetJsonObjectStringItem(root, JSON_KEY_DEVICE_ID, chanInfo->appInfo.peerData.deviceId,
683                                  sizeof(chanInfo->appInfo.peerData.deviceId))) {
684         TRANS_LOGE(TRANS_CTRL, "fail to get json item");
685         cJSON_Delete(root);
686         return SOFTBUS_PARSE_JSON_ERR;
687     }
688     if (!GetJsonObjectNumberItem(root, JSON_KEY_MTU_SIZE, (int32_t *)&(chanInfo->appInfo.peerData.dataConfig))) {
689         TRANS_LOGD(TRANS_CTRL, "peer dataconfig is null.");
690     }
691     chanInfo->appInfo.encrypt = APP_INFO_FILE_FEATURES_SUPPORT;
692     chanInfo->appInfo.algorithm = APP_INFO_ALGORITHM_AES_GCM_256;
693     chanInfo->appInfo.crc = APP_INFO_FILE_FEATURES_NO_SUPPORT;
694 
695     int32_t ret = TransProxyGetAppInfoType(chanInfo->myId, chanInfo->identity, &chanInfo->appInfo.appType);
696     if (ret != SOFTBUS_OK) {
697         TRANS_LOGE(TRANS_CTRL, "failed to get app type");
698         cJSON_Delete(root);
699         return SOFTBUS_TRANS_PROXY_ERROR_APP_TYPE;
700     }
701     if (chanInfo->appInfo.appType == APP_TYPE_NORMAL) {
702         if (!GetJsonObjectNumberItem(root, JSON_KEY_UID, &chanInfo->appInfo.peerData.uid) ||
703             !GetJsonObjectNumberItem(root, JSON_KEY_PID, &chanInfo->appInfo.peerData.pid) ||
704             !GetJsonObjectNumberItem(root, JSON_KEY_ENCRYPT, &chanInfo->appInfo.encrypt) ||
705             !GetJsonObjectNumberItem(root, JSON_KEY_ALGORITHM, &chanInfo->appInfo.algorithm) ||
706             !GetJsonObjectNumberItem(root, JSON_KEY_CRC, &chanInfo->appInfo.crc) ||
707             !GetJsonObjectNumber16Item(root, JSON_KEY_FIRST_DATA_SIZE, fastDataSize) ||
708             !GetJsonObjectStringItem(root, JSON_KEY_SRC_BUS_NAME, chanInfo->appInfo.peerData.sessionName,
709                                      sizeof(chanInfo->appInfo.peerData.sessionName)) ||
710             !GetJsonObjectStringItem(root, JSON_KEY_DST_BUS_NAME, chanInfo->appInfo.myData.sessionName,
711                                      sizeof(chanInfo->appInfo.myData.sessionName))) {
712             TRANS_LOGW(TRANS_CTRL, "unpack handshake ack old version");
713         }
714         if (!GetJsonObjectInt32Item(root, JSON_KEY_MY_HANDLE_ID, &chanInfo->appInfo.peerHandleId)) {
715             chanInfo->appInfo.peerHandleId = -1;
716         }
717     }
718 
719     if (!GetJsonObjectStringItem(root, JSON_KEY_PKG_NAME, chanInfo->appInfo.peerData.pkgName,
720                                  sizeof(chanInfo->appInfo.peerData.pkgName))) {
721         TRANS_LOGW(TRANS_CTRL, "no item to get pkg name");
722     }
723     if (!GetJsonObjectNumberItem(root, TRANS_CAPABILITY, (int32_t *)&(chanInfo->appInfo.channelCapability))) {
724         chanInfo->appInfo.channelCapability = 0;
725     }
726     cJSON_Delete(root);
727     return SOFTBUS_OK;
728 }
729 
UnpackPackHandshakeMsgForFastData(AppInfo * appInfo,cJSON * root)730 static int32_t UnpackPackHandshakeMsgForFastData(AppInfo *appInfo, cJSON *root)
731 {
732     if (!GetJsonObjectNumber16Item(root, JSON_KEY_FIRST_DATA_SIZE, &(appInfo->fastTransDataSize))) {
733         TRANS_LOGW(TRANS_CTRL, "Failed to get handshake msg fast data size");
734         appInfo->fastTransDataSize = 0;
735     }
736     if (appInfo->fastTransDataSize > 0 && appInfo->fastTransDataSize <= MAX_FAST_DATA_LEN) {
737         if (!GetJsonObjectNumberItem(root, JSON_KEY_ROUTE_TYPE, (int32_t*)&(appInfo->routeType))) {
738             TRANS_LOGE(TRANS_CTRL, "Failed to get handshake msg route type");
739             return SOFTBUS_PARSE_JSON_ERR;
740         }
741         uint8_t *encodeFastData = (uint8_t *)SoftBusMalloc(BASE64_FAST_DATA_LEN);
742         if (encodeFastData == NULL) {
743             TRANS_LOGE(TRANS_CTRL, "malloc encode fast data fail.");
744             return SOFTBUS_MALLOC_ERR;
745         }
746         size_t fastDataSize = 0;
747         if (!GetJsonObjectStringItem(root, JSON_KEY_FIRST_DATA, (char *)encodeFastData, BASE64_FAST_DATA_LEN)) {
748             TRANS_LOGE(TRANS_CTRL, "failed to get fast data");
749             SoftBusFree(encodeFastData);
750             return SOFTBUS_PARSE_JSON_ERR;
751         }
752         appInfo->fastTransData = (uint8_t *)SoftBusCalloc(appInfo->fastTransDataSize + FAST_EXT_BYTE_SIZE);
753         if (appInfo->fastTransData == NULL) {
754             TRANS_LOGE(TRANS_CTRL, "malloc fast data fail.");
755             SoftBusFree(encodeFastData);
756             return SOFTBUS_MALLOC_ERR;
757         }
758 
759         int32_t ret = SoftBusBase64Decode((unsigned char *)appInfo->fastTransData, appInfo->fastTransDataSize +
760             FAST_EXT_BYTE_SIZE, &fastDataSize, encodeFastData, strlen((char*)encodeFastData));
761         if (ret != SOFTBUS_OK) {
762             TRANS_LOGE(TRANS_CTRL, "mbedtls decode failed.");
763             SoftBusFree((void *)appInfo->fastTransData);
764             appInfo->fastTransData = NULL;
765             SoftBusFree(encodeFastData);
766             return SOFTBUS_DECRYPT_ERR;
767         }
768         SoftBusFree(encodeFastData);
769     }
770     return SOFTBUS_OK;
771 }
772 
TransProxyUnpackNormalHandshakeMsg(cJSON * root,AppInfo * appInfo,char * sessionKey,int32_t keyLen)773 static int32_t TransProxyUnpackNormalHandshakeMsg(cJSON *root, AppInfo *appInfo, char *sessionKey, int32_t keyLen)
774 {
775     if (!GetJsonObjectNumberItem(root, JSON_KEY_UID, &(appInfo->peerData.uid)) ||
776         !GetJsonObjectNumberItem(root, JSON_KEY_PID, &(appInfo->peerData.pid)) ||
777         !GetJsonObjectStringItem(root, JSON_KEY_PKG_NAME, appInfo->peerData.pkgName,
778                                  sizeof(appInfo->peerData.pkgName)) ||
779         !GetJsonObjectStringItem(root, JSON_KEY_SESSION_KEY, sessionKey, keyLen)) {
780         TRANS_LOGE(TRANS_CTRL, "Failed to get handshake msg APP_TYPE_NORMAL");
781         return SOFTBUS_PARSE_JSON_ERR;
782     }
783     if (!GetJsonObjectNumberItem(root, JSON_KEY_ENCRYPT, &appInfo->encrypt) ||
784         !GetJsonObjectNumberItem(root, JSON_KEY_ALGORITHM, &appInfo->algorithm) ||
785         !GetJsonObjectNumberItem(root, JSON_KEY_CRC, &appInfo->crc)) {
786         TRANS_LOGW(TRANS_CTRL, "unpack handshake old version");
787         appInfo->encrypt = APP_INFO_FILE_FEATURES_SUPPORT;
788         appInfo->algorithm = APP_INFO_ALGORITHM_AES_GCM_256;
789         appInfo->crc = APP_INFO_FILE_FEATURES_NO_SUPPORT;
790     }
791     if (!GetJsonObjectNumberItem(root, JSON_KEY_BUSINESS_TYPE, (int*)&appInfo->businessType)) {
792         appInfo->businessType = BUSINESS_TYPE_NOT_CARE;
793     }
794 
795     GetJsonObjectStringItem(root, JSON_KEY_GROUP_ID, appInfo->groupId, sizeof(appInfo->groupId));
796     if (!GetJsonObjectInt32Item(root, JSON_KEY_MY_HANDLE_ID, &(appInfo->peerHandleId)) ||
797         !GetJsonObjectInt32Item(root, JSON_KEY_PEER_HANDLE_ID, &(appInfo->myHandleId))) {
798             appInfo->myHandleId = -1;
799             appInfo->peerHandleId = -1;
800     }
801     size_t len = 0;
802     int32_t ret = SoftBusBase64Decode((uint8_t *)appInfo->sessionKey, sizeof(appInfo->sessionKey),
803         &len, (uint8_t *)sessionKey, strlen(sessionKey));
804     if (len != sizeof(appInfo->sessionKey) || ret != SOFTBUS_OK) {
805         TRANS_LOGE(TRANS_CTRL, "decode session fail ret=%{public}d", ret);
806         return SOFTBUS_DECRYPT_ERR;
807     }
808     if (UnpackPackHandshakeMsgForFastData(appInfo, root) != SOFTBUS_OK) {
809         TRANS_LOGE(TRANS_CTRL, "unpack fast data failed");
810         return SOFTBUS_TRANS_PROXY_UNPACK_FAST_DATA_FAILED;
811     }
812     if (!GetJsonObjectNumber64Item(root, JSON_KEY_CALLING_TOKEN_ID, (int64_t *)&appInfo->callingTokenId)) {
813         appInfo->callingTokenId = TOKENID_NOT_SET;
814     }
815     (void)GetJsonObjectStringItem(root, JSON_KEY_ACCOUNT_ID, appInfo->peerData.accountId, ACCOUNT_UID_LEN_MAX);
816     if (!GetJsonObjectNumberItem(root, JSON_KEY_USER_ID, &(appInfo->peerData.userId))) {
817         appInfo->peerData.userId = INVALID_USER_ID;
818     }
819     return SOFTBUS_OK;
820 }
821 
TransProxyUnpackAuthHandshakeMsg(cJSON * root,AppInfo * appInfo)822 static int32_t TransProxyUnpackAuthHandshakeMsg(cJSON *root, AppInfo *appInfo)
823 {
824     if (!GetJsonObjectStringItem(root, JSON_KEY_REQUEST_ID, appInfo->reqId, REQ_ID_SIZE_MAX)) {
825         TRANS_LOGE(TRANS_CTRL, "Failed to get handshake msg REQUEST_ID");
826         return SOFTBUS_TRANS_PROXY_HANDSHAKE_GET_REQUEST_FAILED;
827     }
828     if (!GetJsonObjectStringItem(root, JSON_KEY_PKG_NAME,
829         appInfo->peerData.pkgName, sizeof(appInfo->peerData.pkgName))) {
830         TRANS_LOGE(TRANS_CTRL, "Failed to get handshake msg pkgName");
831         return SOFTBUS_TRANS_PROXY_HANDSHAKE_GET_PKG_FAILED;
832     }
833     return SOFTBUS_OK;
834 }
835 
TransProxyUnpackInnerHandshakeMsg(cJSON * root,AppInfo * appInfo,char * sessionKey,int32_t keyLen)836 static int32_t TransProxyUnpackInnerHandshakeMsg(cJSON *root, AppInfo *appInfo, char *sessionKey, int32_t keyLen)
837 {
838     if (!GetJsonObjectStringItem(root, JSON_KEY_SESSION_KEY, sessionKey, keyLen)) {
839         TRANS_LOGE(TRANS_CTRL, "Failed to get handshake msg");
840         return SOFTBUS_TRANS_PROXY_HANDSHAKE_GET_SESSIONKEY_FAILED;
841     }
842     size_t len = 0;
843     int32_t ret = SoftBusBase64Decode((uint8_t *)appInfo->sessionKey, sizeof(appInfo->sessionKey),
844         &len, (uint8_t *)sessionKey, strlen(sessionKey));
845     if (len != sizeof(appInfo->sessionKey) || ret != SOFTBUS_OK) {
846         TRANS_LOGE(TRANS_CTRL, "decode session fail ret=%{public}d", ret);
847         return SOFTBUS_DECRYPT_ERR;
848     }
849     return SOFTBUS_OK;
850 }
851 
TransProxyGetJsonObject(cJSON * root,const char * msg,int32_t len,ProxyChannelInfo * chan)852 static int32_t TransProxyGetJsonObject(cJSON *root, const char *msg, int32_t len, ProxyChannelInfo *chan)
853 {
854     if (!GetJsonObjectNumberItem(root, JSON_KEY_TYPE, (int32_t *)&(chan->appInfo.appType)) ||
855         !GetJsonObjectStringItem(root, JSON_KEY_IDENTITY, chan->identity, sizeof(chan->identity)) ||
856         !GetJsonObjectStringItem(root, JSON_KEY_DEVICE_ID, chan->appInfo.peerData.deviceId,
857                                  sizeof(chan->appInfo.peerData.deviceId)) ||
858         !GetJsonObjectStringItem(root, JSON_KEY_SRC_BUS_NAME, chan->appInfo.peerData.sessionName,
859                                  sizeof(chan->appInfo.peerData.sessionName)) ||
860         !GetJsonObjectStringItem(root, JSON_KEY_DST_BUS_NAME, chan->appInfo.myData.sessionName,
861                                  sizeof(chan->appInfo.myData.sessionName))) {
862         TRANS_LOGE(TRANS_CTRL, "Failed to get handshake msg");
863         return SOFTBUS_PARSE_JSON_ERR;
864     }
865     if (!GetJsonObjectNumberItem(root, JSON_KEY_MTU_SIZE, (int32_t *)&(chan->appInfo.peerData.dataConfig))) {
866         TRANS_LOGD(TRANS_CTRL, "peer dataconfig is null.");
867     }
868     if (!GetJsonObjectNumberItem(root, API_VERSION, (int32_t *)&(chan->appInfo.myData.apiVersion))) {
869         TRANS_LOGD(TRANS_CTRL, "peer apiVersion is null.");
870     }
871     uint32_t remoteCapability = 0;
872     (void)GetJsonObjectNumberItem(root, TRANS_CAPABILITY, (int32_t *)&remoteCapability);
873     chan->appInfo.channelCapability = remoteCapability & TRANS_CHANNEL_CAPABILITY;
874     return SOFTBUS_OK;
875 }
876 
TransProxyUnpackHandshakeMsg(const char * msg,ProxyChannelInfo * chan,int32_t len)877 int32_t TransProxyUnpackHandshakeMsg(const char *msg, ProxyChannelInfo *chan, int32_t len)
878 {
879     TRANS_CHECK_AND_RETURN_RET_LOGE(msg != NULL && chan != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "param invalid.");
880     cJSON *root = cJSON_ParseWithLength(msg, len);
881     TRANS_CHECK_AND_RETURN_RET_LOGE(root != NULL, SOFTBUS_PARSE_JSON_ERR, TRANS_CTRL, "parse json failed.");
882     char sessionKey[BASE64KEY] = { 0 };
883     AppInfo *appInfo = &(chan->appInfo);
884     int32_t ret = TransProxyGetJsonObject(root, msg, len, chan);
885     if (ret != SOFTBUS_OK) {
886         goto ERR_EXIT;
887     }
888     if (appInfo->appType == APP_TYPE_NORMAL) {
889         ret = TransProxyUnpackNormalHandshakeMsg(root, appInfo, sessionKey, BASE64KEY);
890         if (ret != SOFTBUS_OK) {
891             goto ERR_EXIT;
892         }
893     } else if (appInfo->appType == APP_TYPE_AUTH) {
894         ret = TransProxyUnpackAuthHandshakeMsg(root, appInfo);
895         if (ret != SOFTBUS_OK) {
896             goto ERR_EXIT;
897         }
898     } else {
899         ret = TransProxyUnpackInnerHandshakeMsg(root, appInfo, sessionKey, BASE64KEY);
900         if (ret != SOFTBUS_OK) {
901             goto ERR_EXIT;
902         }
903     }
904     GetJsonObjectNumberItem(root, JSON_KEY_TRANS_FLAGS, &appInfo->transFlag);
905     if (((uint32_t)appInfo->transFlag & TRANS_FLAG_HAS_CHANNEL_AUTH) != 0) {
906         GetJsonObjectNumber64Item(root, JSON_KEY_AUTH_SEQ, &appInfo->authSeq);
907     }
908     cJSON_Delete(root);
909     (void)memset_s(sessionKey, sizeof(sessionKey), 0, sizeof(sessionKey));
910     return SOFTBUS_OK;
911 ERR_EXIT:
912     cJSON_Delete(root);
913     (void)memset_s(sessionKey, sizeof(sessionKey), 0, sizeof(sessionKey));
914     return ret;
915 }
916 
TransProxyPackIdentity(const char * identity)917 char *TransProxyPackIdentity(const char *identity)
918 {
919     cJSON *root = NULL;
920     char *buf = NULL;
921 
922     if (identity == NULL) {
923         TRANS_LOGE(TRANS_CTRL, "invalid param.");
924         return NULL;
925     }
926 
927     root = cJSON_CreateObject();
928     if (root == NULL) {
929         TRANS_LOGE(TRANS_CTRL, "create json object failed.");
930         return NULL;
931     }
932 
933     if (!AddStringToJsonObject(root, JSON_KEY_IDENTITY, identity)) {
934         TRANS_LOGE(TRANS_CTRL, "add identity to json object failed.");
935         cJSON_Delete(root);
936         return NULL;
937     }
938 
939     buf = cJSON_PrintUnformatted(root);
940     cJSON_Delete(root);
941     return buf;
942 }
943 
TransProxyUnpackIdentity(const char * msg,char * identity,uint32_t identitySize,int32_t len)944 int32_t TransProxyUnpackIdentity(const char *msg, char *identity, uint32_t identitySize, int32_t len)
945 {
946     cJSON *root = NULL;
947 
948     root = cJSON_ParseWithLength(msg, len);
949     if (root == NULL) {
950         TRANS_LOGE(TRANS_CTRL, "parse json failed.");
951         return SOFTBUS_PARSE_JSON_ERR;
952     }
953 
954     if (!GetJsonObjectStringItem(root, JSON_KEY_IDENTITY, identity, identitySize)) {
955         TRANS_LOGE(TRANS_CTRL, "fail to get json item");
956         cJSON_Delete(root);
957         return SOFTBUS_PARSE_JSON_ERR;
958     }
959 
960     cJSON_Delete(root);
961     return SOFTBUS_OK;
962 }
963 
TransProxyEncryptFastData(const char * sessionKey,int32_t seq,const char * in,uint32_t inLen,char * out,uint32_t * outLen)964 static int32_t TransProxyEncryptFastData(const char *sessionKey, int32_t seq, const char *in, uint32_t inLen,
965     char *out, uint32_t *outLen)
966 {
967     AesGcmCipherKey cipherKey = { 0 };
968     cipherKey.keyLen = SESSION_KEY_LENGTH;
969     if (memcpy_s(cipherKey.key, SESSION_KEY_LENGTH, sessionKey, SESSION_KEY_LENGTH) != EOK) {
970         TRANS_LOGE(TRANS_CTRL, "memcpy key error.");
971         return SOFTBUS_MEM_ERR;
972     }
973 
974     int ret = SoftBusEncryptDataWithSeq(&cipherKey, (unsigned char*)in, inLen,
975         (unsigned char*)out, outLen, seq);
976     (void)memset_s(cipherKey.key, SESSION_KEY_LENGTH, 0, SESSION_KEY_LENGTH);
977 
978     if (ret != SOFTBUS_OK || *outLen != inLen + OVERHEAD_LEN) {
979         TRANS_LOGE(TRANS_CTRL, "encrypt error, ret=%{public}d.", ret);
980         return SOFTBUS_ENCRYPT_ERR;
981     }
982     return SOFTBUS_OK;
983 }
984 
FastDataPackPacketHead(PacketFastHead * data)985 static void FastDataPackPacketHead(PacketFastHead *data)
986 {
987     data->magicNumber = (int32_t)SoftBusHtoLl((uint32_t)data->magicNumber);
988     data->seq = (int32_t)SoftBusHtoLl((uint32_t)data->seq);
989     data->flags = (int32_t)SoftBusHtoLl((uint32_t)data->flags);
990     data->dataLen = (int32_t)SoftBusHtoLl((uint32_t)data->dataLen);
991 }
992 
TransProxyPackFastDataHead(ProxyDataInfo * dataInfo,const AppInfo * appInfo)993 static int32_t TransProxyPackFastDataHead(ProxyDataInfo *dataInfo, const AppInfo *appInfo)
994 {
995 #define MAGIC_NUMBER 0xBABEFACE
996     if (dataInfo == NULL || appInfo ==NULL) {
997         TRANS_LOGE(TRANS_CTRL, "invaild param.");
998         return SOFTBUS_INVALID_PARAM;
999     }
1000     dataInfo->outLen = dataInfo->inLen + OVERHEAD_LEN + sizeof(PacketFastHead);
1001     uint32_t cipherLength = dataInfo->inLen + OVERHEAD_LEN;
1002     dataInfo->outData = (uint8_t *)SoftBusCalloc(dataInfo->outLen);
1003     if (dataInfo->outData == NULL) {
1004         TRANS_LOGE(TRANS_CTRL, "calloc error");
1005         return SOFTBUS_MALLOC_ERR;
1006     }
1007 
1008     int32_t seq = atomic_fetch_add_explicit(&g_proxyPktHeadSeq, 1, memory_order_relaxed);
1009     if (TransProxyEncryptFastData(appInfo->sessionKey, seq, (const char*)dataInfo->inData,
1010         dataInfo->inLen, (char*)dataInfo->outData + sizeof(PacketFastHead), &cipherLength) != SOFTBUS_OK) {
1011         SoftBusFree(dataInfo->outData);
1012         TRANS_LOGE(TRANS_CTRL, "TransProxyEncryptFastData err");
1013         return SOFTBUS_TRANS_PROXY_SESS_ENCRYPT_ERR;
1014     }
1015 
1016     PacketFastHead *pktHead = (PacketFastHead*)dataInfo->outData;
1017     pktHead->magicNumber = MAGIC_NUMBER;
1018     pktHead->seq = seq;
1019     pktHead->flags = (appInfo->businessType == BUSINESS_TYPE_BYTE) ? FLAG_BYTES : FLAG_MESSAGE;
1020     pktHead->dataLen = (int32_t)cipherLength;
1021     FastDataPackPacketHead(pktHead);
1022 
1023     return SOFTBUS_OK;
1024 }
1025 
FastDataPackSliceHead(SliceFastHead * data)1026 static void FastDataPackSliceHead(SliceFastHead *data)
1027 {
1028     data->priority = (int32_t)SoftBusHtoLl((uint32_t)data->priority);
1029     data->sliceNum = (int32_t)SoftBusHtoLl((uint32_t)data->sliceNum);
1030     data->sliceSeq = (int32_t)SoftBusHtoLl((uint32_t)data->sliceSeq);
1031     data->reserved = (int32_t)SoftBusHtoLl((uint32_t)data->reserved);
1032 }
TransProxyMessageData(const AppInfo * appInfo,ProxyDataInfo * dataInfo)1033 static int32_t TransProxyMessageData(const AppInfo *appInfo, ProxyDataInfo *dataInfo)
1034 {
1035     dataInfo->inData = (uint8_t *)SoftBusMalloc(appInfo->fastTransDataSize);
1036     if (dataInfo->inData == NULL) {
1037         TRANS_LOGE(TRANS_CTRL, "malloc error");
1038         return SOFTBUS_MALLOC_ERR;
1039     }
1040     uint16_t fastDataSize = appInfo->fastTransDataSize;
1041     if (memcpy_s(dataInfo->inData, fastDataSize, appInfo->fastTransData, fastDataSize) != EOK) {
1042         TRANS_LOGE(TRANS_CTRL, "memcpy_s fastTransData error.");
1043         SoftBusFree(dataInfo->inData);
1044         return SOFTBUS_MEM_ERR;
1045     }
1046     dataInfo->inLen = fastDataSize;
1047     return SOFTBUS_OK;
1048 }
1049 
TransProxyByteData(const AppInfo * appInfo,ProxyDataInfo * dataInfo)1050 static int32_t TransProxyByteData(const AppInfo *appInfo, ProxyDataInfo *dataInfo)
1051 {
1052     dataInfo->inData = (uint8_t *)SoftBusMalloc(appInfo->fastTransDataSize + sizeof(SessionHead));
1053     if (dataInfo->inData == NULL) {
1054         TRANS_LOGE(TRANS_CTRL, "malloc error");
1055         return SOFTBUS_MALLOC_ERR;
1056     }
1057     uint16_t fastDataSize = appInfo->fastTransDataSize;
1058     SessionHead *sessionHead = (SessionHead*)dataInfo->inData;
1059     sessionHead->seq = atomic_fetch_add_explicit(&g_proxyPktHeadSeq, 1, memory_order_relaxed);
1060     sessionHead->packetFlag = (appInfo->businessType == BUSINESS_TYPE_BYTE) ? FLAG_BYTES : FLAG_MESSAGE;
1061     sessionHead->shouldAck = 0;
1062     if (memcpy_s(dataInfo->inData + sizeof(SessionHead), fastDataSize, appInfo->fastTransData, fastDataSize) != EOK) {
1063         TRANS_LOGE(TRANS_CTRL, "memcpy_s fastTransData error.");
1064         SoftBusFree(dataInfo->inData);
1065         return SOFTBUS_MEM_ERR;
1066     }
1067     dataInfo->inLen = fastDataSize + sizeof(SessionHead);
1068     return SOFTBUS_OK;
1069 }
1070 
TransProxyPackFastData(const AppInfo * appInfo,uint32_t * outLen)1071 char *TransProxyPackFastData(const AppInfo *appInfo, uint32_t *outLen)
1072 {
1073     ProxyDataInfo dataInfo = {0};
1074     if (appInfo->businessType == BUSINESS_TYPE_MESSAGE && appInfo->routeType == WIFI_STA) {
1075         if (TransProxyMessageData(appInfo, &dataInfo) != SOFTBUS_OK) {
1076             TRANS_LOGE(TRANS_CTRL, "TransProxyMessageData error");
1077             return NULL;
1078         }
1079     } else {
1080         if (TransProxyByteData(appInfo, &dataInfo) != SOFTBUS_OK) {
1081             TRANS_LOGE(TRANS_CTRL, "TransProxyByteData error");
1082             return NULL;
1083         }
1084     }
1085     if (TransProxyPackFastDataHead(&dataInfo, appInfo) != SOFTBUS_OK) {
1086         TRANS_LOGE(TRANS_CTRL, "TransProxyPackFastDataHead error");
1087         SoftBusFree(dataInfo.inData);
1088         return NULL;
1089     }
1090 
1091     char *sliceData = (char *)SoftBusMalloc(dataInfo.outLen + sizeof(SliceFastHead));
1092     if (sliceData == NULL) {
1093         TRANS_LOGE(TRANS_CTRL, "malloc slice data error");
1094         SoftBusFree(dataInfo.inData);
1095         SoftBusFree(dataInfo.outData);
1096         return NULL;
1097     }
1098     SliceFastHead *slicehead = (SliceFastHead*)sliceData;
1099     slicehead->priority = (appInfo->businessType == BUSINESS_TYPE_BYTE) ? FLAG_BYTES : FLAG_MESSAGE;
1100     slicehead->sliceNum = 1;
1101     slicehead->sliceSeq = 0;
1102     FastDataPackSliceHead(slicehead);
1103     if (memcpy_s(sliceData + sizeof(SliceFastHead), dataInfo.outLen, dataInfo.outData, dataInfo.outLen) != EOK) {
1104         TRANS_LOGE(TRANS_CTRL, "memcpy_s error");
1105         SoftBusFree(dataInfo.inData);
1106         SoftBusFree(dataInfo.outData);
1107         SoftBusFree(sliceData);
1108         return NULL;
1109     }
1110     *outLen = dataInfo.outLen + sizeof(SliceFastHead);
1111     SoftBusFree(dataInfo.inData);
1112     SoftBusFree(dataInfo.outData);
1113     return sliceData;
1114 }
1115