• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2006-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 BTA JV APIs.
22  *
23  ******************************************************************************/
24 
25 #define LOG_TAG "bluetooth"
26 
27 #include <bluetooth/log.h>
28 #include <com_android_bluetooth_flags.h>
29 
30 #include <cstdint>
31 #include <unordered_set>
32 
33 #include "bta/include/bta_jv_co.h"
34 #include "bta/include/bta_rfcomm_metrics.h"
35 #include "bta/include/bta_rfcomm_scn.h"
36 #include "bta/jv/bta_jv_int.h"
37 #include "bta/sys/bta_sys.h"
38 #include "internal_include/bt_target.h"
39 #include "osi/include/allocator.h"
40 #include "osi/include/properties.h"
41 #include "stack/btm/btm_sec.h"
42 #include "stack/include/bt_hdr.h"
43 #include "stack/include/bt_psm_types.h"
44 #include "stack/include/bt_types.h"
45 #include "stack/include/bt_uuid16.h"
46 #include "stack/include/btm_client_interface.h"
47 #include "stack/include/gap_api.h"
48 #include "stack/include/l2cap_interface.h"
49 #include "stack/include/l2cdefs.h"
50 #include "stack/include/port_api.h"
51 #include "stack/include/rfcdefs.h"
52 #include "stack/include/sdp_api.h"
53 #include "types/bluetooth/uuid.h"
54 #include "types/raw_address.h"
55 
56 using namespace bluetooth::legacy::stack::sdp;
57 using namespace bluetooth;
58 
59 tBTA_JV_CB bta_jv_cb;
60 std::unordered_set<uint16_t> used_l2cap_classic_dynamic_psm;
61 
62 static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb_open);
63 static tBTA_JV_STATUS bta_jv_free_set_pm_profile_cb(uint32_t jv_handle);
64 static void bta_jv_pm_conn_busy(tBTA_JV_PM_CB* p_cb);
65 static void bta_jv_pm_conn_idle(tBTA_JV_PM_CB* p_cb);
66 static void bta_jv_pm_state_change(tBTA_JV_PM_CB* p_cb, const tBTA_JV_CONN_STATE state);
67 static void bta_jv_reset_sniff_timer(tBTA_JV_PM_CB* p_cb);
68 
69 #ifndef BTA_JV_SDP_DB_SIZE
70 #define BTA_JV_SDP_DB_SIZE 4500
71 #endif
72 
73 #ifndef BTA_JV_SDP_RAW_DATA_SIZE
74 #define BTA_JV_SDP_RAW_DATA_SIZE 1800
75 #endif
76 
77 static uint8_t bta_jv_sdp_raw_data[BTA_JV_SDP_RAW_DATA_SIZE];
78 static tSDP_DISCOVERY_DB bta_jv_sdp_db_data[BTA_JV_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)];
79 
80 /* JV configuration structure */
81 struct tBTA_JV_CFG {
82   uint16_t sdp_raw_size;       /* The size of p_sdp_raw_data */
83   uint16_t sdp_db_size;        /* The size of p_sdp_db */
84   uint8_t* p_sdp_raw_data;     /* The data buffer to keep raw data */
85   tSDP_DISCOVERY_DB* p_sdp_db; /* The data buffer to keep SDP database */
86 } bta_jv_cfg = {
87         BTA_JV_SDP_RAW_DATA_SIZE, /* The size of p_sdp_raw_data */
88         (BTA_JV_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)) *
89                 sizeof(tSDP_DISCOVERY_DB), /* The size of p_sdp_db_data */
90         bta_jv_sdp_raw_data,               /* The data buffer to keep raw data */
91         bta_jv_sdp_db_data                 /* The data buffer to keep SDP database */
92 };
93 
94 tBTA_JV_CFG* p_bta_jv_cfg = &bta_jv_cfg;
95 
96 /*******************************************************************************
97  *
98  * Function     bta_jv_alloc_sec_id
99  *
100  * Description  allocate a security id
101  *
102  * Returns
103  *
104  ******************************************************************************/
bta_jv_alloc_sec_id(void)105 static uint8_t bta_jv_alloc_sec_id(void) {
106   uint8_t ret = 0;
107   int i;
108   for (i = 0; i < BTA_JV_NUM_SERVICE_ID; i++) {
109     if (0 == bta_jv_cb.sec_id[i]) {
110       bta_jv_cb.sec_id[i] = BTA_JV_FIRST_SERVICE_ID + i;
111       ret = bta_jv_cb.sec_id[i];
112       break;
113     }
114   }
115   return ret;
116 }
get_sec_id_used(void)117 static int get_sec_id_used(void) {
118   int i;
119   int used = 0;
120   for (i = 0; i < BTA_JV_NUM_SERVICE_ID; i++) {
121     if (bta_jv_cb.sec_id[i]) {
122       used++;
123     }
124   }
125   if (used == BTA_JV_NUM_SERVICE_ID) {
126     log::error("sec id exceeds the limit={}", BTA_JV_NUM_SERVICE_ID);
127   }
128   return used;
129 }
get_rfc_cb_used(void)130 static int get_rfc_cb_used(void) {
131   int i;
132   int used = 0;
133   for (i = 0; i < BTA_JV_MAX_RFC_CONN; i++) {
134     if (bta_jv_cb.rfc_cb[i].handle) {
135       used++;
136     }
137   }
138   if (used == BTA_JV_MAX_RFC_CONN) {
139     log::error("rfc ctrl block exceeds the limit={}", BTA_JV_MAX_RFC_CONN);
140   }
141   return used;
142 }
143 
144 /*******************************************************************************
145  *
146  * Function     bta_jv_free_sec_id
147  *
148  * Description  free the given security id
149  *
150  * Returns
151  *
152  ******************************************************************************/
bta_jv_free_sec_id(uint8_t * p_sec_id)153 static void bta_jv_free_sec_id(uint8_t* p_sec_id) {
154   uint8_t sec_id = *p_sec_id;
155   *p_sec_id = 0;
156   if (sec_id >= BTA_JV_FIRST_SERVICE_ID && sec_id <= BTA_JV_LAST_SERVICE_ID) {
157     BTM_SecClrService(sec_id);
158     bta_jv_cb.sec_id[sec_id - BTA_JV_FIRST_SERVICE_ID] = 0;
159   }
160 }
161 
162 /*******************************************************************************
163  *
164  * Function     bta_jv_from_gap_l2cap_err
165  *
166  * Description  Convert the L2CAP error result propagated from GAP to BTA JV
167  *              L2CAP close reason code.
168  *
169  * Params      l2cap_result: The L2CAP result propagated from GAP error.
170  *
171  * Returns     Appropriate l2cap error reason value
172  *             or BTA_JV_L2CAP_REASON_UNKNOWN if reason isn't defined yet.
173  *
174  ******************************************************************************/
bta_jv_from_gap_l2cap_err(const tL2CAP_CONN & l2cap_result)175 static tBTA_JV_L2CAP_REASON bta_jv_from_gap_l2cap_err(const tL2CAP_CONN& l2cap_result) {
176   switch (l2cap_result) {
177     case tL2CAP_CONN::L2CAP_CONN_ACL_CONNECTION_FAILED:
178       return BTA_JV_L2CAP_REASON_ACL_FAILURE;
179     case tL2CAP_CONN::L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED:
180       return BTA_JV_L2CAP_REASON_CL_SEC_FAILURE;
181     case tL2CAP_CONN::L2CAP_CONN_INSUFFICIENT_AUTHENTICATION:
182       return BTA_JV_L2CAP_REASON_INSUFFICIENT_AUTHENTICATION;
183     case tL2CAP_CONN::L2CAP_CONN_INSUFFICIENT_AUTHORIZATION:
184       return BTA_JV_L2CAP_REASON_INSUFFICIENT_AUTHORIZATION;
185     case tL2CAP_CONN::L2CAP_CONN_INSUFFICIENT_ENCRYP_KEY_SIZE:
186       return BTA_JV_L2CAP_REASON_INSUFFICIENT_ENCRYP_KEY_SIZE;
187     case tL2CAP_CONN::L2CAP_CONN_INSUFFICIENT_ENCRYP:
188       return BTA_JV_L2CAP_REASON_INSUFFICIENT_ENCRYP;
189     case tL2CAP_CONN::L2CAP_CONN_INVALID_SOURCE_CID:
190       return BTA_JV_L2CAP_REASON_INVALID_SOURCE_CID;
191     case tL2CAP_CONN::L2CAP_CONN_SOURCE_CID_ALREADY_ALLOCATED:
192       return BTA_JV_L2CAP_REASON_SOURCE_CID_ALREADY_ALLOCATED;
193     case tL2CAP_CONN::L2CAP_CONN_UNACCEPTABLE_PARAMETERS:
194       return BTA_JV_L2CAP_REASON_UNACCEPTABLE_PARAMETERS;
195     case tL2CAP_CONN::L2CAP_CONN_INVALID_PARAMETERS:
196       return BTA_JV_L2CAP_REASON_INVALID_PARAMETERS;
197     case tL2CAP_CONN::L2CAP_CONN_NO_RESOURCES:
198       return BTA_JV_L2CAP_REASON_NO_RESOURCES;
199     case tL2CAP_CONN::L2CAP_CONN_NO_PSM:
200       return BTA_JV_L2CAP_REASON_NO_PSM;
201     case tL2CAP_CONN::L2CAP_CONN_TIMEOUT:
202       return BTA_JV_L2CAP_REASON_TIMEOUT;
203     default:
204       return BTA_JV_L2CAP_REASON_UNKNOWN;
205   }
206 }
207 /******************************************************************************/
208 
209 /*******************************************************************************
210  *
211  * Function     bta_jv_alloc_rfc_cb
212  *
213  * Description  allocate a control block for the given port handle
214  *
215  * Returns
216  *
217  ******************************************************************************/
bta_jv_alloc_rfc_cb(uint16_t port_handle,tBTA_JV_PCB ** pp_pcb)218 static tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, tBTA_JV_PCB** pp_pcb) {
219   tBTA_JV_RFC_CB* p_cb = NULL;
220   tBTA_JV_PCB* p_pcb;
221   int i, j;
222   for (i = 0; i < BTA_JV_MAX_RFC_CONN; i++) {
223     if (0 == bta_jv_cb.rfc_cb[i].handle) {
224       p_cb = &bta_jv_cb.rfc_cb[i];
225       /* mask handle to distinguish it with L2CAP handle */
226       p_cb->handle = (i + 1) | BTA_JV_RFCOMM_MASK;
227 
228       p_cb->max_sess = 1;
229       p_cb->curr_sess = 1;
230       for (j = 0; j < BTA_JV_MAX_RFC_SR_SESSION; j++) {
231         p_cb->rfc_hdl[j] = 0;
232       }
233       p_cb->rfc_hdl[0] = port_handle;
234       log::verbose("port_handle={}, jv_handle=0x{:x}", port_handle, p_cb->handle);
235 
236       p_pcb = &bta_jv_cb.port_cb[port_handle - 1];
237       p_pcb->handle = p_cb->handle;
238       p_pcb->port_handle = port_handle;
239       p_pcb->p_pm_cb = NULL;
240       *pp_pcb = p_pcb;
241       break;
242     }
243   }
244   if (p_cb == NULL) {
245     log::error("port_handle={} ctrl block exceeds limit:{}", port_handle, BTA_JV_MAX_RFC_CONN);
246   }
247   return p_cb;
248 }
249 
250 /*******************************************************************************
251  *
252  * Function     bta_jv_rfc_port_to_pcb
253  *
254  * Description  find the port control block associated with the given port
255  *              handle
256  *
257  * Returns
258  *
259  ******************************************************************************/
bta_jv_rfc_port_to_pcb(uint16_t port_handle)260 static tBTA_JV_PCB* bta_jv_rfc_port_to_pcb(uint16_t port_handle) {
261   tBTA_JV_PCB* p_pcb = NULL;
262 
263   if ((port_handle > 0) && (port_handle <= MAX_RFC_PORTS) &&
264       bta_jv_cb.port_cb[port_handle - 1].handle) {
265     p_pcb = &bta_jv_cb.port_cb[port_handle - 1];
266   }
267 
268   return p_pcb;
269 }
270 
271 /*******************************************************************************
272  *
273  * Function     bta_jv_rfc_port_to_cb
274  *
275  * Description  find the RFCOMM control block associated with the given port
276  *              handle
277  *
278  * Returns
279  *
280  ******************************************************************************/
bta_jv_rfc_port_to_cb(uint16_t port_handle)281 static tBTA_JV_RFC_CB* bta_jv_rfc_port_to_cb(uint16_t port_handle) {
282   tBTA_JV_RFC_CB* p_cb = NULL;
283   uint32_t handle;
284 
285   if ((port_handle > 0) && (port_handle <= MAX_RFC_PORTS) &&
286       bta_jv_cb.port_cb[port_handle - 1].handle) {
287     handle = bta_jv_cb.port_cb[port_handle - 1].handle;
288     handle &= BTA_JV_RFC_HDL_MASK;
289     handle &= ~BTA_JV_RFCOMM_MASK;
290     if (handle) {
291       p_cb = &bta_jv_cb.rfc_cb[handle - 1];
292     }
293   } else {
294     log::warn("jv handle not found port_handle:{}", port_handle);
295   }
296   return p_cb;
297 }
298 
bta_jv_free_rfc_cb(tBTA_JV_RFC_CB * p_cb,tBTA_JV_PCB * p_pcb)299 static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb) {
300   tBTA_JV_STATUS status = tBTA_JV_STATUS::SUCCESS;
301   bool remove_server = false;
302   int close_pending = 0;
303 
304   if (!p_cb || !p_pcb) {
305     log::error("p_cb or p_pcb cannot be null");
306     return tBTA_JV_STATUS::FAILURE;
307   }
308   log::verbose("max_sess={}, curr_sess={}, p_pcb={}, user={}, state={}, jv_handle=0x{:x}",
309                p_cb->max_sess, p_cb->curr_sess, std::format_ptr(p_pcb), p_pcb->rfcomm_slot_id,
310                p_pcb->state, p_pcb->handle);
311 
312   if (p_cb->curr_sess <= 0) {
313     return tBTA_JV_STATUS::SUCCESS;
314   }
315 
316   switch (p_pcb->state) {
317     case BTA_JV_ST_CL_CLOSING:
318     case BTA_JV_ST_SR_CLOSING:
319       log::warn("return on closing, port state={}, scn={}, p_pcb={}, user_data={}", p_pcb->state,
320                 p_cb->scn, std::format_ptr(p_pcb), p_pcb->rfcomm_slot_id);
321       status = tBTA_JV_STATUS::FAILURE;
322       return status;
323     case BTA_JV_ST_CL_OPEN:
324     case BTA_JV_ST_CL_OPENING:
325       log::verbose("state={}, scn={}, user_data={}", p_pcb->state, p_cb->scn,
326                    p_pcb->rfcomm_slot_id);
327       p_pcb->state = BTA_JV_ST_CL_CLOSING;
328       break;
329     case BTA_JV_ST_SR_LISTEN:
330       p_pcb->state = BTA_JV_ST_SR_CLOSING;
331       remove_server = true;
332       log::verbose("state: BTA_JV_ST_SR_LISTEN, scn={}, user_data={}", p_cb->scn,
333                    p_pcb->rfcomm_slot_id);
334       break;
335     case BTA_JV_ST_SR_OPEN:
336       p_pcb->state = BTA_JV_ST_SR_CLOSING;
337       log::verbose(": state: BTA_JV_ST_SR_OPEN, scn={} user_data={}", p_cb->scn,
338                    p_pcb->rfcomm_slot_id);
339       break;
340     default:
341       log::warn(
342               "failed, ignore port state= {}, scn={}, p_pcb= {}, jv_handle=0x{:x}, "
343               "port_handle={}, user_data={}",
344               p_pcb->state, p_cb->scn, std::format_ptr(p_pcb), p_pcb->handle, p_pcb->port_handle,
345               p_pcb->rfcomm_slot_id);
346       status = tBTA_JV_STATUS::FAILURE;
347       break;
348   }
349   if (tBTA_JV_STATUS::SUCCESS == status) {
350     int port_status;
351 
352     if (!remove_server) {
353       port_status = RFCOMM_RemoveConnection(p_pcb->port_handle);
354     } else {
355       port_status = RFCOMM_RemoveServer(p_pcb->port_handle);
356     }
357     if (port_status != PORT_SUCCESS) {
358       status = tBTA_JV_STATUS::FAILURE;
359       log::warn(
360               "Remove jv_handle=0x{:x}, state={}, port_status={}, port_handle={}, close_pending={}",
361               p_pcb->handle, p_pcb->state, port_status, p_pcb->port_handle, close_pending);
362     }
363   }
364   if (!close_pending) {
365     p_pcb->port_handle = 0;
366     p_pcb->state = BTA_JV_ST_NONE;
367     bta_jv_free_set_pm_profile_cb(p_pcb->handle);
368 
369     // Initialize congestion flags
370     p_pcb->cong = false;
371     p_pcb->rfcomm_slot_id = 0;
372     int si = BTA_JV_RFC_HDL_TO_SIDX(p_pcb->handle);
373     if (0 <= si && si < BTA_JV_MAX_RFC_SR_SESSION) {
374       p_cb->rfc_hdl[si] = 0;
375     }
376     p_pcb->handle = 0;
377     p_cb->curr_sess--;
378     if (p_cb->curr_sess == 0) {
379       p_cb->scn = 0;
380       p_cb->p_cback = NULL;
381       p_cb->handle = 0;
382       p_cb->curr_sess = -1;
383     }
384   }
385   return status;
386 }
387 
388 /*******************************************************************************
389  *
390  * Function     bta_jv_free_l2c_cb
391  *
392  * Description  free the given L2CAP control block
393  *
394  * Returns
395  *
396  ******************************************************************************/
bta_jv_free_l2c_cb(tBTA_JV_L2C_CB * p_cb)397 static tBTA_JV_STATUS bta_jv_free_l2c_cb(tBTA_JV_L2C_CB* p_cb) {
398   tBTA_JV_STATUS status = tBTA_JV_STATUS::SUCCESS;
399 
400   if (BTA_JV_ST_NONE != p_cb->state) {
401     bta_jv_free_set_pm_profile_cb((uint32_t)p_cb->handle);
402     if (GAP_ConnClose(p_cb->handle) != BT_PASS) {
403       status = tBTA_JV_STATUS::FAILURE;
404     }
405   }
406   p_cb->psm = 0;
407   p_cb->state = BTA_JV_ST_NONE;
408   p_cb->cong = false;
409   bta_jv_free_sec_id(&p_cb->sec_id);
410   p_cb->p_cback = NULL;
411   p_cb->handle = 0;
412   p_cb->l2cap_socket_id = 0;
413   return status;
414 }
415 
416 /*******************************************************************************
417  *
418  *
419  * Function    bta_jv_clear_pm_cb
420  *
421  * Description clears jv pm control block and optionally calls
422  *             bta_sys_conn_close()
423  *             In general close_conn should be set to true to remove registering
424  *             with dm pm!
425  *
426  * WARNING:    Make sure to clear pointer form port or l2c to this control block
427  *             too!
428  *
429  ******************************************************************************/
bta_jv_clear_pm_cb(tBTA_JV_PM_CB * p_pm_cb,bool close_conn)430 static void bta_jv_clear_pm_cb(tBTA_JV_PM_CB* p_pm_cb, bool close_conn) {
431   /* needs to be called if registered with bta pm, otherwise we may run out of
432    * dm pm slots! */
433   if (close_conn) {
434     bta_sys_conn_close(BTA_ID_JV, p_pm_cb->app_id, p_pm_cb->peer_bd_addr);
435   }
436   p_pm_cb->state = BTA_JV_PM_FREE_ST;
437   p_pm_cb->app_id = BTA_JV_PM_ALL;
438   p_pm_cb->handle = BTA_JV_PM_HANDLE_CLEAR;
439   p_pm_cb->peer_bd_addr = RawAddress::kEmpty;
440 }
441 
442 /*******************************************************************************
443  *
444  * Function     bta_jv_free_set_pm_profile_cb
445  *
446  * Description  free pm profile control block
447  *
448  * Returns     tBTA_JV_STATUS::SUCCESS if cb has been freed correctly,
449  *             tBTA_JV_STATUS::FAILURE in case of no profile has been registered
450  *                                     or already freed
451  *
452  ******************************************************************************/
bta_jv_free_set_pm_profile_cb(uint32_t jv_handle)453 static tBTA_JV_STATUS bta_jv_free_set_pm_profile_cb(uint32_t jv_handle) {
454   tBTA_JV_STATUS status = tBTA_JV_STATUS::FAILURE;
455   tBTA_JV_PM_CB** p_cb;
456   int i, j, bd_counter = 0, appid_counter = 0;
457 
458   for (i = 0; i < BTA_JV_PM_MAX_NUM; i++) {
459     p_cb = NULL;
460     if ((bta_jv_cb.pm_cb[i].state != BTA_JV_PM_FREE_ST) &&
461         (jv_handle == bta_jv_cb.pm_cb[i].handle)) {
462       for (j = 0; j < BTA_JV_PM_MAX_NUM; j++) {
463         if (bta_jv_cb.pm_cb[j].peer_bd_addr == bta_jv_cb.pm_cb[i].peer_bd_addr) {
464           bd_counter++;
465         }
466         if (bta_jv_cb.pm_cb[j].app_id == bta_jv_cb.pm_cb[i].app_id) {
467           appid_counter++;
468         }
469       }
470 
471       log::verbose("jv_handle=0x{:x}, idx={}, app_id={}, bd_counter={}, appid_counter={}",
472                    jv_handle, i, bta_jv_cb.pm_cb[i].app_id, bd_counter, appid_counter);
473       if (bd_counter > 1) {
474         bta_jv_pm_conn_idle(&bta_jv_cb.pm_cb[i]);
475       }
476 
477       if (bd_counter <= 1 || (appid_counter <= 1)) {
478         bta_jv_clear_pm_cb(&bta_jv_cb.pm_cb[i], true);
479       } else {
480         bta_jv_clear_pm_cb(&bta_jv_cb.pm_cb[i], false);
481       }
482 
483       if (BTA_JV_RFCOMM_MASK & jv_handle) {
484         uint32_t hi = ((jv_handle & BTA_JV_RFC_HDL_MASK) & ~BTA_JV_RFCOMM_MASK) - 1;
485         uint32_t si = BTA_JV_RFC_HDL_TO_SIDX(jv_handle);
486         if (hi < BTA_JV_MAX_RFC_CONN && bta_jv_cb.rfc_cb[hi].p_cback &&
487             si < BTA_JV_MAX_RFC_SR_SESSION && bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) {
488           tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(bta_jv_cb.rfc_cb[hi].rfc_hdl[si]);
489           if (p_pcb) {
490             if (NULL == p_pcb->p_pm_cb) {
491               log::warn("jv_handle=0x{:x}, port_handle={}, i={}, no link to pm_cb?", jv_handle,
492                         p_pcb->port_handle, i);
493             }
494             p_cb = &p_pcb->p_pm_cb;
495           }
496         }
497       } else {
498         if (jv_handle < BTA_JV_MAX_L2C_CONN) {
499           tBTA_JV_L2C_CB* p_l2c_cb = &bta_jv_cb.l2c_cb[jv_handle];
500           if (NULL == p_l2c_cb->p_pm_cb) {
501             log::warn("jv_handle=0x{:x}, i={} no link to pm_cb?", jv_handle, i);
502           }
503           p_cb = &p_l2c_cb->p_pm_cb;
504         }
505       }
506       if (p_cb) {
507         *p_cb = NULL;
508         status = tBTA_JV_STATUS::SUCCESS;
509       }
510     }
511   }
512   return status;
513 }
514 
515 /*******************************************************************************
516  *
517  * Function    bta_jv_alloc_set_pm_profile_cb
518  *
519  * Description set PM profile control block
520  *
521  * Returns     pointer to allocated cb or NULL in case of failure
522  *
523  ******************************************************************************/
bta_jv_alloc_set_pm_profile_cb(uint32_t jv_handle,tBTA_JV_PM_ID app_id)524 static tBTA_JV_PM_CB* bta_jv_alloc_set_pm_profile_cb(uint32_t jv_handle, tBTA_JV_PM_ID app_id) {
525   bool bRfcHandle = (jv_handle & BTA_JV_RFCOMM_MASK) != 0;
526   RawAddress peer_bd_addr = RawAddress::kEmpty;
527   int i, j;
528   tBTA_JV_PM_CB** pp_cb;
529 
530   for (i = 0; i < BTA_JV_PM_MAX_NUM; i++) {
531     pp_cb = NULL;
532     if (bta_jv_cb.pm_cb[i].state == BTA_JV_PM_FREE_ST) {
533       /* rfc handle bd addr retrieval requires core stack handle */
534       if (bRfcHandle) {
535         for (j = 0; j < BTA_JV_MAX_RFC_CONN; j++) {
536           if (jv_handle == bta_jv_cb.port_cb[j].handle) {
537             pp_cb = &bta_jv_cb.port_cb[j].p_pm_cb;
538             if (PORT_SUCCESS !=
539                 PORT_CheckConnection(bta_jv_cb.port_cb[j].port_handle, &peer_bd_addr, NULL)) {
540               i = BTA_JV_PM_MAX_NUM;
541             }
542             break;
543           }
544         }
545       } else {
546         /* use jv handle for l2cap bd address retrieval */
547         for (j = 0; j < BTA_JV_MAX_L2C_CONN; j++) {
548           if (jv_handle == bta_jv_cb.l2c_cb[j].handle) {
549             pp_cb = &bta_jv_cb.l2c_cb[j].p_pm_cb;
550             const RawAddress* p_bd_addr = GAP_ConnGetRemoteAddr((uint16_t)jv_handle);
551             if (p_bd_addr) {
552               peer_bd_addr = *p_bd_addr;
553             } else {
554               i = BTA_JV_PM_MAX_NUM;
555             }
556             break;
557           }
558         }
559       }
560       log::verbose("jv_handle=0x{:x}, app_id={}, idx={}, BTA_JV_PM_MAX_NUM={}, pp_cb={}", jv_handle,
561                    app_id, i, BTA_JV_PM_MAX_NUM, std::format_ptr(pp_cb));
562       break;
563     }
564   }
565 
566   if ((i != BTA_JV_PM_MAX_NUM) && (NULL != pp_cb)) {
567     *pp_cb = &bta_jv_cb.pm_cb[i];
568     bta_jv_cb.pm_cb[i].handle = jv_handle;
569     bta_jv_cb.pm_cb[i].app_id = app_id;
570     bta_jv_cb.pm_cb[i].peer_bd_addr = peer_bd_addr;
571     bta_jv_cb.pm_cb[i].state = BTA_JV_PM_IDLE_ST;
572     return &bta_jv_cb.pm_cb[i];
573   }
574   log::warn("jv_handle=0x{:x}, app_id={}, return NULL", jv_handle, app_id);
575   return NULL;
576 }
577 
578 /*******************************************************************************
579  *
580  * Function     bta_jv_check_psm
581  *
582  * Description  for now use only the legal PSM per JSR82 spec
583  *
584  * Returns      true, if allowed
585  *
586  ******************************************************************************/
bta_jv_check_psm(uint16_t psm)587 static bool bta_jv_check_psm(uint16_t psm) {
588   bool ret = false;
589 
590   if (L2C_IS_VALID_PSM(psm)) {
591     if (psm < 0x1001) {
592       /* see if this is defined by spec */
593       switch (psm) {
594         case BT_PSM_SDP:
595         case BT_PSM_RFCOMM: /* 3 */
596           /* do not allow java app to use these 2 PSMs */
597           break;
598 
599         case BT_PSM_TCS:
600         case BT_PSM_CTP:
601           if (!bta_sys_is_register(BTA_ID_CT) && !bta_sys_is_register(BTA_ID_CG)) {
602             ret = true;
603           }
604           break;
605 
606         case BT_PSM_BNEP: /* F */
607           if (!bta_sys_is_register(BTA_ID_PAN)) {
608             ret = true;
609           }
610           break;
611 
612         case BT_PSM_HIDC:
613         case BT_PSM_HIDI:
614           // FIX: allow HID Device and HID Host to coexist
615           if (!bta_sys_is_register(BTA_ID_HD) || !bta_sys_is_register(BTA_ID_HH)) {
616             ret = true;
617           }
618           break;
619 
620         case BT_PSM_AVCTP: /* 0x17 */
621         case BT_PSM_AVDTP: /* 0x19 */
622           if (!bta_sys_is_register(BTA_ID_AV)) {
623             ret = true;
624           }
625           break;
626 
627         default:
628           ret = true;
629           break;
630       }
631     } else {
632       ret = true;
633     }
634   }
635   return ret;
636 }
637 
638 /* Initialises the JAVA I/F */
bta_jv_enable(tBTA_JV_DM_CBACK * p_cback)639 void bta_jv_enable(tBTA_JV_DM_CBACK* p_cback) {
640   bta_jv_cb.p_dm_cback = p_cback;
641   if (bta_jv_cb.p_dm_cback) {
642     tBTA_JV bta_jv = {
643             .status = tBTA_JV_STATUS::SUCCESS,
644     };
645     bta_jv_cb.p_dm_cback(BTA_JV_ENABLE_EVT, &bta_jv, 0);
646   }
647   memset(bta_jv_cb.free_psm_list, 0, sizeof(bta_jv_cb.free_psm_list));
648   memset(bta_jv_cb.scn_in_use, 0, sizeof(bta_jv_cb.scn_in_use));
649   bta_jv_cb.scn_search_index = 1;
650 }
651 
652 /** Disables the BT device manager free the resources used by java */
bta_jv_disable()653 void bta_jv_disable() { log::info(""); }
654 
655 /**
656  * We keep a list of PSM's that have been freed from JAVA, for reuse.
657  * This function will return a free PSM, and delete it from the free
658  * list.
659  * If no free PSMs exist, 0 will be returned.
660  */
bta_jv_get_free_psm()661 static uint16_t bta_jv_get_free_psm() {
662   const int cnt = sizeof(bta_jv_cb.free_psm_list) / sizeof(bta_jv_cb.free_psm_list[0]);
663   for (int i = 0; i < cnt; i++) {
664     uint16_t psm = bta_jv_cb.free_psm_list[i];
665     if (psm != 0) {
666       log::verbose("Reusing PSM=0x{:x}", psm);
667       bta_jv_cb.free_psm_list[i] = 0;
668       return psm;
669     }
670   }
671   return 0;
672 }
673 
bta_jv_set_free_psm(uint16_t psm)674 static void bta_jv_set_free_psm(uint16_t psm) {
675   int free_index = -1;
676   const int cnt = sizeof(bta_jv_cb.free_psm_list) / sizeof(bta_jv_cb.free_psm_list[0]);
677   for (int i = 0; i < cnt; i++) {
678     if (bta_jv_cb.free_psm_list[i] == 0) {
679       free_index = i;
680     } else if (psm == bta_jv_cb.free_psm_list[i]) {
681       return;  // PSM already freed?
682     }
683   }
684   if (free_index != -1) {
685     bta_jv_cb.free_psm_list[free_index] = psm;
686     log::verbose("Recycling PSM=0x{:x}", psm);
687   } else {
688     log::error("unable to free psm=0x{:x} no more free slots", psm);
689   }
690 }
691 
bta_jv_allocate_l2cap_classic_psm()692 static uint16_t bta_jv_allocate_l2cap_classic_psm() {
693   bool done = false;
694   uint16_t psm = bta_jv_cb.dyn_psm;
695 
696   while (!done) {
697     psm += 2;
698     if (psm > 0xfeff) {
699       psm = 0x1001;
700     } else if (psm & 0x0100) {
701       /* the upper byte must be even */
702       psm += 0x0100;
703     }
704 
705     /* if psm is in range of reserved BRCM Aware features */
706     if ((BRCM_RESERVED_PSM_START <= psm) && (psm <= BRCM_RESERVED_PSM_END)) {
707       continue;
708     }
709 
710     /* make sure the newlly allocated psm is not used right now */
711     if (used_l2cap_classic_dynamic_psm.count(psm) == 0) {
712       done = true;
713     }
714   }
715   bta_jv_cb.dyn_psm = psm;
716 
717   return psm;
718 }
719 
720 /** Obtain a free SCN (Server Channel Number) (RFCOMM channel or L2CAP PSM) */
bta_jv_get_channel_id(tBTA_JV_CONN_TYPE type,int32_t channel,uint32_t l2cap_socket_id,uint32_t rfcomm_slot_id)721 void bta_jv_get_channel_id(tBTA_JV_CONN_TYPE type /* One of BTA_JV_CONN_TYPE_ */,
722                            int32_t channel /* optionally request a specific channel */,
723                            uint32_t l2cap_socket_id, uint32_t rfcomm_slot_id) {
724   uint16_t psm = 0;
725 
726   switch (type) {
727     case tBTA_JV_CONN_TYPE::RFCOMM: {
728       uint8_t scn = 0;
729       if (channel > 0) {
730         if (BTA_TryAllocateSCN(channel)) {
731           scn = static_cast<uint8_t>(channel);
732         } else {
733           log::error("rfc channel {} already in use or invalid", channel);
734         }
735       } else {
736         scn = BTA_AllocateSCN();
737         if (scn == 0) {
738           log::error("out of rfc channels");
739         }
740       }
741       if (bta_jv_cb.p_dm_cback) {
742         tBTA_JV bta_jv;
743         bta_jv.scn = scn;
744         bta_jv_cb.p_dm_cback(BTA_JV_GET_SCN_EVT, &bta_jv, rfcomm_slot_id);
745       }
746       return;
747     }
748     case tBTA_JV_CONN_TYPE::L2CAP:
749       psm = bta_jv_get_free_psm();
750       if (psm == 0) {
751         psm = bta_jv_allocate_l2cap_classic_psm();
752         log::verbose("returned PSM=0x{:x}", psm);
753       }
754       break;
755     case tBTA_JV_CONN_TYPE::L2CAP_LE:
756       psm = stack::l2cap::get_interface().L2CA_AllocateLePSM();
757       if (psm == 0) {
758         log::error("Error: No free LE PSM available");
759       }
760       break;
761     default:
762       break;
763   }
764 
765   if (bta_jv_cb.p_dm_cback) {
766     tBTA_JV bta_jv;
767     bta_jv.psm = psm;
768     bta_jv_cb.p_dm_cback(BTA_JV_GET_PSM_EVT, &bta_jv, l2cap_socket_id);
769   }
770 }
771 
772 /** free a SCN */
bta_jv_free_scn(tBTA_JV_CONN_TYPE type,uint16_t scn)773 void bta_jv_free_scn(tBTA_JV_CONN_TYPE type /* One of BTA_JV_CONN_TYPE_ */, uint16_t scn) {
774   switch (type) {
775     case tBTA_JV_CONN_TYPE::RFCOMM:
776       BTA_FreeSCN(scn);
777       break;
778     case tBTA_JV_CONN_TYPE::L2CAP:
779       bta_jv_set_free_psm(scn);
780       break;
781     case tBTA_JV_CONN_TYPE::L2CAP_LE:
782       log::verbose("type=BTA_JV_CONN_TYPE::L2CAP_LE. psm={}", scn);
783       stack::l2cap::get_interface().L2CA_FreeLePSM(scn);
784       break;
785     default:
786       break;
787   }
788 }
789 
790 /*******************************************************************************
791  *
792  * Function     bta_jv_start_discovery_cback
793  *
794  * Description  Callback for Start Discovery
795  *
796  * Returns      void
797  *
798  ******************************************************************************/
bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id,const RawAddress & bd_addr,tSDP_RESULT result)799 static void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, const RawAddress& bd_addr,
800                                          tSDP_RESULT result) {
801   if (!bta_jv_cb.sdp_cb.sdp_active) {
802     log::warn("Received unexpected service discovery callback bd_addr:{} result:{}", bd_addr,
803               sdp_result_text(result), bta_jv_cb.sdp_cb.sdp_active);
804   }
805   if (bta_jv_cb.sdp_cb.bd_addr != bta_jv_cb.sdp_cb.bd_addr) {
806     log::warn(
807             "Received incorrect service discovery callback expected_bd_addr:{} "
808             "actual_bd_addr:{} result:{}",
809             bta_jv_cb.sdp_cb.bd_addr, bd_addr, sdp_result_text(result),
810             bta_jv_cb.sdp_cb.sdp_active);
811   }
812 
813   if (bta_jv_cb.p_dm_cback) {
814     tBTA_JV bta_jv = {
815             .disc_comp =
816                     {
817                             .status = tBTA_JV_STATUS::FAILURE,
818                             .scn = 0,
819                     },
820     };
821     if (result == tSDP_STATUS::SDP_SUCCESS || result == tSDP_STATUS::SDP_DB_FULL) {
822       log::info("Received service discovery callback success bd_addr:{} result:{}", bd_addr,
823                 sdp_result_text(result));
824       tSDP_PROTOCOL_ELEM pe;
825       tSDP_DISC_REC* p_sdp_rec = NULL;
826       p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb(
827               p_bta_jv_cfg->p_sdp_db, bta_jv_cb.sdp_cb.uuid, p_sdp_rec);
828       log::verbose("bta_jv_cb.uuid={} p_sdp_rec={}", bta_jv_cb.sdp_cb.uuid,
829                    std::format_ptr(p_sdp_rec));
830       if (p_sdp_rec && get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(
831                                p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) {
832         bta_jv = {
833                 .disc_comp =
834                         {
835                                 .status = tBTA_JV_STATUS::SUCCESS,
836                                 .scn = (uint8_t)pe.params[0],
837                         },
838         };
839       }
840     } else {
841       log::warn("Received service discovery callback failed bd_addr:{} result:{}", bd_addr,
842                 sdp_result_text(result));
843     }
844     log::info("Issuing service discovery complete callback bd_addr:{} result:{} status:{} scn:{}",
845               bd_addr, sdp_result_text(result), bta_jv_status_text(bta_jv.disc_comp.status),
846               bta_jv.disc_comp.scn);
847     bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, &bta_jv, rfcomm_slot_id);
848   } else {
849     log::warn("Received service discovery callback when disabled bd_addr:{} result:{}", bd_addr,
850               sdp_result_text(result));
851   }
852   bta_jv_cb.sdp_cb = {};
853 }
854 
855 /* Discovers services on a remote device */
bta_jv_start_discovery(const RawAddress & bd_addr,uint16_t num_uuid,bluetooth::Uuid * uuid_list,uint32_t rfcomm_slot_id)856 void bta_jv_start_discovery(const RawAddress& bd_addr, uint16_t num_uuid,
857                             bluetooth::Uuid* uuid_list, uint32_t rfcomm_slot_id) {
858   log::assert_that(uuid_list != nullptr, "assert failed: uuid_list != nullptr");
859   if (bta_jv_cb.sdp_cb.sdp_active) {
860     log::warn(
861             "Unable to start discovery as already in progress active_bd_addr{} "
862             "request_bd_addr:{} num:uuid:{} rfcomm_slot_id:{}",
863             bta_jv_cb.sdp_cb.bd_addr, bd_addr, num_uuid, rfcomm_slot_id);
864     if (bta_jv_cb.p_dm_cback) {
865       tBTA_JV bta_jv = {
866               .status = tBTA_JV_STATUS::BUSY,
867       };
868       bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, &bta_jv, rfcomm_slot_id);
869     } else {
870       log::warn(
871               "bta::jv module DISABLED so unable to inform caller service discovery is "
872               "unavailable");
873     }
874     return;
875   }
876 
877   /* init the database/set up the filter */
878   if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(
879               p_bta_jv_cfg->p_sdp_db, p_bta_jv_cfg->sdp_db_size, num_uuid, uuid_list, 0, NULL)) {
880     log::warn("Unable to initialize service discovery db bd_addr:{} num:uuid:{} rfcomm_slot_id:{}",
881               bd_addr, num_uuid, rfcomm_slot_id);
882   }
883 
884   /* tell SDP to keep the raw data */
885   p_bta_jv_cfg->p_sdp_db->raw_data = p_bta_jv_cfg->p_sdp_raw_data;
886   p_bta_jv_cfg->p_sdp_db->raw_size = p_bta_jv_cfg->sdp_raw_size;
887 
888   // Optimistically set this as active
889   bta_jv_cb.sdp_cb = {
890           .sdp_active = true,
891           .bd_addr = bd_addr,
892           .uuid = uuid_list[0],
893   };
894 
895   if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2(
896               bd_addr, p_bta_jv_cfg->p_sdp_db,
897               base::BindRepeating(&bta_jv_start_discovery_cback, rfcomm_slot_id))) {
898     bta_jv_cb.sdp_cb = {};
899     log::warn("Unable to original service discovery bd_addr:{} num:uuid:{} rfcomm_slot_id:{}",
900               bd_addr, num_uuid, rfcomm_slot_id);
901     /* failed to start SDP. report the failure right away */
902     if (bta_jv_cb.p_dm_cback) {
903       tBTA_JV bta_jv = {
904               .status = tBTA_JV_STATUS::FAILURE,
905       };
906       bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, &bta_jv, rfcomm_slot_id);
907     } else {
908       log::warn("No callback set for discovery complete event");
909     }
910   } else {
911     log::info("Started service discovery bd_addr:{} num_uuid:{} rfcomm_slot_id:{}", bd_addr,
912               num_uuid, rfcomm_slot_id);
913   }
914 }
915 
bta_jv_cancel_discovery(uint32_t rfcomm_slot_id)916 void bta_jv_cancel_discovery(uint32_t rfcomm_slot_id) {
917   if (!bta_jv_cb.sdp_cb.sdp_active) {
918     log::error("Canceling discovery but discovery is not active");
919     return;
920   }
921   if (!get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch(p_bta_jv_cfg->p_sdp_db)) {
922     log::error("Failed to cancel discovery, clean up the control block anyway");
923     bta_jv_cb.sdp_cb = {};
924     /* Send complete event right away as we might not receive callback from stack */
925     if (bta_jv_cb.p_dm_cback) {
926       tBTA_JV bta_jv = {
927               .status = tBTA_JV_STATUS::FAILURE,
928       };
929       bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, &bta_jv, rfcomm_slot_id);
930     } else {
931       log::warn("No callback set for discovery complete event");
932     }
933   } else {
934     log::info("Canceled discovery");
935   }
936 }
937 
938 /* Create an SDP record with the given attributes */
bta_jv_create_record(uint32_t rfcomm_slot_id)939 void bta_jv_create_record(uint32_t rfcomm_slot_id) {
940   tBTA_JV_CREATE_RECORD evt_data;
941   evt_data.status = tBTA_JV_STATUS::SUCCESS;
942   if (bta_jv_cb.p_dm_cback) {
943     // callback immediately to create the sdp record in stack thread context
944     tBTA_JV bta_jv;
945     bta_jv.create_rec = evt_data;
946     bta_jv_cb.p_dm_cback(BTA_JV_CREATE_RECORD_EVT, &bta_jv, rfcomm_slot_id);
947   }
948 }
949 
950 /* Delete an SDP record */
bta_jv_delete_record(uint32_t handle)951 void bta_jv_delete_record(uint32_t handle) {
952   if (handle) {
953     /* this is a record created by btif layer*/
954     if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(handle)) {
955       log::warn("Unable to delete SDP record handle:{}", handle);
956     }
957   }
958 }
959 
960 /*******************************************************************************
961  *
962  * Function     bta_jv_l2cap_client_cback
963  *
964  * Description  handles the l2cap client events
965  *
966  * Returns      void
967  *
968  ******************************************************************************/
bta_jv_l2cap_client_cback(uint16_t gap_handle,uint16_t event,tGAP_CB_DATA * data)969 static void bta_jv_l2cap_client_cback(uint16_t gap_handle, uint16_t event, tGAP_CB_DATA* data) {
970   tBTA_JV_L2C_CB* p_cb = &bta_jv_cb.l2c_cb[gap_handle];
971   tBTA_JV evt_data;
972 
973   if (gap_handle >= BTA_JV_MAX_L2C_CONN && !p_cb->p_cback) {
974     return;
975   }
976 
977   log::verbose("gap_handle={}, evt=0x{:x}", gap_handle, event);
978   evt_data.l2c_open.status = tBTA_JV_STATUS::SUCCESS;
979   evt_data.l2c_open.handle = gap_handle;
980 
981   switch (event) {
982     case GAP_EVT_CONN_OPENED:
983       if (!com::android::bluetooth::flags::socket_settings_api() ||
984           !GAP_IsTransportLe(gap_handle)) {
985         evt_data.l2c_open.rem_bda = *GAP_ConnGetRemoteAddr(gap_handle);
986         evt_data.l2c_open.tx_mtu = GAP_ConnGetRemMtuSize(gap_handle);
987         if (data != nullptr) {
988           evt_data.l2c_open.local_cid = data->l2cap_cids.local_cid;
989           evt_data.l2c_open.remote_cid = data->l2cap_cids.remote_cid;
990         }
991       } else {
992         uint16_t remote_mtu, local_mps, remote_mps, local_credit, remote_credit;
993         uint16_t local_cid, remote_cid, acl_handle;
994         evt_data.l2c_open.rem_bda = *GAP_ConnGetRemoteAddr(gap_handle);
995         if (GAP_GetLeChannelInfo(gap_handle, &remote_mtu, &local_mps, &remote_mps, &local_credit,
996                                  &remote_credit, &local_cid, &remote_cid,
997                                  &acl_handle) != PORT_SUCCESS) {
998           log::warn("Unable to get GAP channel info gap_handle:{}", gap_handle);
999         }
1000         evt_data.l2c_open.tx_mtu = remote_mtu;
1001         evt_data.l2c_open.local_coc_mps = local_mps;
1002         evt_data.l2c_open.remote_coc_mps = remote_mps;
1003         evt_data.l2c_open.local_coc_credit = local_credit;
1004         evt_data.l2c_open.remote_coc_credit = remote_credit;
1005         evt_data.l2c_open.local_cid = local_cid;
1006         evt_data.l2c_open.remote_cid = remote_cid;
1007         evt_data.l2c_open.acl_handle = acl_handle;
1008       }
1009       p_cb->state = BTA_JV_ST_CL_OPEN;
1010       p_cb->p_cback(BTA_JV_L2CAP_OPEN_EVT, &evt_data, p_cb->l2cap_socket_id);
1011       break;
1012 
1013     case GAP_EVT_CONN_CLOSED:
1014       p_cb->state = BTA_JV_ST_NONE;
1015       bta_jv_free_sec_id(&p_cb->sec_id);
1016       evt_data.l2c_close.async = true;
1017       evt_data.l2c_close.reason = data != nullptr ? bta_jv_from_gap_l2cap_err(data->l2cap_result)
1018                                                   : BTA_JV_L2CAP_REASON_EMPTY;
1019       p_cb->p_cback(BTA_JV_L2CAP_CLOSE_EVT, &evt_data, p_cb->l2cap_socket_id);
1020       p_cb->p_cback = NULL;
1021       break;
1022 
1023     case GAP_EVT_CONN_DATA_AVAIL:
1024       evt_data.data_ind.handle = gap_handle;
1025       /* Reset idle timer to avoid requesting sniff mode while receiving data */
1026       bta_jv_pm_conn_busy(p_cb->p_pm_cb);
1027       p_cb->p_cback(BTA_JV_L2CAP_DATA_IND_EVT, &evt_data, p_cb->l2cap_socket_id);
1028       bta_jv_pm_conn_idle(p_cb->p_pm_cb);
1029       break;
1030 
1031     case GAP_EVT_TX_EMPTY:
1032       bta_jv_pm_conn_idle(p_cb->p_pm_cb);
1033       break;
1034 
1035     case GAP_EVT_CONN_CONGESTED:
1036     case GAP_EVT_CONN_UNCONGESTED:
1037       p_cb->cong = (event == GAP_EVT_CONN_CONGESTED) ? true : false;
1038       evt_data.l2c_cong.cong = p_cb->cong;
1039       p_cb->p_cback(BTA_JV_L2CAP_CONG_EVT, &evt_data, p_cb->l2cap_socket_id);
1040       break;
1041 
1042     default:
1043       break;
1044   }
1045 }
1046 
1047 /* makes an l2cap client connection */
bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type,tBTA_SEC sec_mask,uint16_t remote_psm,uint16_t rx_mtu,const RawAddress & peer_bd_addr,std::unique_ptr<tL2CAP_CFG_INFO> cfg_param,std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info,tBTA_JV_L2CAP_CBACK * p_cback,uint32_t l2cap_socket_id)1048 void bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, uint16_t remote_psm,
1049                           uint16_t rx_mtu, const RawAddress& peer_bd_addr,
1050                           std::unique_ptr<tL2CAP_CFG_INFO> cfg_param,
1051                           std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info, tBTA_JV_L2CAP_CBACK* p_cback,
1052                           uint32_t l2cap_socket_id) {
1053   uint16_t handle = GAP_INVALID_HANDLE;
1054 
1055   tL2CAP_CFG_INFO cfg;
1056   memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
1057   if (cfg_param) {
1058     cfg = *cfg_param;
1059   }
1060 
1061   /* We need to use this value for MTU to be able to handle cases where cfg is
1062    * not set in req. */
1063   cfg.mtu_present = true;
1064   cfg.mtu = rx_mtu;
1065 
1066   uint8_t sec_id = bta_jv_alloc_sec_id();
1067   tBTA_JV_L2CAP_CL_INIT evt_data;
1068   evt_data.sec_id = sec_id;
1069   evt_data.status = tBTA_JV_STATUS::FAILURE;
1070 
1071   if (sec_id) {
1072     /* PSM checking is not required for LE COC */
1073     if ((type != tBTA_JV_CONN_TYPE::L2CAP) || (bta_jv_check_psm(remote_psm))) /* allowed */
1074     {
1075       // Given a client socket type
1076       // return the associated transport
1077       const tBT_TRANSPORT transport = [](tBTA_JV_CONN_TYPE type) -> tBT_TRANSPORT {
1078         switch (type) {
1079           case tBTA_JV_CONN_TYPE::L2CAP:
1080             return BT_TRANSPORT_BR_EDR;
1081           case tBTA_JV_CONN_TYPE::L2CAP_LE:
1082             return BT_TRANSPORT_LE;
1083           case tBTA_JV_CONN_TYPE::RFCOMM:
1084           default:
1085             break;
1086         }
1087         log::warn("Unexpected socket type:{}", bta_jv_conn_type_text(type));
1088         return BT_TRANSPORT_AUTO;
1089       }(type);
1090 
1091       uint16_t max_mps = 0xffff;  // Let GAP_ConnOpen set the max_mps.
1092       handle = GAP_ConnOpen("", sec_id, 0, &peer_bd_addr, remote_psm, max_mps, &cfg,
1093                             ertm_info.get(), sec_mask, bta_jv_l2cap_client_cback, transport);
1094       if (handle != GAP_INVALID_HANDLE) {
1095         evt_data.status = tBTA_JV_STATUS::SUCCESS;
1096       }
1097     }
1098   }
1099 
1100   if (evt_data.status == tBTA_JV_STATUS::SUCCESS) {
1101     tBTA_JV_L2C_CB* p_cb;
1102     p_cb = &bta_jv_cb.l2c_cb[handle];
1103     p_cb->handle = handle;
1104     p_cb->p_cback = p_cback;
1105     p_cb->l2cap_socket_id = l2cap_socket_id;
1106     p_cb->psm = 0; /* not a server */
1107     p_cb->sec_id = sec_id;
1108     p_cb->state = BTA_JV_ST_CL_OPENING;
1109   } else {
1110     bta_jv_free_sec_id(&sec_id);
1111   }
1112 
1113   evt_data.handle = handle;
1114   if (p_cback) {
1115     tBTA_JV bta_jv;
1116     bta_jv.l2c_cl_init = evt_data;
1117     p_cback(BTA_JV_L2CAP_CL_INIT_EVT, &bta_jv, l2cap_socket_id);
1118   }
1119 }
1120 
1121 /** Close an L2CAP client connection */
bta_jv_l2cap_close(uint32_t handle,tBTA_JV_L2C_CB * p_cb)1122 void bta_jv_l2cap_close(uint32_t handle, tBTA_JV_L2C_CB* p_cb) {
1123   tBTA_JV_L2CAP_CLOSE evt_data;
1124   tBTA_JV_L2CAP_CBACK* p_cback = p_cb->p_cback;
1125   uint32_t l2cap_socket_id = p_cb->l2cap_socket_id;
1126 
1127   evt_data.handle = handle;
1128   evt_data.status = bta_jv_free_l2c_cb(p_cb);
1129   evt_data.async = false;
1130 
1131   if (p_cback) {
1132     tBTA_JV bta_jv;
1133     bta_jv.l2c_close = evt_data;
1134     p_cback(BTA_JV_L2CAP_CLOSE_EVT, &bta_jv, l2cap_socket_id);
1135   }
1136 }
1137 
1138 /*******************************************************************************
1139  *
1140  * Function         bta_jv_l2cap_server_cback
1141  *
1142  * Description      handles the l2cap server callback
1143  *
1144  * Returns          void
1145  *
1146  ******************************************************************************/
bta_jv_l2cap_server_cback(uint16_t gap_handle,uint16_t event,tGAP_CB_DATA * data)1147 static void bta_jv_l2cap_server_cback(uint16_t gap_handle, uint16_t event, tGAP_CB_DATA* data) {
1148   tBTA_JV_L2C_CB* p_cb = &bta_jv_cb.l2c_cb[gap_handle];
1149   tBTA_JV evt_data;
1150   tBTA_JV_L2CAP_CBACK* p_cback;
1151   uint32_t socket_id;
1152 
1153   if (gap_handle >= BTA_JV_MAX_L2C_CONN && !p_cb->p_cback) {
1154     return;
1155   }
1156 
1157   log::verbose("gap_handle={}, evt=0x{:x}", gap_handle, event);
1158   evt_data.l2c_open.status = tBTA_JV_STATUS::SUCCESS;
1159   evt_data.l2c_open.handle = gap_handle;
1160 
1161   switch (event) {
1162     case GAP_EVT_CONN_OPENED:
1163       if (!com::android::bluetooth::flags::socket_settings_api() ||
1164           !GAP_IsTransportLe(gap_handle)) {
1165         evt_data.l2c_open.rem_bda = *GAP_ConnGetRemoteAddr(gap_handle);
1166         evt_data.l2c_open.tx_mtu = GAP_ConnGetRemMtuSize(gap_handle);
1167         if (data != nullptr) {
1168           evt_data.l2c_open.local_cid = data->l2cap_cids.local_cid;
1169           evt_data.l2c_open.remote_cid = data->l2cap_cids.remote_cid;
1170         }
1171       } else {
1172         uint16_t remote_mtu, local_mps, remote_mps, local_credit, remote_credit;
1173         uint16_t local_cid, remote_cid, acl_handle;
1174         evt_data.l2c_open.rem_bda = *GAP_ConnGetRemoteAddr(gap_handle);
1175         if (GAP_GetLeChannelInfo(gap_handle, &remote_mtu, &local_mps, &remote_mps, &local_credit,
1176                                  &remote_credit, &local_cid, &remote_cid,
1177                                  &acl_handle) != PORT_SUCCESS) {
1178           log::warn("Unable to get GAP channel info handle:{}", gap_handle);
1179         }
1180         evt_data.l2c_open.tx_mtu = remote_mtu;
1181         evt_data.l2c_open.local_coc_mps = local_mps;
1182         evt_data.l2c_open.remote_coc_mps = remote_mps;
1183         evt_data.l2c_open.local_coc_credit = local_credit;
1184         evt_data.l2c_open.remote_coc_credit = remote_credit;
1185         evt_data.l2c_open.local_cid = local_cid;
1186         evt_data.l2c_open.remote_cid = remote_cid;
1187         evt_data.l2c_open.acl_handle = acl_handle;
1188       }
1189       p_cb->state = BTA_JV_ST_SR_OPEN;
1190       p_cb->p_cback(BTA_JV_L2CAP_OPEN_EVT, &evt_data, p_cb->l2cap_socket_id);
1191       break;
1192 
1193     case GAP_EVT_CONN_CLOSED:
1194       evt_data.l2c_close.async = true;
1195       evt_data.l2c_close.handle = p_cb->handle;
1196       p_cback = p_cb->p_cback;
1197       socket_id = p_cb->l2cap_socket_id;
1198       evt_data.l2c_close.status = bta_jv_free_l2c_cb(p_cb);
1199       p_cback(BTA_JV_L2CAP_CLOSE_EVT, &evt_data, socket_id);
1200       break;
1201 
1202     case GAP_EVT_CONN_DATA_AVAIL:
1203       evt_data.data_ind.handle = gap_handle;
1204       /* Reset idle timer to avoid requesting sniff mode while receiving data */
1205       bta_jv_pm_conn_busy(p_cb->p_pm_cb);
1206       p_cb->p_cback(BTA_JV_L2CAP_DATA_IND_EVT, &evt_data, p_cb->l2cap_socket_id);
1207       bta_jv_pm_conn_idle(p_cb->p_pm_cb);
1208       break;
1209 
1210     case GAP_EVT_TX_EMPTY:
1211       bta_jv_pm_conn_idle(p_cb->p_pm_cb);
1212       break;
1213 
1214     case GAP_EVT_CONN_CONGESTED:
1215     case GAP_EVT_CONN_UNCONGESTED:
1216       p_cb->cong = (event == GAP_EVT_CONN_CONGESTED) ? true : false;
1217       evt_data.l2c_cong.cong = p_cb->cong;
1218       p_cb->p_cback(BTA_JV_L2CAP_CONG_EVT, &evt_data, p_cb->l2cap_socket_id);
1219       break;
1220 
1221     default:
1222       break;
1223   }
1224 }
1225 
1226 /** starts an L2CAP server */
bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type,tBTA_SEC sec_mask,uint16_t local_psm,uint16_t rx_mtu,std::unique_ptr<tL2CAP_CFG_INFO> cfg_param,std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info,tBTA_JV_L2CAP_CBACK * p_cback,uint32_t l2cap_socket_id)1227 void bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, uint16_t local_psm,
1228                                uint16_t rx_mtu, std::unique_ptr<tL2CAP_CFG_INFO> cfg_param,
1229                                std::unique_ptr<tL2CAP_ERTM_INFO> ertm_info,
1230                                tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id) {
1231   uint16_t handle;
1232   tBTA_JV_L2CAP_START evt_data;
1233 
1234   tL2CAP_CFG_INFO cfg;
1235   memset(&cfg, 0, sizeof(tL2CAP_CFG_INFO));
1236   if (cfg_param) {
1237     cfg = *cfg_param;
1238   }
1239 
1240   // FIX: MTU=0 means not present
1241   if (rx_mtu > 0) {
1242     cfg.mtu_present = true;
1243     cfg.mtu = rx_mtu;
1244   } else {
1245     cfg.mtu_present = false;
1246     cfg.mtu = 0;
1247   }
1248 
1249   uint8_t sec_id = bta_jv_alloc_sec_id();
1250   uint16_t max_mps = 0xffff;  // Let GAP_ConnOpen set the max_mps.
1251   /* PSM checking is not required for LE COC */
1252 
1253   // Given a server socket type
1254   // return the associated transport
1255   const tBT_TRANSPORT transport = [](tBTA_JV_CONN_TYPE type) -> tBT_TRANSPORT {
1256     switch (type) {
1257       case tBTA_JV_CONN_TYPE::L2CAP:
1258         return BT_TRANSPORT_BR_EDR;
1259       case tBTA_JV_CONN_TYPE::L2CAP_LE:
1260         return BT_TRANSPORT_LE;
1261       case tBTA_JV_CONN_TYPE::RFCOMM:
1262       default:
1263         break;
1264     }
1265     log::warn("Unexpected socket type:{}", bta_jv_conn_type_text(type));
1266     return BT_TRANSPORT_AUTO;
1267   }(type);
1268 
1269   if (0 == sec_id || ((type == tBTA_JV_CONN_TYPE::L2CAP) && (!bta_jv_check_psm(local_psm))) ||
1270       (handle = GAP_ConnOpen("JV L2CAP", sec_id, 1, nullptr, local_psm, max_mps, &cfg,
1271                              ertm_info.get(), sec_mask, bta_jv_l2cap_server_cback, transport)) ==
1272               GAP_INVALID_HANDLE) {
1273     bta_jv_free_sec_id(&sec_id);
1274     evt_data.status = tBTA_JV_STATUS::FAILURE;
1275   } else {
1276     tBTA_JV_L2C_CB* p_cb = &bta_jv_cb.l2c_cb[handle];
1277     evt_data.status = tBTA_JV_STATUS::SUCCESS;
1278     evt_data.handle = handle;
1279     evt_data.sec_id = sec_id;
1280     p_cb->p_cback = p_cback;
1281     p_cb->l2cap_socket_id = l2cap_socket_id;
1282     p_cb->handle = handle;
1283     p_cb->sec_id = sec_id;
1284     p_cb->state = BTA_JV_ST_SR_LISTEN;
1285     p_cb->psm = local_psm;
1286   }
1287 
1288   if (p_cback) {
1289     tBTA_JV bta_jv;
1290     bta_jv.l2c_start = evt_data;
1291     p_cback(BTA_JV_L2CAP_START_EVT, &bta_jv, l2cap_socket_id);
1292   }
1293 }
1294 
1295 /* stops an L2CAP server */
bta_jv_l2cap_stop_server(uint16_t,uint32_t l2cap_socket_id)1296 void bta_jv_l2cap_stop_server(uint16_t /* local_psm */, uint32_t l2cap_socket_id) {
1297   for (int i = 0; i < BTA_JV_MAX_L2C_CONN; i++) {
1298     if (bta_jv_cb.l2c_cb[i].l2cap_socket_id == l2cap_socket_id) {
1299       tBTA_JV_L2C_CB* p_cb = &bta_jv_cb.l2c_cb[i];
1300       tBTA_JV_L2CAP_CBACK* p_cback = p_cb->p_cback;
1301       tBTA_JV_L2CAP_CLOSE evt_data;
1302       evt_data.handle = p_cb->handle;
1303       evt_data.status = bta_jv_free_l2c_cb(p_cb);
1304       evt_data.async = false;
1305       if (p_cback) {
1306         tBTA_JV bta_jv;
1307         bta_jv.l2c_close = evt_data;
1308         p_cback(BTA_JV_L2CAP_CLOSE_EVT, &bta_jv, l2cap_socket_id);
1309       }
1310       break;
1311     }
1312   }
1313 }
1314 
1315 /* Write data to an L2CAP connection */
bta_jv_l2cap_write(uint32_t handle,uint32_t req_id,BT_HDR * msg,uint32_t user_id,tBTA_JV_L2C_CB * p_cb)1316 void bta_jv_l2cap_write(uint32_t handle, uint32_t req_id, BT_HDR* msg, uint32_t user_id,
1317                         tBTA_JV_L2C_CB* p_cb) {
1318   /* As we check this callback exists before the tBTA_JV_API_L2CAP_WRITE can be
1319    * send through the API this check should not be needed. But the API is not
1320    * designed to be used (safely at least) in a multi-threaded scheduler, hence
1321    * if the peer device disconnects the l2cap link after the API is called, but
1322    * before this message is handled, the ->p_cback will be cleared at this
1323    * point. At first glanch this seems highly unlikely, but for all
1324    * obex-profiles with two channels connected - e.g. MAP, this happens around 1
1325    * of 4 disconnects, as a disconnect on the server channel causes a disconnect
1326    * to be send on the client (notification) channel, but at the peer typically
1327    * disconnects both the OBEX disconnect request crosses the incoming l2cap
1328    * disconnect. If p_cback is cleared, we simply discard the data. RISK: The
1329    * caller must handle any cleanup based on another signal than
1330    * BTA_JV_L2CAP_WRITE_EVT, which is typically not possible, as the pointer to
1331    * the allocated buffer is stored in this message, and can therefore not be
1332    * freed, hence we have a mem-leak-by-design.*/
1333   if (!p_cb->p_cback) {
1334     /* As this pointer is checked in the API function, this occurs only when the
1335      * channel is disconnected after the API function is called, but before the
1336      * message is handled. */
1337     log::error("p_cb->p_cback == NULL");
1338     osi_free(msg);
1339     return;
1340   }
1341 
1342   tBTA_JV_L2CAP_WRITE evt_data;
1343   evt_data.status = tBTA_JV_STATUS::FAILURE;
1344   evt_data.handle = handle;
1345   evt_data.req_id = req_id;
1346   evt_data.cong = p_cb->cong;
1347   evt_data.len = msg->len;
1348 
1349   bta_jv_pm_conn_busy(p_cb->p_pm_cb);
1350 
1351   // TODO: this was set only for non-fixed channel packets. Is that needed ?
1352   msg->event = BT_EVT_TO_BTU_SP_DATA;
1353 
1354   if (evt_data.cong) {
1355     osi_free(msg);
1356   } else {
1357     if (GAP_ConnWriteData(handle, msg) == BT_PASS) {
1358       evt_data.status = tBTA_JV_STATUS::SUCCESS;
1359     }
1360   }
1361 
1362   tBTA_JV bta_jv;
1363   bta_jv.l2c_write = evt_data;
1364   p_cb->p_cback(BTA_JV_L2CAP_WRITE_EVT, &bta_jv, user_id);
1365 }
1366 
1367 /*******************************************************************************
1368  *
1369  * Function     bta_jv_port_data_co_cback
1370  *
1371  * Description  port data callback function of rfcomm
1372  *              connections
1373  *
1374  * Returns      void
1375  *
1376  ******************************************************************************/
bta_jv_port_data_co_cback(uint16_t port_handle,uint8_t * buf,uint16_t len,int type)1377 static int bta_jv_port_data_co_cback(uint16_t port_handle, uint8_t* buf, uint16_t len, int type) {
1378   tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle);
1379   tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle);
1380   log::verbose("p_cb={}, p_pcb={}, len={}, type={}", std::format_ptr(p_cb), std::format_ptr(p_pcb),
1381                len, type);
1382   if (p_pcb != NULL) {
1383     switch (type) {
1384       case DATA_CO_CALLBACK_TYPE_INCOMING:
1385         // Reset sniff timer when receiving data by sysproxy
1386         if (osi_property_get_bool("bluetooth.rfcomm.sysproxy.rx.exit_sniff", false)) {
1387           bta_jv_reset_sniff_timer(p_pcb->p_pm_cb);
1388         }
1389         return bta_co_rfc_data_incoming(p_pcb->rfcomm_slot_id, (BT_HDR*)buf);
1390       case DATA_CO_CALLBACK_TYPE_OUTGOING_SIZE:
1391         return bta_co_rfc_data_outgoing_size(p_pcb->rfcomm_slot_id, (int*)buf);
1392       case DATA_CO_CALLBACK_TYPE_OUTGOING:
1393         return bta_co_rfc_data_outgoing(p_pcb->rfcomm_slot_id, buf, len);
1394       default:
1395         log::error("unknown callout type={}", type);
1396         break;
1397     }
1398   }
1399   return 0;
1400 }
1401 
1402 /*******************************************************************************
1403  *
1404  * Function     bta_jv_port_mgmt_cl_cback
1405  *
1406  * Description  callback for port mamangement function of rfcomm
1407  *              client connections
1408  *
1409  * Returns      void
1410  *
1411  ******************************************************************************/
bta_jv_port_mgmt_cl_cback(const tPORT_RESULT code,uint16_t port_handle)1412 static void bta_jv_port_mgmt_cl_cback(const tPORT_RESULT code, uint16_t port_handle) {
1413   tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle);
1414   tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle);
1415   RawAddress rem_bda = RawAddress::kEmpty;
1416   uint16_t lcid;
1417   tBTA_JV_RFCOMM_CBACK* p_cback; /* the callback function */
1418 
1419   if (p_cb == NULL) {
1420     log::warn("p_cb is NULL, code={}, port_handle={}", code, port_handle);
1421     return;
1422   } else if (p_cb->p_cback == NULL) {
1423     log::warn("p_cb->p_cback is null, code={}, port_handle={}", code, port_handle);
1424     return;
1425   }
1426 
1427   log::verbose("code={}, port_handle={}, rfc_handle={}", code, port_handle, p_cb->handle);
1428 
1429   if (PORT_CheckConnection(port_handle, &rem_bda, &lcid) != PORT_SUCCESS) {
1430     log::warn("Unable to check RFCOMM connection peer:{} port_handle:{}", rem_bda, port_handle);
1431   }
1432 
1433   if (code == PORT_SUCCESS) {
1434     tBTA_JV evt_data = {
1435             .rfc_open =
1436                     {
1437                             .status = tBTA_JV_STATUS::SUCCESS,
1438                             .handle = p_cb->handle,
1439                             .rem_bda = rem_bda,
1440                     },
1441     };
1442     if (com::android::bluetooth::flags::socket_settings_api()) {
1443       if (PORT_GetChannelInfo(port_handle, &evt_data.rfc_open.rx_mtu, &evt_data.rfc_open.tx_mtu,
1444                               &evt_data.rfc_open.local_credit, &evt_data.rfc_open.remote_credit,
1445                               &evt_data.rfc_open.local_cid, &evt_data.rfc_open.remote_cid,
1446                               &evt_data.rfc_open.dlci, &evt_data.rfc_open.max_frame_size,
1447                               &evt_data.rfc_open.acl_handle,
1448                               &evt_data.rfc_open.mux_initiator) != PORT_SUCCESS) {
1449         log::warn("Unable to get RFCOMM channel info peer:{} port_handle:{}", rem_bda, port_handle);
1450       }
1451     }
1452     p_pcb->state = BTA_JV_ST_CL_OPEN;
1453     p_cb->p_cback(BTA_JV_RFCOMM_OPEN_EVT, &evt_data, p_pcb->rfcomm_slot_id);
1454   } else {
1455     tBTA_JV evt_data = {
1456             .rfc_close =
1457                     {
1458                             .status = tBTA_JV_STATUS::FAILURE,
1459                             .port_status = code,
1460                             .handle = p_cb->handle,
1461                             .async = (p_pcb->state == BTA_JV_ST_CL_CLOSING) ? false : true,
1462                     },
1463     };
1464     // p_pcb->state = BTA_JV_ST_NONE;
1465     // p_pcb->cong = false;
1466     p_cback = p_cb->p_cback;
1467     p_cback(BTA_JV_RFCOMM_CLOSE_EVT, &evt_data, p_pcb->rfcomm_slot_id);
1468     // bta_jv_free_rfc_cb(p_cb, p_pcb);
1469   }
1470 }
1471 
1472 /*******************************************************************************
1473  *
1474  * Function     bta_jv_port_event_cl_cback
1475  *
1476  * Description  Callback for RFCOMM client port events
1477  *
1478  * Returns      void
1479  *
1480  ******************************************************************************/
bta_jv_port_event_cl_cback(uint32_t code,uint16_t port_handle)1481 static void bta_jv_port_event_cl_cback(uint32_t code, uint16_t port_handle) {
1482   tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle);
1483   tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle);
1484   tBTA_JV evt_data;
1485 
1486   log::verbose("port_handle={}", port_handle);
1487   if (NULL == p_cb || NULL == p_cb->p_cback) {
1488     return;
1489   }
1490 
1491   log::verbose("code=0x{:x}, port_handle={}, rfc_handle={}", code, port_handle, p_cb->handle);
1492   if (code & PORT_EV_RXCHAR) {
1493     evt_data.data_ind.handle = p_cb->handle;
1494     p_cb->p_cback(BTA_JV_RFCOMM_DATA_IND_EVT, &evt_data, p_pcb->rfcomm_slot_id);
1495   }
1496 
1497   if (code & PORT_EV_FC) {
1498     p_pcb->cong = (code & PORT_EV_FCS) ? false : true;
1499     evt_data.rfc_cong.cong = p_pcb->cong;
1500     evt_data.rfc_cong.handle = p_cb->handle;
1501     evt_data.rfc_cong.status = tBTA_JV_STATUS::SUCCESS;
1502     p_cb->p_cback(BTA_JV_RFCOMM_CONG_EVT, &evt_data, p_pcb->rfcomm_slot_id);
1503   }
1504 
1505   if (code & PORT_EV_TXEMPTY) {
1506     bta_jv_pm_conn_idle(p_pcb->p_pm_cb);
1507   }
1508 }
1509 
1510 /* Client initiates an RFCOMM connection */
bta_jv_rfcomm_connect(tBTA_SEC sec_mask,uint8_t remote_scn,const RawAddress & peer_bd_addr,tBTA_JV_RFCOMM_CBACK * p_cback,uint32_t rfcomm_slot_id,RfcommCfgInfo cfg,uint32_t app_uid,uint64_t sdp_duration_ms)1511 void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, const RawAddress& peer_bd_addr,
1512                            tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id,
1513                            RfcommCfgInfo cfg, uint32_t app_uid, uint64_t sdp_duration_ms) {
1514   uint16_t handle = 0;
1515   uint32_t event_mask = BTA_JV_RFC_EV_MASK;
1516   int port_status;
1517   PortSettings port_settings;
1518 
1519   tBTA_JV bta_jv = {
1520           .rfc_cl_init =
1521                   {
1522                           .status = tBTA_JV_STATUS::SUCCESS,
1523                           .handle = 0,
1524                           .sec_id = 0,
1525                           .use_co = false,
1526                   },
1527   };
1528 
1529   // Update security service record for RFCOMM client so that
1530   // secure RFCOMM connection will be authenticated with MTIM protection
1531   // while creating the L2CAP connection.
1532   get_btm_client_interface().security.BTM_SetSecurityLevel(true, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX,
1533                                                            sec_mask, BT_PSM_RFCOMM,
1534                                                            BTM_SEC_PROTO_RFCOMM, 0);
1535 
1536   port_status = RFCOMM_CreateConnectionWithSecurity(UUID_SERVCLASS_SERIAL_PORT, remote_scn, false,
1537                                                     BTA_JV_DEF_RFC_MTU, peer_bd_addr, &handle,
1538                                                     bta_jv_port_mgmt_cl_cback, sec_mask, cfg);
1539   if (port_status != PORT_SUCCESS) {
1540     log::error("RFCOMM_CreateConnection failed");
1541     bta_collect_rfc_metrics_after_port_fail(
1542             static_cast<tPORT_RESULT>(port_status), sdp_duration_ms > 0, tBTA_JV_STATUS::SUCCESS,
1543             peer_bd_addr, static_cast<int>(app_uid), sec_mask, false, sdp_duration_ms);
1544     bta_jv.rfc_cl_init.status = tBTA_JV_STATUS::FAILURE;
1545   } else {
1546     tBTA_JV_PCB* p_pcb;
1547     tBTA_JV_RFC_CB* p_cb = bta_jv_alloc_rfc_cb(handle, &p_pcb);
1548     if (p_cb) {
1549       p_cb->p_cback = p_cback;
1550       p_cb->scn = 0;
1551       p_pcb->state = BTA_JV_ST_CL_OPENING;
1552       p_pcb->rfcomm_slot_id = rfcomm_slot_id;
1553       bta_jv.rfc_cl_init.use_co = true;
1554 
1555       if (PORT_SetSdpDuration(handle, sdp_duration_ms) != PORT_SUCCESS) {
1556         log::warn("Unable to set sdp_duration for port_handle:{}", handle);
1557       }
1558       if (PORT_SetAppUid(handle, app_uid) != PORT_SUCCESS) {
1559         log::warn("Unable to set app_uid for port_handle:{}", handle);
1560       }
1561       if (PORT_SetEventMaskAndCallback(handle, event_mask, bta_jv_port_event_cl_cback) !=
1562           PORT_SUCCESS) {
1563         log::warn("Unable to set RFCOMM client event mask and callback port_handle:{}", handle);
1564       }
1565       if (PORT_SetDataCOCallback(handle, bta_jv_port_data_co_cback) != PORT_SUCCESS) {
1566         log::warn("Unable to set RFCOMM client data callback port_handle:{}", handle);
1567       }
1568       if (PORT_GetSettings(handle, &port_settings) != PORT_SUCCESS) {
1569         log::warn("Unable to get RFCOMM client state port_handle:{}", handle);
1570       }
1571 
1572       port_settings.fc_type = (PORT_FC_CTS_ON_INPUT | PORT_FC_CTS_ON_OUTPUT);
1573 
1574       if (PORT_SetSettings(handle, &port_settings) != PORT_SUCCESS) {
1575         log::warn("Unable to set RFCOMM client state port_handle:{}", handle);
1576       }
1577 
1578       bta_jv.rfc_cl_init.handle = p_cb->handle;
1579     } else {
1580       bta_jv.rfc_cl_init.status = tBTA_JV_STATUS::FAILURE;
1581       log::error("run out of rfc control block");
1582     }
1583   }
1584 
1585   p_cback(BTA_JV_RFCOMM_CL_INIT_EVT, &bta_jv, rfcomm_slot_id);
1586   if (bta_jv.rfc_cl_init.status == tBTA_JV_STATUS::FAILURE) {
1587     if (handle) {
1588       if (RFCOMM_RemoveConnection(handle) != PORT_SUCCESS) {
1589         log::warn("Unable to remove RFCOMM connection port_handle:{}", handle);
1590       }
1591     }
1592   }
1593 }
1594 
find_rfc_pcb(uint32_t rfcomm_slot_id,tBTA_JV_RFC_CB ** cb,tBTA_JV_PCB ** pcb)1595 static int find_rfc_pcb(uint32_t rfcomm_slot_id, tBTA_JV_RFC_CB** cb, tBTA_JV_PCB** pcb) {
1596   *cb = NULL;
1597   *pcb = NULL;
1598   int i;
1599   for (i = 0; i < MAX_RFC_PORTS; i++) {
1600     uint32_t rfc_handle = bta_jv_cb.port_cb[i].handle & BTA_JV_RFC_HDL_MASK;
1601     rfc_handle &= ~BTA_JV_RFCOMM_MASK;
1602     if (rfc_handle && bta_jv_cb.port_cb[i].rfcomm_slot_id == rfcomm_slot_id) {
1603       *pcb = &bta_jv_cb.port_cb[i];
1604       *cb = &bta_jv_cb.rfc_cb[rfc_handle - 1];
1605       log::verbose(
1606               "FOUND rfc_handle=0x{:x}, port.jv_handle=0x{:x}, state={}, rfc_cb->handle=0x{:x}",
1607               rfc_handle, (*pcb)->handle, (*pcb)->state, (*cb)->handle);
1608       return 1;
1609     }
1610   }
1611   log::verbose("cannot find rfc_cb from user data:{}", rfcomm_slot_id);
1612   return 0;
1613 }
1614 
1615 /* Close an RFCOMM connection */
bta_jv_rfcomm_close(uint32_t handle,uint32_t rfcomm_slot_id)1616 void bta_jv_rfcomm_close(uint32_t handle, uint32_t rfcomm_slot_id) {
1617   if (!handle) {
1618     log::error("rfc_handle is null");
1619     return;
1620   }
1621 
1622   log::verbose("rfc_handle={}", handle);
1623 
1624   tBTA_JV_RFC_CB* p_cb = NULL;
1625   tBTA_JV_PCB* p_pcb = NULL;
1626 
1627   if (!find_rfc_pcb(rfcomm_slot_id, &p_cb, &p_pcb)) {
1628     return;
1629   }
1630   bta_jv_free_rfc_cb(p_cb, p_pcb);
1631 }
1632 
1633 /*******************************************************************************
1634  *
1635  * Function     bta_jv_port_mgmt_sr_cback
1636  *
1637  * Description  callback for port mamangement function of rfcomm
1638  *              server connections
1639  *
1640  * Returns      void
1641  *
1642  ******************************************************************************/
bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code,uint16_t port_handle)1643 static void bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code, uint16_t port_handle) {
1644   tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle);
1645   tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle);
1646   tBTA_JV evt_data;
1647   RawAddress rem_bda = RawAddress::kEmpty;
1648   uint16_t lcid;
1649   log::verbose("code={}, port_handle={}", code, port_handle);
1650   if (NULL == p_cb || NULL == p_cb->p_cback) {
1651     log::error("p_cb={}, p_cb->p_cback={}", std::format_ptr(p_cb),
1652                std::format_ptr(p_cb ? p_cb->p_cback : nullptr));
1653     return;
1654   }
1655   uint32_t rfcomm_slot_id = p_pcb->rfcomm_slot_id;
1656   log::verbose("code={}, port_handle=0x{:x}, jv_handle=0x{:x}, p_pcb{}, user={}", code, port_handle,
1657                p_cb->handle, std::format_ptr(p_pcb), p_pcb->rfcomm_slot_id);
1658 
1659   int status = PORT_CheckConnection(port_handle, &rem_bda, &lcid);
1660   int failed = true;
1661   if (code == PORT_SUCCESS) {
1662     if (status != PORT_SUCCESS) {
1663       log::error("PORT_CheckConnection returned {}, although port is supposed to be connected",
1664                  status);
1665     }
1666     evt_data.rfc_srv_open.handle = p_pcb->handle;
1667     evt_data.rfc_srv_open.status = tBTA_JV_STATUS::SUCCESS;
1668     evt_data.rfc_srv_open.rem_bda = rem_bda;
1669     if (com::android::bluetooth::flags::socket_settings_api()) {
1670       if (PORT_GetChannelInfo(port_handle, &evt_data.rfc_srv_open.rx_mtu,
1671                               &evt_data.rfc_srv_open.tx_mtu, &evt_data.rfc_srv_open.local_credit,
1672                               &evt_data.rfc_srv_open.remote_credit,
1673                               &evt_data.rfc_srv_open.local_cid, &evt_data.rfc_srv_open.remote_cid,
1674                               &evt_data.rfc_srv_open.dlci, &evt_data.rfc_srv_open.max_frame_size,
1675                               &evt_data.rfc_srv_open.acl_handle,
1676                               &evt_data.rfc_srv_open.mux_initiator) != PORT_SUCCESS) {
1677         log::warn("Unable to get RFCOMM channel info peer:{} port_handle:{}", rem_bda, port_handle);
1678       }
1679     }
1680     tBTA_JV_PCB* p_pcb_new_listen = bta_jv_add_rfc_port(p_cb, p_pcb);
1681     if (p_pcb_new_listen) {
1682       evt_data.rfc_srv_open.new_listen_handle = p_pcb_new_listen->handle;
1683       p_pcb_new_listen->rfcomm_slot_id =
1684               p_cb->p_cback(BTA_JV_RFCOMM_SRV_OPEN_EVT, &evt_data, rfcomm_slot_id);
1685       if (p_pcb_new_listen->rfcomm_slot_id == 0) {
1686         log::error("rfcomm_slot_id == {}", p_pcb_new_listen->rfcomm_slot_id);
1687       } else {
1688         log::verbose("curr_sess={}, max_sess={}", p_cb->curr_sess, p_cb->max_sess);
1689         failed = false;
1690       }
1691     } else {
1692       log::error("failed to create new listen port");
1693     }
1694   }
1695   if (failed) {
1696     evt_data.rfc_close.handle = p_cb->handle;
1697     evt_data.rfc_close.status = tBTA_JV_STATUS::FAILURE;
1698     evt_data.rfc_close.async = true;
1699     evt_data.rfc_close.port_status = code;
1700     p_pcb->cong = false;
1701 
1702     tBTA_JV_RFCOMM_CBACK* p_cback = p_cb->p_cback;
1703     log::verbose("PORT_CLOSED before BTA_JV_RFCOMM_CLOSE_EVT: curr_sess={}, max_sess={}",
1704                  p_cb->curr_sess, p_cb->max_sess);
1705     if (BTA_JV_ST_SR_CLOSING == p_pcb->state) {
1706       evt_data.rfc_close.async = false;
1707       evt_data.rfc_close.status = tBTA_JV_STATUS::SUCCESS;
1708     }
1709     // p_pcb->state = BTA_JV_ST_NONE;
1710     p_cback(BTA_JV_RFCOMM_CLOSE_EVT, &evt_data, rfcomm_slot_id);
1711     // bta_jv_free_rfc_cb(p_cb, p_pcb);
1712 
1713     log::verbose("PORT_CLOSED after BTA_JV_RFCOMM_CLOSE_EVT: curr_sess={}, max_sess={}",
1714                  p_cb->curr_sess, p_cb->max_sess);
1715   }
1716 }
1717 
1718 /*******************************************************************************
1719  *
1720  * Function     bta_jv_port_event_sr_cback
1721  *
1722  * Description  Callback for RFCOMM server port events
1723  *
1724  * Returns      void
1725  *
1726  ******************************************************************************/
bta_jv_port_event_sr_cback(uint32_t code,uint16_t port_handle)1727 static void bta_jv_port_event_sr_cback(uint32_t code, uint16_t port_handle) {
1728   tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle);
1729   tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle);
1730   tBTA_JV evt_data;
1731 
1732   if (NULL == p_cb || NULL == p_cb->p_cback) {
1733     log::error("p_cb={}, p_cb->p_cback={}", std::format_ptr(p_cb),
1734                std::format_ptr(p_cb ? p_cb->p_cback : nullptr));
1735     return;
1736   }
1737 
1738   log::verbose("code=0x{:x}, port_handle={}, rfc_handle={}", code, port_handle, p_cb->handle);
1739 
1740   uint32_t user_data = p_pcb->rfcomm_slot_id;
1741   if (code & PORT_EV_RXCHAR) {
1742     evt_data.data_ind.handle = p_cb->handle;
1743     p_cb->p_cback(BTA_JV_RFCOMM_DATA_IND_EVT, &evt_data, user_data);
1744   }
1745 
1746   if (code & PORT_EV_FC) {
1747     p_pcb->cong = (code & PORT_EV_FCS) ? false : true;
1748     evt_data.rfc_cong.cong = p_pcb->cong;
1749     evt_data.rfc_cong.handle = p_cb->handle;
1750     evt_data.rfc_cong.status = tBTA_JV_STATUS::SUCCESS;
1751     p_cb->p_cback(BTA_JV_RFCOMM_CONG_EVT, &evt_data, user_data);
1752   }
1753 
1754   if (code & PORT_EV_TXEMPTY) {
1755     bta_jv_pm_conn_idle(p_pcb->p_pm_cb);
1756   }
1757 }
1758 
1759 /*******************************************************************************
1760  *
1761  * Function     bta_jv_add_rfc_port
1762  *
1763  * Description  add a port for server when the existing posts is open
1764  *
1765  * Returns   return a pointer to tBTA_JV_PCB just added
1766  *
1767  ******************************************************************************/
bta_jv_add_rfc_port(tBTA_JV_RFC_CB * p_cb,tBTA_JV_PCB * p_pcb_open)1768 static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb_open) {
1769   uint8_t used = 0, i, listen = 0;
1770   uint32_t si = 0;
1771   int port_status;
1772   PortSettings port_settings;
1773   uint32_t event_mask = BTA_JV_RFC_EV_MASK;
1774   tBTA_JV_PCB* p_pcb = NULL;
1775   tBTA_SEC sec_mask;
1776   if (p_cb->max_sess > 1) {
1777     for (i = 0; i < p_cb->max_sess; i++) {
1778       if (p_cb->rfc_hdl[i] != 0) {
1779         p_pcb = &bta_jv_cb.port_cb[p_cb->rfc_hdl[i] - 1];
1780         if (p_pcb->state == BTA_JV_ST_SR_LISTEN) {
1781           listen++;
1782           if (p_pcb_open == p_pcb) {
1783             log::verbose("port_handle={}, change the listen port to open state",
1784                          p_pcb->port_handle);
1785             p_pcb->state = BTA_JV_ST_SR_OPEN;
1786 
1787           } else {
1788             log::error(
1789                     "open pcb not matching listen one, count={}, listen port_handle={}, open "
1790                     "pcb={}",
1791                     listen, p_pcb->port_handle, p_pcb_open->handle);
1792             return NULL;
1793           }
1794         }
1795         used++;
1796       } else if (si == 0) {
1797         si = i + 1;
1798       }
1799     }
1800 
1801     log::verbose("max_sess={}, used={}, curr_sess={}, listen={}, si={}", p_cb->max_sess, used,
1802                  p_cb->curr_sess, listen, si);
1803     if (used < p_cb->max_sess && listen == 1 && si) {
1804       si--;
1805       if (PORT_GetSecurityMask(p_pcb_open->port_handle, &sec_mask) != PORT_SUCCESS) {
1806         log::error("RFCOMM_CreateConnection failed: invalid port_handle");
1807       }
1808 
1809       port_status = RFCOMM_CreateConnectionWithSecurity(
1810               p_cb->sec_id, p_cb->scn, true, BTA_JV_DEF_RFC_MTU, RawAddress::kAny,
1811               &(p_cb->rfc_hdl[si]), bta_jv_port_mgmt_sr_cback, sec_mask, RfcommCfgInfo{});
1812       if (port_status == PORT_SUCCESS) {
1813         p_cb->curr_sess++;
1814         p_pcb = &bta_jv_cb.port_cb[p_cb->rfc_hdl[si] - 1];
1815         p_pcb->state = BTA_JV_ST_SR_LISTEN;
1816         p_pcb->port_handle = p_cb->rfc_hdl[si];
1817         p_pcb->rfcomm_slot_id = p_pcb_open->rfcomm_slot_id;
1818 
1819         if (PORT_ClearKeepHandleFlag(p_pcb->port_handle) != PORT_SUCCESS) {
1820           log::warn("Unable to clear RFCOMM server keep handle flag port_handle:{}",
1821                     p_pcb->port_handle);
1822         }
1823         if (PORT_SetEventMaskAndCallback(p_pcb->port_handle, event_mask,
1824                                          bta_jv_port_event_sr_cback) != PORT_SUCCESS) {
1825           log::warn("Unable to set RFCOMM server event mask and callback port_handle:{}",
1826                     p_pcb->port_handle);
1827         }
1828         if (PORT_SetDataCOCallback(p_pcb->port_handle, bta_jv_port_data_co_cback) != PORT_SUCCESS) {
1829           log::warn("Unable to set RFCOMM server data callback port_handle:{}", p_pcb->port_handle);
1830         }
1831         if (PORT_GetSettings(p_pcb->port_handle, &port_settings) != PORT_SUCCESS) {
1832           log::warn("Unable to get RFCOMM server state port_handle:{}", p_pcb->port_handle);
1833         }
1834 
1835         port_settings.fc_type = (PORT_FC_CTS_ON_INPUT | PORT_FC_CTS_ON_OUTPUT);
1836 
1837         if (PORT_SetSettings(p_pcb->port_handle, &port_settings) != PORT_SUCCESS) {
1838           log::warn("Unable to set RFCOMM server state port_handle:{}", p_pcb->port_handle);
1839         }
1840         p_pcb->handle = BTA_JV_RFC_H_S_TO_HDL(p_cb->handle, si);
1841         log::verbose("p_pcb->handle=0x{:x}, curr_sess={}", p_pcb->handle, p_cb->curr_sess);
1842       } else {
1843         log::error("RFCOMM_CreateConnection failed");
1844         bta_collect_rfc_metrics_after_port_fail(static_cast<tPORT_RESULT>(port_status), false,
1845                                                 tBTA_JV_STATUS::SUCCESS, RawAddress::kAny, 0,
1846                                                 sec_mask, true, 0);
1847 
1848         return NULL;
1849       }
1850     } else {
1851       log::error("cannot create new rfc listen port");
1852       return NULL;
1853     }
1854   }
1855   log::verbose("sec id in use={}, rfc_cb in use={}", get_sec_id_used(), get_rfc_cb_used());
1856   return p_pcb;
1857 }
1858 
1859 /* waits for an RFCOMM client to connect */
bta_jv_rfcomm_start_server(tBTA_SEC sec_mask,uint8_t local_scn,uint8_t max_session,tBTA_JV_RFCOMM_CBACK * p_cback,uint32_t rfcomm_slot_id,RfcommCfgInfo cfg,uint32_t app_uid)1860 void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, uint8_t max_session,
1861                                 tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id,
1862                                 RfcommCfgInfo cfg, uint32_t app_uid) {
1863   uint16_t handle = 0;
1864   uint32_t event_mask = BTA_JV_RFC_EV_MASK;
1865   int port_status;
1866   PortSettings port_settings;
1867   tBTA_JV_RFC_CB* p_cb = NULL;
1868   tBTA_JV_PCB* p_pcb;
1869   tBTA_JV_RFCOMM_START evt_data;
1870 
1871   memset(&evt_data, 0, sizeof(evt_data));
1872   evt_data.status = tBTA_JV_STATUS::FAILURE;
1873 
1874   do {
1875     port_status = RFCOMM_CreateConnectionWithSecurity(0, local_scn, true, BTA_JV_DEF_RFC_MTU,
1876                                                       RawAddress::kAny, &handle,
1877                                                       bta_jv_port_mgmt_sr_cback, sec_mask, cfg);
1878     if (port_status != PORT_SUCCESS) {
1879       log::error("RFCOMM_CreateConnection failed");
1880       bta_collect_rfc_metrics_after_port_fail(static_cast<tPORT_RESULT>(port_status), false,
1881                                               tBTA_JV_STATUS::SUCCESS, RawAddress::kAny,
1882                                               static_cast<int>(app_uid), sec_mask, true, 0);
1883       break;
1884     }
1885 
1886     p_cb = bta_jv_alloc_rfc_cb(handle, &p_pcb);
1887     if (!p_cb) {
1888       log::error("run out of rfc control block");
1889       break;
1890     }
1891 
1892     p_cb->max_sess = max_session;
1893     p_cb->p_cback = p_cback;
1894     p_cb->scn = local_scn;
1895     p_pcb->state = BTA_JV_ST_SR_LISTEN;
1896     p_pcb->rfcomm_slot_id = rfcomm_slot_id;
1897     evt_data.status = tBTA_JV_STATUS::SUCCESS;
1898     evt_data.handle = p_cb->handle;
1899     evt_data.use_co = true;
1900 
1901     if (PORT_SetAppUid(handle, app_uid) != PORT_SUCCESS) {
1902       log::warn("Unable to set app_uid for port_handle:{}", handle);
1903     }
1904     if (PORT_ClearKeepHandleFlag(handle) != PORT_SUCCESS) {
1905       log::warn("Unable to clear RFCOMM server keep handle flag port_handle:{}", handle);
1906     }
1907     if (PORT_SetEventMaskAndCallback(handle, event_mask, bta_jv_port_event_sr_cback) !=
1908         PORT_SUCCESS) {
1909       log::warn("Unable to set RFCOMM server event mask and callback port_handle:{}", handle);
1910     }
1911     if (PORT_GetSettings(handle, &port_settings) != PORT_SUCCESS) {
1912       log::warn("Unable to get RFCOMM server state port_handle:{}", handle);
1913     }
1914 
1915     port_settings.fc_type = (PORT_FC_CTS_ON_INPUT | PORT_FC_CTS_ON_OUTPUT);
1916 
1917     if (PORT_SetSettings(handle, &port_settings) != PORT_SUCCESS) {
1918       log::warn("Unable to set RFCOMM port state port_handle:{}", handle);
1919     }
1920   } while (0);
1921 
1922   tBTA_JV bta_jv;
1923   bta_jv.rfc_start = evt_data;
1924   p_cback(BTA_JV_RFCOMM_START_EVT, &bta_jv, rfcomm_slot_id);
1925   if (bta_jv.rfc_start.status == tBTA_JV_STATUS::SUCCESS) {
1926     if (PORT_SetDataCOCallback(handle, bta_jv_port_data_co_cback) != PORT_SUCCESS) {
1927       log::error("Unable to set RFCOMM server data callback port_handle:{}", handle);
1928     }
1929   } else {
1930     if (handle) {
1931       if (RFCOMM_RemoveConnection(handle) != PORT_SUCCESS) {
1932         log::warn("Unable to remote RFCOMM server connection port_handle:{}", handle);
1933       }
1934     }
1935   }
1936 }
1937 
1938 /* stops an RFCOMM server */
bta_jv_rfcomm_stop_server(uint32_t handle,uint32_t rfcomm_slot_id)1939 void bta_jv_rfcomm_stop_server(uint32_t handle, uint32_t rfcomm_slot_id) {
1940   if (!handle) {
1941     log::error("jv_handle is null");
1942     return;
1943   }
1944 
1945   log::verbose("");
1946   tBTA_JV_RFC_CB* p_cb = NULL;
1947   tBTA_JV_PCB* p_pcb = NULL;
1948 
1949   if (!find_rfc_pcb(rfcomm_slot_id, &p_cb, &p_pcb)) {
1950     return;
1951   }
1952   log::verbose("p_pcb={}, p_pcb->port_handle={}", std::format_ptr(p_pcb), p_pcb->port_handle);
1953   bta_jv_free_rfc_cb(p_cb, p_pcb);
1954 }
1955 
1956 /* write data to an RFCOMM connection */
bta_jv_rfcomm_write(uint32_t handle,uint32_t req_id,tBTA_JV_RFC_CB * p_cb,tBTA_JV_PCB * p_pcb)1957 void bta_jv_rfcomm_write(uint32_t handle, uint32_t req_id, tBTA_JV_RFC_CB* p_cb,
1958                          tBTA_JV_PCB* p_pcb) {
1959   if (p_pcb->state == BTA_JV_ST_NONE) {
1960     log::error("in state BTA_JV_ST_NONE - cannot write");
1961     return;
1962   }
1963 
1964   tBTA_JV_RFCOMM_WRITE evt_data;
1965   evt_data.status = tBTA_JV_STATUS::FAILURE;
1966   evt_data.handle = handle;
1967   evt_data.req_id = req_id;
1968   evt_data.cong = p_pcb->cong;
1969   evt_data.len = 0;
1970 
1971   bta_jv_pm_conn_busy(p_pcb->p_pm_cb);
1972 
1973   if (!evt_data.cong && PORT_WriteDataCO(p_pcb->port_handle, &evt_data.len) == PORT_SUCCESS) {
1974     evt_data.status = tBTA_JV_STATUS::SUCCESS;
1975   }
1976 
1977   // Update congestion flag
1978   evt_data.cong = p_pcb->cong;
1979 
1980   if (!p_cb->p_cback) {
1981     log::error("No JV callback set");
1982     return;
1983   }
1984 
1985   tBTA_JV bta_jv;
1986   bta_jv.rfc_write = evt_data;
1987   p_cb->p_cback(BTA_JV_RFCOMM_WRITE_EVT, &bta_jv, p_pcb->rfcomm_slot_id);
1988 }
1989 
1990 /* Set or free power mode profile for a JV application */
bta_jv_set_pm_profile(uint32_t handle,tBTA_JV_PM_ID app_id,tBTA_JV_CONN_STATE init_st)1991 void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, tBTA_JV_CONN_STATE init_st) {
1992   log::verbose("jv_handle=0x{:x}, app_id={}, init_st={}", handle, app_id,
1993                bta_jv_conn_state_text(init_st));
1994 
1995   /* clear PM control block */
1996   if (app_id == BTA_JV_PM_ID_CLEAR) {
1997     tBTA_JV_STATUS status = bta_jv_free_set_pm_profile_cb(handle);
1998     if (status != tBTA_JV_STATUS::SUCCESS) {
1999       log::warn(
2000               "Unable to free a power mode profile jv_handle:0x:{:x} app_id:{} state:{} status:{}",
2001               handle, app_id, init_st, bta_jv_status_text(status));
2002     }
2003   } else { /* set PM control block */
2004     tBTA_JV_PM_CB* p_cb = bta_jv_alloc_set_pm_profile_cb(handle, app_id);
2005     if (p_cb) {
2006       bta_jv_pm_state_change(p_cb, init_st);
2007     } else {
2008       log::warn("Unable to allocate a power mode profile jv_handle:0x:{:x} app_id:{} state:{}",
2009                 handle, app_id, init_st);
2010     }
2011   }
2012 }
2013 
2014 /*******************************************************************************
2015  *
2016  * Function    bta_jv_pm_conn_busy
2017  *
2018  * Description set pm connection busy state (input param safe)
2019  *
2020  * Params      p_cb: pm control block of jv connection
2021  *
2022  * Returns     void
2023  *
2024  ******************************************************************************/
bta_jv_pm_conn_busy(tBTA_JV_PM_CB * p_cb)2025 static void bta_jv_pm_conn_busy(tBTA_JV_PM_CB* p_cb) {
2026   if ((NULL != p_cb) && (BTA_JV_PM_IDLE_ST == p_cb->state)) {
2027     bta_jv_pm_state_change(p_cb, BTA_JV_CONN_BUSY);
2028   }
2029 }
2030 
2031 /*******************************************************************************
2032  *
2033  * Function    bta_jv_pm_conn_idle
2034  *
2035  * Description set pm connection idle state (input param safe)
2036  *
2037  * Params      p_cb: pm control block of jv connection
2038  *
2039  * Returns     void
2040  *
2041  ******************************************************************************/
bta_jv_pm_conn_idle(tBTA_JV_PM_CB * p_cb)2042 static void bta_jv_pm_conn_idle(tBTA_JV_PM_CB* p_cb) {
2043   if ((NULL != p_cb) && (BTA_JV_PM_IDLE_ST != p_cb->state)) {
2044     bta_jv_pm_state_change(p_cb, BTA_JV_CONN_IDLE);
2045   }
2046 }
2047 
2048 /*******************************************************************************
2049  *
2050  * Function     bta_jv_pm_state_change
2051  *
2052  * Description  Notify power manager there is state change
2053  *
2054  * Params      p_cb: must be NONE NULL
2055  *
2056  * Returns      void
2057  *
2058  ******************************************************************************/
bta_jv_pm_state_change(tBTA_JV_PM_CB * p_cb,const tBTA_JV_CONN_STATE state)2059 static void bta_jv_pm_state_change(tBTA_JV_PM_CB* p_cb, const tBTA_JV_CONN_STATE state) {
2060   log::verbose("p_cb={}, jv_handle=0x{:x}, busy/idle_state={}, app_id={}, conn_state={}",
2061                std::format_ptr(p_cb), p_cb->handle, p_cb->state, p_cb->app_id,
2062                bta_jv_conn_state_text(state));
2063 
2064   switch (state) {
2065     case BTA_JV_CONN_OPEN:
2066       bta_sys_conn_open(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2067       break;
2068 
2069     case BTA_JV_CONN_CLOSE:
2070       bta_sys_conn_close(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2071       break;
2072 
2073     case BTA_JV_APP_OPEN:
2074       bta_sys_app_open(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2075       break;
2076 
2077     case BTA_JV_APP_CLOSE:
2078       bta_sys_app_close(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2079       break;
2080 
2081     case BTA_JV_SCO_OPEN:
2082       bta_sys_sco_open(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2083       break;
2084 
2085     case BTA_JV_SCO_CLOSE:
2086       bta_sys_sco_close(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2087       break;
2088 
2089     case BTA_JV_CONN_IDLE:
2090       p_cb->state = BTA_JV_PM_IDLE_ST;
2091       bta_sys_idle(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2092       break;
2093 
2094     case BTA_JV_CONN_BUSY:
2095       p_cb->state = BTA_JV_PM_BUSY_ST;
2096       bta_sys_busy(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2097       break;
2098 
2099     default:
2100       log::warn("Invalid state={}", bta_jv_conn_state_text(state));
2101       break;
2102   }
2103 }
2104 
2105 /*******************************************************************************
2106  *
2107  * Function    bta_jv_reset_sniff_timer
2108  *
2109  * Description reset pm sniff timer state (input param safe)
2110  *
2111  * Params      p_cb: pm control block of jv connection
2112  *
2113  * Returns     void
2114  *
2115  ******************************************************************************/
bta_jv_reset_sniff_timer(tBTA_JV_PM_CB * p_cb)2116 static void bta_jv_reset_sniff_timer(tBTA_JV_PM_CB* p_cb) {
2117   if (NULL != p_cb) {
2118     p_cb->state = BTA_JV_PM_IDLE_ST;
2119     bta_sys_reset_sniff(BTA_ID_JV, p_cb->app_id, p_cb->peer_bd_addr);
2120   }
2121 }
2122 /******************************************************************************/
2123 
2124 namespace bluetooth::legacy::testing {
2125 
bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id,const RawAddress & bd_addr,tSDP_RESULT result)2126 void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, const RawAddress& bd_addr,
2127                                   tSDP_RESULT result) {
2128   ::bta_jv_start_discovery_cback(rfcomm_slot_id, bd_addr, result);
2129 }
2130 
2131 }  // namespace bluetooth::legacy::testing
2132