• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2009-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 #define LOG_TAG "bt_btif_sock_rfcomm"
20 
21 #include "btif_sock_rfc.h"
22 
23 #include <bluetooth/log.h>
24 #include <com_android_bluetooth_flags.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
27 #include <sys/types.h>
28 
29 #include <cstdint>
30 #include <mutex>
31 
32 #include "bta/include/bta_jv_api.h"
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 "btif/include/btif_sock.h"
37 #include "btif/include/btif_sock_l2cap.h"
38 #include "btif/include/btif_sock_logging.h"
39 #include "btif/include/btif_sock_sdp.h"
40 #include "btif/include/btif_sock_thread.h"
41 #include "btif/include/btif_sock_util.h"
42 #include "common/time_util.h"
43 #include "gd/os/rand.h"
44 #include "include/hardware/bt_sock.h"
45 #include "lpp/lpp_offload_interface.h"
46 #include "main/shim/entry.h"
47 #include "main/shim/metrics_api.h"
48 #include "osi/include/allocator.h"
49 #include "osi/include/compat.h"
50 #include "osi/include/list.h"
51 #include "osi/include/osi.h"  // INVALID_FD
52 #include "stack/include/bt_hdr.h"
53 #include "stack/include/port_api.h"
54 #include "types/bluetooth/uuid.h"
55 #include "types/raw_address.h"
56 
57 using bluetooth::Uuid;
58 using namespace bluetooth;
59 
60 // Maximum number of RFCOMM channels (1-30 inclusive).
61 #define MAX_RFC_CHANNEL 30
62 
63 // Maximum number of devices we can have an RFCOMM connection with.
64 #define MAX_RFC_SESSION 7
65 
66 typedef struct {
67   int outgoing_congest : 1;
68   int pending_sdp_request : 1;
69   int doing_sdp_request : 1;
70   int server : 1;
71   int connected : 1;
72   int closing : 1;
73 } flags_t;
74 
75 typedef struct {
76   flags_t f;
77   uint32_t id;  // Non-zero indicates a valid (in-use) slot.
78   int security;
79   int scn;  // Server channel number
80   int scn_notified;
81   RawAddress addr;
82   int is_service_uuid_valid;
83   Uuid service_uuid;
84   char service_name[256];
85   int fd;
86   int app_fd;   // Temporary storage for the half of the socketpair that's
87                 // sent back to upper layers.
88   int listen_fd;  // listen socket fd from our side
89   int app_uid;  // UID of the app for which this socket was created.
90   int mtu;
91   uint8_t* packet;
92   int sdp_handle;
93   uint64_t sdp_start_time_ms;
94   uint64_t sdp_end_time_ms;
95   int rfc_handle;
96   int rfc_port_handle;
97   int role;
98   list_t* incoming_queue;
99   // Cumulative number of bytes transmitted on this socket
100   int64_t tx_bytes;
101   // Cumulative number of bytes received on this socket
102   int64_t rx_bytes;
103   uint64_t socket_id;            // Socket ID in connected state
104   btsock_data_path_t data_path;  // socket data path
105   char socket_name[128];         // descriptive socket name
106   uint64_t hub_id;               // ID of the hub to which the end point belongs
107   uint64_t endpoint_id;          // ID of the hub end point
108   bool is_accepting;             // is app accepting on server socket?
109   uint64_t connection_start_time_ms;  // Timestamp when the connection state started
110 } rfc_slot_t;
111 
112 static rfc_slot_t rfc_slots[MAX_RFC_CHANNEL];
113 static uint32_t rfc_slot_id;
114 static volatile int pth = -1;  // poll thread handle
115 static std::recursive_mutex slot_lock;
116 static uid_set_t* uid_set = NULL;
117 
118 static rfc_slot_t* find_free_slot(void);
119 static void cleanup_rfc_slot(rfc_slot_t* rs, btsock_error_code_t error_code);
120 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id);
121 static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id);
122 static bool send_app_scn(rfc_slot_t* rs);
123 static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id);
124 static uint64_t btif_rfc_sock_generate_socket_id();
125 
is_init_done(void)126 static bool is_init_done(void) { return pth != -1; }
127 
btsock_rfc_init(int poll_thread_handle,uid_set_t * set)128 bt_status_t btsock_rfc_init(int poll_thread_handle, uid_set_t* set) {
129   pth = poll_thread_handle;
130   uid_set = set;
131 
132   memset(rfc_slots, 0, sizeof(rfc_slots));
133   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
134     rfc_slots[i].scn = -1;
135     rfc_slots[i].sdp_handle = 0;
136     rfc_slots[i].fd = INVALID_FD;
137     rfc_slots[i].app_fd = INVALID_FD;
138     rfc_slots[i].incoming_queue = list_new(osi_free);
139     log::assert_that(rfc_slots[i].incoming_queue != NULL,
140                      "assert failed: rfc_slots[i].incoming_queue != NULL");
141   }
142 
143   BTA_JvEnable(jv_dm_cback);
144 
145   return BT_STATUS_SUCCESS;
146 }
147 
btsock_rfc_cleanup(void)148 void btsock_rfc_cleanup(void) {
149   pth = -1;
150 
151   BTA_JvDisable();
152 
153   std::unique_lock<std::recursive_mutex> lock(slot_lock);
154   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
155     if (rfc_slots[i].id) {
156       cleanup_rfc_slot(&rfc_slots[i], BTSOCK_ERROR_NONE);
157     }
158     list_free(rfc_slots[i].incoming_queue);
159     rfc_slots[i].incoming_queue = NULL;
160   }
161 
162   uid_set = NULL;
163 
164   log::debug("cleanup finished");
165 }
166 
find_free_slot(void)167 static rfc_slot_t* find_free_slot(void) {
168   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
169     if (rfc_slots[i].fd == INVALID_FD) {
170       return &rfc_slots[i];
171     }
172   }
173   return NULL;
174 }
175 
find_rfc_slot_by_id(uint32_t id)176 static rfc_slot_t* find_rfc_slot_by_id(uint32_t id) {
177   CHECK_NE(0u, id);
178 
179   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
180     if (rfc_slots[i].id == id) {
181       return &rfc_slots[i];
182     }
183   }
184 
185   return NULL;
186 }
187 
find_rfc_slot_by_pending_sdp(void)188 static rfc_slot_t* find_rfc_slot_by_pending_sdp(void) {
189   uint32_t min_id = UINT32_MAX;
190   int slot = -1;
191   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
192     if (rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request && rfc_slots[i].id < min_id) {
193       min_id = rfc_slots[i].id;
194       slot = i;
195     }
196   }
197 
198   return (slot == -1) ? NULL : &rfc_slots[slot];
199 }
200 
is_requesting_sdp(void)201 static bool is_requesting_sdp(void) {
202   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
203     if (rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request) {
204       log::info("slot_id {} is doing sdp request", rfc_slots[i].id);
205       return true;
206     }
207   }
208   return false;
209 }
210 
alloc_rfc_slot(const RawAddress * addr,const char * name,const Uuid & uuid,int channel,int flags,bool server)211 static rfc_slot_t* alloc_rfc_slot(const RawAddress* addr, const char* name, const Uuid& uuid,
212                                   int channel, int flags, bool server) {
213   int security = 0;
214   if (flags & BTSOCK_FLAG_ENCRYPT) {
215     security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
216   }
217   if (flags & BTSOCK_FLAG_AUTH) {
218     security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
219   }
220   if (flags & BTSOCK_FLAG_AUTH_MITM) {
221     security |= server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
222   }
223   if (flags & BTSOCK_FLAG_AUTH_16_DIGIT) {
224     security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
225   }
226 
227   rfc_slot_t* slot = find_free_slot();
228   if (!slot) {
229     log::error("unable to find free RFCOMM slot.");
230     return NULL;
231   }
232 
233   int fds[2] = {INVALID_FD, INVALID_FD};
234   if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) == -1) {
235     log::error("error creating socketpair: {}", strerror(errno));
236     return NULL;
237   }
238 
239   // Increment slot id and make sure we don't use id=0.
240   if (++rfc_slot_id == 0) {
241     rfc_slot_id = 1;
242   }
243 
244   slot->fd = fds[0];
245   slot->app_fd = fds[1];
246   slot->listen_fd = -1;
247   slot->security = security;
248   slot->scn = channel;
249   slot->app_uid = -1;
250   slot->socket_id = 0;
251   slot->data_path = BTSOCK_DATA_PATH_NO_OFFLOAD;
252   slot->hub_id = 0;
253   slot->endpoint_id = 0;
254   slot->is_accepting = false;
255   slot->connection_start_time_ms = 0;
256 
257   slot->is_service_uuid_valid = !uuid.IsEmpty();
258   slot->service_uuid = uuid;
259 
260   if (name && *name) {
261     osi_strlcpy(slot->service_name, name, sizeof(slot->service_name));
262   } else {
263     memset(slot->service_name, 0, sizeof(slot->service_name));
264   }
265   if (addr) {
266     slot->addr = *addr;
267   } else {
268     slot->addr = RawAddress::kEmpty;
269   }
270   slot->id = rfc_slot_id;
271   slot->f.server = server;
272   slot->role = server;
273   slot->tx_bytes = 0;
274   slot->rx_bytes = 0;
275   return slot;
276 }
277 
create_srv_accept_rfc_slot(rfc_slot_t * srv_rs,const RawAddress * addr,int open_handle,int new_listen_handle)278 static rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, const RawAddress* addr,
279                                               int open_handle, int new_listen_handle) {
280   rfc_slot_t* accept_rs =
281           alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, false);
282   if (!accept_rs) {
283     log::error("unable to allocate RFCOMM slot.");
284     return NULL;
285   }
286 
287   accept_rs->f.server = false;
288   accept_rs->f.connected = true;
289   accept_rs->security = srv_rs->security;
290   accept_rs->mtu = srv_rs->mtu;
291   accept_rs->role = srv_rs->role;
292   accept_rs->rfc_handle = open_handle;
293   accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
294   accept_rs->app_uid = srv_rs->app_uid;
295 
296   if (com::android::bluetooth::flags::socket_settings_api()) {
297     accept_rs->socket_id = btif_rfc_sock_generate_socket_id();
298     accept_rs->data_path = srv_rs->data_path;
299     strncpy(accept_rs->socket_name, srv_rs->socket_name, sizeof(accept_rs->socket_name) - 1);
300     accept_rs->socket_name[sizeof(accept_rs->socket_name) - 1] = '\0';
301     accept_rs->hub_id = srv_rs->hub_id;
302     accept_rs->endpoint_id = srv_rs->endpoint_id;
303     accept_rs->listen_fd = srv_rs->fd;
304   }
305 
306   srv_rs->rfc_handle = new_listen_handle;
307   srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
308 
309   if (accept_rs->rfc_port_handle == srv_rs->rfc_port_handle) {
310     log::error(
311             "accept_rs->rfc_port_handle == srv_rs->rfc_port_handle, "
312             "rfc_port_handle={}",
313             accept_rs->rfc_port_handle);
314   }
315   log::assert_that(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle,
316                    "assert failed: accept_rs->rfc_port_handle != srv_rs->rfc_port_handle");
317 
318   // now swap the slot id
319   uint32_t new_listen_id = accept_rs->id;
320   accept_rs->id = srv_rs->id;
321   srv_rs->id = new_listen_id;
322 
323   return accept_rs;
324 }
325 
btsock_rfc_control_req(uint8_t dlci,const RawAddress & bd_addr,uint8_t modem_signal,uint8_t break_signal,uint8_t discard_buffers,uint8_t break_signal_seq,bool fc)326 bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal,
327                                    uint8_t break_signal, uint8_t discard_buffers,
328                                    uint8_t break_signal_seq, bool fc) {
329   int status = RFCOMM_ControlReqFromBTSOCK(dlci, bd_addr, modem_signal, break_signal,
330                                            discard_buffers, break_signal_seq, fc);
331   if (status != PORT_SUCCESS) {
332     log::warn("failed to send control parameters, status={}", status);
333     return BT_STATUS_FAIL;
334   }
335   return BT_STATUS_SUCCESS;
336 }
337 
338 /// Determine the local MTU for the offloaded RFCOMM connection.
339 ///
340 /// The local MTU is selected as the minimum of:
341 ///   - The socket hal's offload capabilities (socket_cap.rfcommCapabilities.max_frame_size)
342 ///   - The application's requested maximum RX packet size (app_max_rx_packet_size)
343 ///
344 /// However, the MTU must be at least the minimum required by the RFCOMM
345 /// specification (RFCOMM_MIN_MTU).
btsock_rfc_get_offload_mtu(int app_max_rx_packet_size,int * rx_mtu)346 static bool btsock_rfc_get_offload_mtu(int app_max_rx_packet_size, int* rx_mtu) {
347   hal::SocketCapabilities socket_cap =
348           bluetooth::shim::GetLppOffloadManager()->GetSocketCapabilities();
349   if (!socket_cap.rfcomm_capabilities.number_of_supported_sockets) {
350     return false;
351   }
352   // Socket HAL client has already verified that the MTU is in a valid range.
353   int mtu = static_cast<int>(socket_cap.rfcomm_capabilities.max_frame_size);
354   mtu = std::min(mtu, app_max_rx_packet_size);
355   mtu = std::max(mtu, RFCOMM_MIN_MTU);
356   *rx_mtu = mtu;
357   return true;
358 }
359 
btsock_rfc_listen(const char * service_name,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid,btsock_data_path_t data_path,const char * socket_name,uint64_t hub_id,uint64_t endpoint_id,int max_rx_packet_size)360 bt_status_t btsock_rfc_listen(const char* service_name, const Uuid* service_uuid, int channel,
361                               int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
362                               const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
363                               int max_rx_packet_size) {
364   log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL");
365   log::assert_that((service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL) ||
366                            ((flags & BTSOCK_FLAG_NO_SDP) != 0),
367                    "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= "
368                    "MAX_RFC_CHANNEL) || ((flags & BTSOCK_FLAG_NO_SDP) != 0)");
369 
370   *sock_fd = INVALID_FD;
371 
372   // TODO(sharvil): not sure that this check makes sense; seems like a logic
373   // error to call
374   // functions on RFCOMM sockets before initializing the module. Probably
375   // should be an assert.
376   if (!is_init_done()) {
377     log::error("BT not ready");
378     return BT_STATUS_NOT_READY;
379   }
380 
381   if ((flags & BTSOCK_FLAG_NO_SDP) == 0) {
382     if (!service_uuid || service_uuid->IsEmpty()) {
383       // Use serial port profile to listen to specified channel
384       service_uuid = &UUID_SPP;
385     } else {
386       // Check the service_uuid. overwrite the channel # if reserved
387       int reserved_channel = get_reserved_rfc_channel(*service_uuid);
388       if (reserved_channel > 0) {
389         channel = reserved_channel;
390       }
391     }
392   }
393 
394   std::unique_lock<std::recursive_mutex> lock(slot_lock);
395 
396   rfc_slot_t* slot = alloc_rfc_slot(NULL, service_name, *service_uuid, channel, flags, true);
397   if (!slot) {
398     log::error("unable to allocate RFCOMM slot");
399     return BT_STATUS_NOMEM;
400   }
401   log::info("Adding listening socket service_name: {} - channel: {}", service_name, channel);
402   BTA_JvGetChannelId(tBTA_JV_CONN_TYPE::RFCOMM, slot->id, channel);
403   *sock_fd = slot->app_fd;  // Transfer ownership of fd to caller.
404   /*TODO:
405    * We are leaking one of the app_fd's - either the listen socket, or the
406    connection socket.
407    * WE need to close this in native, as the FD might belong to another process
408     - This is the server socket FD
409     - For accepted connections, we close the FD after passing it to JAVA.
410     - Try to simply remove the = -1 to free the FD at rs cleanup.*/
411   //        close(rs->app_fd);
412   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
413   slot->app_uid = app_uid;
414   if (com::android::bluetooth::flags::socket_settings_api()) {
415     slot->data_path = data_path;
416     if (socket_name) {
417       strncpy(slot->socket_name, socket_name, sizeof(slot->socket_name) - 1);
418       slot->socket_name[sizeof(slot->socket_name) - 1] = '\0';
419     }
420     slot->hub_id = hub_id;
421     slot->endpoint_id = endpoint_id;
422     if (data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
423       if (!btsock_rfc_get_offload_mtu(max_rx_packet_size, &slot->mtu)) {
424         return BT_STATUS_UNSUPPORTED;
425       }
426     }
427   }
428   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, slot->id);
429   // start monitoring the socketpair to get call back when app is accepting on server socket
430   if (com::android::bluetooth::flags::socket_settings_api()) {
431     btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
432   }
433 
434   return BT_STATUS_SUCCESS;
435 }
436 
btsock_rfc_connect(const RawAddress * bd_addr,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid,btsock_data_path_t data_path,const char * socket_name,uint64_t hub_id,uint64_t endpoint_id,int max_rx_packet_size)437 bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, const Uuid* service_uuid, int channel,
438                                int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
439                                const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
440                                int max_rx_packet_size) {
441   log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL");
442   log::assert_that((service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL),
443                    "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= "
444                    "MAX_RFC_CHANNEL)");
445 
446   *sock_fd = INVALID_FD;
447 
448   // TODO(sharvil): not sure that this check makes sense; seems like a logic
449   // error to call
450   // functions on RFCOMM sockets before initializing the module. Probably should
451   // be an assert.
452   if (!is_init_done()) {
453     log::error("BT not ready");
454     return BT_STATUS_NOT_READY;
455   }
456 
457   std::unique_lock<std::recursive_mutex> lock(slot_lock);
458 
459   rfc_slot_t* slot = alloc_rfc_slot(bd_addr, NULL, *service_uuid, channel, flags, false);
460   if (!slot) {
461     log::error("unable to allocate RFCOMM slot. bd_addr:{}", *bd_addr);
462     return BT_STATUS_NOMEM;
463   }
464 
465   if (!service_uuid || service_uuid->IsEmpty()) {
466     tBTA_JV_STATUS ret = BTA_JvRfcommConnect(slot->security, slot->scn, slot->addr, rfcomm_cback,
467                                              slot->id, RfcommCfgInfo{}, slot->app_uid, 0);
468     if (ret != tBTA_JV_STATUS::SUCCESS) {
469       log::error("unable to initiate RFCOMM connection. status:{}, scn:{}, bd_addr:{}",
470                  bta_jv_status_text(ret), slot->scn, slot->addr);
471       cleanup_rfc_slot(slot, BTSOCK_ERROR_CONNECTION_FAILURE);
472       return BT_STATUS_SOCKET_ERROR;
473     }
474 
475     if (!send_app_scn(slot)) {
476       log::error("send_app_scn() failed, closing slot_id:{}", slot->id);
477       cleanup_rfc_slot(slot, BTSOCK_ERROR_SEND_SCN_FAILURE);
478       return BT_STATUS_SOCKET_ERROR;
479     }
480   } else {
481     log::info("service_uuid:{}, bd_addr:{}, slot_id:{}", service_uuid->ToString(), *bd_addr,
482               slot->id);
483     if (!is_requesting_sdp()) {
484       slot->sdp_start_time_ms = common::time_gettimeofday_us() / 1000;
485       BTA_JvStartDiscovery(*bd_addr, 1, service_uuid, slot->id);
486       slot->f.pending_sdp_request = false;
487       slot->f.doing_sdp_request = true;
488     } else {
489       slot->f.pending_sdp_request = true;
490       slot->f.doing_sdp_request = false;
491     }
492   }
493 
494   *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
495   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
496   slot->app_uid = app_uid;
497   if (com::android::bluetooth::flags::socket_settings_api()) {
498     slot->data_path = data_path;
499     if (socket_name) {
500       strncpy(slot->socket_name, socket_name, sizeof(slot->socket_name) - 1);
501       slot->socket_name[sizeof(slot->socket_name) - 1] = '\0';
502     }
503     slot->hub_id = hub_id;
504     slot->endpoint_id = endpoint_id;
505     if (data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
506       if (!btsock_rfc_get_offload_mtu(max_rx_packet_size, &slot->mtu)) {
507         return BT_STATUS_UNSUPPORTED;
508       }
509     }
510   }
511   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
512 
513   return BT_STATUS_SUCCESS;
514 }
515 
create_server_sdp_record(rfc_slot_t * slot)516 static int create_server_sdp_record(rfc_slot_t* slot) {
517   if (slot->scn == 0) {
518     return false;
519   }
520   slot->sdp_handle = add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn);
521   return slot->sdp_handle > 0;
522 }
523 
free_rfc_slot_scn(rfc_slot_t * slot)524 static void free_rfc_slot_scn(rfc_slot_t* slot) {
525   if (slot->scn <= 0) {
526     return;
527   }
528 
529   if (slot->f.server && !slot->f.closing && slot->rfc_handle) {
530     BTA_JvRfcommStopServer(slot->rfc_handle, slot->id);
531     slot->rfc_handle = 0;
532   }
533 
534   if (slot->f.server) {
535     BTA_FreeSCN(slot->scn);
536   }
537   slot->scn = 0;
538 }
539 
cleanup_rfc_slot(rfc_slot_t * slot,btsock_error_code_t error_code)540 static void cleanup_rfc_slot(rfc_slot_t* slot, btsock_error_code_t error_code) {
541   if (slot->fd != INVALID_FD) {
542     shutdown(slot->fd, SHUT_RDWR);
543     close(slot->fd);
544     log::info(
545             "disconnected from RFCOMM socket connections for device: {}, scn: {}, "
546             "app_uid: {}, slot_id: {}, socket_id: {}",
547             slot->addr, slot->scn, slot->app_uid, slot->id, slot->socket_id);
548     btif_sock_connection_logger(
549             slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_DISCONNECTED,
550             slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn,
551             slot->tx_bytes, slot->rx_bytes,
552             slot->role ? slot->service_name : slot->service_uuid.ToString().c_str(),
553             slot->connection_start_time_ms, error_code, slot->data_path);
554 
555     slot->fd = INVALID_FD;
556 
557     if (com::android::bluetooth::flags::socket_settings_api()) {
558       if (slot->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD && !slot->f.server &&
559           slot->socket_id != 0) {
560         bluetooth::shim::GetLppOffloadManager()->SocketClosed(slot->socket_id);
561         slot->socket_id = 0;
562       }
563     }
564   }
565 
566   if (slot->app_fd != INVALID_FD) {
567     close(slot->app_fd);
568     slot->app_fd = INVALID_FD;
569   }
570 
571   if (slot->sdp_handle > 0) {
572     del_rfc_sdp_rec(slot->sdp_handle);
573     slot->sdp_handle = 0;
574   }
575 
576   if (slot->rfc_handle && !slot->f.closing && !slot->f.server) {
577     BTA_JvRfcommClose(slot->rfc_handle, slot->id);
578     slot->rfc_handle = 0;
579   }
580 
581   free_rfc_slot_scn(slot);
582   list_clear(slot->incoming_queue);
583 
584   slot->rfc_port_handle = 0;
585   memset(&slot->f, 0, sizeof(slot->f));
586   slot->id = 0;
587   slot->scn_notified = false;
588   slot->tx_bytes = 0;
589   slot->rx_bytes = 0;
590 }
591 
send_app_scn(rfc_slot_t * slot)592 static bool send_app_scn(rfc_slot_t* slot) {
593   if (slot->scn_notified) {
594     // already sent, just return success.
595     return true;
596   }
597   log::debug("Sending scn for slot_id {}. bd_addr:{}", slot->id, slot->addr);
598   slot->scn_notified = true;
599   return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, sizeof(slot->scn)) ==
600          sizeof(slot->scn);
601 }
602 
send_app_connect_signal(int fd,const RawAddress * addr,int channel,int status,int send_fd,uint64_t socket_id)603 static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, int status,
604                                     int send_fd, uint64_t socket_id) {
605   sock_connect_signal_t cs;
606   cs.size = sizeof(cs);
607   cs.bd_addr = *addr;
608   cs.channel = channel;
609   cs.status = status;
610   cs.max_rx_packet_size = 0;  // not used for RFCOMM
611   cs.max_tx_packet_size = 0;  // not used for RFCOMM
612   cs.conn_uuid_lsb = 0;       // not used for RFCOMM
613   cs.conn_uuid_msb = 0;       // not used for RFCOMM
614   cs.socket_id = socket_id;
615   if (send_fd == INVALID_FD) {
616     return sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs);
617   }
618 
619   return sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs);
620 }
621 
on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT * p_init,uint32_t id)622 static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT* p_init, uint32_t id) {
623   std::unique_lock<std::recursive_mutex> lock(slot_lock);
624   rfc_slot_t* slot = find_rfc_slot_by_id(id);
625   if (!slot) {
626     log::error("RFCOMM slot_id {} not found. p_init->status={}", id,
627                bta_jv_status_text(p_init->status));
628   } else if (p_init->status != tBTA_JV_STATUS::SUCCESS) {
629     log::warn("INIT unsuccessful, status {}. Cleaning up slot_id {}",
630               bta_jv_status_text(p_init->status), slot->id);
631     cleanup_rfc_slot(slot, BTSOCK_ERROR_CLIENT_INIT_FAILURE);
632   } else {
633     slot->rfc_handle = p_init->handle;
634   }
635 }
636 
on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START * p_start,uint32_t id)637 static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start, uint32_t id) {
638   std::unique_lock<std::recursive_mutex> lock(slot_lock);
639   rfc_slot_t* slot = find_rfc_slot_by_id(id);
640   if (!slot) {
641     log::error("RFCOMM slot_id {} not found", id);
642     return;
643   } else if (p_start->status != tBTA_JV_STATUS::SUCCESS) {
644     log::warn("START unsuccessful, status {}. Cleaning up slot_id {}",
645               bta_jv_status_text(p_start->status), slot->id);
646     cleanup_rfc_slot(slot, BTSOCK_ERROR_SERVER_START_FAILURE);
647     return;
648   }
649 
650   slot->rfc_handle = p_start->handle;
651   log::info(
652           "listening for RFCOMM socket connections for device: {}, scn: {}, "
653           "app_uid: {}, id: {}",
654           slot->addr, slot->scn, slot->app_uid, id);
655   btif_sock_connection_logger(
656           slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_LISTENING,
657           slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn, 0,
658           0, slot->service_name, 0, BTSOCK_ERROR_NONE, slot->data_path);
659 }
660 
on_srv_rfc_connect_offload(tBTA_JV_RFCOMM_SRV_OPEN * p_open,rfc_slot_t * srv_rs)661 static uint32_t on_srv_rfc_connect_offload(tBTA_JV_RFCOMM_SRV_OPEN* p_open, rfc_slot_t* srv_rs) {
662   rfc_slot_t* accept_rs;
663   accept_rs = create_srv_accept_rfc_slot(srv_rs, &p_open->rem_bda, p_open->handle,
664                                          p_open->new_listen_handle);
665   if (!accept_rs) {
666     return 0;
667   }
668 
669   log::info(
670           "connected to RFCOMM socket connections for device: {}, scn: {}, "
671           "app_uid: {}, id: {}, socket_id: {}",
672           accept_rs->addr, accept_rs->scn, accept_rs->app_uid, accept_rs->id, accept_rs->socket_id);
673   btif_sock_connection_logger(accept_rs->addr, accept_rs->id, BTSOCK_RFCOMM,
674                               SOCKET_CONNECTION_STATE_CONNECTED,
675                               accept_rs->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
676                               accept_rs->app_uid, accept_rs->scn, 0, 0, accept_rs->service_name, 0,
677                               BTSOCK_ERROR_NONE, accept_rs->data_path);
678   accept_rs->connection_start_time_ms = common::time_gettimeofday_us() / 1000;
679 
680   bluetooth::hal::SocketContext socket_context = {
681           .socket_id = accept_rs->socket_id,
682           .name = accept_rs->socket_name,
683           .acl_connection_handle = p_open->acl_handle,
684           .channel_info = bluetooth::hal::RfcommChannelInfo(
685                   p_open->local_cid, p_open->remote_cid, p_open->rx_mtu, p_open->tx_mtu,
686                   p_open->local_credit, p_open->remote_credit, p_open->dlci, p_open->max_frame_size,
687                   p_open->mux_initiator),
688           .endpoint_info.hub_id = accept_rs->hub_id,
689           .endpoint_info.endpoint_id = accept_rs->endpoint_id,
690   };
691   if (!srv_rs->is_accepting) {
692     log::warn("Server socket is not accepting. Disconnect the incoming connection.");
693     cleanup_rfc_slot(accept_rs, BTSOCK_ERROR_OFFLOAD_SERVER_NOT_ACCEPTING);
694   } else if (!bluetooth::shim::GetLppOffloadManager()->SocketOpened(socket_context)) {
695     log::warn("RFCOMM socket opened failed. Disconnect the incoming connection.");
696     cleanup_rfc_slot(accept_rs, BTSOCK_ERROR_OFFLOAD_HAL_OPEN_FAILURE);
697   } else {
698     log::info("RFCOMM socket opened successful. Will send connect signal in async callback.");
699   }
700 
701   // Start monitoring the socket.
702   btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
703   // start monitoring the socketpair to get call back when app is accepting on server socket
704   btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, srv_rs->id);
705   return srv_rs->id;
706 }
707 
on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN * p_open,uint32_t id)708 static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open, uint32_t id) {
709   log::verbose("id:{}", id);
710   std::unique_lock<std::recursive_mutex> lock(slot_lock);
711   rfc_slot_t* accept_rs;
712   rfc_slot_t* srv_rs = find_rfc_slot_by_id(id);
713   if (!srv_rs) {
714     log::error("RFCOMM slot_id {} not found.", id);
715     return 0;
716   }
717 
718   if (com::android::bluetooth::flags::socket_settings_api() &&
719       srv_rs->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
720     return on_srv_rfc_connect_offload(p_open, srv_rs);
721   }
722 
723   accept_rs = create_srv_accept_rfc_slot(srv_rs, &p_open->rem_bda, p_open->handle,
724                                          p_open->new_listen_handle);
725   if (!accept_rs) {
726     return 0;
727   }
728 
729   log::info(
730           "connected to RFCOMM socket connections for device: {}, scn: {}, "
731           "app_uid: {}, slot_id: {}, socket_id: {}",
732           accept_rs->addr, accept_rs->scn, accept_rs->app_uid, accept_rs->id, accept_rs->socket_id);
733   btif_sock_connection_logger(accept_rs->addr, accept_rs->id, BTSOCK_RFCOMM,
734                               SOCKET_CONNECTION_STATE_CONNECTED,
735                               accept_rs->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
736                               accept_rs->app_uid, accept_rs->scn, 0, 0, accept_rs->service_name, 0,
737                               BTSOCK_ERROR_NONE, accept_rs->data_path);
738   accept_rs->connection_start_time_ms = common::time_gettimeofday_us() / 1000;
739 
740   // Start monitoring the socket.
741   btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
742   btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id);
743   send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd,
744                           accept_rs->socket_id);
745   accept_rs->app_fd = INVALID_FD;  // Ownership of the application fd has been transferred.
746   // start monitoring the socketpair to get call back when app is accepting on server socket
747   if (com::android::bluetooth::flags::socket_settings_api()) {
748     btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, srv_rs->id);
749   }
750   return srv_rs->id;
751 }
752 
on_cli_rfc_connect_offload(tBTA_JV_RFCOMM_OPEN * p_open,rfc_slot_t * slot)753 static void on_cli_rfc_connect_offload(tBTA_JV_RFCOMM_OPEN* p_open, rfc_slot_t* slot) {
754   slot->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
755   slot->addr = p_open->rem_bda;
756   slot->socket_id = btif_rfc_sock_generate_socket_id();
757 
758   log::info(
759           "connected to RFCOMM socket connections for device: {}, scn: {}, "
760           "app_uid: {}, id: {}, socket_id: {}",
761           slot->addr, slot->scn, slot->app_uid, slot->id, slot->socket_id);
762   btif_sock_connection_logger(
763           slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_CONNECTED,
764           slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn, 0,
765           0, slot->service_uuid.ToString().c_str(), 0, BTSOCK_ERROR_NONE, slot->data_path);
766   slot->connection_start_time_ms = common::time_gettimeofday_us() / 1000;
767 
768   bluetooth::hal::SocketContext socket_context = {
769           .socket_id = slot->socket_id,
770           .name = slot->socket_name,
771           .acl_connection_handle = p_open->acl_handle,
772           .channel_info = bluetooth::hal::RfcommChannelInfo(
773                   p_open->local_cid, p_open->remote_cid, p_open->rx_mtu, p_open->tx_mtu,
774                   p_open->local_credit, p_open->remote_credit, p_open->dlci, p_open->max_frame_size,
775                   p_open->mux_initiator),
776           .endpoint_info.hub_id = slot->hub_id,
777           .endpoint_info.endpoint_id = slot->endpoint_id,
778   };
779   if (!bluetooth::shim::GetLppOffloadManager()->SocketOpened(socket_context)) {
780     log::warn("RFCOMM socket opened failed. Disconnect the incoming connection.");
781     cleanup_rfc_slot(slot, BTSOCK_ERROR_OFFLOAD_HAL_OPEN_FAILURE);
782   } else {
783     log::info(
784             "RFCOMM socket opened successful. Will send connect signal in "
785             "on_btsocket_rfc_opened_complete() asynchronously.");
786   }
787 }
788 
on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN * p_open,uint32_t id)789 static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN* p_open, uint32_t id) {
790   log::verbose("id:{}", id);
791   std::unique_lock<std::recursive_mutex> lock(slot_lock);
792   rfc_slot_t* slot = find_rfc_slot_by_id(id);
793   if (!slot) {
794     log::error("RFCOMM slot_id {} not found.", id);
795     return;
796   }
797 
798   if (p_open->status != tBTA_JV_STATUS::SUCCESS) {
799     log::warn("CONNECT unsuccessful, status {}. Cleaning up slot_id {}",
800               bta_jv_status_text(p_open->status), slot->id);
801     cleanup_rfc_slot(slot, BTSOCK_ERROR_CONNECTION_FAILURE);
802     return;
803   }
804 
805   if (com::android::bluetooth::flags::socket_settings_api() &&
806       slot->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
807     on_cli_rfc_connect_offload(p_open, slot);
808     return;
809   }
810 
811   slot->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
812   slot->addr = p_open->rem_bda;
813   slot->socket_id = btif_rfc_sock_generate_socket_id();
814 
815   log::info(
816           "connected to RFCOMM socket connections for device: {}, scn: {}, "
817           "app_uid: {}, id: {}, socket_id: {}",
818           slot->addr, slot->scn, slot->app_uid, slot->id, slot->socket_id);
819   btif_sock_connection_logger(
820           slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_CONNECTED,
821           slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn, 0,
822           0, slot->service_uuid.ToString().c_str(), 0, BTSOCK_ERROR_NONE, slot->data_path);
823   slot->connection_start_time_ms = common::time_gettimeofday_us() / 1000;
824 
825   if (send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1, slot->socket_id)) {
826     slot->f.connected = true;
827   } else {
828     log::error("unable to send connect completion signal to caller.");
829   }
830 }
831 
832 /* only call with slot_lock taken */
find_rfc_slot_by_socket_id(uint64_t socket_id)833 static rfc_slot_t* find_rfc_slot_by_socket_id(uint64_t socket_id) {
834   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
835     if (rfc_slots[i].socket_id == socket_id) {
836       return &rfc_slots[i];
837     }
838   }
839 
840   return nullptr;
841 }
842 
btsock_rfc_in_use(uint64_t socket_id)843 bool btsock_rfc_in_use(uint64_t socket_id) {
844   std::unique_lock<std::recursive_mutex> lock(slot_lock);
845   return find_rfc_slot_by_socket_id(socket_id) != nullptr;
846 }
847 
on_btsocket_rfc_opened_complete(uint64_t socket_id,bool success)848 void on_btsocket_rfc_opened_complete(uint64_t socket_id, bool success) {
849   rfc_slot_t* slot;
850 
851   std::unique_lock<std::recursive_mutex> lock(slot_lock);
852   slot = find_rfc_slot_by_socket_id(socket_id);
853   if (!slot) {
854     log::error("Unable to find rfcomm socket with socket_id: {}", socket_id);
855     return;
856   }
857   if (!success) {
858     log::error("RFCOMM opened complete failed with socket_id: {}", socket_id);
859     cleanup_rfc_slot(slot, BTSOCK_ERROR_OPEN_FAILURE);
860     return;
861   }
862   // If the socket was accepted from listen socket, use listen_fd.
863   if (slot->listen_fd != -1) {
864     send_app_connect_signal(slot->listen_fd, &slot->addr, slot->scn, 0, slot->app_fd,
865                             slot->socket_id);
866     // The fd is closed after sent to app in send_app_connect_signal()
867     slot->app_fd = -1;
868   } else {
869     if (!send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1, slot->socket_id)) {
870       log::error("Unable to connect rfcomm socket to application socket_id: {}", slot->id);
871       return;
872     }
873 
874     log::info("Connected rfcomm socket socket_id: {}", slot->id);
875     slot->f.connected = true;
876   }
877 }
878 
on_btsocket_rfc_close(uint64_t socket_id)879 void on_btsocket_rfc_close(uint64_t socket_id) {
880   rfc_slot_t* slot;
881 
882   std::unique_lock<std::recursive_mutex> lock(slot_lock);
883   slot = find_rfc_slot_by_socket_id(socket_id);
884   if (!slot) {
885     log::error("Unable to find rfcomm socket with socket_id: {}", socket_id);
886     return;
887   }
888   log::info("RFCOMM close request for socket_id: {}", socket_id);
889   cleanup_rfc_slot(slot, BTSOCK_ERROR_NONE);
890 }
891 
892 // TODO(b/380189525): Replace the randomized socket ID with static counter when we don't have
893 // security concerns about using static counter.
btif_rfc_sock_generate_socket_id()894 static uint64_t btif_rfc_sock_generate_socket_id() {
895   uint64_t socket_id;
896   do {
897     socket_id = bluetooth::os::GenerateRandomUint64();
898   } while (!socket_id);
899   return socket_id;
900 }
901 
on_rfc_close(tBTA_JV_RFCOMM_CLOSE *,uint32_t id)902 static void on_rfc_close(tBTA_JV_RFCOMM_CLOSE* /* p_close */, uint32_t id) {
903   log::verbose("id:{}", id);
904   std::unique_lock<std::recursive_mutex> lock(slot_lock);
905 
906   // rfc_handle already closed when receiving rfcomm close event from stack.
907   rfc_slot_t* slot = find_rfc_slot_by_id(id);
908   if (!slot) {
909     log::warn("RFCOMM slot with id {} not found.", id);
910     return;
911   }
912   bluetooth::shim::LogMetricSocketConnectionState(
913           slot->addr, slot->id, BTSOCK_RFCOMM,
914           android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0, slot->app_uid, slot->scn,
915           slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
916                          : android::bluetooth::SOCKET_ROLE_CONNECTION,
917           0, android::bluetooth::SOCKET_ERROR_NONE, slot->data_path);
918   cleanup_rfc_slot(slot, BTSOCK_ERROR_NONE);
919 }
920 
on_rfc_write_done(tBTA_JV_RFCOMM_WRITE * p,uint32_t id)921 static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE* p, uint32_t id) {
922   if (p->status != tBTA_JV_STATUS::SUCCESS) {
923     log::error("error writing to RFCOMM socket, req_id:{}.", p->req_id);
924     return;
925   }
926 
927   int app_uid = -1;
928   std::unique_lock<std::recursive_mutex> lock(slot_lock);
929 
930   rfc_slot_t* slot = find_rfc_slot_by_id(id);
931   if (!slot) {
932     log::error("RFCOMM slot_id {} not found.", id);
933     return;
934   }
935   app_uid = slot->app_uid;
936   if (!slot->f.outgoing_congest) {
937     btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
938   }
939   slot->tx_bytes += p->len;
940   uid_set_add_tx(uid_set, app_uid, p->len);
941 }
942 
on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG * p,uint32_t id)943 static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG* p, uint32_t id) {
944   std::unique_lock<std::recursive_mutex> lock(slot_lock);
945 
946   rfc_slot_t* slot = find_rfc_slot_by_id(id);
947   if (!slot) {
948     log::error("RFCOMM slot_id {} not found.", id);
949     return;
950   }
951 
952   slot->f.outgoing_congest = p->cong ? 1 : 0;
953   if (!slot->f.outgoing_congest) {
954     btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
955   }
956 }
957 
rfcomm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t rfcomm_slot_id)958 static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id) {
959   uint32_t id = 0;
960 
961   switch (event) {
962     case BTA_JV_RFCOMM_START_EVT:
963       log::info("handling {}, slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
964       on_srv_rfc_listen_started(&p_data->rfc_start, rfcomm_slot_id);
965       break;
966 
967     case BTA_JV_RFCOMM_CL_INIT_EVT:
968       log::info("handling {}, slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
969       on_cl_rfc_init(&p_data->rfc_cl_init, rfcomm_slot_id);
970       break;
971 
972     case BTA_JV_RFCOMM_OPEN_EVT:
973       log::info("handling {}, slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
974       BTA_JvSetPmProfile(p_data->rfc_open.handle, BTA_JV_PM_ID_1, BTA_JV_CONN_OPEN);
975       on_cli_rfc_connect(&p_data->rfc_open, rfcomm_slot_id);
976       break;
977 
978     case BTA_JV_RFCOMM_SRV_OPEN_EVT:
979       log::info("handling {}, slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
980       BTA_JvSetPmProfile(p_data->rfc_srv_open.handle, BTA_JV_PM_ALL, BTA_JV_CONN_OPEN);
981       id = on_srv_rfc_connect(&p_data->rfc_srv_open, rfcomm_slot_id);
982       break;
983 
984     case BTA_JV_RFCOMM_CLOSE_EVT:
985       log::info("handling {}, slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
986       on_rfc_close(&p_data->rfc_close, rfcomm_slot_id);
987       break;
988 
989     case BTA_JV_RFCOMM_WRITE_EVT:
990       log::verbose("handling {}, slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
991       on_rfc_write_done(&p_data->rfc_write, rfcomm_slot_id);
992       break;
993 
994     case BTA_JV_RFCOMM_CONG_EVT:
995       log::verbose("handling {}, slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
996       on_rfc_outgoing_congest(&p_data->rfc_cong, rfcomm_slot_id);
997       break;
998 
999     case BTA_JV_RFCOMM_DATA_IND_EVT:
1000       // Unused.
1001       break;
1002 
1003     default:
1004       log::warn("unhandled event {}, slot_id: {}", bta_jv_event_text(event), rfcomm_slot_id);
1005       break;
1006   }
1007   return id;
1008 }
1009 
jv_dm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t id)1010 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) {
1011   log::info("handling event:{}, slot_id:{}", bta_jv_event_text(event), id);
1012   switch (event) {
1013     case BTA_JV_GET_SCN_EVT: {
1014       std::unique_lock<std::recursive_mutex> lock(slot_lock);
1015       rfc_slot_t* rs = find_rfc_slot_by_id(id);
1016       if (!rs) {
1017         log::error("RFCOMM slot with slot_id {} not found. event:{}", id, bta_jv_event_text(event));
1018         break;
1019       }
1020       if (p_data->scn == 0) {
1021         log::error("Unable to allocate scn: all resources exhausted. slot found: {}",
1022                    std::format_ptr(rs));
1023         cleanup_rfc_slot(rs, BTSOCK_ERROR_SCN_ALLOCATION_FAILURE);
1024         break;
1025       }
1026 
1027       rs->scn = p_data->scn;
1028       // Send channel ID to java layer
1029       if (!send_app_scn(rs)) {
1030         log::warn("send_app_scn() failed, closing rs->id:{}", rs->id);
1031         cleanup_rfc_slot(rs, BTSOCK_ERROR_SEND_SCN_FAILURE);
1032         break;
1033       }
1034 
1035       if (rs->is_service_uuid_valid) {
1036         // BTA_JvCreateRecordByUser will only create a record if a UUID is
1037         // specified. RFC-only profiles
1038         BTA_JvCreateRecordByUser(rs->id);
1039       } else {
1040         // If uuid is null, just allocate a RFC channel and start the RFCOMM
1041         // thread needed for the java layer to get a RFCOMM channel.
1042         // create_sdp_record() will be called from Java when it has received the
1043         // RFCOMM and L2CAP channel numbers through the sockets.
1044         log::debug(
1045                 "Since UUID is not valid; not setting SDP-record and just starting "
1046                 "the RFCOMM server");
1047         // Setup optional configurations
1048         RfcommCfgInfo cfg = {};
1049         // For hardware offload data path, host stack sets the initial credits to 0. The offload
1050         // stack should send initial credits to peer device through RFCOMM signaling command when
1051         // the data path is switched successfully.
1052         if (com::android::bluetooth::flags::socket_settings_api()) {
1053           if (rs->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
1054             cfg.init_credit_present = true;
1055             cfg.init_credit = 0;
1056             cfg.rx_mtu_present = rs->mtu > 0;
1057             cfg.rx_mtu = rs->mtu;
1058           }
1059         }
1060         // now start the rfcomm server after sdp & channel # assigned
1061         BTA_JvRfcommStartServer(rs->security, rs->scn, MAX_RFC_SESSION, rfcomm_cback, rs->id, cfg,
1062                                 rs->app_uid);
1063       }
1064       break;
1065     }
1066 
1067     case BTA_JV_GET_PSM_EVT: {
1068       log::verbose("Received PSM: 0x{:04x}", p_data->psm);
1069       on_l2cap_psm_assigned(id, p_data->psm);
1070       break;
1071     }
1072 
1073     case BTA_JV_CREATE_RECORD_EVT: {
1074       std::unique_lock<std::recursive_mutex> lock(slot_lock);
1075       rfc_slot_t* slot = find_rfc_slot_by_id(id);
1076 
1077       if (!slot) {
1078         log::error("RFCOMM slot_id {} not found. event:{}", id, bta_jv_event_text(event));
1079         break;
1080       }
1081 
1082       if (!create_server_sdp_record(slot)) {
1083         log::error("cannot start server, slot found: {}", std::format_ptr(slot));
1084         cleanup_rfc_slot(slot, BTSOCK_ERROR_ADD_SDP_FAILURE);
1085         break;
1086       }
1087 
1088       // Setup optional configurations
1089       RfcommCfgInfo cfg = {};
1090       // For hardware offload data path, host stack sets the initial credits to 0. The offload
1091       // stack should send initial credits to peer device through RFCOMM signaling command when
1092       // the data path is switched successfully.
1093       if (com::android::bluetooth::flags::socket_settings_api()) {
1094         if (slot->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
1095           cfg.init_credit_present = true;
1096           cfg.init_credit = 0;
1097           cfg.rx_mtu_present = slot->mtu > 0;
1098           cfg.rx_mtu = slot->mtu;
1099           cfg.data_path = slot->data_path;
1100         }
1101       }
1102       // Start the rfcomm server after sdp & channel # assigned.
1103       BTA_JvRfcommStartServer(slot->security, slot->scn, MAX_RFC_SESSION, rfcomm_cback, slot->id,
1104                               cfg, slot->app_uid);
1105       break;
1106     }
1107 
1108     case BTA_JV_DISCOVERY_COMP_EVT: {
1109       std::unique_lock<std::recursive_mutex> lock(slot_lock);
1110       handle_discovery_comp(p_data->disc_comp.status, p_data->disc_comp.scn, id);
1111       // Find the next slot that needs to perform an SDP request and service it.
1112       rfc_slot_t* slot = find_rfc_slot_by_pending_sdp();
1113       if (slot) {
1114         BTA_JvStartDiscovery(slot->addr, 1, &slot->service_uuid, slot->id);
1115         slot->sdp_start_time_ms = common::time_gettimeofday_us() / 1000;
1116         slot->f.pending_sdp_request = false;
1117         slot->f.doing_sdp_request = true;
1118       }
1119       break;
1120     }
1121 
1122     default:
1123       log::debug("unhandled event:{}, slot_id:{}", bta_jv_event_text(event), id);
1124       break;
1125   }
1126 }
1127 
handle_discovery_comp(tBTA_JV_STATUS status,int scn,uint32_t id)1128 static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id) {
1129   uint64_t sdp_duration_ms;
1130   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1131   if (!slot) {
1132     log::error("RFCOMM slot_id {} not found. event: BTA_JV_DISCOVERY_COMP_EVT", id);
1133     return;
1134   }
1135   if (!slot->f.doing_sdp_request) {
1136     log::error("SDP response returned but RFCOMM slot_id {} did not request SDP record.", id);
1137     return;
1138   }
1139 
1140   slot->sdp_end_time_ms = common::time_gettimeofday_us() / 1000;
1141   sdp_duration_ms = slot->sdp_end_time_ms - slot->sdp_start_time_ms;
1142 
1143   if (status != tBTA_JV_STATUS::SUCCESS || !scn) {
1144     log::error(
1145             "SDP service discovery completed for slot_id: {} with the result "
1146             "status: {}, scn: {}",
1147             id, bta_jv_status_text(status), scn);
1148     bta_collect_rfc_metrics_after_sdp_fail(status, slot->addr, slot->app_uid, slot->security,
1149                                            static_cast<bool>(slot->f.server), sdp_duration_ms);
1150     cleanup_rfc_slot(slot, BTSOCK_ERROR_SDP_DISCOVERY_FAILURE);
1151     return;
1152   }
1153 
1154   // Setup optional configurations
1155   RfcommCfgInfo cfg = {};
1156   // For hardware offload data path, host stack sets the initial credits to 0. The offload
1157   // stack should send initial credits to peer device through RFCOMM signaling command when
1158   // the data path is switched successfully.
1159   if (com::android::bluetooth::flags::socket_settings_api()) {
1160     if (slot->data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) {
1161       cfg.init_credit_present = true;
1162       cfg.init_credit = 0;
1163       cfg.rx_mtu_present = slot->mtu > 0;
1164       cfg.rx_mtu = slot->mtu;
1165       cfg.data_path = slot->data_path;
1166     }
1167   }
1168 
1169   if (BTA_JvRfcommConnect(slot->security, scn, slot->addr, rfcomm_cback, slot->id, cfg,
1170                           slot->app_uid, sdp_duration_ms) != tBTA_JV_STATUS::SUCCESS) {
1171     log::warn("BTA_JvRfcommConnect() returned BTA_JV_FAILURE for RFCOMM slot_id:{}", id);
1172     cleanup_rfc_slot(slot, BTSOCK_ERROR_CONNECTION_FAILURE);
1173     return;
1174   }
1175   // Establish connection if successfully found channel number to connect.
1176   slot->scn = scn;
1177   slot->f.doing_sdp_request = false;
1178 
1179   if (!send_app_scn(slot)) {
1180     log::warn("send_app_scn() failed, closing slot_id {}", slot->id);
1181     cleanup_rfc_slot(slot, BTSOCK_ERROR_SEND_SCN_FAILURE);
1182     return;
1183   }
1184 }
1185 
1186 typedef enum {
1187   SENT_FAILED,
1188   SENT_NONE,
1189   SENT_PARTIAL,
1190   SENT_ALL,
1191 } sent_status_t;
1192 
send_data_to_app(int fd,BT_HDR * p_buf)1193 static sent_status_t send_data_to_app(int fd, BT_HDR* p_buf) {
1194   if (p_buf->len == 0) {
1195     return SENT_ALL;
1196   }
1197 
1198   ssize_t sent;
1199   OSI_NO_INTR(sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT));
1200 
1201   if (sent == -1) {
1202     if (errno == EAGAIN || errno == EWOULDBLOCK) {
1203       return SENT_NONE;
1204     }
1205     log::error("error writing RFCOMM data back to app: {}", strerror(errno));
1206     return SENT_FAILED;
1207   }
1208 
1209   if (sent == 0) {
1210     return SENT_FAILED;
1211   }
1212 
1213   if (sent == p_buf->len) {
1214     return SENT_ALL;
1215   }
1216 
1217   p_buf->offset += sent;
1218   p_buf->len -= sent;
1219   return SENT_PARTIAL;
1220 }
1221 
flush_incoming_que_on_wr_signal(rfc_slot_t * slot)1222 static bool flush_incoming_que_on_wr_signal(rfc_slot_t* slot) {
1223   while (!list_is_empty(slot->incoming_queue)) {
1224     BT_HDR* p_buf = (BT_HDR*)list_front(slot->incoming_queue);
1225     switch (send_data_to_app(slot->fd, p_buf)) {
1226       case SENT_NONE:
1227       case SENT_PARTIAL:
1228         // monitor the fd to get callback when app is ready to receive data
1229         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
1230         return true;
1231 
1232       case SENT_ALL:
1233         list_remove(slot->incoming_queue, p_buf);
1234         break;
1235 
1236       case SENT_FAILED:
1237         list_remove(slot->incoming_queue, p_buf);
1238         return false;
1239     }
1240   }
1241 
1242   // app is ready to receive data, tell stack to start the data flow
1243   // fix me: need a jv flow control api to serialize the call in stack
1244   log::verbose("enable data flow, rfc_handle:0x{:x}, rfc_port_handle:0x{:x}, user_id:{}",
1245                slot->rfc_handle, slot->rfc_port_handle, slot->id);
1246   if (PORT_FlowControl_MaxCredit(slot->rfc_port_handle, true) != PORT_SUCCESS) {
1247     log::warn("Unable to open RFCOMM port peer:{}", slot->addr);
1248   }
1249   return true;
1250 }
1251 
btsock_rfc_read_signaled_on_connected_socket(int,int flags,uint32_t,rfc_slot_t * slot)1252 static bool btsock_rfc_read_signaled_on_connected_socket(int /* fd */, int flags, uint32_t /* id */,
1253                                                          rfc_slot_t* slot) {
1254   if (!slot->f.connected) {
1255     log::error("socket signaled for read while disconnected, slot_id: {}, channel: {}", slot->id,
1256                slot->scn);
1257     return false;
1258   }
1259   // Make sure there's data pending in case the peer closed the socket.
1260   int size = 0;
1261   if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) {
1262     BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
1263   }
1264   return true;
1265 }
1266 
btsock_rfc_read_signaled_on_listen_socket(int fd,int,uint32_t,rfc_slot_t * slot)1267 static bool btsock_rfc_read_signaled_on_listen_socket(int fd, int /* flags */, uint32_t /* id */,
1268                                                       rfc_slot_t* slot) {
1269   int size = 0;
1270   bool ioctl_success = ioctl(slot->fd, FIONREAD, &size) == 0;
1271   if (ioctl_success && size) {
1272     sock_accept_signal_t accept_signal = {};
1273     ssize_t count;
1274     OSI_NO_INTR(count = recv(fd, reinterpret_cast<uint8_t*>(&accept_signal), sizeof(accept_signal),
1275                              MSG_NOSIGNAL | MSG_DONTWAIT | MSG_TRUNC));
1276     if (count != sizeof(accept_signal) || count != accept_signal.size) {
1277       log::error("Unexpected count: {}, sizeof(accept_signal): {}, accept_signal.size: {}", count,
1278                  sizeof(accept_signal), accept_signal.size);
1279       return false;
1280     }
1281     slot->is_accepting = accept_signal.is_accepting;
1282     log::info("Server socket slot_id: {}, is_accepting: {}", slot->id, slot->is_accepting);
1283   }
1284   return true;
1285 }
1286 
btsock_rfc_signaled_flagged(int fd,int flags,uint32_t id)1287 static void btsock_rfc_signaled_flagged(int fd, int flags, uint32_t id) {
1288   bool need_close = false;
1289   btsock_error_code_t error_code = BTSOCK_ERROR_NONE;
1290   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1291   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1292   if (!slot) {
1293     log::warn("RFCOMM slot_id {} not found.", id);
1294     return;
1295   }
1296 
1297   // Data available from app, tell stack we have outgoing data.
1298   if (flags & SOCK_THREAD_FD_RD) {
1299     if (!slot->f.server) {
1300       // app sending data on connection socket
1301       if (!btsock_rfc_read_signaled_on_connected_socket(fd, flags, id, slot)) {
1302         need_close = true;
1303         error_code = BTSOCK_ERROR_READ_SIGNALED_FAILURE;
1304       }
1305     } else {
1306       // app sending signal on listen socket
1307       if (!btsock_rfc_read_signaled_on_listen_socket(fd, flags, id, slot)) {
1308         need_close = true;
1309         error_code = BTSOCK_ERROR_READ_SIGNALED_FAILURE;
1310       }
1311     }
1312   }
1313 
1314   if (flags & SOCK_THREAD_FD_WR) {
1315     // App is ready to receive more data, tell stack to enable data flow.
1316     if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
1317       log::error(
1318               "socket signaled for write while disconnected (or write failure), "
1319               "slot_id: {}, channel: {}",
1320               slot->id, slot->scn);
1321       need_close = true;
1322       error_code = BTSOCK_ERROR_WRITE_SIGNALED_FAILURE;
1323     }
1324   }
1325 
1326   if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1327     // Clean up if there's no data pending.
1328     int size = 0;
1329     if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size) {
1330       if (com::android::bluetooth::flags::rfcomm_cancel_ongoing_sdp_on_close() &&
1331           slot->f.doing_sdp_request) {
1332         BTA_JvCancelDiscovery(slot->id);
1333       }
1334       cleanup_rfc_slot(slot, error_code);
1335     }
1336   }
1337 }
1338 
btsock_rfc_signaled(int fd,int flags,uint32_t id)1339 void btsock_rfc_signaled(int fd, int flags, uint32_t id) {
1340   if (com::android::bluetooth::flags::socket_settings_api()) {
1341     btsock_rfc_signaled_flagged(fd, flags, id);
1342     return;
1343   }
1344   bool need_close = false;
1345   btsock_error_code_t error_code = BTSOCK_ERROR_NONE;
1346   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1347   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1348   if (!slot) {
1349     log::warn("RFCOMM slot with id {} not found.", id);
1350     return;
1351   }
1352 
1353   // Data available from app, tell stack we have outgoing data.
1354   if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
1355     if (slot->f.connected) {
1356       // Make sure there's data pending in case the peer closed the socket.
1357       int size = 0;
1358       if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) {
1359         BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
1360       }
1361     } else {
1362       log::error("socket signaled for read while disconnected, slot_id: {}, channel: {}", slot->id,
1363                  slot->scn);
1364       error_code = BTSOCK_ERROR_READ_SIGNALED_FAILURE;
1365       need_close = true;
1366     }
1367   }
1368 
1369   if (flags & SOCK_THREAD_FD_WR) {
1370     // App is ready to receive more data, tell stack to enable data flow.
1371     if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
1372       log::error(
1373               "socket signaled for write while disconnected (or write failure), "
1374               "slot_id: {}, channel: {}",
1375               slot->id, slot->scn);
1376       error_code = BTSOCK_ERROR_WRITE_SIGNALED_FAILURE;
1377       need_close = true;
1378     }
1379   }
1380 
1381   if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
1382     // Clean up if there's no data pending.
1383     int size = 0;
1384     if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size) {
1385       if (com::android::bluetooth::flags::rfcomm_cancel_ongoing_sdp_on_close() &&
1386           slot->f.doing_sdp_request) {
1387         BTA_JvCancelDiscovery(slot->id);
1388       }
1389       cleanup_rfc_slot(slot, error_code);
1390     }
1391   }
1392 }
1393 
bta_co_rfc_data_incoming(uint32_t id,BT_HDR * p_buf)1394 int bta_co_rfc_data_incoming(uint32_t id, BT_HDR* p_buf) {
1395   int app_uid = -1;
1396   uint64_t bytes_rx = 0;
1397   int ret = 0;
1398   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1399   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1400   if (!slot) {
1401     log::error("RFCOMM slot_id {} not found.", id);
1402     return 0;
1403   }
1404 
1405   app_uid = slot->app_uid;
1406   bytes_rx = p_buf->len;
1407 
1408   if (list_is_empty(slot->incoming_queue)) {
1409     switch (send_data_to_app(slot->fd, p_buf)) {
1410       case SENT_NONE:
1411       case SENT_PARTIAL:
1412         list_append(slot->incoming_queue, p_buf);
1413         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
1414         break;
1415 
1416       case SENT_ALL:
1417         osi_free(p_buf);
1418         ret = 1;  // Enable data flow.
1419         break;
1420 
1421       case SENT_FAILED:
1422         osi_free(p_buf);
1423         cleanup_rfc_slot(slot, BTSOCK_ERROR_SEND_TO_APP_FAILURE);
1424         break;
1425     }
1426   } else {
1427     list_append(slot->incoming_queue, p_buf);
1428   }
1429 
1430   slot->rx_bytes += bytes_rx;
1431   uid_set_add_rx(uid_set, app_uid, bytes_rx);
1432 
1433   return ret;  // Return 0 to disable data flow.
1434 }
1435 
bta_co_rfc_data_outgoing_size(uint32_t id,int * size)1436 int bta_co_rfc_data_outgoing_size(uint32_t id, int* size) {
1437   *size = 0;
1438   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1439   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1440   if (!slot) {
1441     log::error("RFCOMM slot_id {} not found.", id);
1442     return false;
1443   }
1444 
1445   if (ioctl(slot->fd, FIONREAD, size) != 0) {
1446     log::error("unable to determine bytes remaining to be read on fd {}: {}", slot->fd,
1447                strerror(errno));
1448     cleanup_rfc_slot(slot, BTSOCK_ERROR_RECEIVE_DATA_FAILURE);
1449     return false;
1450   }
1451 
1452   return true;
1453 }
1454 
bta_co_rfc_data_outgoing(uint32_t id,uint8_t * buf,uint16_t size)1455 int bta_co_rfc_data_outgoing(uint32_t id, uint8_t* buf, uint16_t size) {
1456   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1457   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1458   if (!slot) {
1459     log::error("RFCOMM slot_id {} not found.", id);
1460     return false;
1461   }
1462 
1463   ssize_t received;
1464   OSI_NO_INTR(received = recv(slot->fd, buf, size, 0));
1465 
1466   if (received != size) {
1467     log::error("error receiving RFCOMM data from app: {}", strerror(errno));
1468     cleanup_rfc_slot(slot, BTSOCK_ERROR_RECEIVE_DATA_FAILURE);
1469     return false;
1470   }
1471 
1472   return true;
1473 }
1474 
btsock_rfc_disconnect(const RawAddress * bd_addr)1475 bt_status_t btsock_rfc_disconnect(const RawAddress* bd_addr) {
1476   log::assert_that(bd_addr != NULL, "assert failed: bd_addr != NULL");
1477   if (!is_init_done()) {
1478     log::error("BT not ready");
1479     return BT_STATUS_NOT_READY;
1480   }
1481 
1482   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1483   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
1484     if (rfc_slots[i].id && rfc_slots[i].addr == *bd_addr) {
1485       cleanup_rfc_slot(&rfc_slots[i], BTSOCK_ERROR_NONE);
1486     }
1487   }
1488 
1489   return BT_STATUS_SUCCESS;
1490 }
1491