• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2003-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains action functions for the audio gateway.
22  *
23  ******************************************************************************/
24 
25 #include <base/logging.h>
26 
27 #include <cstdint>
28 #include <cstring>
29 
30 #include "bta/ag/bta_ag_int.h"
31 #include "bta/include/bta_dm_api.h"
32 
33 #ifdef __ANDROID__
34 #include "bta/le_audio/devices.h"
35 #endif
36 
37 #include "btif/include/btif_config.h"
38 #include "device/include/device_iot_config.h"
39 #include "os/system_properties.h"
40 #include "osi/include/osi.h"  // UNUSED_ATTR
41 #include "stack/include/l2c_api.h"
42 #include "stack/include/port_api.h"
43 #include "types/raw_address.h"
44 
45 /*****************************************************************************
46  *  Constants
47  ****************************************************************************/
48 
49 /* maximum length of data to read from RFCOMM */
50 #define BTA_AG_RFC_READ_MAX 512
51 
52 /* maximum AT command length */
53 #define BTA_AG_CMD_MAX 512
54 
55 const uint16_t bta_ag_uuid[BTA_AG_NUM_IDX] = {
56     UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, UUID_SERVCLASS_AG_HANDSFREE};
57 
58 const uint8_t bta_ag_sec_id[BTA_AG_NUM_IDX] = {BTM_SEC_SERVICE_HEADSET_AG,
59                                                BTM_SEC_SERVICE_AG_HANDSFREE};
60 
61 const tBTA_SERVICE_ID bta_ag_svc_id[BTA_AG_NUM_IDX] = {BTA_HSP_SERVICE_ID,
62                                                        BTA_HFP_SERVICE_ID};
63 
64 const tBTA_SERVICE_MASK bta_ag_svc_mask[BTA_AG_NUM_IDX] = {
65     BTA_HSP_SERVICE_MASK, BTA_HFP_SERVICE_MASK};
66 
67 typedef void (*tBTA_AG_ATCMD_CBACK)(tBTA_AG_SCB* p_scb, uint16_t cmd,
68                                     uint8_t arg_type, char* p_arg, char* p_end,
69                                     int16_t int_arg);
70 
71 const tBTA_AG_ATCMD_CBACK bta_ag_at_cback_tbl[BTA_AG_NUM_IDX] = {
72     bta_ag_at_hsp_cback, bta_ag_at_hfp_cback};
73 
74 /*******************************************************************************
75  *
76  * Function         bta_ag_cback_open
77  *
78  * Description      Send open callback event to application.
79  *
80  *
81  * Returns          void
82  *
83  ******************************************************************************/
bta_ag_cback_open(tBTA_AG_SCB * p_scb,const RawAddress & bd_addr,tBTA_AG_STATUS status)84 static void bta_ag_cback_open(tBTA_AG_SCB* p_scb, const RawAddress& bd_addr,
85                               tBTA_AG_STATUS status) {
86   tBTA_AG_OPEN open = {};
87 
88   /* call app callback with open event */
89   open.hdr.handle = bta_ag_scb_to_idx(p_scb);
90   open.hdr.app_id = p_scb->app_id;
91   open.status = status;
92   open.service_id = bta_ag_svc_id[p_scb->conn_service];
93   open.bd_addr = bd_addr;
94 
95   (*bta_ag_cb.p_cback)(BTA_AG_OPEN_EVT, (tBTA_AG*)&open);
96 }
97 
98 /*******************************************************************************
99  *
100  * Function         bta_ag_register
101  *
102  * Description      This function initializes values of the AG cb and sets up
103  *                  the SDP record for the services.
104  *
105  *
106  * Returns          void
107  *
108  ******************************************************************************/
bta_ag_register(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)109 void bta_ag_register(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
110   /* initialize control block */
111   p_scb->reg_services = data.api_register.services;
112   p_scb->features = data.api_register.features;
113   p_scb->masked_features = data.api_register.features;
114   p_scb->app_id = data.api_register.app_id;
115 
116   /* create SDP records */
117   bta_ag_create_records(p_scb, data);
118 
119   /* start RFCOMM servers */
120   bta_ag_start_servers(p_scb, p_scb->reg_services);
121 
122   /* call app callback with register event */
123   tBTA_AG_REGISTER reg = {};
124   reg.hdr.handle = bta_ag_scb_to_idx(p_scb);
125   reg.hdr.app_id = p_scb->app_id;
126   reg.status = BTA_AG_SUCCESS;
127   (*bta_ag_cb.p_cback)(BTA_AG_REGISTER_EVT, (tBTA_AG*)&reg);
128 }
129 
130 /*******************************************************************************
131  *
132  * Function         bta_ag_deregister
133  *
134  * Description      This function removes the sdp records, closes the RFCOMM
135  *                  servers, and deallocates the service control block.
136  *
137  *
138  * Returns          void
139  *
140  ******************************************************************************/
bta_ag_deregister(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)141 void bta_ag_deregister(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
142   /* set dealloc */
143   p_scb->dealloc = true;
144 
145   /* remove sdp records */
146   bta_ag_del_records(p_scb);
147 
148   /* remove rfcomm servers */
149   bta_ag_close_servers(p_scb, p_scb->reg_services);
150 
151   /* dealloc */
152   bta_ag_scb_dealloc(p_scb);
153 }
154 
155 /*******************************************************************************
156  *
157  * Function         bta_ag_start_dereg
158  *
159  * Description      Start a deregister event.
160  *
161  *
162  * Returns          void
163  *
164  ******************************************************************************/
bta_ag_start_dereg(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)165 void bta_ag_start_dereg(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
166   /* set dealloc */
167   p_scb->dealloc = true;
168 
169   /* remove sdp records */
170   bta_ag_del_records(p_scb);
171 }
172 
173 /*******************************************************************************
174  *
175  * Function         bta_ag_start_open
176  *
177  * Description      This starts an AG open.
178  *
179  *
180  * Returns          void
181  *
182  ******************************************************************************/
bta_ag_start_open(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)183 void bta_ag_start_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
184   p_scb->peer_addr = data.api_open.bd_addr;
185   p_scb->open_services = p_scb->reg_services;
186 
187   /* Check if RFCOMM has any incoming connection to avoid collision. */
188   RawAddress pending_bd_addr = RawAddress::kEmpty;
189   if (PORT_IsOpening(&pending_bd_addr)) {
190     /* Let the incoming connection goes through.                        */
191     /* Issue collision for this scb for now.                            */
192     /* We will decide what to do when we find incoming connetion later. */
193     bta_ag_collision_cback(BTA_SYS_CONN_OPEN, BTA_ID_AG, 0, p_scb->peer_addr);
194     return;
195   }
196 
197   /* close servers */
198   bta_ag_close_servers(p_scb, p_scb->reg_services);
199 
200   /* set role */
201   p_scb->role = BTA_AG_INT;
202 
203   /* do service search */
204   bta_ag_do_disc(p_scb, p_scb->open_services);
205 }
206 
207 /*******************************************************************************
208  *
209  * Function         bta_ag_disc_int_res
210  *
211  * Description      This function handles a discovery result when initiator.
212  *
213  *
214  * Returns          void
215  *
216  ******************************************************************************/
bta_ag_disc_int_res(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)217 void bta_ag_disc_int_res(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
218   uint16_t event = BTA_AG_DISC_FAIL_EVT;
219 
220   APPL_TRACE_DEBUG("bta_ag_disc_int_res: Status: %d", data.disc_result.status);
221 
222   /* if found service */
223   if (data.disc_result.status == SDP_SUCCESS ||
224       data.disc_result.status == SDP_DB_FULL) {
225     /* get attributes */
226     if (bta_ag_sdp_find_attr(p_scb, p_scb->open_services)) {
227       /* set connected service */
228       p_scb->conn_service = bta_ag_service_to_idx(p_scb->open_services);
229 
230       /* send ourselves sdp ok event */
231       event = BTA_AG_DISC_OK_EVT;
232 
233       DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(
234           p_scb->peer_addr, IOT_CONF_KEY_HFP_VERSION, p_scb->peer_version,
235           IOT_CONF_BYTE_NUM_2);
236     }
237   }
238 
239   /* free discovery db */
240   bta_ag_free_db(p_scb, data);
241 
242   /* if service not found check if we should search for other service */
243   if ((event == BTA_AG_DISC_FAIL_EVT) &&
244       (data.disc_result.status == SDP_SUCCESS ||
245        data.disc_result.status == SDP_DB_FULL ||
246        data.disc_result.status == SDP_NO_RECS_MATCH)) {
247     if ((p_scb->open_services & BTA_HFP_SERVICE_MASK) &&
248         (p_scb->open_services & BTA_HSP_SERVICE_MASK)) {
249       /* search for HSP */
250       p_scb->open_services &= ~BTA_HFP_SERVICE_MASK;
251       bta_ag_do_disc(p_scb, p_scb->open_services);
252     } else if ((p_scb->open_services & BTA_HSP_SERVICE_MASK) &&
253                (p_scb->hsp_version == HSP_VERSION_1_2)) {
254       /* search for UUID_SERVCLASS_HEADSET instead */
255       p_scb->hsp_version = HSP_VERSION_1_0;
256       bta_ag_do_disc(p_scb, p_scb->open_services);
257     } else {
258       /* send ourselves sdp ok/fail event */
259       bta_ag_sm_execute(p_scb, event, data);
260     }
261   } else {
262     /* send ourselves sdp ok/fail event */
263     bta_ag_sm_execute(p_scb, event, data);
264   }
265 }
266 
267 /*******************************************************************************
268  *
269  * Function         bta_ag_disc_acp_res
270  *
271  * Description      This function handles a discovery result when acceptor.
272  *
273  *
274  * Returns          void
275  *
276  ******************************************************************************/
bta_ag_disc_acp_res(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)277 void bta_ag_disc_acp_res(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
278   /* if found service */
279   if (data.disc_result.status == SDP_SUCCESS ||
280       data.disc_result.status == SDP_DB_FULL) {
281     /* get attributes */
282     bta_ag_sdp_find_attr(p_scb, bta_ag_svc_mask[p_scb->conn_service]);
283     DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(
284         p_scb->peer_addr, IOT_CONF_KEY_HFP_VERSION, p_scb->peer_version,
285         IOT_CONF_BYTE_NUM_2);
286   }
287 
288   /* free discovery db */
289   bta_ag_free_db(p_scb, data);
290 }
291 
292 /*******************************************************************************
293  *
294  * Function         bta_ag_disc_fail
295  *
296  * Description      This function handles a discovery failure.
297  *
298  *
299  * Returns          void
300  *
301  ******************************************************************************/
bta_ag_disc_fail(tBTA_AG_SCB * p_scb,UNUSED_ATTR const tBTA_AG_DATA & data)302 void bta_ag_disc_fail(tBTA_AG_SCB* p_scb,
303                       UNUSED_ATTR const tBTA_AG_DATA& data) {
304   /* reopen registered servers */
305   bta_ag_start_servers(p_scb, p_scb->reg_services);
306 
307   /* reinitialize stuff */
308 
309   /* clear the remote BD address */
310   RawAddress peer_addr = p_scb->peer_addr;
311   p_scb->peer_addr = RawAddress::kEmpty;
312 
313   /* call open cback w. failure */
314   bta_ag_cback_open(p_scb, peer_addr, BTA_AG_FAIL_SDP);
315 }
316 
317 /*******************************************************************************
318  *
319  * Function         bta_ag_open_fail
320  *
321  * Description      open connection failed.
322  *
323  *
324  * Returns          void
325  *
326  ******************************************************************************/
bta_ag_open_fail(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)327 void bta_ag_open_fail(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
328   /* call open cback w. failure */
329   LOG_DEBUG("state [0x%02x]", p_scb->state);
330   bta_ag_cback_open(p_scb, data.api_open.bd_addr, BTA_AG_FAIL_RESOURCES);
331 }
332 
333 /*******************************************************************************
334  *
335  * Function         bta_ag_rfc_fail
336  *
337  * Description      RFCOMM connection failed.
338  *
339  *
340  * Returns          void
341  *
342  ******************************************************************************/
bta_ag_rfc_fail(tBTA_AG_SCB * p_scb,UNUSED_ATTR const tBTA_AG_DATA & data)343 void bta_ag_rfc_fail(tBTA_AG_SCB* p_scb, UNUSED_ATTR const tBTA_AG_DATA& data) {
344   RawAddress peer_addr = p_scb->peer_addr;
345   /* reinitialize stuff */
346   p_scb->conn_handle = 0;
347   p_scb->conn_service = 0;
348   p_scb->peer_features = 0;
349   p_scb->peer_codecs = BTM_SCO_CODEC_CVSD;
350   p_scb->sco_codec = BTM_SCO_CODEC_CVSD;
351   p_scb->role = 0;
352   p_scb->svc_conn = false;
353   p_scb->hsp_version = HSP_VERSION_1_2;
354   /*Clear the BD address*/
355   p_scb->peer_addr = RawAddress::kEmpty;
356 
357   /* reopen registered servers */
358   bta_ag_start_servers(p_scb, p_scb->reg_services);
359 
360   /* call open cback w. failure */
361   bta_ag_cback_open(p_scb, peer_addr, BTA_AG_FAIL_RFCOMM);
362 }
363 
364 /*******************************************************************************
365  *
366  * Function         bta_ag_rfc_close
367  *
368  * Description      RFCOMM connection closed.
369  *
370  *
371  * Returns          void
372  *
373  ******************************************************************************/
bta_ag_rfc_close(tBTA_AG_SCB * p_scb,UNUSED_ATTR const tBTA_AG_DATA & data)374 void bta_ag_rfc_close(tBTA_AG_SCB* p_scb,
375                       UNUSED_ATTR const tBTA_AG_DATA& data) {
376   tBTA_AG_CLOSE close = {};
377   tBTA_SERVICE_MASK services;
378   int i, num_active_conn = 0;
379 
380   /* reinitialize stuff */
381   p_scb->conn_service = 0;
382   p_scb->peer_features = 0;
383   p_scb->masked_features = p_scb->features;
384   p_scb->peer_codecs = BTM_SCO_CODEC_CVSD;
385   p_scb->sco_codec = BTM_SCO_CODEC_CVSD;
386   /* Clear these flags upon SLC teardown */
387   p_scb->codec_updated = false;
388   p_scb->codec_fallback = false;
389   p_scb->codec_msbc_settings = BTA_AG_SCO_MSBC_SETTINGS_T2;
390   p_scb->codec_lc3_settings = BTA_AG_SCO_LC3_SETTINGS_T2;
391   p_scb->role = 0;
392   p_scb->svc_conn = false;
393   p_scb->hsp_version = HSP_VERSION_1_2;
394   bta_ag_at_reinit(&p_scb->at_cb);
395 
396   for (auto& peer_hf_indicator : p_scb->peer_hf_indicators) {
397     peer_hf_indicator = {};
398   }
399   for (auto& local_hf_indicator : p_scb->local_hf_indicators) {
400     local_hf_indicator = {};
401   }
402 
403   /* stop timers */
404   alarm_cancel(p_scb->ring_timer);
405   alarm_cancel(p_scb->codec_negotiation_timer);
406 
407   close.hdr.handle = bta_ag_scb_to_idx(p_scb);
408   close.hdr.app_id = p_scb->app_id;
409   close.bd_addr = p_scb->peer_addr;
410 
411   bta_sys_conn_close(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
412 
413   if (bta_ag_get_active_device() == p_scb->peer_addr) {
414     bta_clear_active_device();
415   }
416 
417   /* call close cback */
418   (*bta_ag_cb.p_cback)(BTA_AG_CLOSE_EVT, (tBTA_AG*)&close);
419 
420   /* if not deregistering (deallocating) reopen registered servers */
421   if (!p_scb->dealloc) {
422     /* Clear peer bd_addr so instance can be reused */
423     p_scb->peer_addr = RawAddress::kEmpty;
424 
425     /* start only unopened server */
426     services = p_scb->reg_services;
427     for (i = 0; i < BTA_AG_NUM_IDX && services != 0; i++) {
428       if (p_scb->serv_handle[i])
429         services &= ~((tBTA_SERVICE_MASK)1 << (BTA_HSP_SERVICE_ID + i));
430     }
431     bta_ag_start_servers(p_scb, services);
432 
433     p_scb->conn_handle = 0;
434 
435     /* Make sure SCO state is BTA_AG_SCO_SHUTDOWN_ST */
436     bta_ag_sco_shutdown(p_scb, tBTA_AG_DATA::kEmpty);
437 
438     /* Check if all the SLCs are down */
439     for (i = 0; i < BTA_AG_MAX_NUM_CLIENTS; i++) {
440       if (bta_ag_cb.scb[i].in_use && bta_ag_cb.scb[i].svc_conn)
441         num_active_conn++;
442     }
443 
444     if (!num_active_conn) {
445       bta_sys_sco_unuse(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
446     }
447 
448   }
449   /* else close port and deallocate scb */
450   else {
451     RFCOMM_RemoveServer(p_scb->conn_handle);
452     bta_ag_scb_dealloc(p_scb);
453   }
454 }
455 
456 /*******************************************************************************
457  *
458  * Function         bta_ag_rfc_open
459  *
460  * Description      Handle RFCOMM channel open.
461  *
462  *
463  * Returns          void
464  *
465  ******************************************************************************/
bta_ag_rfc_open(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)466 void bta_ag_rfc_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
467   /* initialize AT feature variables */
468   p_scb->clip_enabled = false;
469   p_scb->ccwa_enabled = false;
470   p_scb->cmer_enabled = false;
471   p_scb->cmee_enabled = false;
472   p_scb->inband_enabled =
473       ((p_scb->features & BTA_AG_FEAT_INBAND) == BTA_AG_FEAT_INBAND);
474   if (p_scb->conn_service == BTA_AG_HFP) {
475     size_t version_value_size = sizeof(p_scb->peer_version);
476     if (!btif_config_get_bin(
477             p_scb->peer_addr.ToString(), HFP_VERSION_CONFIG_KEY,
478             (uint8_t*)&p_scb->peer_version, &version_value_size)) {
479       APPL_TRACE_WARNING("%s: Failed read cached peer HFP version for %s",
480                          __func__, ADDRESS_TO_LOGGABLE_CSTR(p_scb->peer_addr));
481       p_scb->peer_version = HFP_HSP_VERSION_UNKNOWN;
482     }
483     size_t sdp_features_size = sizeof(p_scb->peer_sdp_features);
484     if (btif_config_get_bin(
485             p_scb->peer_addr.ToString(), HFP_SDP_FEATURES_CONFIG_KEY,
486             (uint8_t*)&p_scb->peer_sdp_features, &sdp_features_size)) {
487       bool sdp_wbs_support = p_scb->peer_sdp_features & BTA_AG_FEAT_WBS_SUPPORT;
488       if (!p_scb->received_at_bac && sdp_wbs_support) {
489         p_scb->codec_updated = true;
490         p_scb->peer_codecs = BTM_SCO_CODEC_CVSD | BTM_SCO_CODEC_MSBC;
491         p_scb->sco_codec = BTM_SCO_CODEC_MSBC;
492       }
493       bool sdp_swb_support = p_scb->peer_sdp_features & BTA_AG_FEAT_SWB_SUPPORT;
494       if (!p_scb->received_at_bac && sdp_swb_support) {
495         p_scb->codec_updated = true;
496         p_scb->peer_codecs |= BTM_SCO_CODEC_LC3;
497         p_scb->sco_codec = BTM_SCO_CODEC_LC3;
498       }
499     } else {
500       APPL_TRACE_WARNING("%s: Failed read cached peer HFP SDP features for %s",
501                          __func__, ADDRESS_TO_LOGGABLE_CSTR(p_scb->peer_addr));
502     }
503   }
504 
505   /* set up AT command interpreter */
506   p_scb->at_cb.p_at_tbl = bta_ag_at_tbl[p_scb->conn_service];
507   p_scb->at_cb.p_cmd_cback = bta_ag_at_cback_tbl[p_scb->conn_service];
508   p_scb->at_cb.p_err_cback = bta_ag_at_err_cback;
509   p_scb->at_cb.p_user = p_scb;
510   p_scb->at_cb.cmd_max_len = BTA_AG_CMD_MAX;
511   bta_ag_at_init(&p_scb->at_cb);
512 
513   bta_sys_conn_open(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
514 
515   bta_ag_cback_open(p_scb, p_scb->peer_addr, BTA_AG_SUCCESS);
516 
517   if (p_scb->conn_service == BTA_AG_HFP) {
518     /* if hfp start timer for service level conn */
519     bta_sys_start_timer(p_scb->ring_timer, p_bta_ag_cfg->conn_tout,
520                         BTA_AG_SVC_TIMEOUT_EVT, bta_ag_scb_to_idx(p_scb));
521   } else {
522     /* else service level conn is open */
523     bta_ag_svc_conn_open(p_scb, data);
524   }
525 }
526 
527 /*******************************************************************************
528  *
529  * Function         bta_ag_rfc_acp_open
530  *
531  * Description      Handle RFCOMM channel open when accepting connection.
532  *
533  *
534  * Returns          void
535  *
536  ******************************************************************************/
bta_ag_rfc_acp_open(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)537 void bta_ag_rfc_acp_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
538   APPL_TRACE_DEBUG("%s: serv_handle0 = %d serv_handle = %d", __func__,
539                    p_scb->serv_handle[0], p_scb->serv_handle[1]);
540   /* set role */
541   p_scb->role = BTA_AG_ACP;
542 
543   /* get bd addr of peer */
544   uint16_t lcid = 0;
545   uint16_t hfp_version = 0;
546   RawAddress dev_addr = RawAddress::kEmpty;
547   int status = PORT_CheckConnection(data.rfc.port_handle, &dev_addr, &lcid);
548   if (status != PORT_SUCCESS) {
549     LOG(ERROR) << __func__ << ", PORT_CheckConnection returned " << status;
550     return;
551   }
552 
553   /* Collision Handling */
554   for (tBTA_AG_SCB& ag_scb : bta_ag_cb.scb) {
555     // Cancel any pending collision timers
556     if (ag_scb.in_use && alarm_is_scheduled(ag_scb.collision_timer)) {
557       VLOG(1) << __func__ << ": cancel collision alarm for "
558               << ag_scb.peer_addr;
559       alarm_cancel(ag_scb.collision_timer);
560       if (dev_addr != ag_scb.peer_addr && p_scb != &ag_scb) {
561         // Resume outgoing connection if incoming is not on the same device
562         bta_ag_resume_open(&ag_scb);
563       }
564     }
565     if (dev_addr == ag_scb.peer_addr && p_scb != &ag_scb) {
566       VLOG(1) << __func__ << ": fail outgoing connection before accepting "
567               << ag_scb.peer_addr;
568       // Fail the outgoing connection to clean up any upper layer states
569       bta_ag_rfc_fail(&ag_scb, tBTA_AG_DATA::kEmpty);
570       // If client port is opened, close it
571       if (ag_scb.conn_handle > 0) {
572         status = RFCOMM_RemoveConnection(ag_scb.conn_handle);
573         if (status != PORT_SUCCESS) {
574           LOG(WARNING) << __func__ << ": RFCOMM_RemoveConnection failed for "
575                        << dev_addr << ", handle "
576                        << std::to_string(ag_scb.conn_handle) << ", error "
577                        << status;
578         }
579       }
580     }
581     VLOG(1) << __func__ << ": dev_addr=" << dev_addr
582             << ", peer_addr=" << ag_scb.peer_addr
583             << ", in_use=" << ag_scb.in_use
584             << ", index=" << bta_ag_scb_to_idx(p_scb);
585   }
586 
587   p_scb->peer_addr = dev_addr;
588 
589   /* determine connected service from port handle */
590   for (uint8_t i = 0; i < BTA_AG_NUM_IDX; i++) {
591     APPL_TRACE_DEBUG(
592         "bta_ag_rfc_acp_open: i = %d serv_handle = %d port_handle = %d", i,
593         p_scb->serv_handle[i], data.rfc.port_handle);
594 
595     if (p_scb->serv_handle[i] == data.rfc.port_handle) {
596       p_scb->conn_service = i;
597       p_scb->conn_handle = data.rfc.port_handle;
598       break;
599     }
600   }
601 
602   APPL_TRACE_DEBUG("bta_ag_rfc_acp_open: conn_service = %d conn_handle = %d",
603                    p_scb->conn_service, p_scb->conn_handle);
604 
605   /* close any unopened server */
606   bta_ag_close_servers(
607       p_scb, (p_scb->reg_services & ~bta_ag_svc_mask[p_scb->conn_service]));
608 
609   size_t version_value_size = sizeof(hfp_version);
610   bool get_version =
611       btif_config_get_bin(p_scb->peer_addr.ToString(), HFP_VERSION_CONFIG_KEY,
612                           (uint8_t*)&hfp_version, &version_value_size);
613 
614   if (p_scb->conn_service == BTA_AG_HFP && get_version) {
615     DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_scb->peer_addr,
616                                               IOT_CONF_KEY_HFP_VERSION,
617                                               hfp_version, IOT_CONF_BYTE_NUM_2);
618   }
619   /* do service discovery to get features */
620   bta_ag_do_disc(p_scb, bta_ag_svc_mask[p_scb->conn_service]);
621 
622   /* continue with common open processing */
623   bta_ag_rfc_open(p_scb, data);
624 }
625 
626 /*******************************************************************************
627  *
628  * Function         bta_ag_rfc_data
629  *
630  * Description      Read and process data from RFCOMM.
631  *
632  *
633  * Returns          void
634  *
635  ******************************************************************************/
bta_ag_rfc_data(tBTA_AG_SCB * p_scb,UNUSED_ATTR const tBTA_AG_DATA & data)636 void bta_ag_rfc_data(tBTA_AG_SCB* p_scb, UNUSED_ATTR const tBTA_AG_DATA& data) {
637   uint16_t len;
638   char buf[BTA_AG_RFC_READ_MAX] = "";
639 
640   APPL_TRACE_DEBUG("%s", __func__);
641 
642   /* do the following */
643   for (;;) {
644     /* read data from rfcomm; if bad status, we're done */
645     if (PORT_ReadData(p_scb->conn_handle, buf, BTA_AG_RFC_READ_MAX, &len) !=
646         PORT_SUCCESS) {
647       LOG(ERROR) << __func__ << ": failed to read data " << p_scb->peer_addr;
648       break;
649     }
650 
651     /* if no data, we're done */
652     if (len == 0) {
653       LOG(WARNING) << __func__ << ": no data for " << p_scb->peer_addr;
654       break;
655     }
656 
657     /* run AT command interpreter on data */
658     bta_sys_busy(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
659     bta_ag_at_parse(&p_scb->at_cb, buf, len);
660     if ((p_scb->sco_idx != BTM_INVALID_SCO_INDEX) &&
661         bta_ag_sco_is_open(p_scb)) {
662       APPL_TRACE_DEBUG("%s change link policy for SCO", __func__);
663       bta_sys_sco_open(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
664     } else {
665       bta_sys_idle(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
666     }
667 
668     /* no more data to read, we're done */
669     if (len < BTA_AG_RFC_READ_MAX) {
670       break;
671     }
672   }
673 }
674 
675 /*******************************************************************************
676  *
677  * Function         bta_ag_start_close
678  *
679  * Description      Start the process of closing SCO and RFCOMM connection.
680  *
681  *
682  * Returns          void
683  *
684  ******************************************************************************/
bta_ag_start_close(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)685 void bta_ag_start_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
686   /* Take the link out of sniff and set L2C idle time to 0 */
687   bta_dm_pm_active(p_scb->peer_addr);
688   L2CA_SetIdleTimeoutByBdAddr(p_scb->peer_addr, 0, BT_TRANSPORT_BR_EDR);
689 
690   /* if SCO is open close SCO and wait on RFCOMM close */
691   if (bta_ag_sco_is_open(p_scb)) {
692     p_scb->post_sco = BTA_AG_POST_SCO_CLOSE_RFC;
693   } else {
694     p_scb->post_sco = BTA_AG_POST_SCO_NONE;
695     bta_ag_rfc_do_close(p_scb, data);
696   }
697 
698   /* always do SCO shutdown to handle all SCO corner cases */
699   bta_ag_sco_shutdown(p_scb, data);
700 }
701 
702 /*******************************************************************************
703  *
704  * Function         bta_ag_post_sco_open
705  *
706  * Description      Perform post-SCO open action, if any
707  *
708  *
709  * Returns          void
710  *
711  ******************************************************************************/
bta_ag_post_sco_open(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)712 void bta_ag_post_sco_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
713   switch (p_scb->post_sco) {
714     case BTA_AG_POST_SCO_RING:
715       bta_ag_send_ring(p_scb, data);
716       p_scb->post_sco = BTA_AG_POST_SCO_NONE;
717       break;
718 
719     case BTA_AG_POST_SCO_CALL_CONN:
720       bta_ag_send_call_inds(p_scb, BTA_AG_IN_CALL_CONN_RES);
721       p_scb->post_sco = BTA_AG_POST_SCO_NONE;
722       break;
723 
724     default:
725       break;
726   }
727 }
728 
729 /*******************************************************************************
730  *
731  * Function         bta_ag_post_sco_close
732  *
733  * Description      Perform post-SCO close action, if any
734  *
735  *
736  * Returns          void
737  *
738  ******************************************************************************/
bta_ag_post_sco_close(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)739 void bta_ag_post_sco_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
740   switch (p_scb->post_sco) {
741     case BTA_AG_POST_SCO_CLOSE_RFC:
742       bta_ag_rfc_do_close(p_scb, data);
743       p_scb->post_sco = BTA_AG_POST_SCO_NONE;
744       break;
745 
746     case BTA_AG_POST_SCO_CALL_CONN:
747       bta_ag_send_call_inds(p_scb, BTA_AG_IN_CALL_CONN_RES);
748       p_scb->post_sco = BTA_AG_POST_SCO_NONE;
749       break;
750 
751     case BTA_AG_POST_SCO_CALL_ORIG:
752       bta_ag_send_call_inds(p_scb, BTA_AG_OUT_CALL_ORIG_RES);
753       p_scb->post_sco = BTA_AG_POST_SCO_NONE;
754       break;
755 
756     case BTA_AG_POST_SCO_CALL_END:
757       bta_ag_send_call_inds(p_scb, BTA_AG_END_CALL_RES);
758       p_scb->post_sco = BTA_AG_POST_SCO_NONE;
759       break;
760 
761     case BTA_AG_POST_SCO_CALL_END_INCALL:
762       bta_ag_send_call_inds(p_scb, BTA_AG_END_CALL_RES);
763 
764       /* Sending callsetup IND and Ring were defered to after SCO close. */
765       bta_ag_send_call_inds(p_scb, BTA_AG_IN_CALL_RES);
766 
767       if (bta_ag_inband_enabled(p_scb) &&
768           !(p_scb->features & BTA_AG_FEAT_NOSCO)) {
769         p_scb->post_sco = BTA_AG_POST_SCO_RING;
770         if (!bta_ag_is_sco_open_allowed(p_scb,
771                                         "BTA_AG_POST_SCO_CALL_END_INCALL")) {
772           break;
773         }
774         bta_ag_sco_open(p_scb, data);
775       } else {
776         p_scb->post_sco = BTA_AG_POST_SCO_NONE;
777         bta_ag_send_ring(p_scb, data);
778       }
779       break;
780 
781     default:
782       break;
783   }
784 }
785 
786 /*******************************************************************************
787  *
788  * Function         bta_ag_svc_conn_open
789  *
790  * Description      Service level connection opened
791  *
792  *
793  * Returns          void
794  *
795  ******************************************************************************/
bta_ag_svc_conn_open(tBTA_AG_SCB * p_scb,UNUSED_ATTR const tBTA_AG_DATA & data)796 void bta_ag_svc_conn_open(tBTA_AG_SCB* p_scb,
797                           UNUSED_ATTR const tBTA_AG_DATA& data) {
798   tBTA_AG_CONN evt = {};
799 
800   if (!p_scb->svc_conn) {
801     /* set state variable */
802     p_scb->svc_conn = true;
803 
804     /* Clear AT+BIA mask from previous SLC if any. */
805     p_scb->bia_masked_out = 0;
806 
807     alarm_cancel(p_scb->ring_timer);
808 
809     /* call callback */
810     evt.hdr.handle = bta_ag_scb_to_idx(p_scb);
811     evt.hdr.app_id = p_scb->app_id;
812     evt.peer_feat = p_scb->peer_features;
813     evt.bd_addr = p_scb->peer_addr;
814     evt.peer_codec = p_scb->peer_codecs;
815 
816     if ((p_scb->call_ind != BTA_AG_CALL_INACTIVE) ||
817         (p_scb->callsetup_ind != BTA_AG_CALLSETUP_NONE)) {
818       bta_sys_sco_use(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr);
819     }
820     if (bta_ag_get_active_device().IsEmpty()) {
821       bta_ag_api_set_active_device(p_scb->peer_addr);
822     }
823     (*bta_ag_cb.p_cback)(BTA_AG_CONN_EVT, (tBTA_AG*)&evt);
824   }
825 }
826 
827 /*******************************************************************************
828  *
829  * Function         bta_ag_setcodec
830  *
831  * Description      Handle API SetCodec
832  *
833  *
834  * Returns          void
835  *
836  ******************************************************************************/
bta_ag_setcodec(tBTA_AG_SCB * p_scb,const tBTA_AG_DATA & data)837 void bta_ag_setcodec(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) {
838   tBTA_AG_PEER_CODEC codec_type = data.api_setcodec.codec;
839   tBTA_AG_VAL val = {};
840   val.hdr.handle = bta_ag_scb_to_idx(p_scb);
841 
842   /* Check if the requested codec type is valid */
843   if ((codec_type != BTM_SCO_CODEC_NONE) &&
844       (codec_type != BTM_SCO_CODEC_CVSD) &&
845       (codec_type != BTM_SCO_CODEC_MSBC) && (codec_type != BTM_SCO_CODEC_LC3)) {
846     val.num = codec_type;
847     val.hdr.status = BTA_AG_FAIL_RESOURCES;
848     LOG_ERROR("bta_ag_setcodec error: unsupported codec type %d", codec_type);
849     (*bta_ag_cb.p_cback)(BTA_AG_CODEC_EVT, (tBTA_AG*)&val);
850     return;
851   }
852 
853   if ((p_scb->peer_codecs & codec_type) || (codec_type == BTM_SCO_CODEC_NONE) ||
854       (codec_type == BTM_SCO_CODEC_CVSD)) {
855     p_scb->sco_codec = codec_type;
856     p_scb->codec_updated = true;
857     val.num = codec_type;
858     val.hdr.status = BTA_AG_SUCCESS;
859     APPL_TRACE_DEBUG("bta_ag_setcodec: Updated codec type %d", codec_type);
860   } else {
861     val.num = codec_type;
862     val.hdr.status = BTA_AG_FAIL_RESOURCES;
863     LOG_ERROR("bta_ag_setcodec error: unsupported codec type %d", codec_type);
864   }
865 
866   (*bta_ag_cb.p_cback)(BTA_AG_CODEC_EVT, (tBTA_AG*)&val);
867 }
868 
bta_ag_collision_timer_cback(void * data)869 static void bta_ag_collision_timer_cback(void* data) {
870   if (data == nullptr) {
871     LOG(ERROR) << __func__ << ": data should never be null in a timer callback";
872     return;
873   }
874   /* If the peer haven't opened AG connection     */
875   /* we will restart opening process.             */
876   bta_ag_resume_open(static_cast<tBTA_AG_SCB*>(data));
877 }
878 
bta_ag_handle_collision(tBTA_AG_SCB * p_scb,UNUSED_ATTR const tBTA_AG_DATA & data)879 void bta_ag_handle_collision(tBTA_AG_SCB* p_scb,
880                              UNUSED_ATTR const tBTA_AG_DATA& data) {
881   /* Cancel SDP if it had been started. */
882   if (p_scb->p_disc_db) {
883     SDP_CancelServiceSearch(p_scb->p_disc_db);
884     bta_ag_free_db(p_scb, tBTA_AG_DATA::kEmpty);
885   }
886 
887   /* reopen registered servers */
888   /* Collision may be detected before or after we close servers. */
889   if (bta_ag_is_server_closed(p_scb)) {
890     bta_ag_start_servers(p_scb, p_scb->reg_services);
891   }
892 
893   /* Start timer to han */
894   alarm_set_on_mloop(p_scb->collision_timer, BTA_AG_COLLISION_TIMEOUT_MS,
895                      bta_ag_collision_timer_cback, p_scb);
896 }
897