1  /*
2   * Copyright (C) 2021 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 "gap.h"
17  
18  #include "log.h"
19  #include "securec.h"
20  
21  #include "btm.h"
22  #include "btstack.h"
23  
24  #include "allocator.h"
25  #include "module.h"
26  
27  #include "btm/btm_controller.h"
28  #include "btm/btm_inq_db.h"
29  #include "btm/btm_interop.h"
30  #include "btm/btm_le_sec.h"
31  #include "btm/btm_thread.h"
32  #include "hci/hci.h"
33  #include "hci/hci_error.h"
34  #include "smp/smp.h"
35  #include "smp/smp_def.h"
36  
37  #include "gap_internal.h"
38  #include "gap_le.h"
39  #include "gap_task_internal.h"
40  
41  static GapMng g_gapMng;
42  
43  typedef struct {
44      int traceLevel;
45  } GapInitializeParam;
46  
47  static int GapWriteScanEnable(void);
48  static int GapWriteInquiryScanActivity(void);
49  static int GapWriteInquiryScanType(void);
50  static int GapWriteCurrentIACLAP(void);
51  static int GapWritePageScanActivity(void);
52  static int GapWritePageScanType(void);
53  static int GapWriteClassOfDevice(uint32_t cod);
54  
55  static void GapFreeRegSecInfo(void *data);
56  static void GapFreeReqSecInfo(void *data);
57  static void GapFreeDeviceInfo(void *data);
58  
GapFreeListNode(void * data)59  static void GapFreeListNode(void *data)
60  {
61      MEM_MALLOC.free(data);
62  }
63  
GapInitializeTask(void * ctx)64  static void GapInitializeTask(void *ctx)
65  {
66      LOG_DEBUG("%{public}s:", __FUNCTION__);
67  
68      (void)memset_s(&g_gapMng, sizeof(GapMng), 0x00, sizeof(GapMng));
69      g_gapMng.traceLevel = ((GapInitializeParam *)ctx)->traceLevel;
70  #ifdef GAP_BREDR_SUPPORT
71      g_gapMng.bredr.profileSecBlock.registerlist = ListCreate(GapFreeRegSecInfo);
72      g_gapMng.bredr.profileSecBlock.requestlist = ListCreate(GapFreeReqSecInfo);
73      g_gapMng.bredr.connectionInfoBlock.devicelist = ListCreate(GapFreeDeviceInfo);
74  #endif
75  #ifdef GAP_LE_SUPPORT
76      g_gapMng.le.connectionInfoBlock.deviceList = ListCreate(GapFreeLeDeviceInfo);
77      g_gapMng.le.signatureBlock.RequestList = ListCreate(GapFreeLeSignatureRequest);
78      g_gapMng.le.randomAddressBlock.reportRPAResolveList = ListCreate(GapFreeReportRPAResolveInfo);
79      g_gapMng.le.exAdvBlock.exAdvInfoList = ListCreate(GapFreeListNode);
80  #endif
81  }
82  
GapInitialize(int traceLevel)83  static void GapInitialize(int traceLevel)
84  {
85      LOG_INFO("%{public}s:", __FUNCTION__);
86  
87      BTM_CreateProcessingQueue(PROCESSING_QUEUE_ID_GAP, BTM_PROCESSING_QUEUE_SIZE_DEFAULT);
88  
89      GapInitializeParam *ctx = MEM_MALLOC.alloc(sizeof(GapInitializeParam));
90      if (ctx == NULL) {
91          LOG_ERROR("%{public}s: Alloc error.", __FUNCTION__);
92          return;
93      }
94  
95      int ret = GapRunTaskBlockProcess(GapInitializeTask, ctx);
96      if (ret != BT_SUCCESS) {
97          LOG_ERROR("%{public}s: Run task error.", __FUNCTION__);
98      }
99  
100      MEM_MALLOC.free(ctx);
101  }
102  
GapEnableBredr(void)103  static void GapEnableBredr(void)
104  {
105      if (BTM_IsControllerSupportBrEdr()) {
106          g_gapMng.bredr.isEnable = true;
107  
108          g_gapMng.bredr.keyMissingRetry = true;
109  
110          HciWriteInquiryModeParam writeInquiryModeParam = {
111              .inquiryMode = HCI_INQUIRY_MODE_STANDARD,
112          };
113  
114          if (BTM_IsControllerSupportEirInquiryResponse()) {
115              writeInquiryModeParam.inquiryMode = HCI_INQUIRY_MODE_EIR;
116          } else if (BTM_IsControllerSupportRssiInquiryResponse()) {
117              writeInquiryModeParam.inquiryMode = HCI_INQUIRY_MODE_RSSI;
118          }
119  
120          HCI_WriteInquiryMode(&writeInquiryModeParam);
121      }
122  }
123  
GapEnableLe(void)124  static void GapEnableLe(void)
125  {
126      if (BTM_IsControllerSupportLe()) {
127          g_gapMng.le.isEnable = true;
128          g_gapMng.le.local.minEncKeySize = GAP_ENC_KEY_MAX_SIZE;
129          int ret = BTM_GetLocalAddr(&g_gapMng.le.local.addr);
130          if (ret == BT_SUCCESS) {
131              g_gapMng.le.local.addr.type = LOCAL_ADDR_TYPE_PUBLIC;
132          } else {
133              g_gapMng.le.local.addr.type = LOCAL_ADDR_TYPE_RANDOM;
134          }
135  
136          if (BTM_IsControllerSupportLeExtendedAdvertising()) {
137              HCI_LeReadMaximumAdvertisingDataLength();
138              HCI_LeReadNumberofSupportedAdvertisingSets();
139          }
140  
141          GapRegisterL2capCallbacks();
142          GapRegisterSmCallbacks();
143      }
144  }
145  
GapEnableTask(void * ctx)146  static void GapEnableTask(void *ctx)
147  {
148      LOG_DEBUG("%{public}s:", __FUNCTION__);
149  
150  #ifdef GAP_BREDR_SUPPORT
151      GapEnableBredr();
152  #endif
153  #ifdef GAP_LE_SUPPORT
154      GapEnableLe();
155  #endif
156      GapRegisterHciEventCallbacks();
157      GapRegisterBtmAclCallbacks();
158  }
159  
GapEnable(void)160  static void GapEnable(void)
161  {
162      LOG_INFO("%{public}s:", __FUNCTION__);
163  
164      int ret = GapRunTaskBlockProcess(GapEnableTask, NULL);
165      if (ret != BT_SUCCESS) {
166          LOG_ERROR("%{public}s: Run task error.", __FUNCTION__);
167      }
168  }
169  
GapDisableTask(void * ctx)170  static void GapDisableTask(void *ctx)
171  {
172      LOG_DEBUG("%{public}s:", __FUNCTION__);
173      GapDeregisterHciEventCallbacks();
174      GapDeregisterBtmAclCallbacks();
175      if (BTM_IsControllerSupportBrEdr()) {
176          ListClear(g_gapMng.bredr.profileSecBlock.registerlist);
177          ListNode *node = ListGetFirstNode(g_gapMng.bredr.profileSecBlock.requestlist);
178          while (node != NULL) {
179              RequestSecInfo *reqInfo = ListGetNodeData(node);
180              node = ListGetNextNode(node);
181              if (!reqInfo->doCallback) {
182                  ListRemoveNode(g_gapMng.bredr.profileSecBlock.requestlist, reqInfo);
183              }
184          }
185          ListClear(g_gapMng.bredr.connectionInfoBlock.devicelist);
186          g_gapMng.bredr.scanModeBlock.status = GAP_SCANMODE_STATUS_IDLE;
187          g_gapMng.bredr.inquiryBlock.status = GAP_INQUIRY_STATUS_IDLE;
188          g_gapMng.bredr.remoteNameBlock.status = GAP_REMOTE_NAME_STATUS_IDLE;
189          g_gapMng.bredr.encryptionBlock.status = GAP_SET_ENCRYPTION_STATUS_IDLE;
190          g_gapMng.bredr.isEnable = false;
191      }
192  
193      if (BTM_IsControllerSupportLe()) {
194          GapDeregisterL2capCallbacks();
195          GapDeregisterSmCallbacks();
196          ListClear(g_gapMng.le.connectionInfoBlock.deviceList);
197          ListClear(g_gapMng.le.signatureBlock.RequestList);
198          ListClear(g_gapMng.le.randomAddressBlock.reportRPAResolveList);
199          ListClear(g_gapMng.le.exAdvBlock.exAdvInfoList);
200          g_gapMng.le.bondBlock.isPairing = false;
201          g_gapMng.le.randomAddressBlock.generationInfo.processing = false;
202          g_gapMng.le.isEnable = false;
203      }
204  }
205  
GapDisable(void * ctx)206  static void GapDisable(void *ctx)
207  {
208      LOG_INFO("%{public}s:", __FUNCTION__);
209  
210      int ret = GapRunTaskBlockProcess(GapDisableTask, NULL);
211      if (ret != BT_SUCCESS) {
212          LOG_ERROR("%{public}s: Run task error.", __FUNCTION__);
213      }
214  }
215  
GapFinalizeTask(void * ctx)216  static void GapFinalizeTask(void *ctx)
217  {
218      LOG_INFO("%{public}s:", __FUNCTION__);
219  
220  #ifdef GAP_BREDR_SUPPORT
221      ListDelete(g_gapMng.bredr.profileSecBlock.registerlist);
222      ListDelete(g_gapMng.bredr.profileSecBlock.requestlist);
223      ListDelete(g_gapMng.bredr.connectionInfoBlock.devicelist);
224  #endif
225  #ifdef GAP_LE_SUPPORT
226      ListDelete(g_gapMng.le.connectionInfoBlock.deviceList);
227      ListDelete(g_gapMng.le.signatureBlock.RequestList);
228      ListDelete(g_gapMng.le.randomAddressBlock.reportRPAResolveList);
229      ListDelete(g_gapMng.le.exAdvBlock.exAdvInfoList);
230  #endif
231  
232      (void)memset_s(&g_gapMng, sizeof(GapMng), 0x00, sizeof(GapMng));
233  
234      BTM_DeleteProcessingQueue(PROCESSING_QUEUE_ID_GAP);
235  }
236  
GapFinalize(void)237  static void GapFinalize(void)
238  {
239      LOG_INFO("%{public}s:", __FUNCTION__);
240  
241      int ret = GapRunTaskBlockProcess(GapFinalizeTask, NULL);
242      if (ret != BT_SUCCESS) {
243          LOG_ERROR("%{public}s: Run task error.", __FUNCTION__);
244      }
245  }
246  
GapChangeHCIAddr(BtAddr * addr,const HciBdAddr * hciAddr,uint8_t addrType)247  void GapChangeHCIAddr(BtAddr *addr, const HciBdAddr *hciAddr, uint8_t addrType)
248  {
249      (void)memcpy_s(addr->addr, BT_ADDRESS_SIZE, hciAddr->raw, BT_ADDRESS_SIZE);
250      addr->type = addrType;
251  }
252  
GapIsEmptyAddr(const uint8_t * addr)253  bool GapIsEmptyAddr(const uint8_t *addr)
254  {
255      for (int i = 0; i < BT_ADDRESS_SIZE; i++) {
256          if (addr[i] != 0) {
257              return false;
258          }
259      }
260      return true;
261  }
262  
GapAddrCompare(const BtAddr * addr1,const BtAddr * addr2)263  bool GapAddrCompare(const BtAddr *addr1, const BtAddr *addr2)
264  {
265      return (!memcmp(addr1->addr, addr2->addr, BT_ADDRESS_SIZE) &&
266              !((addr1->type == BT_PUBLIC_DEVICE_ADDRESS || addr1->type == BT_PUBLIC_IDENTITY_ADDRESS) ^
267                  (addr2->type == BT_PUBLIC_DEVICE_ADDRESS || addr2->type == BT_PUBLIC_IDENTITY_ADDRESS)));
268  }
269  
GapCompareChannelID(GAP_SecMultiplexingProtocol protocolID,GapSecChannel channelID1,GapSecChannel channelID2)270  bool GapCompareChannelID(GAP_SecMultiplexingProtocol protocolID, GapSecChannel channelID1, GapSecChannel channelID2)
271  {
272      return (protocolID == SEC_PROTOCOL_L2CAP) ? (channelID1.l2capPsm == channelID2.l2capPsm)
273                                                : (channelID1.rfcommChannel == channelID2.rfcommChannel);
274  }
275  
276  #ifdef GAP_BREDR_SUPPORT
277  
GapIsBredrEnable(void)278  bool GapIsBredrEnable(void)
279  {
280      return g_gapMng.bredr.isEnable;
281  }
282  
GapGetScanModeBlock(void)283  ScanModeBlock *GapGetScanModeBlock(void)
284  {
285      return &g_gapMng.bredr.scanModeBlock;
286  }
287  
GapGetInquiryBlock(void)288  InquiryBlock *GapGetInquiryBlock(void)
289  {
290      return &g_gapMng.bredr.inquiryBlock;
291  }
292  
GapGetRemoteNameBlock(void)293  RemoteNameBlock *GapGetRemoteNameBlock(void)
294  {
295      return &g_gapMng.bredr.remoteNameBlock;
296  }
297  
GapGetSecurityMode(void)298  GAP_SecurityMode *GapGetSecurityMode(void)
299  {
300      return &g_gapMng.bredr.secMode;
301  }
302  
GapGetProfileSecurityBlock(void)303  ProfileSecurityBlock *GapGetProfileSecurityBlock(void)
304  {
305      return &g_gapMng.bredr.profileSecBlock;
306  }
307  
GapGetConnectionInfoBlock(void)308  ConnectionInfoBlock *GapGetConnectionInfoBlock(void)
309  {
310      return &g_gapMng.bredr.connectionInfoBlock;
311  }
312  
GapGetEncryptionBlock(void)313  EncryptionBlock *GapGetEncryptionBlock(void)
314  {
315      return &g_gapMng.bredr.encryptionBlock;
316  }
317  
GapIsBondMode(void)318  bool GapIsBondMode(void)
319  {
320      bool isBondMode;
321      isBondMode = (g_gapMng.bredr.bondableMode == GAP_BONDABLE_MODE);
322      return isBondMode;
323  }
324  #endif
325  
326  #ifdef GAP_LE_SUPPORT
327  
GapIsLeEnable(void)328  bool GapIsLeEnable(void)
329  {
330      return g_gapMng.le.isEnable;
331  }
332  
GapLeRolesCheck(uint8_t role)333  bool GapLeRolesCheck(uint8_t role)
334  {
335      return !!(g_gapMng.le.local.role & role);
336  }
337  
GapFreeLeDeviceInfo(void * data)338  void GapFreeLeDeviceInfo(void *data)
339  {
340      LeDeviceInfo *deviceInfo = data;
341  
342      AlarmCancel(deviceInfo->alarm);
343      AlarmDelete(deviceInfo->alarm);
344      if (deviceInfo->securityReq != NULL) {
345          MEM_MALLOC.free(deviceInfo->securityReq);
346          deviceInfo->securityReq = NULL;
347      }
348      if (deviceInfo->paramUpdateReq != NULL) {
349          MEM_MALLOC.free(deviceInfo->paramUpdateReq);
350          deviceInfo->paramUpdateReq = NULL;
351      }
352      MEM_MALLOC.free(deviceInfo);
353  }
354  
GapFreeLeSignatureRequest(void * data)355  void GapFreeLeSignatureRequest(void *data)
356  {
357      MEM_MALLOC.free(data);
358  }
359  
GapGetLeBondBlock(void)360  LeBondBlock *GapGetLeBondBlock(void)
361  {
362      return &g_gapMng.le.bondBlock;
363  }
364  
GapGetLeConnectionInfoBlock(void)365  LeConnectionInfoBlock *GapGetLeConnectionInfoBlock(void)
366  {
367      return &g_gapMng.le.connectionInfoBlock;
368  }
369  
GapGetLeSignatureBlock(void)370  LeSignatureBlock *GapGetLeSignatureBlock(void)
371  {
372      return &g_gapMng.le.signatureBlock;
373  }
374  
GapGetLeRandomAddressBlock(void)375  LeRandomAddressBlock *GapGetLeRandomAddressBlock(void)
376  {
377      return &g_gapMng.le.randomAddressBlock;
378  }
379  
GapGetLeExAdvBlock(void)380  LeExAdvBlock *GapGetLeExAdvBlock(void)
381  {
382      return &g_gapMng.le.exAdvBlock;
383  }
384  
GapIsLeBondableMode(void)385  bool GapIsLeBondableMode(void)
386  {
387      return g_gapMng.le.local.bondableMode == GAP_BONDABLE_MODE;
388  }
389  
GapGetLeLocalInfo(void)390  LeLocalInfo *GapGetLeLocalInfo(void)
391  {
392      return &g_gapMng.le.local;
393  }
394  
395  #endif
396  
397  #ifdef GAP_BREDR_SUPPORT
398  
GAP_SetScanMode(const GapDiscoverModeInfo * discoverInfo,const GapConnectableModeInfo * connectableInfo,GapSetScanModeResultCallback callback,void * context)399  int GAP_SetScanMode(const GapDiscoverModeInfo *discoverInfo, const GapConnectableModeInfo *connectableInfo,
400      GapSetScanModeResultCallback callback, void *context)
401  {
402      int ret;
403      ScanModeBlock *scanModeBlock = NULL;
404  
405      LOG_INFO("%{public}s:discoverable:[%hhu][%hhu][%04x][%04x], connectable:[%hhu][%hhu][%04x][%04x]",
406          __FUNCTION__,
407          discoverInfo->mode,
408          discoverInfo->type,
409          discoverInfo->scanInterval,
410          discoverInfo->scanWindow,
411          connectableInfo->mode,
412          connectableInfo->type,
413          connectableInfo->scanInterval,
414          connectableInfo->scanWindow);
415  
416      if (GapIsBredrEnable() == false) {
417          return GAP_ERR_NOT_ENABLE;
418      }
419  
420      if (discoverInfo->mode > GAP_DISCOVERABLE_MODE_GENERAL || discoverInfo->type > GAP_INQUIRY_SCAN_TYPE_INTERLACED ||
421          discoverInfo->scanInterval < GAP_SCAN_INTERVAL_RANGE_MIN ||
422          discoverInfo->scanInterval > GAP_SCAN_INTERVAL_RANGE_MAX ||
423          discoverInfo->scanWindow < GAP_SCAN_WINDOW_RANGE_MIN || discoverInfo->scanWindow > discoverInfo->scanInterval ||
424          connectableInfo->mode > GAP_CONNECTABLE_MODE || connectableInfo->type > GAP_PAGE_SCAN_TYPE_INTERLACED ||
425          connectableInfo->scanInterval < GAP_SCAN_INTERVAL_RANGE_MIN ||
426          connectableInfo->scanInterval > GAP_SCAN_INTERVAL_RANGE_MAX ||
427          connectableInfo->scanWindow < GAP_SCAN_WINDOW_RANGE_MIN ||
428          connectableInfo->scanWindow > connectableInfo->scanInterval) {
429          return GAP_ERR_INVAL_PARAM;
430      }
431  
432      scanModeBlock = GapGetScanModeBlock();
433      if (scanModeBlock->status != GAP_SCANMODE_STATUS_IDLE) {
434          ret = GAP_ERR_INVAL_STATE;
435      } else {
436          (void)memcpy_s(
437              &scanModeBlock->discoverMode, sizeof(GapDiscoverModeInfo), discoverInfo, sizeof(GapDiscoverModeInfo));
438          (void)memcpy_s(&scanModeBlock->connectableMode,
439              sizeof(GapConnectableModeInfo),
440              connectableInfo,
441              sizeof(GapConnectableModeInfo));
442          scanModeBlock->callback = callback;
443          scanModeBlock->context = context;
444          scanModeBlock->status = GAP_SCANMODE_STATUS_CLOSING;
445  
446          ret = GapWriteScanEnable();
447          if (ret != BT_SUCCESS) {
448              LOG_WARN("");
449              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
450          }
451      }
452  
453      return ret;
454  }
455  
GapWriteScanEnable(void)456  static int GapWriteScanEnable(void)
457  {
458      LOG_DEBUG("%{public}s:", __FUNCTION__);
459      HciWriteScanEnableParam hciCmdParam;
460      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
461      uint8_t discoverMode = scanModeBlock->discoverMode.mode;
462      uint8_t connectableMode = scanModeBlock->connectableMode.mode;
463      int ret;
464  
465      if (scanModeBlock->status == GAP_SCANMODE_STATUS_CLOSING) {
466          hciCmdParam.scanEnable = 0;
467          ret = HCI_WriteScanEnable(&hciCmdParam);
468      } else if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
469          if (discoverMode != GAP_DISCOVERABLE_MODE_NON && connectableMode != GAP_CONNECTABLE_MODE_NON) {
470              hciCmdParam.scanEnable = INQUIRY_SCAN_ENABLED_PAGE_SCAN_ENABLED;
471          } else if (connectableMode != GAP_DISCOVERABLE_MODE_NON) {
472              hciCmdParam.scanEnable = INQUIRY_SCAN_DISABLED_PAGE_SCAN_ENABLED;
473          } else if (discoverMode != GAP_CONNECTABLE_MODE_NON) {
474              hciCmdParam.scanEnable = INQUIRY_SCAN_ENABLED_PAGE_SCAN_DISABLED;
475          } else {
476              hciCmdParam.scanEnable = NO_SCANS_ENABLED;
477          }
478          ret = HCI_WriteScanEnable(&hciCmdParam);
479      } else {
480          ret = GAP_ERR_INVAL_STATE;
481      }
482      return ret;
483  }
484  
GapWriteScanEnableComplete(const HciWriteScanEnableReturnParam * param)485  NO_SANITIZE("cfi") void GapWriteScanEnableComplete(const HciWriteScanEnableReturnParam *param)
486  {
487      LOG_DEBUG("%{public}s:", __FUNCTION__);
488      int ret = GAP_SUCCESS;
489      GapSetScanModeResultCallback callback = NULL;
490      ScanModeBlock *scanModeBlock = NULL;
491      uint8_t retStatus = param->status;
492  
493      if (GapIsBredrEnable() == false) {
494          LOG_ERROR("Not Enable.");
495          return;
496      }
497  
498      scanModeBlock = GapGetScanModeBlock();
499      if (scanModeBlock->status == GAP_SCANMODE_STATUS_CLOSING) {
500          if (retStatus == HCI_SUCCESS) {
501              if (scanModeBlock->discoverMode.mode) {
502                  scanModeBlock->status = GAP_SCANMODE_STATUS_SETTING;
503                  ret = GapWriteInquiryScanActivity();
504              } else if (scanModeBlock->connectableMode.mode) {
505                  scanModeBlock->status = GAP_SCANMODE_STATUS_SETTING;
506                  ret = GapWritePageScanActivity();
507              } else {
508                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
509                  callback = scanModeBlock->callback;
510              }
511              if (ret != BT_SUCCESS) {
512                  LOG_ERROR("HCI Command Error ret = %{public}d.", ret);
513                  retStatus = GAP_STATUS_FAILED;
514                  callback = scanModeBlock->callback;
515                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
516              }
517          } else {
518              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
519              callback = scanModeBlock->callback;
520          }
521      } else if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
522          scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
523          callback = scanModeBlock->callback;
524      } else {
525          LOG_WARN("");
526      }
527  
528      if (callback != NULL) {
529          callback(retStatus, scanModeBlock->context);
530      }
531  }
532  
GapWriteInquiryScanActivity(void)533  static int GapWriteInquiryScanActivity(void)
534  {
535      LOG_DEBUG("%{public}s:", __FUNCTION__);
536      int ret;
537      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
538      HciWriteInquiryScanActivityParam hciCmdParam;
539  
540      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
541          hciCmdParam.inquiryScanInterval = scanModeBlock->discoverMode.scanInterval;
542          hciCmdParam.inquiryScanWindow = scanModeBlock->discoverMode.scanWindow;
543          ret = HCI_WriteInquiryScanActivity(&hciCmdParam);
544      } else {
545          ret = GAP_ERR_INVAL_STATE;
546      }
547      return ret;
548  }
549  
GapWriteInquiryScanActivityComplete(const HciWriteInquiryScanActivityReturnParam * param)550  void GapWriteInquiryScanActivityComplete(const HciWriteInquiryScanActivityReturnParam *param)
551  {
552      LOG_DEBUG("%{public}s:", __FUNCTION__);
553      GapSetScanModeResultCallback callback = NULL;
554      uint8_t retStatus = param->status;
555  
556      if (GapIsBredrEnable() == false) {
557          LOG_ERROR("%sNot Enable.", "");
558          return;
559      }
560  
561      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
562      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
563          if (retStatus == HCI_SUCCESS) {
564              int ret = GapWriteInquiryScanType();
565              if (ret != BT_SUCCESS) {
566                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
567                  retStatus = GAP_STATUS_FAILED;
568                  callback = scanModeBlock->callback;
569                  LOG_ERROR("HCI Command Error ret = %{public}d.", ret);
570              }
571          } else {
572              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
573              callback = scanModeBlock->callback;
574          }
575      }
576  
577      if (callback != NULL) {
578          callback(retStatus, scanModeBlock->context);
579      }
580  }
581  
GapWriteInquiryScanType(void)582  static int GapWriteInquiryScanType(void)
583  {
584      LOG_DEBUG("%{public}s:", __FUNCTION__);
585      int ret;
586      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
587      HciWriteInquiryScanTypeParam hciCmdParam;
588  
589      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
590          hciCmdParam.scanType = scanModeBlock->discoverMode.type;
591          ret = HCI_WriteInquiryScanType(&hciCmdParam);
592      } else {
593          ret = GAP_ERR_INVAL_STATE;
594      }
595      return ret;
596  }
597  
GapWriteInquiryScanTypeComplete(const HciWriteInquiryScanTypeReturnParam * param)598  void GapWriteInquiryScanTypeComplete(const HciWriteInquiryScanTypeReturnParam *param)
599  {
600      LOG_DEBUG("%{public}s:", __FUNCTION__);
601      ScanModeBlock *scanModeBlock = NULL;
602      GapSetScanModeResultCallback callback = NULL;
603      uint8_t retStatus = param->status;
604  
605      if (GapIsBredrEnable() == false) {
606          LOG_ERROR("%sNot Enable.", "");
607          return;
608      }
609  
610      scanModeBlock = GapGetScanModeBlock();
611      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
612          if (retStatus == HCI_SUCCESS) {
613              int ret = GapWriteCurrentIACLAP();
614              if (ret != BT_SUCCESS) {
615                  LOG_ERROR("HCI Command Error ret = %{public}d.", ret);
616                  callback = scanModeBlock->callback;
617                  retStatus = GAP_STATUS_FAILED;
618                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
619              }
620          } else {
621              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
622              callback = scanModeBlock->callback;
623          }
624      }
625  
626      if (callback != NULL) {
627          callback(retStatus, scanModeBlock->context);
628      }
629  }
630  
GapWriteCurrentIACLAP(void)631  static int GapWriteCurrentIACLAP(void)
632  {
633      LOG_DEBUG("%{public}s:", __FUNCTION__);
634      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
635      uint8_t discoverableMode = scanModeBlock->discoverMode.mode;
636      uint8_t numCurrentIAC = 0;
637      uint32_t iacLAP[CURRENT_IAC_MAX_NUM];
638  
639      if (discoverableMode & GAP_DISCOVERABLE_MODE_GENERAL) {
640          iacLAP[numCurrentIAC] = LAP_GENERAL_INQUIRY_ACCESS;
641          numCurrentIAC++;
642      } else if (discoverableMode & GAP_DISCOVERABLE_MODE_LIMITED) {
643          iacLAP[numCurrentIAC] = LAP_GENERAL_INQUIRY_ACCESS;
644          numCurrentIAC++;
645          iacLAP[numCurrentIAC] = LAP_LIMITED_INQUIRY_ACCESS;
646          numCurrentIAC++;
647      }
648  
649      HciWriteCurrentIacLapParam param = {
650          .numCurrentIAC = numCurrentIAC,
651          .iacLAP = iacLAP,
652      };
653  
654      return HCI_WriteCurrentIacLap(&param);
655  }
656  
GapWriteCurrentIACLAPComplete(const HciWriteCurrentIacLapReturnParam * param)657  void GapWriteCurrentIACLAPComplete(const HciWriteCurrentIacLapReturnParam *param)
658  {
659      LOG_DEBUG("%{public}s:", __FUNCTION__);
660      ScanModeBlock *scanModeBlock = NULL;
661      GapSetScanModeResultCallback callback = NULL;
662      uint8_t retStatus = param->status;
663  
664      if (GapIsBredrEnable() == false) {
665          LOG_ERROR("%sNot Enable.", "");
666          return;
667      }
668  
669      scanModeBlock = GapGetScanModeBlock();
670      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
671          if (retStatus == HCI_SUCCESS) {
672              if (scanModeBlock->discoverMode.mode & GAP_INQUIRY_MODE_LIMITED) {
673                  g_gapMng.bredr.classOfDevice |= COD_LIMITED_DISCOVERABLE_BIT;
674              } else {
675                  g_gapMng.bredr.classOfDevice &= ~COD_LIMITED_DISCOVERABLE_BIT;
676              }
677  
678              int ret = GapWriteClassOfDevice(g_gapMng.bredr.classOfDevice);
679              if (ret != BT_SUCCESS) {
680                  LOG_ERROR("HCI Command Error ret = %{public}d.", ret);
681                  retStatus = GAP_STATUS_FAILED;
682                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
683                  callback = scanModeBlock->callback;
684              }
685          } else {
686              callback = scanModeBlock->callback;
687              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
688          }
689      }
690  
691      if (callback != NULL) {
692          callback(retStatus, scanModeBlock->context);
693      }
694  }
695  
GapWritePageScanActivity(void)696  static int GapWritePageScanActivity(void)
697  {
698      LOG_DEBUG("%{public}s:", __FUNCTION__);
699      int ret;
700      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
701      HciWritePageScanActivityParam hciCmdParam;
702  
703      hciCmdParam.pageScanInterval = scanModeBlock->connectableMode.scanInterval;
704      hciCmdParam.pageScanWindow = scanModeBlock->connectableMode.scanWindow;
705      ret = HCI_WritePageScanActivity(&hciCmdParam);
706      return ret;
707  }
708  
GapWritePageScanActivityComplete(const HciWritePageScanActivityReturnParam * param)709  void GapWritePageScanActivityComplete(const HciWritePageScanActivityReturnParam *param)
710  {
711      LOG_DEBUG("%{public}s:", __FUNCTION__);
712      GapSetScanModeResultCallback callback = NULL;
713      uint8_t retStatus = param->status;
714  
715      if (GapIsBredrEnable() == false) {
716          LOG_ERROR("%sNot Enable.", "");
717          return;
718      }
719  
720      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
721      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
722          if (retStatus == HCI_SUCCESS) {
723              int ret = GapWritePageScanType();
724              if (ret != BT_SUCCESS) {
725                  LOG_ERROR("HCI Command Error ret = %{public}d.", ret);
726                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
727                  callback = scanModeBlock->callback;
728                  retStatus = GAP_STATUS_FAILED;
729              }
730          } else {
731              callback = scanModeBlock->callback;
732              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
733          }
734      }
735  
736      if (callback != NULL) {
737          callback(retStatus, scanModeBlock->context);
738      }
739  }
740  
GapWritePageScanType(void)741  static int GapWritePageScanType(void)
742  {
743      LOG_DEBUG("%{public}s:", __FUNCTION__);
744      int ret;
745      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
746      HciWritePageScanTypeParam hciCmdParam;
747  
748      hciCmdParam.pageScanType = scanModeBlock->connectableMode.type;
749      ret = HCI_WritePageScanType(&hciCmdParam);
750      return ret;
751  }
752  
GapWritePageScanTypeComplete(const HciWritePageScanTypeReturnParam * param)753  void GapWritePageScanTypeComplete(const HciWritePageScanTypeReturnParam *param)
754  {
755      LOG_DEBUG("%{public}s:", __FUNCTION__);
756      GapSetScanModeResultCallback callback = NULL;
757      uint8_t retStatus = param->status;
758  
759      if (GapIsBredrEnable() == false) {
760          LOG_ERROR("%sNot Enable.", "");
761          return;
762      }
763  
764      ScanModeBlock *scanModeBlock = GapGetScanModeBlock();
765      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
766          if (retStatus == HCI_SUCCESS) {
767              int ret = GapWriteScanEnable();
768              if (ret != BT_SUCCESS) {
769                  LOG_ERROR("HCI Command Error ret = %{public}d.", ret);
770                  callback = scanModeBlock->callback;
771                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
772                  retStatus = GAP_STATUS_FAILED;
773              }
774          } else {
775              callback = scanModeBlock->callback;
776              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
777          }
778      }
779  
780      if (callback != NULL) {
781          callback(retStatus, scanModeBlock->context);
782      }
783  }
784  
GapReadLocalOobExtendedDataComplete(const HciReadLocalOobExtendedDataReturnParam * param)785  void GapReadLocalOobExtendedDataComplete(const HciReadLocalOobExtendedDataReturnParam *param)
786  {
787      if (param->status == HCI_SUCCESS) {
788          (void)memcpy_s(g_gapMng.bredr.oobData256.C, GAP_OOB_DATA_CONFIRM_SIZE, param->c256, GAP_OOB_DATA_CONFIRM_SIZE);
789          (void)memcpy_s(g_gapMng.bredr.oobData256.R, GAP_OOB_DATA_RANDOM_SIZE, param->r256, GAP_OOB_DATA_RANDOM_SIZE);
790          (void)memcpy_s(g_gapMng.bredr.oobData192.C, GAP_OOB_DATA_CONFIRM_SIZE, param->c192, GAP_OOB_DATA_CONFIRM_SIZE);
791          (void)memcpy_s(g_gapMng.bredr.oobData192.R, GAP_OOB_DATA_RANDOM_SIZE, param->r192, GAP_OOB_DATA_RANDOM_SIZE);
792      } else {
793          int ret = HCI_ReadLocalOOBData();
794          if (ret != BT_SUCCESS) {
795              LOG_WARN("%{public}s: Local OOB data read failed", __FUNCTION__);
796          }
797      }
798  }
799  
GapReadLocalOobDataComplete(const HciReadLocalOOBDataReturnParam * param)800  void GapReadLocalOobDataComplete(const HciReadLocalOOBDataReturnParam *param)
801  {
802      if (param->status == HCI_SUCCESS) {
803          (void)memset_s(g_gapMng.bredr.oobData256.C, GAP_OOB_DATA_CONFIRM_SIZE, 0x00, GAP_OOB_DATA_CONFIRM_SIZE);
804          (void)memset_s(g_gapMng.bredr.oobData256.R, GAP_OOB_DATA_RANDOM_SIZE, 0x00, GAP_OOB_DATA_RANDOM_SIZE);
805          (void)memcpy_s(g_gapMng.bredr.oobData192.C, GAP_OOB_DATA_CONFIRM_SIZE, param->C, GAP_OOB_DATA_CONFIRM_SIZE);
806          (void)memcpy_s(g_gapMng.bredr.oobData192.R, GAP_OOB_DATA_RANDOM_SIZE, param->R, GAP_OOB_DATA_RANDOM_SIZE);
807      } else {
808          (void)memset_s(g_gapMng.bredr.oobData256.C, GAP_OOB_DATA_CONFIRM_SIZE, 0x00, GAP_OOB_DATA_CONFIRM_SIZE);
809          (void)memset_s(g_gapMng.bredr.oobData256.R, GAP_OOB_DATA_RANDOM_SIZE, 0x00, GAP_OOB_DATA_RANDOM_SIZE);
810          (void)memset_s(g_gapMng.bredr.oobData192.C, GAP_OOB_DATA_CONFIRM_SIZE, 0x00, GAP_OOB_DATA_CONFIRM_SIZE);
811          (void)memset_s(g_gapMng.bredr.oobData192.R, GAP_OOB_DATA_RANDOM_SIZE, 0x00, GAP_OOB_DATA_RANDOM_SIZE);
812      }
813  }
814  
GapReadNewLocalOOBData(void)815  int GapReadNewLocalOOBData(void)
816  {
817      int ret;
818  
819      BtmLocalVersionInformation version;
820      BTM_GetLocalVersionInformation(&version);
821      if (version.hciVersion >= BLUETOOTH_CORE_SPECIFICATION_4_1) {
822          ret = HCI_ReadLocalOOBExtendedData();
823          if (ret != BT_SUCCESS) {
824              LOG_WARN("%{public}s: Local OOB data read failed", __FUNCTION__);
825          }
826      } else {
827          ret = HCI_ReadLocalOOBData();
828          if (ret != BT_SUCCESS) {
829              LOG_WARN("%{public}s: Local OOB data read failed", __FUNCTION__);
830          }
831      }
832  
833      return ret;
834  }
835  
GapIsKeyMissingRetry(void)836  bool GapIsKeyMissingRetry(void)
837  {
838      return g_gapMng.bredr.keyMissingRetry;
839  }
840  
GAP_SetKeyMissingRetry(bool retry)841  int GAP_SetKeyMissingRetry(bool retry)
842  {
843      g_gapMng.bredr.keyMissingRetry = retry;
844      return GAP_SUCCESS;
845  }
846  
GAP_SetBondableMode(uint8_t bondableMode)847  int GAP_SetBondableMode(uint8_t bondableMode)
848  {
849      LOG_INFO("%{public}s:bondable[%hhu]", __FUNCTION__, bondableMode);
850  
851      if (GapIsBredrEnable() == false) {
852          return GAP_ERR_NOT_ENABLE;
853      }
854  
855      g_gapMng.bredr.bondableMode = bondableMode;
856      if (bondableMode == GAP_BONDABLE_MODE) {
857          GapReadNewLocalOOBData();
858      }
859  
860      return GAP_SUCCESS;
861  }
862  
GapFreeRegSecInfo(void * data)863  static void GapFreeRegSecInfo(void *data)
864  {
865      MEM_MALLOC.free(data);
866  }
867  
GapFreeReqSecInfo(void * data)868  static void GapFreeReqSecInfo(void *data)
869  {
870      GapAuthenticationClearInfo(data);
871      MEM_MALLOC.free(data);
872  }
873  
GapFreeDeviceInfo(void * data)874  static void GapFreeDeviceInfo(void *data)
875  {
876      DeviceInfo *devInfo = data;
877      if (devInfo != NULL) {
878          AlarmCancel(devInfo->alarm);
879          AlarmDelete(devInfo->alarm);
880          AlarmCancel(devInfo->aclAlarm);
881          AlarmDelete(devInfo->aclAlarm);
882          if (devInfo->waitEncryptAlarm != NULL) {
883              AlarmCancel(devInfo->waitEncryptAlarm);
884              AlarmDelete(devInfo->waitEncryptAlarm);
885          }
886          MEM_MALLOC.free(devInfo);
887      }
888  }
889  
GAP_RegisterServiceSecurity(const BtAddr * addr,const GapServiceSecurityInfo * serviceInfo,uint16_t securityMode)890  int GAP_RegisterServiceSecurity(const BtAddr *addr, const GapServiceSecurityInfo *serviceInfo, uint16_t securityMode)
891  {
892      int ret = GAP_SUCCESS;
893      ListNode *node = NULL;
894      ProfileSecurityInfo *regInfo = NULL;
895  
896      if (GapIsBredrEnable() == false) {
897          return GAP_ERR_NOT_ENABLE;
898      }
899  
900      ProfileSecurityBlock *profileSecurityBlock = GapGetProfileSecurityBlock();
901      node = ListGetFirstNode(profileSecurityBlock->registerlist);
902      while (node != 0) {
903          regInfo = (ProfileSecurityInfo *)ListGetNodeData(node);
904          if ((addr == NULL || GapIsEmptyAddr(addr->addr) || GapAddrCompare(addr, &regInfo->addr)) &&
905              (regInfo->info.direction == serviceInfo->direction) &&
906              (regInfo->info.serviceId == serviceInfo->serviceId) &&
907              (regInfo->info.protocolId == serviceInfo->protocolId) &&
908              GapCompareChannelID(serviceInfo->protocolId, regInfo->info.channelId, serviceInfo->channelId)) {
909              ret = GAP_ERR_REPEATED;
910              LOG_WARN("Repeated Register Security %{public}d", serviceInfo->serviceId);
911              break;
912          }
913          node = ListGetNextNode(node);
914      }
915  
916      if (node == NULL) {
917          regInfo = MEM_MALLOC.alloc(sizeof(ProfileSecurityInfo));
918          if (regInfo == NULL) {
919              ret = GAP_ERR_OUT_OF_RES;
920          } else {
921              (void)memset_s(regInfo, sizeof(ProfileSecurityInfo), 0x00, sizeof(ProfileSecurityInfo));
922              if (addr != NULL) {
923                  (void)memcpy_s(&regInfo->addr, BT_ADDRESS_SIZE, addr, BT_ADDRESS_SIZE);
924              }
925              regInfo->info = *serviceInfo;
926              regInfo->securityMode = securityMode;
927  
928              ListAddFirst(profileSecurityBlock->registerlist, regInfo);
929          }
930      }
931  
932      if (addr != NULL) {
933          LOG_INFO("%{public}s:" BT_ADDR_FMT, __FUNCTION__, BT_ADDR_FMT_OUTPUT(addr->addr));
934      }
935  
936      return ret;
937  }
GAP_DeregisterServiceSecurity(const BtAddr * addr,const GapServiceSecurityInfo * serviceInfo)938  int GAP_DeregisterServiceSecurity(const BtAddr *addr, const GapServiceSecurityInfo *serviceInfo)
939  {
940      int ret = GAP_SUCCESS;
941      ProfileSecurityBlock *profileSecurityBlock = NULL;
942      ListNode *node = NULL;
943      ProfileSecurityInfo *regInfo = NULL;
944  
945      if (GapIsBredrEnable() == false) {
946          return GAP_ERR_NOT_ENABLE;
947      }
948  
949      profileSecurityBlock = GapGetProfileSecurityBlock();
950      node = ListGetFirstNode(profileSecurityBlock->registerlist);
951      while (node != 0) {
952          regInfo = (ProfileSecurityInfo *)ListGetNodeData(node);
953          if ((addr == NULL || GapIsEmptyAddr(addr->addr) || GapAddrCompare(addr, &regInfo->addr)) &&
954              regInfo->info.direction == serviceInfo->direction && regInfo->info.serviceId == serviceInfo->serviceId &&
955              regInfo->info.protocolId == serviceInfo->protocolId &&
956              GapCompareChannelID(serviceInfo->protocolId, regInfo->info.channelId, serviceInfo->channelId)) {
957              ListRemoveNode(profileSecurityBlock->registerlist, regInfo);
958              break;
959          }
960          node = ListGetNextNode(node);
961      }
962  
963      if (node == NULL) {
964          LOG_WARN("%{public}s:not found", __FUNCTION__);
965          ret = GAP_ERR_INVAL_PARAM;
966      }
967  
968      if (addr != NULL) {
969          LOG_INFO("%{public}s:" BT_ADDR_FMT, __FUNCTION__, BT_ADDR_FMT_OUTPUT(addr->addr));
970      }
971  
972      return ret;
973  }
974  
GapFindConnectionDeviceByAddr(void * nodeData,void * param)975  bool GapFindConnectionDeviceByAddr(void *nodeData, void *param)
976  {
977      DeviceInfo *deviceInfo = nodeData;
978      BtAddr *addr = param;
979  
980      if (!memcmp(&deviceInfo->addr, addr, sizeof(BtAddr))) {
981          return true;
982      }
983  
984      return false;
985  }
986  
GapFindConnectionDeviceByHandle(void * nodeData,void * param)987  bool GapFindConnectionDeviceByHandle(void *nodeData, void *param)
988  {
989      DeviceInfo *deviceInfo = nodeData;
990      uint16_t handle = *(uint16_t *)param;
991  
992      if (handle == deviceInfo->handle) {
993          return true;
994      }
995  
996      return false;
997  }
998  
GapFindCmpListData(void * nodeData,void * param)999  bool GapFindCmpListData(void *nodeData, void *param)
1000  {
1001      return (nodeData == param);
1002  }
1003  
GapStopUseAclConnection(void * dev)1004  void GapStopUseAclConnection(void *dev)
1005  {
1006      DeviceInfo *device = ListForEachData(GapGetConnectionInfoBlock()->devicelist, GapFindCmpListData, dev);
1007      if (device != NULL) {
1008          AlarmCancel(device->aclAlarm);
1009          BTM_AclRelease(device->handle);
1010      }
1011  }
1012  
GapUseAclConnectionTimeoutTask(void * ctx)1013  void GapUseAclConnectionTimeoutTask(void *ctx)
1014  {
1015      DeviceInfo *dev = ((GapGeneralPointerInfo *)ctx)->pointer;
1016  
1017      GapStopUseAclConnection(dev);
1018  }
1019  
GapUseAclConnectionTimeout(void * dev)1020  void GapUseAclConnectionTimeout(void *dev)
1021  {
1022      LOG_INFO("%{public}s: ", __FUNCTION__);
1023      GapGeneralPointerInfo *ctx = MEM_MALLOC.alloc(sizeof(GapGeneralPointerInfo));
1024      if (ctx == NULL) {
1025          LOG_ERROR("%{public}s: Alloc error.", __FUNCTION__);
1026          return;
1027      }
1028  
1029      ctx->pointer = dev;
1030  
1031      int ret = GapRunTaskUnBlockProcess(GapUseAclConnectionTimeoutTask, ctx, NULL);
1032      if (ret != BT_SUCCESS) {
1033          LOG_ERROR("%{public}s: Task error:%{public}d.", __FUNCTION__, ret);
1034      }
1035  }
1036  
GapStartUseAclConnection(DeviceInfo * device,uint64_t timeMs)1037  void GapStartUseAclConnection(DeviceInfo *device, uint64_t timeMs)
1038  {
1039      if (device != NULL) {
1040          AlarmCancel(device->aclAlarm);
1041          BTM_AclAddRef(device->handle);
1042          AlarmSet(device->aclAlarm, timeMs, GapUseAclConnectionTimeout, device);
1043      }
1044  }
1045  
GAP_GetLocalExtendedOOBData(GapOOBData * oobData192,GapOOBData * oobData256)1046  int GAP_GetLocalExtendedOOBData(GapOOBData *oobData192, GapOOBData *oobData256)
1047  {
1048      int ret = GAP_SUCCESS;
1049  
1050      (void)memcpy_s(oobData192, sizeof(GapOOBData), &g_gapMng.bredr.oobData192, sizeof(GapOOBData));
1051      (void)memcpy_s(oobData256, sizeof(GapOOBData), &g_gapMng.bredr.oobData256, sizeof(GapOOBData));
1052  
1053      return ret;
1054  }
1055  
GAP_GetLocalAddr(BtAddr * addr)1056  int GAP_GetLocalAddr(BtAddr *addr)
1057  {
1058      LOG_INFO("%{public}s:" BT_ADDR_FMT, __FUNCTION__, BT_ADDR_FMT_OUTPUT(addr->addr));
1059  
1060      return BTM_GetLocalAddr(addr);
1061  }
1062  
GAP_SetLocalName(const char * name,int length)1063  int GAP_SetLocalName(const char *name, int length)
1064  {
1065      HciWriteLocalNameParam param = {0};
1066  
1067      LOG_INFO("%{public}s: name:%{public}s", __FUNCTION__, name);
1068  
1069      if (GapIsBredrEnable() == false) {
1070          return GAP_ERR_NOT_ENABLE;
1071      }
1072  
1073      (void)memcpy_s(param.localName, sizeof(param.localName), name, length);
1074      return HCI_WriteLocalName(&param);
1075  }
1076  
GAP_SetClassOfDevice(uint32_t cod)1077  int GAP_SetClassOfDevice(uint32_t cod)
1078  {
1079      LOG_INFO("%{public}s: cmd:%06x", __FUNCTION__, cod);
1080  
1081      if (GapIsBredrEnable() == false) {
1082          return GAP_ERR_NOT_ENABLE;
1083      }
1084  
1085      g_gapMng.bredr.classOfDevice = cod;
1086  
1087      return GapWriteClassOfDevice(cod);
1088  }
1089  
GapWriteClassOfDevice(uint32_t cod)1090  static int GapWriteClassOfDevice(uint32_t cod)
1091  {
1092      HciWriteClassofDeviceParam param = {
1093          .classofDevice = COD_UINT_TO_ARRAY(cod),
1094      };
1095  
1096      return HCI_WriteClassofDevice(&param);
1097  }
1098  
GapWriteClassOfDeviceComplete(const HciWriteClassofDeviceReturnParam * param)1099  void GapWriteClassOfDeviceComplete(const HciWriteClassofDeviceReturnParam *param)
1100  {
1101      LOG_DEBUG("%{public}s:", __FUNCTION__);
1102      ScanModeBlock *scanModeBlock = NULL;
1103      GapSetScanModeResultCallback callback = NULL;
1104      uint8_t retStatus = param->status;
1105  
1106      if (GapIsBredrEnable() == false) {
1107          LOG_ERROR("%sNot Enable.", "");
1108          return;
1109      }
1110  
1111      scanModeBlock = GapGetScanModeBlock();
1112      if (scanModeBlock->status == GAP_SCANMODE_STATUS_SETTING) {
1113          if (retStatus == HCI_SUCCESS) {
1114              int ret;
1115              if (scanModeBlock->connectableMode.mode) {
1116                  ret = GapWritePageScanActivity();
1117              } else {
1118                  ret = GapWriteScanEnable();
1119              }
1120              if (ret != BT_SUCCESS) {
1121                  LOG_ERROR("HCI Command Error ret = %{public}d.", ret);
1122                  retStatus = GAP_STATUS_FAILED;
1123                  scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
1124                  callback = scanModeBlock->callback;
1125              }
1126          } else {
1127              scanModeBlock->status = GAP_SCANMODE_STATUS_IDLE;
1128              callback = scanModeBlock->callback;
1129          }
1130      }
1131  
1132      if (callback != NULL) {
1133          callback(retStatus, scanModeBlock->context);
1134      }
1135  }
1136  
GAP_SetExtendedInquiryResponse(const uint8_t eir[GAP_EIR_SIZE_MAX])1137  int GAP_SetExtendedInquiryResponse(const uint8_t eir[GAP_EIR_SIZE_MAX])
1138  {
1139      int ret;
1140      HciWriteExtendedInquiryResponseParam hciCmdParam;
1141  
1142      LOG_INFO("%{public}s:", __FUNCTION__);
1143  
1144      if (GapIsBredrEnable() == false) {
1145          return GAP_ERR_NOT_ENABLE;
1146      }
1147  
1148      (void)memcpy_s(hciCmdParam.extendInquiryRes, sizeof(hciCmdParam.extendInquiryRes), eir, GAP_EIR_SIZE_MAX);
1149      hciCmdParam.fecRequired = GAP_EIR_FEC_REQUIRED;
1150  
1151      ret = HCI_WriteExtendedInquiryResponse(&hciCmdParam);
1152  
1153      return ret;
1154  }
1155  
GapSetExtendedInquiryResponseComplete(const HciWriteExtendedInquiryResponseReturnParam * param)1156  void GapSetExtendedInquiryResponseComplete(const HciWriteExtendedInquiryResponseReturnParam *param)
1157  {
1158      if (param->status) {
1159          LOG_WARN("%{public}s:", __FUNCTION__);
1160      }
1161  }
1162  
GapAllocDeviceInfo(const BtAddr * addr,const uint16_t handle)1163  static DeviceInfo *GapAllocDeviceInfo(const BtAddr *addr, const uint16_t handle)
1164  {
1165      DeviceInfo *deviceInfo = MEM_MALLOC.alloc(sizeof(DeviceInfo));
1166      if (deviceInfo == NULL) {
1167          LOG_ERROR("%{public}s:malloc error.", __FUNCTION__);
1168      } else {
1169          (void)memset_s(deviceInfo, sizeof(DeviceInfo), 0x00, sizeof(DeviceInfo));
1170          deviceInfo->addr = *addr;
1171          deviceInfo->handle = handle;
1172          deviceInfo->status = GAP_DEV_SEC_STATUS_IDLE;
1173          deviceInfo->authenticationStatus = GAP_AUTH_STATUS_IDLE;
1174          deviceInfo->encryptionStatus = GAP_ENC_STATUS_IDLE;
1175          deviceInfo->inDedicatedBonding = false;
1176          deviceInfo->linkkeyType = GAP_LINK_KEY_TYPE_UNKNOWN;
1177          deviceInfo->remoteAuthReq = AUTHENTICATION_UNKNOWN_MITM;
1178          deviceInfo->alarm = AlarmCreate("gapSec", false);
1179          deviceInfo->aclAlarm = AlarmCreate("gapAcl", false);
1180      }
1181  
1182      return deviceInfo;
1183  }
1184  
GapAclConnectionComplete(const BtmAclConnectCompleteParam * param,void * context)1185  void GapAclConnectionComplete(const BtmAclConnectCompleteParam *param, void *context)
1186  {
1187      ConnectionInfoBlock *connectionInfoBlock = NULL;
1188      ProfileSecurityBlock *profileSecurityBlock = NULL;
1189      DeviceInfo *deviceInfo = NULL;
1190      RequestSecInfo *reqInfo = NULL;
1191      connectionInfoBlock = GapGetConnectionInfoBlock();
1192      profileSecurityBlock = GapGetProfileSecurityBlock();
1193      if (param->status == HCI_SUCCESS) {
1194          deviceInfo = GapAllocDeviceInfo(param->addr, param->connectionHandle);
1195          if (deviceInfo == NULL) {
1196              LOG_ERROR("%{public}s:malloc error.", __FUNCTION__);
1197          } else {
1198              ListAddFirst(connectionInfoBlock->devicelist, deviceInfo);
1199              GapUpdateSecurityRequest(deviceInfo, GAP_SEC_EVENT_CONNECT_COMP, param->status);
1200              if (*GapGetSecurityMode() != SEC_MODE_2) {
1201                  GapIsRemoteDeviceSupportHostSecureSimplePairingAsync(&deviceInfo->addr);
1202              }
1203              GapRequestSecurityProcess();
1204          }
1205      } else {
1206          ListNode *node = ListGetFirstNode(profileSecurityBlock->requestlist);
1207          while (node != 0) {
1208              reqInfo = ListGetNodeData(node);
1209              node = ListGetNextNode(node);
1210              if (!GapAddrCompare(&reqInfo->addr, param->addr)) {
1211                  continue;
1212              }
1213              if (BtmInteropIsMatchedAddr(INTEROP_AUTO_RETRY_PAIRING, param->addr)) {
1214                  GapAuthenticationRetry(NULL, reqInfo, param->status);
1215                  continue;
1216              }
1217  
1218              reqInfo->status = GAP_SEC_REQ_STATUS_FAILED;
1219              reqInfo->hciStatus = param->status;
1220              if (reqInfo->info.serviceId == GAP) {
1221                  GapDoAuthenticationCallback(reqInfo);
1222              }
1223              if (!reqInfo->doCallback) {
1224                  reqInfo->doCallback = true;
1225                  GapDoSecurityCallback(reqInfo);
1226              }
1227          }
1228      }
1229  }
1230  
GapAclDisconnectionComplete(uint8_t status,uint16_t connectionHandle,uint8_t reason,void * context)1231  void GapAclDisconnectionComplete(uint8_t status, uint16_t connectionHandle, uint8_t reason, void *context)
1232  {
1233      ConnectionInfoBlock *connectionInfoBlock = NULL;
1234      if (status == HCI_SUCCESS) {
1235          DeviceInfo *info = NULL;
1236          connectionInfoBlock = GapGetConnectionInfoBlock();
1237          info = ListForEachData(
1238              connectionInfoBlock->devicelist, GapFindConnectionDeviceByHandle, (void *)&connectionHandle);
1239          if (info != NULL) {
1240              GapUpdateSecurityRequest(info, GAP_SEC_EVENT_ACL_DISCONNECT, reason);
1241              GapRequestSecurityProcess();
1242  
1243              ListRemoveNode(connectionInfoBlock->devicelist, info);
1244          }
1245      }
1246  }
1247  
1248  #endif
1249  
1250  #ifdef GAP_LE_SUPPORT
1251  
GapAddrIsResolvablePrivateAddress(const BtAddr * addr)1252  bool GapAddrIsResolvablePrivateAddress(const BtAddr *addr)
1253  {
1254      return (addr->type == BT_RANDOM_DEVICE_ADDRESS) && (addr->addr[5] & 0x40) && !(addr->addr[5] & 0x80);
1255  }
1256  
GapAddrIsStaticAddress(const BtAddr * addr)1257  bool GapAddrIsStaticAddress(const BtAddr *addr)
1258  {
1259      return (addr->type == BT_RANDOM_DEVICE_ADDRESS) && (addr->addr[5] & 0x40) && (addr->addr[5] & 0x80);
1260  }
1261  
GapAddrIsPublicAddress(const BtAddr * addr)1262  bool GapAddrIsPublicAddress(const BtAddr *addr)
1263  {
1264      return addr->type == BT_PUBLIC_DEVICE_ADDRESS;
1265  }
1266  
GapAddrIsIdentityAddress(const BtAddr * addr)1267  bool GapAddrIsIdentityAddress(const BtAddr *addr)
1268  {
1269      return addr->type == BT_PUBLIC_IDENTITY_ADDRESS || addr->type == BT_RANDOM_IDENTITY_ADDRESS;
1270  }
1271  
GapFindLeConnectionDeviceByAddr(void * nodeData,void * param)1272  bool GapFindLeConnectionDeviceByAddr(void *nodeData, void *param)
1273  {
1274      LeDeviceInfo *deviceInfo = nodeData;
1275      BtAddr *addr = param;
1276  
1277      return GapAddrCompare(&deviceInfo->addr, addr);
1278  }
1279  
GapFindLeConnectionDeviceByHandle(void * nodeData,void * param)1280  bool GapFindLeConnectionDeviceByHandle(void *nodeData, void *param)
1281  {
1282      LeDeviceInfo *deviceInfo = nodeData;
1283      uint16_t *handle = (uint16_t *)param;
1284  
1285      return deviceInfo->handle == *handle;
1286  }
1287  
GAP_LeSetRole(uint8_t role)1288  int GAP_LeSetRole(uint8_t role)
1289  {
1290      LOG_INFO("%{public}s: role[%02x]", __FUNCTION__, role);
1291  
1292      if (GapIsLeEnable() == false) {
1293          return GAP_ERR_NOT_ENABLE;
1294      }
1295  
1296      g_gapMng.le.local.role = role;
1297      if (GapLeRolesCheck(GAP_LE_ROLE_PREIPHERAL | GAP_LE_ROLE_CENTRAL) == true) {
1298          BtmKey key;
1299          BTM_GetLocalIdentityResolvingKey(&key);
1300          SMP_SetIRK(key.key);
1301          SMP_SetIdentAddr(&g_gapMng.le.local.addr);
1302      }
1303  
1304      return GAP_SUCCESS;
1305  }
1306  
GAP_LeSetStaticIdentityAddr(uint8_t addr[BT_ADDRESS_SIZE])1307  int GAP_LeSetStaticIdentityAddr(uint8_t addr[BT_ADDRESS_SIZE])
1308  {
1309      int ret;
1310      LeLocalInfo *localInfo = NULL;
1311  
1312      LOG_INFO("%{public}s:" BT_ADDR_FMT, __FUNCTION__, BT_ADDR_FMT_OUTPUT(addr));
1313  
1314      if (GapIsLeEnable() == false) {
1315          return GAP_ERR_NOT_ENABLE;
1316      }
1317  
1318      localInfo = GapGetLeLocalInfo();
1319      if (localInfo->addr.type == BT_PUBLIC_DEVICE_ADDRESS) {
1320          LOG_WARN("%{public}s: have public address " BT_ADDR_FMT, __FUNCTION__, BT_ADDR_FMT_OUTPUT(localInfo->addr.addr));
1321          localInfo->addr.type = BT_RANDOM_DEVICE_ADDRESS;
1322      }
1323      (void)memcpy_s(localInfo->addr.addr, BT_ADDRESS_SIZE, addr, BT_ADDRESS_SIZE);
1324      ret = SMP_SetIdentAddr(&localInfo->addr);
1325  
1326      return ret;
1327  }
1328  
GapGenerateRPAResult(uint8_t status,const uint8_t * addr)1329  NO_SANITIZE("cfi") void GapGenerateRPAResult(uint8_t status, const uint8_t *addr)
1330  {
1331      GenResPriAddrResult callback = NULL;
1332      void *context = NULL;
1333  
1334      if (GapGetLeRandomAddressBlock()->generationInfo.processing) {
1335          callback = GapGetLeRandomAddressBlock()->generationInfo.callback;
1336          context = GapGetLeRandomAddressBlock()->generationInfo.context;
1337  
1338          GapGetLeRandomAddressBlock()->generationInfo.processing = false;
1339          GapGetLeRandomAddressBlock()->generationInfo.callback = NULL;
1340          GapGetLeRandomAddressBlock()->generationInfo.context = NULL;
1341      }
1342  
1343      if (callback != NULL) {
1344          callback(status, addr, context);
1345      }
1346  }
1347  
GAP_LeGenResPriAddrAsync(GenResPriAddrResult callback,void * context)1348  int GAP_LeGenResPriAddrAsync(GenResPriAddrResult callback, void *context)
1349  {
1350      LOG_INFO("%{public}s:", __FUNCTION__);
1351      int ret;
1352  
1353      BtmKey localIRK = {0};
1354  
1355      ret = BTM_GetLocalIdentityResolvingKey(&localIRK);
1356      if (ret != BT_SUCCESS) {
1357          return ret;
1358      }
1359  
1360      ret = SMP_GenerateRPA(localIRK.key);
1361      if (ret != BT_SUCCESS) {
1362          return ret;
1363      }
1364  
1365      if (GapGetLeRandomAddressBlock()->generationInfo.processing == false) {
1366          GapGetLeRandomAddressBlock()->generationInfo.callback = callback;
1367          GapGetLeRandomAddressBlock()->generationInfo.context = context;
1368          GapGetLeRandomAddressBlock()->generationInfo.processing = true;
1369      } else {
1370          ret = GAP_ERR_INVAL_STATE;
1371      }
1372  
1373      return ret;
1374  }
1375  
1376  #endif
1377  
1378  Module g_gap = {
1379      .name = MODULE_NAME_GAP,
1380      .init = GapInitialize,
1381      .startup = GapEnable,
1382      .shutdown = GapDisable,
1383      .cleanup = GapFinalize,
1384      .dependencies = {MODULE_NAME_HCI, MODULE_NAME_L2CAP, MODULE_NAME_SMP},
1385  };
1386  
1387  MODULE_DECL(g_gap)
1388