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 <bluetooth/log.h>
22 #include <com_android_bluetooth_flags.h>
23 #include <sys/ioctl.h>
24 #include <sys/socket.h>
25 #include <sys/types.h>
26 
27 #include <cstdint>
28 #include <mutex>
29 
30 #include "bta/include/bta_jv_api.h"
31 #include "bta/include/bta_rfcomm_scn.h"
32 #include "btif/include/btif_metrics_logging.h"
33 #include "btif/include/btif_sock.h"
34 #include "btif/include/btif_sock_l2cap.h"
35 #include "btif/include/btif_sock_logging.h"
36 #include "btif/include/btif_sock_sdp.h"
37 #include "btif/include/btif_sock_thread.h"
38 #include "btif/include/btif_sock_util.h"
39 #include "include/hardware/bt_sock.h"
40 #include "osi/include/allocator.h"
41 #include "osi/include/compat.h"
42 #include "osi/include/list.h"
43 #include "osi/include/osi.h"  // INVALID_FD
44 #include "stack/include/bt_hdr.h"
45 #include "stack/include/port_api.h"
46 #include "types/bluetooth/uuid.h"
47 #include "types/raw_address.h"
48 
49 // TODO(b/369381361) Enfore -Wmissing-prototypes
50 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
51 
52 using bluetooth::Uuid;
53 using namespace bluetooth;
54 
55 // Maximum number of RFCOMM channels (1-30 inclusive).
56 #define MAX_RFC_CHANNEL 30
57 
58 // Maximum number of devices we can have an RFCOMM connection with.
59 #define MAX_RFC_SESSION 7
60 
61 typedef struct {
62   int outgoing_congest : 1;
63   int pending_sdp_request : 1;
64   int doing_sdp_request : 1;
65   int server : 1;
66   int connected : 1;
67   int closing : 1;
68 } flags_t;
69 
70 typedef struct {
71   flags_t f;
72   uint32_t id;  // Non-zero indicates a valid (in-use) slot.
73   int security;
74   int scn;  // Server channel number
75   int scn_notified;
76   RawAddress addr;
77   int is_service_uuid_valid;
78   Uuid service_uuid;
79   char service_name[256];
80   int fd;
81   int app_fd;   // Temporary storage for the half of the socketpair that's
82                 // sent back to upper layers.
83   int app_uid;  // UID of the app for which this socket was created.
84   int mtu;
85   uint8_t* packet;
86   int sdp_handle;
87   int rfc_handle;
88   int rfc_port_handle;
89   int role;
90   list_t* incoming_queue;
91   // Cumulative number of bytes transmitted on this socket
92   int64_t tx_bytes;
93   // Cumulative number of bytes received on this socket
94   int64_t rx_bytes;
95 } rfc_slot_t;
96 
97 static rfc_slot_t rfc_slots[MAX_RFC_CHANNEL];
98 static uint32_t rfc_slot_id;
99 static volatile int pth = -1;  // poll thread handle
100 static std::recursive_mutex slot_lock;
101 static uid_set_t* uid_set = NULL;
102 
103 static rfc_slot_t* find_free_slot(void);
104 static void cleanup_rfc_slot(rfc_slot_t* rs);
105 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id);
106 static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id);
107 static bool send_app_scn(rfc_slot_t* rs);
108 static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id);
109 
is_init_done(void)110 static bool is_init_done(void) { return pth != -1; }
111 
btsock_rfc_init(int poll_thread_handle,uid_set_t * set)112 bt_status_t btsock_rfc_init(int poll_thread_handle, uid_set_t* set) {
113   pth = poll_thread_handle;
114   uid_set = set;
115 
116   memset(rfc_slots, 0, sizeof(rfc_slots));
117   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
118     rfc_slots[i].scn = -1;
119     rfc_slots[i].sdp_handle = 0;
120     rfc_slots[i].fd = INVALID_FD;
121     rfc_slots[i].app_fd = INVALID_FD;
122     rfc_slots[i].incoming_queue = list_new(osi_free);
123     log::assert_that(rfc_slots[i].incoming_queue != NULL,
124                      "assert failed: rfc_slots[i].incoming_queue != NULL");
125   }
126 
127   BTA_JvEnable(jv_dm_cback);
128 
129   return BT_STATUS_SUCCESS;
130 }
131 
btsock_rfc_cleanup(void)132 void btsock_rfc_cleanup(void) {
133   pth = -1;
134 
135   BTA_JvDisable();
136 
137   std::unique_lock<std::recursive_mutex> lock(slot_lock);
138   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
139     if (rfc_slots[i].id) {
140       cleanup_rfc_slot(&rfc_slots[i]);
141     }
142     list_free(rfc_slots[i].incoming_queue);
143     rfc_slots[i].incoming_queue = NULL;
144   }
145 
146   uid_set = NULL;
147 
148   log::debug("cleanup finished");
149 }
150 
find_free_slot(void)151 static rfc_slot_t* find_free_slot(void) {
152   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
153     if (rfc_slots[i].fd == INVALID_FD) {
154       return &rfc_slots[i];
155     }
156   }
157   return NULL;
158 }
159 
find_rfc_slot_by_id(uint32_t id)160 static rfc_slot_t* find_rfc_slot_by_id(uint32_t id) {
161   CHECK_NE(0u, id);
162 
163   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
164     if (rfc_slots[i].id == id) {
165       return &rfc_slots[i];
166     }
167   }
168 
169   return NULL;
170 }
171 
find_rfc_slot_by_pending_sdp(void)172 static rfc_slot_t* find_rfc_slot_by_pending_sdp(void) {
173   uint32_t min_id = UINT32_MAX;
174   int slot = -1;
175   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
176     if (rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request && rfc_slots[i].id < min_id) {
177       min_id = rfc_slots[i].id;
178       slot = i;
179     }
180   }
181 
182   return (slot == -1) ? NULL : &rfc_slots[slot];
183 }
184 
is_requesting_sdp(void)185 static bool is_requesting_sdp(void) {
186   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
187     if (rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request) {
188       log::info("slot id {} is doing sdp request", rfc_slots[i].id);
189       return true;
190     }
191   }
192   return false;
193 }
194 
alloc_rfc_slot(const RawAddress * addr,const char * name,const Uuid & uuid,int channel,int flags,bool server)195 static rfc_slot_t* alloc_rfc_slot(const RawAddress* addr, const char* name, const Uuid& uuid,
196                                   int channel, int flags, bool server) {
197   int security = 0;
198   if (flags & BTSOCK_FLAG_ENCRYPT) {
199     security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
200   }
201   if (flags & BTSOCK_FLAG_AUTH) {
202     security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
203   }
204   if (flags & BTSOCK_FLAG_AUTH_MITM) {
205     security |= server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM;
206   }
207   if (flags & BTSOCK_FLAG_AUTH_16_DIGIT) {
208     security |= BTM_SEC_IN_MIN_16_DIGIT_PIN;
209   }
210 
211   rfc_slot_t* slot = find_free_slot();
212   if (!slot) {
213     log::error("unable to find free RFCOMM slot.");
214     return NULL;
215   }
216 
217   int fds[2] = {INVALID_FD, INVALID_FD};
218   if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) == -1) {
219     log::error("error creating socketpair: {}", strerror(errno));
220     return NULL;
221   }
222 
223   // Increment slot id and make sure we don't use id=0.
224   if (++rfc_slot_id == 0) {
225     rfc_slot_id = 1;
226   }
227 
228   slot->fd = fds[0];
229   slot->app_fd = fds[1];
230   slot->security = security;
231   slot->scn = channel;
232   slot->app_uid = -1;
233 
234   slot->is_service_uuid_valid = !uuid.IsEmpty();
235   slot->service_uuid = uuid;
236 
237   if (name && *name) {
238     osi_strlcpy(slot->service_name, name, sizeof(slot->service_name));
239   } else {
240     memset(slot->service_name, 0, sizeof(slot->service_name));
241   }
242   if (addr) {
243     slot->addr = *addr;
244   } else {
245     slot->addr = RawAddress::kEmpty;
246   }
247   slot->id = rfc_slot_id;
248   slot->f.server = server;
249   slot->role = server;
250   slot->tx_bytes = 0;
251   slot->rx_bytes = 0;
252   return slot;
253 }
254 
create_srv_accept_rfc_slot(rfc_slot_t * srv_rs,const RawAddress * addr,int open_handle,int new_listen_handle)255 static rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, const RawAddress* addr,
256                                               int open_handle, int new_listen_handle) {
257   rfc_slot_t* accept_rs =
258           alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, false);
259   if (!accept_rs) {
260     log::error("unable to allocate RFCOMM slot.");
261     return NULL;
262   }
263 
264   accept_rs->f.server = false;
265   accept_rs->f.connected = true;
266   accept_rs->security = srv_rs->security;
267   accept_rs->mtu = srv_rs->mtu;
268   accept_rs->role = srv_rs->role;
269   accept_rs->rfc_handle = open_handle;
270   accept_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(open_handle);
271   accept_rs->app_uid = srv_rs->app_uid;
272 
273   srv_rs->rfc_handle = new_listen_handle;
274   srv_rs->rfc_port_handle = BTA_JvRfcommGetPortHdl(new_listen_handle);
275 
276   if (accept_rs->rfc_port_handle == srv_rs->rfc_port_handle) {
277     log::error(
278             "accept_rs->rfc_port_handle == srv_rs->rfc_port_handle, "
279             "rfc_port_handle={}",
280             accept_rs->rfc_port_handle);
281   }
282   log::assert_that(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle,
283                    "assert failed: accept_rs->rfc_port_handle != srv_rs->rfc_port_handle");
284 
285   // now swap the slot id
286   uint32_t new_listen_id = accept_rs->id;
287   accept_rs->id = srv_rs->id;
288   srv_rs->id = new_listen_id;
289 
290   return accept_rs;
291 }
292 
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)293 bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal,
294                                    uint8_t break_signal, uint8_t discard_buffers,
295                                    uint8_t break_signal_seq, bool fc) {
296   int status = RFCOMM_ControlReqFromBTSOCK(dlci, bd_addr, modem_signal, break_signal,
297                                            discard_buffers, break_signal_seq, fc);
298   if (status != PORT_SUCCESS) {
299     log::warn("failed to send control parameters, status={}", status);
300     return BT_STATUS_FAIL;
301   }
302   return BT_STATUS_SUCCESS;
303 }
304 
btsock_rfc_listen(const char * service_name,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid)305 bt_status_t btsock_rfc_listen(const char* service_name, const Uuid* service_uuid, int channel,
306                               int* sock_fd, int flags, int app_uid) {
307   log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL");
308   log::assert_that((service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL) ||
309                            ((flags & BTSOCK_FLAG_NO_SDP) != 0),
310                    "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= "
311                    "MAX_RFC_CHANNEL) || ((flags & BTSOCK_FLAG_NO_SDP) != 0)");
312 
313   *sock_fd = INVALID_FD;
314 
315   // TODO(sharvil): not sure that this check makes sense; seems like a logic
316   // error to call
317   // functions on RFCOMM sockets before initializing the module. Probably
318   // should be an assert.
319   if (!is_init_done()) {
320     log::error("BT not ready");
321     return BT_STATUS_NOT_READY;
322   }
323 
324   if ((flags & BTSOCK_FLAG_NO_SDP) == 0) {
325     if (!service_uuid || service_uuid->IsEmpty()) {
326       // Use serial port profile to listen to specified channel
327       service_uuid = &UUID_SPP;
328     } else {
329       // Check the service_uuid. overwrite the channel # if reserved
330       int reserved_channel = get_reserved_rfc_channel(*service_uuid);
331       if (reserved_channel > 0) {
332         channel = reserved_channel;
333       }
334     }
335   }
336 
337   std::unique_lock<std::recursive_mutex> lock(slot_lock);
338 
339   rfc_slot_t* slot = alloc_rfc_slot(NULL, service_name, *service_uuid, channel, flags, true);
340   if (!slot) {
341     log::error("unable to allocate RFCOMM slot");
342     return BT_STATUS_NOMEM;
343   }
344   log::info("Adding listening socket service_name: {} - channel: {}", service_name, channel);
345   BTA_JvGetChannelId(tBTA_JV_CONN_TYPE::RFCOMM, slot->id, channel);
346   *sock_fd = slot->app_fd;  // Transfer ownership of fd to caller.
347   /*TODO:
348    * We are leaking one of the app_fd's - either the listen socket, or the
349    connection socket.
350    * WE need to close this in native, as the FD might belong to another process
351     - This is the server socket FD
352     - For accepted connections, we close the FD after passing it to JAVA.
353     - Try to simply remove the = -1 to free the FD at rs cleanup.*/
354   //        close(rs->app_fd);
355   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
356   slot->app_uid = app_uid;
357   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, slot->id);
358 
359   return BT_STATUS_SUCCESS;
360 }
361 
btsock_rfc_connect(const RawAddress * bd_addr,const Uuid * service_uuid,int channel,int * sock_fd,int flags,int app_uid)362 bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, const Uuid* service_uuid, int channel,
363                                int* sock_fd, int flags, int app_uid) {
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                    "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= "
367                    "MAX_RFC_CHANNEL)");
368 
369   *sock_fd = INVALID_FD;
370 
371   // TODO(sharvil): not sure that this check makes sense; seems like a logic
372   // error to call
373   // functions on RFCOMM sockets before initializing the module. Probably should
374   // be an assert.
375   if (!is_init_done()) {
376     log::error("BT not ready");
377     return BT_STATUS_NOT_READY;
378   }
379 
380   std::unique_lock<std::recursive_mutex> lock(slot_lock);
381 
382   rfc_slot_t* slot = alloc_rfc_slot(bd_addr, NULL, *service_uuid, channel, flags, false);
383   if (!slot) {
384     log::error("unable to allocate RFCOMM slot. bd_addr:{}", *bd_addr);
385     return BT_STATUS_NOMEM;
386   }
387 
388   if (!service_uuid || service_uuid->IsEmpty()) {
389     tBTA_JV_STATUS ret =
390             BTA_JvRfcommConnect(slot->security, slot->scn, slot->addr, rfcomm_cback, slot->id);
391     if (ret != tBTA_JV_STATUS::SUCCESS) {
392       log::error("unable to initiate RFCOMM connection. status:{}, scn:{}, bd_addr:{}",
393                  bta_jv_status_text(ret), slot->scn, slot->addr);
394       cleanup_rfc_slot(slot);
395       return BT_STATUS_SOCKET_ERROR;
396     }
397 
398     if (!send_app_scn(slot)) {
399       log::error("send_app_scn() failed, closing slot->id:{}", slot->id);
400       cleanup_rfc_slot(slot);
401       return BT_STATUS_SOCKET_ERROR;
402     }
403   } else {
404     log::info("service_uuid:{}, bd_addr:{}, slot_id:{}", service_uuid->ToString(), *bd_addr,
405               slot->id);
406     if (!is_requesting_sdp()) {
407       BTA_JvStartDiscovery(*bd_addr, 1, service_uuid, slot->id);
408       slot->f.pending_sdp_request = false;
409       slot->f.doing_sdp_request = true;
410     } else {
411       slot->f.pending_sdp_request = true;
412       slot->f.doing_sdp_request = false;
413     }
414   }
415 
416   *sock_fd = slot->app_fd;    // Transfer ownership of fd to caller.
417   slot->app_fd = INVALID_FD;  // Drop our reference to the fd.
418   slot->app_uid = app_uid;
419   btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
420 
421   return BT_STATUS_SUCCESS;
422 }
423 
create_server_sdp_record(rfc_slot_t * slot)424 static int create_server_sdp_record(rfc_slot_t* slot) {
425   if (slot->scn == 0) {
426     return false;
427   }
428   slot->sdp_handle = add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn);
429   return slot->sdp_handle > 0;
430 }
431 
free_rfc_slot_scn(rfc_slot_t * slot)432 static void free_rfc_slot_scn(rfc_slot_t* slot) {
433   if (slot->scn <= 0) {
434     return;
435   }
436 
437   if (slot->f.server && !slot->f.closing && slot->rfc_handle) {
438     BTA_JvRfcommStopServer(slot->rfc_handle, slot->id);
439     slot->rfc_handle = 0;
440   }
441 
442   if (slot->f.server) {
443     BTA_FreeSCN(slot->scn);
444   }
445   slot->scn = 0;
446 }
447 
cleanup_rfc_slot(rfc_slot_t * slot)448 static void cleanup_rfc_slot(rfc_slot_t* slot) {
449   if (slot->fd != INVALID_FD) {
450     shutdown(slot->fd, SHUT_RDWR);
451     close(slot->fd);
452     log::info(
453             "disconnected from RFCOMM socket connections for device: {}, scn: {}, "
454             "app_uid: {}, id: {}",
455             slot->addr, slot->scn, slot->app_uid, slot->id);
456     btif_sock_connection_logger(
457             slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_DISCONNECTED,
458             slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn,
459             slot->tx_bytes, slot->rx_bytes,
460             slot->role ? slot->service_name : slot->service_uuid.ToString().c_str());
461 
462     slot->fd = INVALID_FD;
463   }
464 
465   if (slot->app_fd != INVALID_FD) {
466     close(slot->app_fd);
467     slot->app_fd = INVALID_FD;
468   }
469 
470   if (slot->sdp_handle > 0) {
471     del_rfc_sdp_rec(slot->sdp_handle);
472     slot->sdp_handle = 0;
473   }
474 
475   if (slot->rfc_handle && !slot->f.closing && !slot->f.server) {
476     BTA_JvRfcommClose(slot->rfc_handle, slot->id);
477     slot->rfc_handle = 0;
478   }
479 
480   free_rfc_slot_scn(slot);
481   list_clear(slot->incoming_queue);
482 
483   slot->rfc_port_handle = 0;
484   memset(&slot->f, 0, sizeof(slot->f));
485   slot->id = 0;
486   slot->scn_notified = false;
487   slot->tx_bytes = 0;
488   slot->rx_bytes = 0;
489 }
490 
send_app_scn(rfc_slot_t * slot)491 static bool send_app_scn(rfc_slot_t* slot) {
492   if (slot->scn_notified) {
493     // already sent, just return success.
494     return true;
495   }
496   log::debug("Sending scn for slot {}. bd_addr:{}", slot->id, slot->addr);
497   slot->scn_notified = true;
498   return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, sizeof(slot->scn)) ==
499          sizeof(slot->scn);
500 }
501 
send_app_connect_signal(int fd,const RawAddress * addr,int channel,int status,int send_fd)502 static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, int status,
503                                     int send_fd) {
504   sock_connect_signal_t cs;
505   cs.size = sizeof(cs);
506   cs.bd_addr = *addr;
507   cs.channel = channel;
508   cs.status = status;
509   cs.max_rx_packet_size = 0;  // not used for RFCOMM
510   cs.max_tx_packet_size = 0;  // not used for RFCOMM
511   cs.conn_uuid_lsb = 0;       // not used for RFCOMM
512   cs.conn_uuid_msb = 0;       // not used for RFCOMM
513   cs.socket_id = 0;           // not used for RFCOMM
514   if (send_fd == INVALID_FD) {
515     return sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs);
516   }
517 
518   return sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs);
519 }
520 
on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT * p_init,uint32_t id)521 static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT* p_init, uint32_t id) {
522   std::unique_lock<std::recursive_mutex> lock(slot_lock);
523   rfc_slot_t* slot = find_rfc_slot_by_id(id);
524   if (!slot) {
525     log::error("RFCOMM slot with id {} not found. p_init->status={}", id,
526                bta_jv_status_text(p_init->status));
527   } else if (p_init->status != tBTA_JV_STATUS::SUCCESS) {
528     log::warn("INIT unsuccessful, status {}. Cleaning up slot with id {}",
529               bta_jv_status_text(p_init->status), slot->id);
530     cleanup_rfc_slot(slot);
531   } else {
532     slot->rfc_handle = p_init->handle;
533   }
534 }
535 
on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START * p_start,uint32_t id)536 static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start, uint32_t id) {
537   std::unique_lock<std::recursive_mutex> lock(slot_lock);
538   rfc_slot_t* slot = find_rfc_slot_by_id(id);
539   if (!slot) {
540     log::error("RFCOMM slot with id {} not found", id);
541     return;
542   } else if (p_start->status != tBTA_JV_STATUS::SUCCESS) {
543     log::warn("START unsuccessful, status {}. Cleaning up slot with id {}",
544               bta_jv_status_text(p_start->status), slot->id);
545     cleanup_rfc_slot(slot);
546     return;
547   }
548 
549   slot->rfc_handle = p_start->handle;
550   log::info(
551           "listening for RFCOMM socket connections for device: {}, scn: {}, "
552           "app_uid: {}, id: {}",
553           slot->addr, slot->scn, slot->app_uid, id);
554   btif_sock_connection_logger(slot->addr, slot->id, BTSOCK_RFCOMM,
555                               SOCKET_CONNECTION_STATE_LISTENING,
556                               slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
557                               slot->app_uid, slot->scn, 0, 0, slot->service_name);
558 }
559 
on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN * p_open,uint32_t id)560 static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open, uint32_t id) {
561   log::verbose("id:{}", id);
562   std::unique_lock<std::recursive_mutex> lock(slot_lock);
563   rfc_slot_t* accept_rs;
564   rfc_slot_t* srv_rs = find_rfc_slot_by_id(id);
565   if (!srv_rs) {
566     log::error("RFCOMM slot with id {} not found.", id);
567     return 0;
568   }
569 
570   accept_rs = create_srv_accept_rfc_slot(srv_rs, &p_open->rem_bda, p_open->handle,
571                                          p_open->new_listen_handle);
572   if (!accept_rs) {
573     return 0;
574   }
575 
576   log::info(
577           "connected to RFCOMM socket connections for device: {}, scn: {}, "
578           "app_uid: {}, id: {}",
579           accept_rs->addr, accept_rs->scn, accept_rs->app_uid, id);
580   btif_sock_connection_logger(accept_rs->addr, accept_rs->id, BTSOCK_RFCOMM,
581                               SOCKET_CONNECTION_STATE_DISCONNECTED,
582                               accept_rs->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION,
583                               accept_rs->app_uid, accept_rs->scn, 0, 0, accept_rs->service_name);
584 
585   // Start monitoring the socket.
586   btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id);
587   btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id);
588   send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd);
589   accept_rs->app_fd = INVALID_FD;  // Ownership of the application fd has been transferred.
590   return srv_rs->id;
591 }
592 
on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN * p_open,uint32_t id)593 static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN* p_open, uint32_t id) {
594   log::verbose("id:{}", id);
595   std::unique_lock<std::recursive_mutex> lock(slot_lock);
596   rfc_slot_t* slot = find_rfc_slot_by_id(id);
597   if (!slot) {
598     log::error("RFCOMM slot with id {} not found.", id);
599     return;
600   }
601 
602   if (p_open->status != tBTA_JV_STATUS::SUCCESS) {
603     log::warn("CONNECT unsuccessful, status {}. Cleaning up slot with id {}",
604               bta_jv_status_text(p_open->status), slot->id);
605     cleanup_rfc_slot(slot);
606     return;
607   }
608 
609   slot->rfc_port_handle = BTA_JvRfcommGetPortHdl(p_open->handle);
610   slot->addr = p_open->rem_bda;
611 
612   log::info(
613           "connected to RFCOMM socket connections for device: {}, scn: {}, "
614           "app_uid: {}, id: {}",
615           slot->addr, slot->scn, slot->app_uid, id);
616   btif_sock_connection_logger(
617           slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_CONNECTED,
618           slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn, 0,
619           0, slot->service_uuid.ToString().c_str());
620 
621   if (send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1)) {
622     slot->f.connected = true;
623   } else {
624     log::error("unable to send connect completion signal to caller.");
625   }
626 }
627 
on_rfc_close(tBTA_JV_RFCOMM_CLOSE *,uint32_t id)628 static void on_rfc_close(tBTA_JV_RFCOMM_CLOSE* /* p_close */, uint32_t id) {
629   log::verbose("id:{}", id);
630   std::unique_lock<std::recursive_mutex> lock(slot_lock);
631 
632   // rfc_handle already closed when receiving rfcomm close event from stack.
633   rfc_slot_t* slot = find_rfc_slot_by_id(id);
634   if (!slot) {
635     log::warn("RFCOMM slot with id {} not found.", id);
636     return;
637   }
638   log_socket_connection_state(slot->addr, slot->id, BTSOCK_RFCOMM,
639                               android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0,
640                               slot->app_uid, slot->scn,
641                               slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN
642                                              : android::bluetooth::SOCKET_ROLE_CONNECTION);
643   cleanup_rfc_slot(slot);
644 }
645 
on_rfc_write_done(tBTA_JV_RFCOMM_WRITE * p,uint32_t id)646 static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE* p, uint32_t id) {
647   if (p->status != tBTA_JV_STATUS::SUCCESS) {
648     log::error("error writing to RFCOMM socket with slot {}.", p->req_id);
649     return;
650   }
651 
652   int app_uid = -1;
653   std::unique_lock<std::recursive_mutex> lock(slot_lock);
654 
655   rfc_slot_t* slot = find_rfc_slot_by_id(id);
656   if (!slot) {
657     log::error("RFCOMM slot with id {} not found.", id);
658     return;
659   }
660   app_uid = slot->app_uid;
661   if (!slot->f.outgoing_congest) {
662     btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
663   }
664   slot->tx_bytes += p->len;
665   uid_set_add_tx(uid_set, app_uid, p->len);
666 }
667 
on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG * p,uint32_t id)668 static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG* p, uint32_t id) {
669   std::unique_lock<std::recursive_mutex> lock(slot_lock);
670 
671   rfc_slot_t* slot = find_rfc_slot_by_id(id);
672   if (!slot) {
673     log::error("RFCOMM slot with id {} not found.", id);
674     return;
675   }
676 
677   slot->f.outgoing_congest = p->cong ? 1 : 0;
678   if (!slot->f.outgoing_congest) {
679     btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id);
680   }
681 }
682 
rfcomm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t rfcomm_slot_id)683 static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id) {
684   uint32_t id = 0;
685 
686   switch (event) {
687     case BTA_JV_RFCOMM_START_EVT:
688       log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
689       on_srv_rfc_listen_started(&p_data->rfc_start, rfcomm_slot_id);
690       break;
691 
692     case BTA_JV_RFCOMM_CL_INIT_EVT:
693       log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
694       on_cl_rfc_init(&p_data->rfc_cl_init, rfcomm_slot_id);
695       break;
696 
697     case BTA_JV_RFCOMM_OPEN_EVT:
698       log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
699       BTA_JvSetPmProfile(p_data->rfc_open.handle, BTA_JV_PM_ID_1, BTA_JV_CONN_OPEN);
700       on_cli_rfc_connect(&p_data->rfc_open, rfcomm_slot_id);
701       break;
702 
703     case BTA_JV_RFCOMM_SRV_OPEN_EVT:
704       log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
705       BTA_JvSetPmProfile(p_data->rfc_srv_open.handle, BTA_JV_PM_ALL, BTA_JV_CONN_OPEN);
706       id = on_srv_rfc_connect(&p_data->rfc_srv_open, rfcomm_slot_id);
707       break;
708 
709     case BTA_JV_RFCOMM_CLOSE_EVT:
710       log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
711       on_rfc_close(&p_data->rfc_close, rfcomm_slot_id);
712       break;
713 
714     case BTA_JV_RFCOMM_WRITE_EVT:
715       log::verbose("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
716       on_rfc_write_done(&p_data->rfc_write, rfcomm_slot_id);
717       break;
718 
719     case BTA_JV_RFCOMM_CONG_EVT:
720       log::verbose("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id);
721       on_rfc_outgoing_congest(&p_data->rfc_cong, rfcomm_slot_id);
722       break;
723 
724     case BTA_JV_RFCOMM_DATA_IND_EVT:
725       // Unused.
726       break;
727 
728     default:
729       log::warn("unhandled event {}, slot id: {}", bta_jv_event_text(event), rfcomm_slot_id);
730       break;
731   }
732   return id;
733 }
734 
jv_dm_cback(tBTA_JV_EVT event,tBTA_JV * p_data,uint32_t id)735 static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) {
736   log::info("handling event:{}, id:{}", bta_jv_event_text(event), id);
737   switch (event) {
738     case BTA_JV_GET_SCN_EVT: {
739       std::unique_lock<std::recursive_mutex> lock(slot_lock);
740       rfc_slot_t* rs = find_rfc_slot_by_id(id);
741       if (!rs) {
742         log::error("RFCOMM slot with id {} not found. event:{}", id, bta_jv_event_text(event));
743         break;
744       }
745       if (p_data->scn == 0) {
746         log::error("Unable to allocate scn: all resources exhausted. slot found: {}",
747                    std::format_ptr(rs));
748         cleanup_rfc_slot(rs);
749         break;
750       }
751 
752       rs->scn = p_data->scn;
753       // Send channel ID to java layer
754       if (!send_app_scn(rs)) {
755         log::warn("send_app_scn() failed, closing rs->id:{}", rs->id);
756         cleanup_rfc_slot(rs);
757         break;
758       }
759 
760       if (rs->is_service_uuid_valid) {
761         // BTA_JvCreateRecordByUser will only create a record if a UUID is
762         // specified. RFC-only profiles
763         BTA_JvCreateRecordByUser(rs->id);
764       } else {
765         // If uuid is null, just allocate a RFC channel and start the RFCOMM
766         // thread needed for the java layer to get a RFCOMM channel.
767         // create_sdp_record() will be called from Java when it has received the
768         // RFCOMM and L2CAP channel numbers through the sockets.
769         log::debug(
770                 "Since UUID is not valid; not setting SDP-record and just starting "
771                 "the RFCOMM server");
772         // now start the rfcomm server after sdp & channel # assigned
773         BTA_JvRfcommStartServer(rs->security, rs->scn, MAX_RFC_SESSION, rfcomm_cback, rs->id);
774       }
775       break;
776     }
777 
778     case BTA_JV_GET_PSM_EVT: {
779       log::verbose("Received PSM: 0x{:04x}", p_data->psm);
780       on_l2cap_psm_assigned(id, p_data->psm);
781       break;
782     }
783 
784     case BTA_JV_CREATE_RECORD_EVT: {
785       std::unique_lock<std::recursive_mutex> lock(slot_lock);
786       rfc_slot_t* slot = find_rfc_slot_by_id(id);
787 
788       if (!slot) {
789         log::error("RFCOMM slot with id {} not found. event:{}", id, bta_jv_event_text(event));
790         break;
791       }
792 
793       if (!create_server_sdp_record(slot)) {
794         log::error("cannot start server, slot found: {}", std::format_ptr(slot));
795         cleanup_rfc_slot(slot);
796         break;
797       }
798 
799       // Start the rfcomm server after sdp & channel # assigned.
800       BTA_JvRfcommStartServer(slot->security, slot->scn, MAX_RFC_SESSION, rfcomm_cback, slot->id);
801       break;
802     }
803 
804     case BTA_JV_DISCOVERY_COMP_EVT: {
805       std::unique_lock<std::recursive_mutex> lock(slot_lock);
806       handle_discovery_comp(p_data->disc_comp.status, p_data->disc_comp.scn, id);
807       // Find the next slot that needs to perform an SDP request and service it.
808       rfc_slot_t* slot = find_rfc_slot_by_pending_sdp();
809       if (slot) {
810         BTA_JvStartDiscovery(slot->addr, 1, &slot->service_uuid, slot->id);
811         slot->f.pending_sdp_request = false;
812         slot->f.doing_sdp_request = true;
813       }
814       break;
815     }
816 
817     default:
818       log::debug("unhandled event:{}, slot id:{}", bta_jv_event_text(event), id);
819       break;
820   }
821 }
822 
handle_discovery_comp(tBTA_JV_STATUS status,int scn,uint32_t id)823 static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id) {
824   rfc_slot_t* slot = find_rfc_slot_by_id(id);
825   if (!slot) {
826     log::error("RFCOMM slot with id {} not found. event: BTA_JV_DISCOVERY_COMP_EVT", id);
827     return;
828   }
829 
830   if (!slot->f.doing_sdp_request) {
831     log::error("SDP response returned but RFCOMM slot {} did not request SDP record.", id);
832     return;
833   }
834 
835   if (status != tBTA_JV_STATUS::SUCCESS || !scn) {
836     log::error(
837             "SDP service discovery completed for slot id: {} with the result "
838             "status: {}, scn: {}",
839             id, bta_jv_status_text(status), scn);
840     cleanup_rfc_slot(slot);
841     return;
842   }
843 
844   if (BTA_JvRfcommConnect(slot->security, scn, slot->addr, rfcomm_cback, slot->id) !=
845       tBTA_JV_STATUS::SUCCESS) {
846     log::warn(
847             "BTA_JvRfcommConnect() returned BTA_JV_FAILURE for RFCOMM slot with "
848             "id: {}",
849             id);
850     cleanup_rfc_slot(slot);
851     return;
852   }
853   // Establish connection if successfully found channel number to connect.
854   slot->scn = scn;
855   slot->f.doing_sdp_request = false;
856 
857   if (!send_app_scn(slot)) {
858     log::warn("send_app_scn() failed, closing slot->id {}", slot->id);
859     cleanup_rfc_slot(slot);
860     return;
861   }
862 }
863 
864 typedef enum {
865   SENT_FAILED,
866   SENT_NONE,
867   SENT_PARTIAL,
868   SENT_ALL,
869 } sent_status_t;
870 
send_data_to_app(int fd,BT_HDR * p_buf)871 static sent_status_t send_data_to_app(int fd, BT_HDR* p_buf) {
872   if (p_buf->len == 0) {
873     return SENT_ALL;
874   }
875 
876   ssize_t sent;
877   OSI_NO_INTR(sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT));
878 
879   if (sent == -1) {
880     if (errno == EAGAIN || errno == EWOULDBLOCK) {
881       return SENT_NONE;
882     }
883     log::error("error writing RFCOMM data back to app: {}", strerror(errno));
884     return SENT_FAILED;
885   }
886 
887   if (sent == 0) {
888     return SENT_FAILED;
889   }
890 
891   if (sent == p_buf->len) {
892     return SENT_ALL;
893   }
894 
895   p_buf->offset += sent;
896   p_buf->len -= sent;
897   return SENT_PARTIAL;
898 }
899 
flush_incoming_que_on_wr_signal(rfc_slot_t * slot)900 static bool flush_incoming_que_on_wr_signal(rfc_slot_t* slot) {
901   while (!list_is_empty(slot->incoming_queue)) {
902     BT_HDR* p_buf = (BT_HDR*)list_front(slot->incoming_queue);
903     switch (send_data_to_app(slot->fd, p_buf)) {
904       case SENT_NONE:
905       case SENT_PARTIAL:
906         // monitor the fd to get callback when app is ready to receive data
907         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
908         return true;
909 
910       case SENT_ALL:
911         list_remove(slot->incoming_queue, p_buf);
912         break;
913 
914       case SENT_FAILED:
915         list_remove(slot->incoming_queue, p_buf);
916         return false;
917     }
918   }
919 
920   // app is ready to receive data, tell stack to start the data flow
921   // fix me: need a jv flow control api to serialize the call in stack
922   log::verbose("enable data flow, rfc_handle:0x{:x}, rfc_port_handle:0x{:x}, user_id:{}",
923                slot->rfc_handle, slot->rfc_port_handle, slot->id);
924   if (PORT_FlowControl_MaxCredit(slot->rfc_port_handle, true) != PORT_SUCCESS) {
925     log::warn("Unable to open RFCOMM port peer:{}", slot->addr);
926   }
927   return true;
928 }
929 
btsock_rfc_signaled(int,int flags,uint32_t id)930 void btsock_rfc_signaled(int /* fd */, int flags, uint32_t id) {
931   bool need_close = false;
932   std::unique_lock<std::recursive_mutex> lock(slot_lock);
933   rfc_slot_t* slot = find_rfc_slot_by_id(id);
934   if (!slot) {
935     log::warn("RFCOMM slot with id {} not found.", id);
936     return;
937   }
938 
939   // Data available from app, tell stack we have outgoing data.
940   if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
941     if (slot->f.connected) {
942       // Make sure there's data pending in case the peer closed the socket.
943       int size = 0;
944       if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) {
945         BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
946       }
947     } else {
948       log::error("socket signaled for read while disconnected, slot: {}, channel: {}", slot->id,
949                  slot->scn);
950       need_close = true;
951     }
952   }
953 
954   if (flags & SOCK_THREAD_FD_WR) {
955     // App is ready to receive more data, tell stack to enable data flow.
956     if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
957       log::error(
958               "socket signaled for write while disconnected (or write failure), "
959               "slot: {}, channel: {}",
960               slot->id, slot->scn);
961       need_close = true;
962     }
963   }
964 
965   if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
966     // Clean up if there's no data pending.
967     int size = 0;
968     if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size) {
969       if (com::android::bluetooth::flags::rfcomm_cancel_ongoing_sdp_on_close() &&
970           slot->f.doing_sdp_request) {
971         BTA_JvCancelDiscovery(slot->id);
972       }
973       cleanup_rfc_slot(slot);
974     }
975   }
976 }
977 
bta_co_rfc_data_incoming(uint32_t id,BT_HDR * p_buf)978 int bta_co_rfc_data_incoming(uint32_t id, BT_HDR* p_buf) {
979   int app_uid = -1;
980   uint64_t bytes_rx = 0;
981   int ret = 0;
982   std::unique_lock<std::recursive_mutex> lock(slot_lock);
983   rfc_slot_t* slot = find_rfc_slot_by_id(id);
984   if (!slot) {
985     log::error("RFCOMM slot with id {} not found.", id);
986     return 0;
987   }
988 
989   app_uid = slot->app_uid;
990   bytes_rx = p_buf->len;
991 
992   if (list_is_empty(slot->incoming_queue)) {
993     switch (send_data_to_app(slot->fd, p_buf)) {
994       case SENT_NONE:
995       case SENT_PARTIAL:
996         list_append(slot->incoming_queue, p_buf);
997         btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id);
998         break;
999 
1000       case SENT_ALL:
1001         osi_free(p_buf);
1002         ret = 1;  // Enable data flow.
1003         break;
1004 
1005       case SENT_FAILED:
1006         osi_free(p_buf);
1007         cleanup_rfc_slot(slot);
1008         break;
1009     }
1010   } else {
1011     list_append(slot->incoming_queue, p_buf);
1012   }
1013 
1014   slot->rx_bytes += bytes_rx;
1015   uid_set_add_rx(uid_set, app_uid, bytes_rx);
1016 
1017   return ret;  // Return 0 to disable data flow.
1018 }
1019 
bta_co_rfc_data_outgoing_size(uint32_t id,int * size)1020 int bta_co_rfc_data_outgoing_size(uint32_t id, int* size) {
1021   *size = 0;
1022   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1023   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1024   if (!slot) {
1025     log::error("RFCOMM slot with id {} not found.", id);
1026     return false;
1027   }
1028 
1029   if (ioctl(slot->fd, FIONREAD, size) != 0) {
1030     log::error("unable to determine bytes remaining to be read on fd {}: {}", slot->fd,
1031                strerror(errno));
1032     cleanup_rfc_slot(slot);
1033     return false;
1034   }
1035 
1036   return true;
1037 }
1038 
bta_co_rfc_data_outgoing(uint32_t id,uint8_t * buf,uint16_t size)1039 int bta_co_rfc_data_outgoing(uint32_t id, uint8_t* buf, uint16_t size) {
1040   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1041   rfc_slot_t* slot = find_rfc_slot_by_id(id);
1042   if (!slot) {
1043     log::error("RFCOMM slot with id {} not found.", id);
1044     return false;
1045   }
1046 
1047   ssize_t received;
1048   OSI_NO_INTR(received = recv(slot->fd, buf, size, 0));
1049 
1050   if (received != size) {
1051     log::error("error receiving RFCOMM data from app: {}", strerror(errno));
1052     cleanup_rfc_slot(slot);
1053     return false;
1054   }
1055 
1056   return true;
1057 }
1058 
btsock_rfc_disconnect(const RawAddress * bd_addr)1059 bt_status_t btsock_rfc_disconnect(const RawAddress* bd_addr) {
1060   log::assert_that(bd_addr != NULL, "assert failed: bd_addr != NULL");
1061   if (!is_init_done()) {
1062     log::error("BT not ready");
1063     return BT_STATUS_NOT_READY;
1064   }
1065 
1066   std::unique_lock<std::recursive_mutex> lock(slot_lock);
1067   for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) {
1068     if (rfc_slots[i].id && rfc_slots[i].addr == *bd_addr) {
1069       cleanup_rfc_slot(&rfc_slots[i]);
1070     }
1071   }
1072 
1073   return BT_STATUS_SUCCESS;
1074 }
1075